[Exploration] Specialize numeric list storage and reductions #1025
<!-- branch-diff -->
Branch diff: specialized-lists
| Commit | Message | Production | Test | Docs | Other |
| --- | --- | --: | --: | --: | --: |
| 486709c54 | Specialize numeric list stora… | +739 -180 | +536 -6 | +0 -0 | +4 -0 |
| 92161be82 | Fix benchmark imports and Pyt… | +0 -0 | +12 -9 | +0 -0 | +0 -0 |
| 139b3d1e0 | Represent lists as explicit s… | +192 -227 | +14 -8 | +0 -0 | +0 -0 |
| f6f0116d8 | Consolidate list helpers and … | +477 -485 | +0 -0 | +0 -0 | +0 -0 |
| 10d2fb8bf | Fix list review findings and … | +84 -18 | +20 -20 | +0 -0 | +0 -0 |
| 0e7c82fe3 | Separate specialized list sto… | +806 -321 | +19 -405 | +0 -0 | +0 -4 |
| | TOTAL | +1506 -439 | +171 -18 | +0 -0 | +0 -0 |
<!-- cubic:v=027ff4f3-4eed-46de-8da1-1ffb1b43e1f3 -->
<!-- cubic:review-run=c3179796-593c-575c-8fbf-3e0eb8a52f7c -->
<!-- metadata:{"confidence":10} -->
P2: The unspecialized revision does not contain this newly added benchmark target, so the documented baseline command fails there. State that users must backport the benchmark harness and target before running the baseline command.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty-bench/README.md, line 81:
<comment>The unspecialized revision does not contain this newly added benchmark target, so the documented baseline command fails there. State that users must backport the benchmark harness and target before running the baseline command.</comment>
<file context>
@@ -0,0 +1,147 @@
+The `len_int` case measures the fixed call overhead.
+Fresh sessions prevent mutating cases from measuring an already-promoted list on subsequent iterations.
+
+Run on the unspecialized revision to record a baseline, then compare on the specialized revision:
+
+sh</file context>
</details>
suggestionRun the same benchmark on both revisions; backport this newly added benchmark file and target to the unspecialized revision before recording its baseline:
``
7b8128e`<!-- cubic:v=f590fd9a-3189-46fa-9a66-cea7864566ff -->
<!-- cubic:review-run=c3179796-593c-575c-8fbf-3e0eb8a52f7c -->
<!-- metadata:{"confidence":8} -->
P2: Extending an empty list with homogeneous numbers allocates a second buffer, but this early return skips check_allocation; Storage::new builds the numeric Vec while the incoming Vec<Value> is still live. Preflight those bytes so a large extension raises MemoryError instead of bypassing the soft memory limit.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/list/storage.rs, line 139:
<comment>Extending an empty list with homogeneous numbers allocates a second buffer, but this early return skips `check_allocation`; `Storage::new` builds the numeric `Vec` while the incoming `Vec<Value>` is still live. Preflight those bytes so a large extension raises `MemoryError` instead of bypassing the soft memory limit.</comment>
<file context>
@@ -0,0 +1,407 @@
+ }
+
+ pub fn check_extend(&self, values: &[Value], tracker: &ResourceTracker) -> Result<(), ResourceError> {
+ if values.is_empty() || matches!(self, Self::Empty) {
+ // Empty storage takes the admitted vector, compacting numeric values in place.
+ return Ok(());
</file context>
</details>
✅ Addressed in 72dfe10
<!-- cubic:v=2b1ceb8f-fd59-419e-b04d-d7bf9b8cee73 -->
<!-- cubic:review-run=c3179796-593c-575c-8fbf-3e0eb8a52f7c -->
<!-- metadata:{"confidence":9} -->
P3: The sales workload also sorts a numeric list, and list.sort() expands numeric storage into Value elements. Mention sales sorting here too so readers can account for that path in both workload results.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty-bench/README.md, line 16:
<comment>The sales workload also sorts a numeric list, and `list.sort()` expands numeric storage into `Value` elements. Mention sales sorting here too so readers can account for that path in both workload results.</comment>
<file context>
@@ -0,0 +1,147 @@
+
+Construction is timed along with processing; there is no prebuilt input fixture.
+Sales reports exercise typed slices and integer reductions.
+Latency analysis includes sorting, which currently expands numeric storage into `Value` elements.
+Sensor summaries exercise float copies and slices alongside ordinary float reductions.
+Portfolio valuation spends more time in Python arithmetic and indexing, so it serves as a control for dispatch costs.
</file context>
</details>
Latency and sales sorting currently expand numeric storage into `Value` elements.
✅ Addressed in 7b8128e
<!-- cubic:v=e89e9c63-91aa-4b74-860b-8c6872b2f259 -->
<!-- cubic:review-run=c3179796-593c-575c-8fbf-3e0eb8a52f7c -->
<!-- metadata:{"confidence":9} -->
P3: This conversion allocates a new numeric buffer while the admitted Vec<Value> is still live, so it does not compact in place. Update the comment to avoid implying that this path is allocation-free.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/list/storage.rs, line 140:
<comment>This conversion allocates a new numeric buffer while the admitted `Vec<Value>` is still live, so it does not compact in place. Update the comment to avoid implying that this path is allocation-free.</comment>
<file context>
@@ -0,0 +1,407 @@
+
+ pub fn check_extend(&self, values: &[Value], tracker: &ResourceTracker) -> Result<(), ResourceError> {
+ if values.is_empty() || matches!(self, Self::Empty) {
+ // Empty storage takes the admitted vector, compacting numeric values in place.
+ return Ok(());
+ }
</file context>
</details>
// Empty storage adopts generic values; numeric values are compacted into a new buffer.
✅ Addressed in 72dfe10
<!-- cubic:review-summary:start -->
All reported issues were addressed across 19 files
<!-- cubic:review-summary:end -->
<sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Re-trigger cubic</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_be677e19bebfe7586acc783b164723946106563d02eb141dce6c5c89a0df52ff:e2a417b189b0769b229d1fac193d12edb43f4aa1:c3179796-593c-575c-8fbf-3e0eb8a52f7c -->
<!-- cubic:v=42ae98e6-5e6f-462b-9a08-936c9ff6a1be -->
<!-- cubic:review-run=8669c4cd-3fe1-59eb-a514-200faadb4ed1 -->
<!-- metadata:{"confidence":7} -->
P3: The PR description says snapshot encoding remains unchanged, but this delta replaces the old flat {I: [values], C: bool} list encoding (sequence of Values, independent of storage) with externally-tagged enum variants, deletes the same-version encoding pin, and bumps DUMP_VERSION 13→14 in the same commit. The bump keeps loading safe (old dumps are rejected by version), so no compatibility break — just update the description so the merge checklist reflects that a snapshot-format change happened.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/list.rs, line 32:
<comment>The PR description says snapshot encoding remains unchanged, but this delta replaces the old flat `{I: [values], C: bool}` list encoding (sequence of `Value`s, independent of storage) with externally-tagged enum variants, deletes the same-version encoding pin, and bumps `DUMP_VERSION` 13→14 in the same commit. The bump keeps loading safe (old dumps are rejected by version), so no compatibility break — just update the description so the merge checklist reflects that a snapshot-format change happened.</comment>
<file context>
@@ -29,73 +27,44 @@ use crate::{
-pub(crate) struct List {
+/// Python list with compact numeric buffers and generic reference-owning storage.
+#[derive(Debug, Default, Serialize, Deserialize)]
+pub(crate) enum List {
+ #[default]
+ #[serde(rename = "E")]
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/42ae98e6-5e6f-462b-9a08-936c9ff6a1be" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
<!-- cubic:review-summary:start -->
All reported issues were addressed across 7 files (changes from recent commits).
<!-- cubic:review-summary:end -->
<sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Re-trigger cubic</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_4e3b8afd67d6051d07867243798f6f1957a607092a26b3ff8eac52fc080585ea:a9e253c2f0568625be05ea7cf72eff222971d93f:8669c4cd-3fe1-59eb-a514-200faadb4ed1 -->
<!-- cubic:v=aa80ce9a-b5a4-4b70-938a-bae3e15b11be -->
<!-- cubic:review-run=3543b1ae-1517-5341-ac85-5a17b91980a9 -->
<!-- metadata:{"confidence":9} -->
P1: Generic slicing and repetition preflight only the Vec<Value> output, but List::new allocates a second compact buffer while that vector is still live. Preflight those extra bytes so homogeneous results cannot exceed max_memory or the allocator hard limit.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/list.rs, line 86:
<comment>Generic slicing and repetition preflight only the `Vec<Value>` output, but `List::new` allocates a second compact buffer while that vector is still live. Preflight those extra bytes so homogeneous results cannot exceed `max_memory` or the allocator hard limit.</comment>
<file context>
@@ -61,49 +60,426 @@ impl List {
+ if values.is_empty() {
+ Self::Empty
+ } else if values.iter().all(|v| matches!(v, Value::Int(_))) {
+ let mut ints: Vec<i64> = values
+ .into_iter()
+ .map(|v| match v {
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/aa80ce9a-b5a4-4b70-938a-bae3e15b11be" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
<!-- cubic:review-summary:start -->
All reported issues were addressed across 3 files (changes from recent commits).
<!-- cubic:review-summary:end -->
<sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Re-trigger cubic</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_fe867341912df4654b193566a8f15b12738a1c728098851eef46300e33599f13:72dfe100748cda1a48c835c1d0101ae963458460:3543b1ae-1517-5341-ac85-5a17b91980a9 -->
<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->
Merging this PR will regress 2 benchmarks
⚡ 5 improved benchmarks ❌ 2 regressed benchmarks ✅ 93 untouched benchmarks ⏩ 74 skipped benchmarks[^skipped]
[!WARNING]
Please fix the performance issues or acknowledge them on CodSpeed.
Performance Changes
| | Mode | Benchmark | BASE | HEAD | Efficiency |
| --- | ---- | --------- | ------ | ------ | ---------- |
| ❌ | WallTime | ` builtin_args__monty | 43.4 ms | 59.3 ms | -26.87% |
| ❌ | WallTime | empty_tuples__monty | 13.8 ms | 15.5 ms | -10.93% |
| ⚡ | Memory | list_append_int__monty | 2 MB | 1 MB | +97.19% |
| ⚡ | WallTime | list_append_int__monty | 33.1 ms | 26.2 ms | +26.07% |
| ⚡ | WallTime | func_call_kwargs__monty | 5 µs | 4.2 µs | +19.43% |
| ⚡ | WallTime | pair_tuples__monty | 46.3 ms | 40.6 ms | +14.03% |
| ⚡ | WallTime | attr_dispatch_minimal__monty | 15.2 ms | 13.6 ms | +12.24% |
[!TIP]
Investigate this regression by commenting @codspeedbot fix this regression` on this PR, or directly use the CodSpeed MCP with your agent.
---
<sub>Comparing <code>jaheba:specialized-lists</code> (0e7c82f) with <code>main</code> (03f566b)</sub>
<a href="https://app.codspeed.io/pydantic/monty/branches/jaheba%3Aspecialized-lists?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>
[^skipped]: 74 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
_Auto response from Codex running fix-pr-comments:_
Updated locally: the baseline instructions now say to copy benches/lists.rs and its Cargo benchmark target into the unspecialized revision before recording the baseline. This change is not committed or pushed yet.
_Auto response from Codex running fix-pr-comments:_
Updated locally to mention that both latency and sales sorting expand numeric storage into Value elements. This documentation change is not committed or pushed yet.
_Auto response from Codex running fix-pr-comments:_
The current PR description already documents direct enum serialization, the dump-version bump from 13 to 14, regenerated fixtures, and rejection of version-13 snapshots. Verified that both the main description and summary reflect the format change.
_Auto response from Codex running fix-pr-comments:_
Confirmed with an allocation-counter probe. Fixed locally by keeping generic slice and repetition results generic, reusing the already-preflighted output buffer instead of passing it through List::new. For 100,000 numeric elements, measured peak allocation falls from 2.4 MB to 1.6 MB for slicing and from 4.8 MB to 3.2 MB for repetition, with one fewer allocation. Added a regression test for both integer and float results; all seven list unit tests pass with memory-model checks, and the subprocess allocation-limit test passes. This fix is not committed or pushed yet.
<!-- cubic:v=6397b3b3-76a4-41a2-b2eb-4b6b209fa834 -->
<!-- cubic:review-run=94d6277a-1e0c-5bcf-880a-dd99bb440678 -->
<!-- metadata:{"confidence":9} -->
P3: This test now holds an iterator, not a slice, so the explanation no longer describes what keeps the heap borrow alive. Update the comment to say the iterator borrows the list.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/tests/heap_reader_compile_fail_cases/cases.rs, line 33:
<comment>This test now holds an iterator, not a slice, so the explanation no longer describes what keeps the heap borrow alive. Update the comment to say the iterator borrows the list.</comment>
<file context>
@@ -30,9 +30,9 @@ fn heap_mutation_while_reading(list_id: HeapId, heap: &mut Heap) {
_ => unreachable!(),
};
- let slice = a.get(heap).as_slice();
+ let items = a.get(heap).iter();
let _ = allocate_string("boom", heap.heap_mut());
- let _ = slice.len();
</file context>
</details>
✅ Addressed in 0e7c82f
<!-- cubic:review-summary:start -->
All reported issues were addressed across 8 files (changes from recent commits).
<!-- cubic:review-summary:end -->
<sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Re-trigger cubic</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_1be5cc2c4f4203552a7c563d00de87a5dd8ed8bb2047c1a88256e6b9436c2485:7b8128e4976d57b65684a931e9b787313413f936:94d6277a-1e0c-5bcf-880a-dd99bb440678 -->
Codecov Report
:x: Patch coverage is
94.29892% with 37 lines in your changes missing coverage. Please review.| Files with missing lines | Patch % | Lines |
|---|---|---|
| crates/monty/src/types/list.rs | 94.52% | 19 Missing and 14 partials :warning: |
| crates/monty/src/bytecode/vm/collections.rs | 81.81% | 0 Missing and 2 partials :warning: |
| crates/monty/src/builtins/sum.rs | 85.71% | 0 Missing and 1 partial :warning: |
| crates/monty/src/types/csv/writer.rs | 80.00% | 0 Missing and 1 partial :warning: |
:loudspeaker: Thoughts on this report? Let us know!
_Auto response from Codex running fix-pr-comments:_ Updated locally: the explanation now says the iterator borrows the list and keeps the immutable heap borrow alive. This comment-only change is not committed or pushed yet.
This is interesting: on one hand, it'd be nice to have faster numeric operations. On the other hand, I worry that lists are not really the right place to do it, and things like numpy support is a better primitive. Also, I worry that this approach presumably has O(n) performance hits such as appending a non-integer to a previously homogeneous list.
I also wonder if we can theoretically implement a JIT or other form of specializing interpreter to remove a lot of the dynamic overhead (?)
I also wonder if we can theoretically implement a JIT or other form of specializing interpreter to remove a lot of the dynamic overhead (?)
For me it would be the other way around: Specialized lists could enable further optimizations in a JIT or spelializing interpreter.
This is foremost intended as a storage optimization (saving memory) not necessarily one to improve runtime.
The point about numpy is fair, but that would be a "conscious" choice the agent would have to make. This PR improves any list[int].
Also, I worry that this approach presumably has O(n) performance hits such as appending a non-integer to a previously homogeneous list.
Yes, but I'd argue that would only happen once and probably early. Growing a list might already require multiple re-allocations.
---
The biggest problem might be that this is a breaking change, since this would break the representation of list? Let me try that.
<!-- cubic:v=b9712808-9a69-4e1b-8f6f-b20c792c9da1 -->
<!-- cubic:review-run=18317c76-bba8-542d-a3ae-3c92dbc8e0bc -->
<!-- metadata:{"confidence":8} -->
P2: Importing a numeric MontyNode::List allocates a full boxed vector and a typed vector concurrently, adding an avoidable peak that can breach the allocator limit for large host inputs. Construct the typed storage directly or preflight this conversion before allocating it.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/object_bridge.rs, line 853:
<comment>Importing a numeric `MontyNode::List` allocates a full boxed vector and a typed vector concurrently, adding an avoidable peak that can breach the allocator limit for large host inputs. Construct the typed storage directly or preflight this conversion before allocating it.</comment>
<file context>
@@ -839,7 +848,10 @@ fn import_node(
- Ok(Value::Ref(vm.heap.allocate(HeapData::List(List::new(values)))))
+ Ok(Value::Ref(
+ vm.heap
+ .allocate(HeapData::SpecializedList(SpecializedList::new(values))),
+ ))
}
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/b9712808-9a69-4e1b-8f6f-b20c792c9da1" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
<!-- cubic:v=69465370-d173-4666-84fd-23c28948ff0d -->
<!-- cubic:review-run=18317c76-bba8-542d-a3ae-3c92dbc8e0bc -->
<!-- metadata:{"confidence":8} -->
P2: filter() now allocates a second full result buffer when its output is homogeneous numeric, while the boxed buffer is still live, without preflighting that extra allocation. Large numeric results can cross the memory hard limit during SpecializedList::new; preflight the conversion or collect directly into typed storage.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/builtins/filter.rs, line 61:
<comment>`filter()` now allocates a second full result buffer when its output is homogeneous numeric, while the boxed buffer is still live, without preflighting that extra allocation. Large numeric results can cross the memory hard limit during `SpecializedList::new`; preflight the conversion or collect directly into typed storage.</comment>
<file context>
@@ -58,6 +58,6 @@ pub fn builtin_filter(vm: &mut VM<'_>, args: ArgValues) -> RunResult<Value> {
let (out, vm) = out_guard.into_parts();
- let heap_id = vm.heap.allocate(HeapData::List(List::new(out)));
+ let heap_id = vm.heap.allocate(HeapData::SpecializedList(SpecializedList::new(out)));
Ok(Value::Ref(heap_id))
}
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/69465370-d173-4666-84fd-23c28948ff0d" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
<!-- cubic:v=6362a453-3804-4b4f-861d-204b39470164 -->
<!-- cubic:review-run=18317c76-bba8-542d-a3ae-3c92dbc8e0bc -->
<!-- metadata:{"confidence":7} -->
P2: Removing the list arm from exact_sequence_items drops the borrowed fast path for a, b = some_list. UNPACK_SEQUENCE now allocates a temporary Vec and clones each item before pushing it. Add a slice accessor on List and restore the arm, and update the helper's doc comment to match.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/bytecode/vm/collections.rs, line 655:
<comment>Removing the list arm from `exact_sequence_items` drops the borrowed fast path for `a, b = some_list`. `UNPACK_SEQUENCE` now allocates a temporary Vec and clones each item before pushing it. Add a slice accessor on `List` and restore the arm, and update the helper's doc comment to match.</comment>
<file context>
@@ -9,7 +9,7 @@ use crate::{
heap::{DropGuard, DropWithContext, Heap, HeapData, HeapReadOutput},
intern::StringId,
types::{
- Dict, List, PyTrait, Set, Slice, allocate_tuple, collect_iterable, collect_iterable_bounded,
+ Dict, PyTrait, Set, Slice, SpecializedList, allocate_tuple, collect_iterable, collect_iterable_bounded,
instance::instance_defines_iter, slice::value_to_option_i64,
},
value::{VALUE_SIZE, Value},
@@ -19,8 +19,8 @@ impl VM<'_> {
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/6362a453-3804-4b4f-861d-204b39470164" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
<!-- cubic:v=dae666ee-0ad5-4145-8326-5a41e65d31f4 -->
<!-- cubic:review-run=18317c76-bba8-542d-a3ae-3c92dbc8e0bc -->
<!-- metadata:{"confidence":9} -->
P2: copy.copy boxes every specialized numeric element before allocating the typed result, creating a large temporary buffer and charging VALUE_SIZE instead of the compact element size. Copy the specialized buffer directly with an element-size-aware preflight so large copies do not hit the memory ceiling from avoidable peak usage.
(Based on your team's feedback about one-shot preflights for clone-style list bursts.) [c43505f3-f2ba-4e7e-ace6-447cb4b75a07]
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/modules/copy.rs, line 116:
<comment>`copy.copy` boxes every specialized numeric element before allocating the typed result, creating a large temporary buffer and charging `VALUE_SIZE` instead of the compact element size. Copy the specialized buffer directly with an element-size-aware preflight so large copies do not hit the memory ceiling from avoidable peak usage.
(Based on your team's feedback about one-shot preflights for clone-style list bursts.) [c43505f3-f2ba-4e7e-ace6-447cb4b75a07]</comment>
<file context>
@@ -108,7 +108,15 @@ fn shallow_copy(value: &Value, vm: &mut VM<'_>) -> RunResult<Value> {
+ ))
+ }
+ HeapReadOutput::SpecializedList(list) => {
+ let items = clone_items(list.get(vm.heap).len(), vm, |index, vm| list.clone_item(index, vm))?;
+ Ok(Value::Ref(
+ vm.heap.allocate(HeapData::SpecializedList(SpecializedList::new(items))),
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/dae666ee-0ad5-4145-8326-5a41e65d31f4" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
<!-- cubic:review-summary:start -->
All reported issues were addressed across 44 files (changes from recent commits).
<!-- cubic:review-summary:end -->
<sub>Reply with feedback, questions, or to request a fix.<br /><br />View guided diff | Re-trigger cubic</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_463adb194e843368b6a503f0d502ca022aab569ac2ae7e5547520d1ea3f7f558:0e7c82fe3bd5b1155730f0503aa3f940135e4bf0:18317c76-bba8-542d-a3ae-3c92dbc8e0bc -->
<!-- cubic:v=0073e277-13db-4740-9fa0-696f9a7ce8d7 -->
<!-- cubic:review-run=18317c76-bba8-542d-a3ae-3c92dbc8e0bc -->
<!-- metadata:{"confidence":5} -->
P3: No test exercises json.dumps(..., separators=[1, 2]) with an all-numeric list, which is now stored as typed Int/Float storage. Add a case to json__dumps_errors.py so the new SpecializedList arm in parse_separators_value is covered.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/modules/json/dump.rs, line 269:
<comment>No test exercises `json.dumps(..., separators=[1, 2])` with an all-numeric list, which is now stored as typed `Int`/`Float` storage. Add a case to `json__dumps_errors.py` so the new `SpecializedList` arm in `parse_separators_value` is covered.</comment>
<file context>
@@ -266,6 +266,14 @@ fn parse_separators_value(value: Value, vm: &mut VM<'_>) -> RunResult<Option<(St
json_separator_to_string(&list.get(1).expect("length checked"), "key_separator", vm)?,
)
}
+ HeapReadOutput::SpecializedList(list) => {
+ let list = list.get(vm.heap);
+ check_separators_length(list.len())?;
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/0073e277-13db-4740-9fa0-696f9a7ce8d7" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
<!-- cubic:v=66ead0e8-f91b-4a38-b5f1-f28dfb47f9cc -->
<!-- cubic:review-run=18317c76-bba8-542d-a3ae-3c92dbc8e0bc -->
<!-- metadata:{"confidence":5} -->
P3: Every all-float record now goes through SpecializedList::new's typed conversion, which scans all fields, allocates a second buffer, copies, and frees the original Vec<Value>. The previous List::new just moved the vector. Consider whether the reader should build the typed buffer directly during parsing, or accept this per-row cost on QUOTE_NONNUMERIC readers.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/types/csv/reader.rs, line 71:
<comment>Every all-float record now goes through `SpecializedList::new`'s typed conversion, which scans all fields, allocates a second buffer, copies, and frees the original `Vec<Value>`. The previous `List::new` just moved the vector. Consider whether the reader should build the typed buffer directly during parsing, or accept this per-row cost on `QUOTE_NONNUMERIC` readers.</comment>
<file context>
@@ -67,7 +67,12 @@ impl Reader {
let fields = next_fields(obj, vm)?;
- Ok(fields.map(|fields| Value::Ref(vm.heap.allocate(HeapData::List(List::new(fields))))))
+ Ok(fields.map(|fields| {
+ Value::Ref(
+ vm.heap
+ .allocate(HeapData::SpecializedList(SpecializedList::new(fields))),
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/66ead0e8-f91b-4a38-b5f1-f28dfb47f9cc" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
<!-- cubic:v=2efce260-c0a6-42ae-ba77-4da79e016d01 -->
<!-- cubic:review-run=18317c76-bba8-542d-a3ae-3c92dbc8e0bc -->
<!-- metadata:{"confidence":5} -->
P3: This SpecializedList arm is a copy of the List arm directly above it, so the snapshot-then-push_all logic now exists in three places. Consider a small helper generic over the list storage type that returns the snapshot Vec<Value>, and call it from all three arms so a future change to the snapshot rule only happens once.
<details>
<summary>Prompt for AI agents</summary>
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At crates/monty/src/object_bridge.rs, line 266:
<comment>This `SpecializedList` arm is a copy of the `List` arm directly above it, so the snapshot-then-`push_all` logic now exists in three places. Consider a small helper generic over the list storage type that returns the snapshot `Vec<Value>`, and call it from all three arms so a future change to the snapshot rule only happens once.</comment>
<file context>
@@ -264,6 +263,16 @@ impl GraphExporter {
defer_drop!(children, vm);
MontyNode::List(self.push_all(children, vm))
}
+ HeapReadOutput::SpecializedList(list) => {
+ // Snapshot before recursing: a nested `__repr__` may mutate this list.
+ let children: Vec<Value> = list
</file context>
</details>
<a href="https://www.cubic.dev/action/fix/violation/2efce260-c0a6-42ae-ba77-4da79e016d01" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://cubic.dev/buttons/fix-with-cubic-light.svg">
<img alt="Fix with cubic" src="https://cubic.dev/buttons/fix-with-cubic-dark.svg">
</picture>
</a>
_Auto response from Codex running fix-pr-comments:_
Fixed locally by constructing specialized storage directly from borrowed imported children. Integer and float imports now allocate only their typed result buffer; mixed imports clone into generic storage and preserve reference ownership. Added typed-storage and reference-cleanup regression tests. The fix is not committed or pushed yet.
_Auto response from Codex running fix-pr-comments:_
Fixed locally: filter now collects directly into SpecializedList, with checked growth before each admitted element. Numeric output no longer passes through a full temporary Vec<Value> and conversion. Promotion remains guarded on errors. Added integer/float filter regression tests under memory-model checks. The fix is not committed or pushed yet.
_Auto response from Codex running fix-pr-comments:_
Fixed locally with a borrowed exact-sequence view for tuples, legacy lists and specialized lists. UNPACK_SEQUENCE pushes directly from that view, including inline numeric elements, without a temporary Vec. This retains list encapsulation rather than restoring a general slice accessor. Added a regression test covering legacy, integer, float and promoted storage, and updated the helper documentation. The fix is not committed or pushed yet.
_Auto response from Codex running fix-pr-comments:_
Fixed locally by routing copy.copy through the existing storage-aware list-copy helper. It preflights the actual element size and copies numeric buffers directly; generic buffers remain generic without a second conversion. Added a regression test for integer, float and promoted-numeric storage. The fix is not committed or pushed yet.
_Auto response from Codex running fix-pr-comments:_
Added integer and float numeric separators tests for both lists and tuples. These exposed a validation-order difference: CPython checks key_separator first when both values are invalid. Fixed that order through a shared pair validator. All 1,342 Monty/CPython fixture cases pass with Python 3.14.8. The fix is not committed or pushed yet.
_Auto response from Codex running fix-pr-comments:_
Considered this tradeoff and am accepting the per-row conversion cost for now. The current parser produces Vec<Value> for both csv.reader and DictReader, and compacting homogeneous float rows enables typed downstream operations. Building typed records during parsing is a separate optimization and should be measured against mixed/quoted rows before changing that shared parser.
_Auto response from Codex running fix-pr-comments:_
Consolidated the snapshot collection locally into one helper shared by legacy lists, specialized lists and deques. It clones all children before recursive export, preserving the nested __repr__ mutation rule. Memory-model tests and the full fixture suite pass. The refactor is not committed or pushed yet.
jaheba
Homogeneous integer and float lists use compact numeric buffers instead of storing a
Valuefor every element. Numeric reductions and bulk operations work directly on those buffers, while existing snapshots retain their original generic list representation.Representation and mutation
HeapData::List(List)with its originalitems: Vec<Value>andcontains_refsfields.HeapData::SpecializedList(SpecializedList), withEmpty,Int(Vec<i64>),Float(Vec<f64>), andGeneric(List)storage variants.Generic(List)without changing the heap variant orHeapId. Existing aliases, typed heap handles and iterators remain valid.ListStorage. Comparisons, concatenation, copying, JSON/CSV handling and host-value conversion support both heap representations.sum()uses an exacti128accumulator, widening the output to a bigint when needed. Floatsum()preserves the existing left-to-right addition order. Both check execution deadlines during the buffer walk.The first incompatible mutation costs O(n). Nullable integers stay generic, and sorting currently expands numeric storage into
Valueelements.Dump compatibility
DUMP_VERSIONremains 13. The existing heap variant and list field names retain their original serde encoding; old snapshots deserialize directly intoList, with no compatibility deserializer. Specialized lists use a separate heap variant taggedVand derive their own serde implementation.The unchanged version-13 fixture loads, resumes its suspended host call, and passes its state checks. Newly written snapshots also round-trip specialized, promoted, empty and self-referential lists. Loading new specialized-list snapshots in an older Monty build is not guaranteed.
Scope
There are no changes to
monty-benchormonty-runtimerelative toorigin/main.Benchmark code, workloads and added subprocess tests are excluded from this PR. The measurements below remain historical evidence for the optimization; the benchmark harness and application workloads can be added to Flying Circus separately.
Historical benchmark results
These measurements precede the current split heap representation and have not been rerun on it. Local Apple Silicon runs compared the cached
tagged-heap-main-f190cda9baseline against earlier release builds of this branch; baseline compiler flags were not independently verified.| Operation, one million elements | Baseline | Specialized | Speedup |
| --- | ---: | ---: | ---: |
| Integer sum | 21.23 ms | 0.425 ms | 49.9x |
| Float sum | 20.08 ms | 1.06 ms | 19x |
| Integer copy | 2.65 ms | 0.512 ms | 5.2x |
| Integer slice | 13.64 ms | 1.57 ms | 8.7x |
| Integer repetition | 8.74 ms | 1.05 ms | 8.3x |
Retained session memory for one million integers fell from 16.82 MB to 8.04 MB. An incompatible append increased from about 0.024 ms to 0.584 ms. At 4,096 elements, short runs measured range construction about 6.5% slower and mixed-list copying about 7.7% slower.
Application processing improved about 2.7x for integer sales reports, 16–17% for float sensor summaries, and 13% for float portfolio valuation. Integer latency analysis had no confirmed timing improvement. Sorting, construction and Python arithmetic limit application gains.
The earlier full Flying Circus run found no statistically supported changes at its 5% threshold, with 21 comparisons inconclusive. Both builds had the same two OS-call suspension failures and two unsupported workloads. That run preceded typed float summation; the float application workloads were rerun afterward. Generated reports remain local artifacts.
Validation
memory-model-checks: passed.prekchecks: passed.large_allocations_are_rejected_before_the_hard_limit,reading_partial_args_cannot_kill_the_worker, andan_export_that_outgrows_the_hard_limit_exits_with_the_oom_code. Their memory-pressure inputs and expected allocation figures assume boxed integer lists. Compact storage changes those assumptions: one reported usage differs, one test gets worker EOF during export, and the expected-OOM export now leaves the worker alive. The suite passed with the test adjustments before those changes were removed.Possible follow-ups
1. Construct
list(range(...))directly into integer storage, avoiding a temporaryVec<Value>. Investigate typed comprehension construction separately.2. Add typed
min()andmax()scans while preserving key/default behavior and NaN semantics.3. Sort numeric buffers directly when no key is supplied, preserving float ordering and mutation detection.
4. Optimize membership,
count()andindex()while retaining cross-type equality such asTrue == 1 == 1.0.5. Compare matching numeric buffers directly for equality and ordering.
6. Benchmark nullable numeric storage before adding another specialization.