← Back to Pull requests

Add `Value::InlineString` variant #994

Merged
jaheba merged 82 files (2167 lines) on Oct 30, 2026 11:05 UTC
View on GitHub
jaheba jaheba commented on Oct 07, 2026 20:21 UTC
Author

Depends on #1183, which extracts the string accessors, caller migrations, and name-conversion refactoring. Merge that PR first.

Review the inline-only diff. GitHub's base remains main because the prerequisite branch lives in the fork; until #1183 merges, the normal Files changed view includes both commits.

Store runtime strings of 2–15 UTF-8 bytes directly in Value::InlineString(InlineStr), avoiding a separate interpreter heap object. The niche in InlineLen keeps Value at 16 bytes, enforced by a size test. Empty strings and single ASCII characters retain reserved interned IDs; longer strings use the heap.

Extend the shared string views, iteration, hashing, host conversions, and attribute names to support inline storage. json.loads() bypasses its string cache for strings up to 15 bytes and caches repeated strings of 16–64 bytes.

Equal inline strings share identity under is and id(), as documented in docs/limitations/builtins.md and covered by identity tests. The dump version is 15; versions 13 and 14 remain readable. Reference-count and memory-limit tests use longer strings where they need heap allocations.

Validation: the standalone refactoring passes the full Monty Rust suite and 718 fixtures with memory-model-checks and ref-count-return. The stacked production source matches the previously validated #994 tree exactly, and all 719 fixtures pass with the shared tests renamed.

All prek hooks pass on both branches.

Diff: 2167 lines (+1507 / -660) across 82 files Reviewer: rewitt94 Review duration: 32563m
All Vouch review confidence checks passed
Residual risk 0.05 = Change Risk (0.72) × (1 − Review Confidence (0.94)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.72 · 2167 lines diff across 82 files
0.72
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.96 · 5 substantive comment(s)
0.96
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
93%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Mass File Touch mass_file_touch
0.080
Real PR Conversation Timeline
46 items
github-actions[bot] github-actions[bot] commented on Oct 07, 2026 20:21 UTC
Bot

<!-- branch-diff -->

Branch diff: codex/inline-strings

| Commit | Message | Production | Test | Docs | Other |
| --- | --- | --: | --: | --: | --: |
| 303d4d3f7 | Centralize string access and … | +440 -531 | +347 -0 | +0 -0 | +0 -0 |
| b77c1af59 | Address string refactoring re… | +3 -3 | +9 -2 | +0 -0 | +0 -0 |
| 5934b274a | Store short runtime strings i… | +485 -107 | +224 -22 | +4 -0 | +0 -0 |
| | TOTAL | +925 -638 | +578 -22 | +4 -0 | +0 -0 |

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 07, 2026 20:26 UTC
Code Review
crates/monty/src/identity.rs:1
@@ -42,6 +42,8 @@ pub(crate) enum Identity {
     Float(u64),
     /// Identity of an interned string.
     InternString(usize),
+    /// Content identity of a short string stored inline.
+    InlineString { len: u8, bytes: [u8; 15] },

<!-- cubic:v=f01c3dc4-0e09-4e8a-b767-2566614fd728 -->
<!-- cubic:review-run=76bb3e5e-7fef-5e20-83c5-c8d2ab9d89fb -->
<!-- metadata:{"confidence":7} -->
P2: Identity::InlineString is content-based, so two separately created short strings with equal content now compare equal under is and share the same id() value. Before this PR every string ≥2 bytes was heap-allocated with a unique heap id, so bin(4) is bin(4) was False with distinct id()s; now both are True/equal for any short result routed through allocate_string/allocate_string_no_interning (bin/hex/oct, datetime/time/date formatting, json string cache, str(n), slicing). This deviates from CPython, where runtime-created strings are distinct objects (bin(4) is bin(4) is False, and two simultaneously alive distinct strings have distinct id()), and it silently widens shared identity from compile-time-interned literals to all runtime strings. If this is an accepted tradeoff for the exploration, document it; otherwise keep the unique heap identity path for strings whose identity can be observed.

<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/identity.rs, line 46:

<comment>`Identity::InlineString` is content-based, so two separately created short strings with equal content now compare equal under `is` and share the same `id()` value. Before this PR every string ≥2 bytes was heap-allocated with a unique heap id, so `bin(4) is bin(4)` was False with distinct `id()`s; now both are True/equal for any short result routed through `allocate_string`/`allocate_string_no_interning` (bin/hex/oct, datetime/time/date formatting, `json` string cache, `str(n)`, slicing). This deviates from CPython, where runtime-created strings are distinct objects (`bin(4) is bin(4)` is False, and two simultaneously alive distinct strings have distinct `id()`), and it silently widens shared identity from compile-time-interned literals to all runtime strings. If this is an accepted tradeoff for the exploration, document it; otherwise keep the unique heap identity path for strings whose identity can be observed.</comment>

<file context>
@@ -42,6 +42,8 @@ pub(crate) enum Identity {
     /// Identity of an interned string.
     InternString(usize),
+    /// Content identity of a short string stored inline.
+    InlineString { len: u8, bytes: [u8; 15] },
     /// Identity of an interned bytes value.
     InternBytes(usize),
</file context>

</details>

<a href="https://www.cubic.dev/action/fix/violation/f01c3dc4-0e09-4e8a-b767-2566614fd728" 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-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 07, 2026 20:26 UTC
Code Review
crates/monty/src/bytecode/vm/collections.rs:1
@@ -250,7 +250,7 @@ impl VM<'_> {
             for (key, value) in copied_items {
                 // Validate key is a string (InternString or heap-allocated Str)
                 let is_string = match &key {
-                    Value::InternString(_) => true,
+                    Value::InternString(_) | Value::InlineString { .. } => true,

<!-- cubic:v=7eba8f50-7f90-4fc8-adbf-e7fc4ddcf6e5 -->
<!-- cubic:review-run=76bb3e5e-7fef-5e20-83c5-c8d2ab9d89fb -->
<!-- metadata:{"confidence":0.9} -->
P3: The comment directly above this match still says keys are validated as "InternString or heap-allocated Str", but the match now also accepts InlineString (neither interned nor heap-allocated). Update the comment to reflect the new accepted forms.

<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 253:

<comment>The comment directly above this match still says keys are validated as "InternString or heap-allocated Str", but the match now also accepts `InlineString` (neither interned nor heap-allocated). Update the comment to reflect the new accepted forms.</comment>

<file context>
@@ -250,7 +250,7 @@ impl VM<'_> {
                 // Validate key is a string (InternString or heap-allocated Str)
                 let is_string = match &key {
-                    Value::InternString(_) => true,
+                    Value::InternString(_) | Value::InlineString { .. } => true,
                     Value::Ref(id) => matches!(this.heap.get(*id), HeapData::Str(_)),
                     _ => false,
</file context>

</details>

✅ Addressed in 5a38951

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 07, 2026 20:26 UTC
Code Review
crates/monty/src/types/str.rs:1
@@ -201,8 +217,7 @@ pub fn allocate_char(c: char, heap: &Heap) -> Value {
     if c.is_ascii() {
         Value::InternString(StringId::from_ascii(c as u8))
     } else {
-        let heap_id = heap.allocate(HeapData::Str(Str::new(c.to_string())));
-        Value::Ref(heap_id)
+        allocate_string(c.to_string(), heap)

<!-- cubic:v=217683cf-45de-4985-a94f-d66e2259a428 -->
<!-- cubic:review-run=76bb3e5e-7fef-5e20-83c5-c8d2ab9d89fb -->
<!-- metadata:{"confidence":10} -->
P3: This now stores every non-ASCII character inline, contradicting the comment above that promises heap allocation. Update the documentation to describe inline 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/types/str.rs, line 220:

<comment>This now stores every non-ASCII character inline, contradicting the comment above that promises heap allocation. Update the documentation to describe inline storage.</comment>

<file context>
@@ -201,8 +217,7 @@ pub fn allocate_char(c: char, heap: &Heap) -> Value {
     } else {
-        let heap_id = heap.allocate(HeapData::Str(Str::new(c.to_string())));
-        Value::Ref(heap_id)
+        allocate_string(c.to_string(), heap)
     }
 }
</file context>

</details>

✅ Addressed in 5a38951

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 07, 2026 20:26 UTC
Code Review
crates/monty/src/value.rs:1
@@ -2246,6 +2416,7 @@ impl Value {
     pub fn as_either_str(&self, heap: &Heap) -> Option<EitherStr> {
         match self {
             Self::InternString(id) => Some(EitherStr::Interned(*id)),
+            Self::InlineString { .. } => Some(EitherStr::Heap(self.inline_str().unwrap().to_owned())),

<!-- cubic:v=ad2d760b-88c6-4348-92c4-fd7d5e85ed0d -->
<!-- cubic:review-run=76bb3e5e-7fef-5e20-83c5-c8d2ab9d89fb -->
<!-- metadata:{"confidence":6} -->
P3: as_either_str heap-allocates an owned clone for every inline string, so these callers pay a String allocation plus a copy even though the value is already stored inline. The same allocation is unavoidable for heap Ref strings, but an inline string could be handed out borrowed; if EitherStr has no borrowed variant, consider adding one or documenting that as_either_str on short strings does not benefit from inline storage. (The interned variant already returns a borrow, so the asymmetry is visible to callers.)

<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/value.rs, line 2419:

<comment>`as_either_str` heap-allocates an owned clone for every inline string, so these callers pay a `String` allocation plus a copy even though the value is already stored inline. The same allocation is unavoidable for heap `Ref` strings, but an inline string could be handed out borrowed; if `EitherStr` has no borrowed variant, consider adding one or documenting that `as_either_str` on short strings does not benefit from inline storage. (The `interned` variant already returns a borrow, so the asymmetry is visible to callers.)</comment>

<file context>
@@ -2246,6 +2416,7 @@ impl Value {
     pub fn as_either_str(&self, heap: &Heap) -> Option<EitherStr> {
         match self {
             Self::InternString(id) => Some(EitherStr::Interned(*id)),
+            Self::InlineString { .. } => Some(EitherStr::Heap(self.inline_str().unwrap().to_owned())),
             Self::Ref(heap_id) => match heap.get(*heap_id) {
                 HeapData::Str(s) => Some(EitherStr::Heap(s.as_str().to_owned())),
</file context>

</details>

✅ Addressed in 5a38951

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on Oct 07, 2026 20:26 UTC
Reviewer

<!-- cubic:review-summary:start -->
All reported issues were addressed across 24 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_5958d7fed1d9bbf60a26bd4e09aab7c2784ad1c3e9e7d92bfc9c45df08d32f5b:2b043d08a01f9d29e3b27f9de87f8539bdfb3d96:76bb3e5e-7fef-5e20-83c5-c8d2ab9d89fb -->

codspeed[bot] codspeed[bot] commented on Oct 07, 2026 20:36 UTC
Bot

<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

Merging this PR will regress 2 benchmarks

⚡ 14 improved benchmarks
❌ 2 regressed benchmarks
✅ 104 untouched benchmarks
⏩ 78 skipped benchmarks[^skipped]

[!WARNING]

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

| | Mode | Benchmark | BASE | HEAD | Efficiency |
| --- | ---- | --------- | ------ | ------ | ---------- |
| ❌ | Walltime | ` fib__monty | 86 ms | 97 ms | -11.28% |
| ❌ | Walltime |
pair_tuples__monty | 37.1 ms | 41.8 ms | -11.27% |
| ⚡ | Memory |
list_append_str__monty | 13.4 MB | 2 MB | ×6.6 |
| ⚡ | Walltime |
list_append_str__monty | 68.8 ms | 45.7 ms | +50.47% |
| ⚡ | Memory |
ext_call_rows | 461.7 KB | 317.6 KB | +45.35% |
| ⚡ | Memory |
datetime_ops__monty | 104 KB | 77.9 KB | +33.5% |
| ⚡ | Memory |
csv_read__monty | 973.9 KB | 749.4 KB | +29.97% |
| ⚡ | Memory |
re_extract__monty | 715.4 KB | 559.4 KB | +27.9% |
| ⚡ | Walltime |
str_parse__monty | 35.2 ms | 28.3 ms | +24.46% |
| ⚡ | Memory |
container_repr__monty | 274.3 KB | 221 KB | +24.15% |
| ⚡ | Walltime |
container_repr__monty | 13.8 ms | 11.2 ms | +22.94% |
| ⚡ | Walltime |
re_extract__monty | 9.3 ms | 7.8 ms | +19.08% |
| ⚡ | Walltime |
csv_read__monty | 96.3 ms | 82.1 ms | +17.31% |
| ⚡ | Memory |
csv_write__monty | 1.6 MB | 1.4 MB | +15.61% |
| ⚡ | Walltime |
json_dumps__monty | 28.1 ms | 24.6 ms | +14.3% |
| ⚡ | Walltime |
datetime_ops__monty | 17.5 ms | 15.7 ms | +11.88% |

[!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:codex/inline-strings</code> (5934b27) with <code>main</code> (bbd5023)</sub>

<a href="https://app.codspeed.io/pydantic/monty/branches/jaheba%3Acodex%2Finline-strings?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]: 78 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.

jaheba jaheba commented on code on Oct 07, 2026 20:52 UTC
Code Review
crates/monty/src/identity.rs:1
@@ -42,6 +42,8 @@ pub(crate) enum Identity {
     Float(u64),
     /// Identity of an interned string.
     InternString(usize),
+    /// Content identity of a short string stored inline.
+    InlineString { len: u8, bytes: [u8; 15] },

_Auto response from GPT-6 Codex running fix-pr-comments:_ The content-based identity follows from the requested inline layout, which carries no per-object identity token. I documented the divergence and added tests showing separate bin(4) results share identity while separately created heap strings remain distinct.

jaheba jaheba commented on code on Oct 07, 2026 20:52 UTC
Code Review
crates/monty/src/bytecode/vm/collections.rs:1
@@ -250,7 +250,7 @@ impl VM<'_> {
             for (key, value) in copied_items {
                 // Validate key is a string (InternString or heap-allocated Str)
                 let is_string = match &key {
-                    Value::InternString(_) => true,
+                    Value::InternString(_) | Value::InlineString { .. } => true,

_Auto response from GPT-6 Codex running fix-pr-comments:_ Updated the validation comment to list interned, inline, and heap-allocated strings.

jaheba jaheba commented on code on Oct 07, 2026 20:52 UTC
Code Review
crates/monty/src/types/str.rs:1
@@ -201,8 +217,7 @@ pub fn allocate_char(c: char, heap: &Heap) -> Value {
     if c.is_ascii() {
         Value::InternString(StringId::from_ascii(c as u8))
     } else {
-        let heap_id = heap.allocate(HeapData::Str(Str::new(c.to_string())));
-        Value::Ref(heap_id)
+        allocate_string(c.to_string(), heap)

_Auto response from GPT-6 Codex running fix-pr-comments:_ Updated allocate_char documentation: ASCII characters use pre-interned values, and non-ASCII characters fit inline.

jaheba jaheba commented on code on Oct 07, 2026 20:52 UTC
Code Review
crates/monty/src/value.rs:1
@@ -2246,6 +2416,7 @@ impl Value {
     pub fn as_either_str(&self, heap: &Heap) -> Option<EitherStr> {
         match self {
             Self::InternString(id) => Some(EitherStr::Interned(*id)),
+            Self::InlineString { .. } => Some(EitherStr::Heap(self.inline_str().unwrap().to_owned())),

_Auto response from GPT-6 Codex running fix-pr-comments:_ Added an inline representation to EitherStr; as_either_str now returns the fixed-size inline form instead of allocating a String. Inline values stay inline through attribute and field-name conversion, with a regression test for the representation.

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 07, 2026 20:55 UTC
Code Review
crates/monty/src/value.rs:1
@@ -2403,38 +2582,41 @@ impl From<String> for EitherStr {
 }
 
 impl EitherStr {
-    /// Returns the keyword as a str slice for error messages or comparisons.
+    /// Returns the keyword text for error messages or comparisons.
     pub fn as_str<'a>(&'a self, interns: &'a Interns) -> &'a str {
         match self {
             Self::Interned(id) => interns.get_str(*id),
+            Self::Inline { len, bytes } => str::from_utf8(&bytes[..len.get()]).expect("inline string is valid UTF-8"),
             Self::Heap(s) => s.as_str(),
         }
     }
 
-    /// The text as a `Cow` borrowing only `interns`, so it outlives heap
-    /// borrows — error messages format the name after `drop_with` cleanup.
+    /// The text as a `Cow` that outlives heap borrows, for error messages
+    /// formatted after `drop_with` cleanup.
     pub fn to_cow<'i>(&self, interns: &'i Interns) -> Cow<'i, str> {
         match self {
             Self::Interned(id) => Cow::Borrowed(interns.get_str(*id)),
+            Self::Inline { .. } => Cow::Owned(self.as_str(interns).to_owned()),
             Self::Heap(s) => Cow::Owned(s.clone()),
         }
     }
 
-    /// Re-resolves a heap string to its interned id when the interner already
-    /// knows the text.
+    /// Re-resolves a runtime string to its interned id when the interner knows it.
     ///
     /// Builtin attribute dispatch matches on `StringId`, so a name computed at
-    /// runtime (`getattr(x, 'up' + 'per')`) arrives as [`Heap`](Self::Heap) and
-    /// misses every builtin attribute — while still resolving on instances and
-    /// modules, which compare by text. Interning is a lookup, never an insert,
-    /// so sandboxed code cannot grow the interner by guessing names.
+    /// Runtime attribute names can arrive inline or heap-owned. Interning is a
+    /// lookup, never an insert, so sandboxed code cannot grow the interner.
     #[must_use]

<!-- cubic:v=c75c5ddd-187a-485b-a863-c33e33d3bbcc -->
<!-- cubic:review-run=ab04616e-a8bd-53ba-ad10-5fdb7476c776 -->
<!-- metadata:{"confidence":9} -->
P3: This doc comment now reads "a name computed at Runtime attribute names can arrive inline or heap-owned" — the first line is a dangling fragment from the previous wording. Rewrite the paragraph so it forms coherent sentences (and consider restoring the note about instances/modules resolving by text, which the old text carried).

<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/value.rs, line 2607:

<comment>This doc comment now reads "a name computed at Runtime attribute names can arrive inline or heap-owned" — the first line is a dangling fragment from the previous wording. Rewrite the paragraph so it forms coherent sentences (and consider restoring the note about instances/modules resolving by text, which the old text carried).</comment>

<file context>
@@ -2577,38 +2582,41 @@ impl From<String> for EitherStr {
-    /// misses every builtin attribute — while still resolving on instances and
-    /// modules, which compare by text. Interning is a lookup, never an insert,
-    /// so sandboxed code cannot grow the interner by guessing names.
+    /// Runtime attribute names can arrive inline or heap-owned. Interning is a
+    /// lookup, never an insert, so sandboxed code cannot grow the interner.
     #[must_use]
</file context>

</details>

    /// Builtin attribute dispatch matches on `StringId`, so a name computed
    /// at runtime (e.g. `getattr(x, 'up' + 'per')`) arrives inline or
    /// heap-owned and misses every builtin attribute — while still resolving
    /// on instances and modules, which compare by text. Interning is a
    /// lookup, never an insert, so sandboxed code cannot grow the interner.

✅ Addressed in 3dacd17

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on Oct 07, 2026 20:55 UTC
Reviewer

<!-- cubic:review-summary:start -->
All reported issues were addressed across 10 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_a4ece9796e32ad9a587cc49bc0450e5364c2ba74d454042b0a6e4c1703c76dd0:5a38951724e4f46679e9c1af85b666d55fe133d8:ab04616e-a8bd-53ba-ad10-5fdb7476c776 -->

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 07, 2026 21:02 UTC
Code Review
crates/monty/src/modules/json/string_cache.rs:1
@@ -33,9 +33,9 @@ const CAPACITY: usize = 16_384;
 
 /// Minimum string length eligible for caching.
 ///
-/// Empty strings and single-ASCII-character strings are already interned by
-/// `allocate_string`, so caching them would be redundant.
-const MIN_LEN: usize = 2;
+/// Strings up to 15 UTF-8 bytes are interned or stored inline, so caching them
+/// would be redundant.
+const MIN_LEN: usize = 16;

<!-- cubic:v=d9f4847b-9bd9-4840-9a91-447b73b9d24f -->
<!-- cubic:review-run=fdd6f3a4-d64e-51a6-8de8-6d10d05697e5 -->
<!-- metadata:{"confidence":8} -->
P3: The module-level doc comment still motivates this cache with the exact strings this change removes from it: "especially dict keys like "id", "name", "type" — across multiple json.loads() calls. This cache deduplicates heap allocations for those strings." All of those keys are ≤ 15 bytes and now bypass the cache (they are interned or inlined in allocate_cached_string), so the cache only ever sees 16–64-byte strings. Update the module doc's rationale to describe the cache's actual post-change role: deduplicating repeated strings of 16–64 bytes.

<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/string_cache.rs, line 38:

<comment>The module-level doc comment still motivates this cache with the exact strings this change removes from it: "especially dict keys like `"id"`, `"name"`, `"type"` — across multiple `json.loads()` calls. This cache deduplicates heap allocations for those strings." All of those keys are ≤ 15 bytes and now bypass the cache (they are interned or inlined in `allocate_cached_string`), so the cache only ever sees 16–64-byte strings. Update the module doc's rationale to describe the cache's actual post-change role: deduplicating repeated strings of 16–64 bytes.</comment>

<file context>
@@ -33,9 +33,9 @@ const CAPACITY: usize = 16_384;
-const MIN_LEN: usize = 2;
+/// Strings up to 15 UTF-8 bytes are interned or stored inline, so caching them
+/// would be redundant.
+const MIN_LEN: usize = 16;
 
 /// Maximum string length eligible for caching.
</file context>

</details>

✅ Addressed in a44ee70

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 07, 2026 21:02 UTC
Code Review
crates/monty/src/modules/json/load.rs:1
@@ -173,12 +174,10 @@ fn parse_json_value_from_peek(
     }
 }
 
-/// Allocates a string using the cache when eligible, falling back to direct
-/// allocation for empty/single-char strings (already interned by
-/// `allocate_string`).
+/// Allocates short strings directly and caches longer repeated strings.

<!-- cubic:v=4db71a7e-eb09-4975-a151-4c25dc1adcab -->
<!-- cubic:review-run=fdd6f3a4-d64e-51a6-8de8-6d10d05697e5 -->
<!-- metadata:{"confidence":9} -->
P3: This helper only caches eligible 16–64-byte strings; strings over 64 bytes bypass the cache. Qualify the description so it does not imply that every longer string is cached.

<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/load.rs, line 177:

<comment>This helper only caches eligible 16–64-byte strings; strings over 64 bytes bypass the cache. Qualify the description so it does not imply that every longer string is cached.</comment>

<file context>
@@ -174,12 +174,10 @@ fn parse_json_value_from_peek(
-/// Allocates a string using the cache when eligible, falling back to direct
-/// allocation for empty/single-char strings (already interned by
-/// `allocate_string`).
+/// Allocates short strings directly and caches longer repeated strings.
 fn allocate_cached_string(s: String, cache: &mut JsonStringCache, heap: &HeapReader<'_>) -> Value {
-    if s.len() < 2 {
</file context>

</details>

/// Allocates short strings directly and caches eligible longer strings.

✅ Addressed in a44ee70

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on Oct 07, 2026 21:02 UTC
Reviewer

<!-- cubic:review-summary:start -->
All reported issues were addressed across 2 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_1dc9dfb9561783f1a7d550b685ec3fa6637d1ab7c0b25d734baa7e20f34b880f:31e1b603f4f7e1854cedbe654bb58f95ea53bf2c:fdd6f3a4-d64e-51a6-8de8-6d10d05697e5 -->

jaheba jaheba commented on code on Oct 12, 2026 11:30 UTC
Code Review
crates/monty/src/value.rs:1
@@ -2403,38 +2582,41 @@ impl From<String> for EitherStr {
 }
 
 impl EitherStr {
-    /// Returns the keyword as a str slice for error messages or comparisons.
+    /// Returns the keyword text for error messages or comparisons.
     pub fn as_str<'a>(&'a self, interns: &'a Interns) -> &'a str {
         match self {
             Self::Interned(id) => interns.get_str(*id),
+            Self::Inline { len, bytes } => str::from_utf8(&bytes[..len.get()]).expect("inline string is valid UTF-8"),
             Self::Heap(s) => s.as_str(),
         }
     }
 
-    /// The text as a `Cow` borrowing only `interns`, so it outlives heap
-    /// borrows — error messages format the name after `drop_with` cleanup.
+    /// The text as a `Cow` that outlives heap borrows, for error messages
+    /// formatted after `drop_with` cleanup.
     pub fn to_cow<'i>(&self, interns: &'i Interns) -> Cow<'i, str> {
         match self {
             Self::Interned(id) => Cow::Borrowed(interns.get_str(*id)),
+            Self::Inline { .. } => Cow::Owned(self.as_str(interns).to_owned()),
             Self::Heap(s) => Cow::Owned(s.clone()),
         }
     }
 
-    /// Re-resolves a heap string to its interned id when the interner already
-    /// knows the text.
+    /// Re-resolves a runtime string to its interned id when the interner knows it.
     ///
     /// Builtin attribute dispatch matches on `StringId`, so a name computed at
-    /// runtime (`getattr(x, 'up' + 'per')`) arrives as [`Heap`](Self::Heap) and
-    /// misses every builtin attribute — while still resolving on instances and
-    /// modules, which compare by text. Interning is a lookup, never an insert,
-    /// so sandboxed code cannot grow the interner by guessing names.
+    /// Runtime attribute names can arrive inline or heap-owned. Interning is a
+    /// lookup, never an insert, so sandboxed code cannot grow the interner.
     #[must_use]

_Auto response from GPT-6 / Codex running fix-pr-comments:_ Fixed the dangling sentence and restored the distinction between builtin StringId dispatch and instance/module text lookup. The documentation fix is in the local codex/inline-strings branch; it has not been committed or pushed.

jaheba jaheba commented on code on Oct 12, 2026 11:30 UTC
Code Review
crates/monty/src/modules/json/string_cache.rs:1
@@ -33,9 +33,9 @@ const CAPACITY: usize = 16_384;
 
 /// Minimum string length eligible for caching.
 ///
-/// Empty strings and single-ASCII-character strings are already interned by
-/// `allocate_string`, so caching them would be redundant.
-const MIN_LEN: usize = 2;
+/// Strings up to 15 UTF-8 bytes are interned or stored inline, so caching them
+/// would be redundant.
+const MIN_LEN: usize = 16;

_Auto response from GPT-6 / Codex running fix-pr-comments:_ Updated the module rationale to describe deduplication of 16–64 UTF-8 byte strings and explain that shorter strings are interned or inline. The documentation fix is in the local codex/inline-strings branch; it has not been committed or pushed.

jaheba jaheba commented on code on Oct 12, 2026 11:31 UTC
Code Review
crates/monty/src/modules/json/load.rs:1
@@ -173,12 +174,10 @@ fn parse_json_value_from_peek(
     }
 }
 
-/// Allocates a string using the cache when eligible, falling back to direct
-/// allocation for empty/single-char strings (already interned by
-/// `allocate_string`).
+/// Allocates short strings directly and caches longer repeated strings.

_Auto response from GPT-6 / Codex running fix-pr-comments:_ Qualified the helper documentation with the exact 16–64 UTF-8 byte cache range; other strings are allocated directly. The documentation fix is in the local codex/inline-strings branch; it has not been committed or pushed.

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 13, 2026 12:00 UTC
Code Review
crates/monty-js/__test__/limits.spec.ts:1
@@ -79,7 +79,7 @@ test('an allocation refused at an interpreter checkpoint leaves the session usab
   const maxMemory = 1024 * 1024
   await using session = await pool().checkout({ limits: { maxMemory } })
   const error = await t.throwsAsync(() => session.feedRun('[str(i) for i in range(131_072)]'), isRuntimeError)
-  assertMemoryError(error, isWasm ? 1_068_412 : 1_162_198, maxMemory)
+  assertMemoryError(error, isWasm ? 1_081_440 : 1_091_521, maxMemory)

<!-- cubic:v=47ad28b6-ef2e-4fad-8c65-3841d11e2122 -->
<!-- cubic:review-run=56f46d7c-089c-5daf-81cf-48cf55a5d1b0 -->
<!-- metadata:{"confidence":8} -->
P2: This verifies only the formatted message, so a non-MemoryError exception with the same text would pass; also assert error.exception.typeName is MemoryError.

(Based on your team's feedback about wrapped MemoryError assertions.)

View Feedback

<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-js/__test__/limits.spec.ts, line 82:

<comment>This verifies only the formatted message, so a non-`MemoryError` exception with the same text would pass; also assert `error.exception.typeName` is `MemoryError`.

(Based on your team's feedback about wrapped MemoryError assertions.) </comment>

<file context>
@@ -79,7 +79,7 @@ test('an allocation refused at an interpreter checkpoint leaves the session usab
   await using session = await pool().checkout({ limits: { maxMemory } })
   const error = await t.throwsAsync(() => session.feedRun('[str(i) for i in range(131_072)]'), isRuntimeError)
-  assertMemoryError(error, isWasm ? 1_068_412 : 1_091_521, maxMemory)
+  assertMemoryError(error, isWasm ? 1_081_440 : 1_091_521, maxMemory)
   t.is(await session.feedRun('1 + 1'), 2)
 })
</file context>

</details>

  assertMemoryError(error, isWasm ? 1_081_440 : 1_091_521, maxMemory)
  t.is(error.exception.typeName, 'MemoryError')

<a href="https://www.cubic.dev/action/fix/violation/47ad28b6-ef2e-4fad-8c65-3841d11e2122" 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-dev-ai[bot] cubic-dev-ai[bot] commented on Oct 13, 2026 12:00 UTC
Reviewer

<!-- cubic:review-summary:start -->
All reported issues were addressed across 1 file (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_40f7f8cc8837f86bc8027a18ed90a98b58ebcb112638767f15077b9e500058db:9dee2e7823ed1fc5a054d78584b1166afa830b73:56f46d7c-089c-5daf-81cf-48cf55a5d1b0 -->

jaheba jaheba commented on code on Oct 13, 2026 12:50 UTC
Code Review
crates/monty-js/__test__/limits.spec.ts:1
@@ -79,7 +79,7 @@ test('an allocation refused at an interpreter checkpoint leaves the session usab
   const maxMemory = 1024 * 1024
   await using session = await pool().checkout({ limits: { maxMemory } })
   const error = await t.throwsAsync(() => session.feedRun('[str(i) for i in range(131_072)]'), isRuntimeError)
-  assertMemoryError(error, isWasm ? 1_068_412 : 1_162_198, maxMemory)
+  assertMemoryError(error, isWasm ? 1_081_440 : 1_091_521, maxMemory)

_Auto response from GPT-6 / Codex running fix-pr-comments:_ This is already covered by the current assertion. The test first requires a MontyRuntimeError. MontyError's constructor formats its message as ${typeName}: ${message}, using the same typeName exposed by error.exception; assertMemoryError then matches an anchored /^MemoryError: memory limit exceeded: ...$/ expression. A non-MemoryError with the same inner text therefore fails (verified with MemoryError and ValueError instances). No code change is needed.

codecov[bot] codecov[bot] commented on Oct 13, 2026 12:58 UTC
Bot

Codecov Report


:x: Patch coverage is 98.88535% with 7 lines in your changes missing coverage. Please review.
| Files with missing lines | Patch % | Lines |
|---|---|---|
| crates/monty/src/value.rs | 96.80% | 0 Missing and 4 partials :warning: |
| crates/monty/src/modules/json/string\_cache.rs | 95.45% | 0 Missing and 1 partial :warning: |
| crates/monty/src/types/instance.rs | 96.87% | 1 Missing :warning: |
| crates/monty/src/types/str.rs | 99.11% | 1 Missing :warning: |

:loudspeaker: Thoughts on this report? Let us know!

davidhewitt davidhewitt commented on Oct 15, 2026 14:40 UTC
Contributor

This is definitely tempting. What do you think of #1050 to help with the possible duplication risk?

davidhewitt davidhewitt commented on Oct 21, 2026 10:31 UTC
Contributor

Following discussion - I think we can merge this as-is regardless of whether we switch heap ids to u32 or not. (It will be backwards-compatible to make the inline variant wider.) Please fix CI and let's merge 👍

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on Oct 21, 2026 12:05 UTC
Reviewer

<!-- cubic:review-summary:start -->
All reported issues were addressed across 13 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_67f0b0e54ed64d19bbaa5833fb2ac26c70995ca509895e5fa8ee0a260952508d:6c426bfa66af1259513ead9ea28a2ba8e67ced54:885f4112-fff2-5cad-9222-8131a4bb8208 -->

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 21, 2026 12:05 UTC
Code Review
crates/monty/src/builtins/eval_exec.rs:1
@@ -201,11 +201,13 @@ fn compile_and_push(
 
 /// The snippet's text: a `str`, or `bytes` decoded as UTF-8.
 fn snippet_source(name: &str, source: &Value, vm: &mut VM<'_>) -> RunResult<Arc<str>> {
+    if let Ok(text) = source.to_str(vm) {
+        return Ok(Arc::from(text));
+    }

<!-- cubic:v=3ea98477-0d75-432e-9091-49e9dc27c1a1 -->
<!-- cubic:review-run=885f4112-fff2-5cad-9222-8131a4bb8208 -->
<!-- metadata:{"confidence":9} -->
P2: The new branch constructs and discards a formatted TypeError for every bytes source before reaching the byte-specific match. Guard the accessor with source.is_str(vm.heap) (which includes inline strings), or dispatch byte values first, so valid byte sources avoid this allocation on every eval/exec call.

<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/eval_exec.rs, line 204:

<comment>The new branch constructs and discards a formatted `TypeError` for every `bytes` source before reaching the byte-specific match. Guard the accessor with `source.is_str(vm.heap)` (which includes inline strings), or dispatch byte values first, so valid byte sources avoid this allocation on every `eval`/`exec` call.</comment>

<file context>
@@ -201,8 +201,8 @@ fn compile_and_push(
 fn snippet_source(name: &str, source: &Value, vm: &mut VM<'_>) -> RunResult<Arc<str>> {
-    if source.is_str(vm.heap) {
-        return Ok(Arc::from(source.to_str(vm).expect("is_str checked above")));
+    if let Ok(text) = source.to_str(vm) {
+        return Ok(Arc::from(text));
     }
</file context>

</details>

    if source.is_str(vm.heap) {
        return Ok(Arc::from(source.to_str(vm).expect("is_str checked above")));
    }

✅ Addressed in 017fc7f

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on code on Oct 21, 2026 12:29 UTC
Code Review
crates/monty/src/types/str.rs:1
@@ -667,23 +725,12 @@ fn str_join<'h>(separator: &impl HeapView<'h, str>, iterable: Value, vm: &mut VM
             result.push_str(separator.get(vm.heap));
         }
 
-        // Check item is a string and extract its content
-        match item {
-            Value::InternString(id) => {
-                result.push_str(vm.interns.get_str(*id));
-            }
-            Value::Ref(heap_id) => {
-                if let HeapData::Str(s) = vm.heap.get(*heap_id) {
-                    result.push_str(s.as_str());
-                } else {
-                    let t = item.py_type_name(vm);
-                    return Err(ExcType::type_error_join_item(index, &t));
-                }
-            }
-            _ => {
-                let t = item.py_type_name(vm);
-                return Err(ExcType::type_error_join_item(index, &t));
-            }
+        // `to_str` borrows all string representations without copying.
+        if let Some(text) = item.as_str(vm) {

<!-- cubic:v=bc319ca6-d8e8-4baf-aa2f-db2278f3b184 -->
<!-- cubic:review-run=a3d67a5a-422e-5ab4-9a85-b8bfdd6c3b83 -->
<!-- metadata:{"confidence":10} -->
P3: Update this comment to reference as_str; to_str was removed, so the current wording misdirects maintainers searching for the accessor.

<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/str.rs, line 729:

<comment>Update this comment to reference `as_str`; `to_str` was removed, so the current wording misdirects maintainers searching for the accessor.</comment>

<file context>
@@ -726,8 +726,8 @@ fn str_join<'h>(separator: &impl HeapView<'h, str>, iterable: Value, vm: &mut VM
         // `to_str` borrows all string representations without copying.
-        if item.is_str(vm.heap) {
-            result.push_str(item.to_str(vm).expect("is_str checked above"));
+        if let Some(text) = item.as_str(vm) {
+            result.push_str(text);
         } else {
</file context>

</details>

✅ Addressed in c47f3c3

cubic-dev-ai[bot] cubic-dev-ai[bot] commented on Oct 21, 2026 12:29 UTC
Reviewer

<!-- cubic:review-summary:start -->
All reported issues were addressed across 39 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_800095360d01b1a4ceda76ce6a7655ec08c81769c0199244c3fe7d8dc56ddbc2:017fc7fc4dd25dee39b4bf2924cd5260b9648726:a3d67a5a-422e-5ab4-9a85-b8bfdd6c3b83 -->

jaheba jaheba commented on code on Oct 21, 2026 12:33 UTC
Code Review
crates/monty/src/types/str.rs:1
@@ -667,23 +725,12 @@ fn str_join<'h>(separator: &impl HeapView<'h, str>, iterable: Value, vm: &mut VM
             result.push_str(separator.get(vm.heap));
         }
 
-        // Check item is a string and extract its content
-        match item {
-            Value::InternString(id) => {
-                result.push_str(vm.interns.get_str(*id));
-            }
-            Value::Ref(heap_id) => {
-                if let HeapData::Str(s) = vm.heap.get(*heap_id) {
-                    result.push_str(s.as_str());
-                } else {
-                    let t = item.py_type_name(vm);
-                    return Err(ExcType::type_error_join_item(index, &t));
-                }
-            }
-            _ => {
-                let t = item.py_type_name(vm);
-                return Err(ExcType::type_error_join_item(index, &t));
-            }
+        // `to_str` borrows all string representations without copying.
+        if let Some(text) = item.as_str(vm) {

_Auto response from GPT-6 Codex running fix-pr-comments:_ The comment now names as_str and clarifies that it borrows interned, inline, and heap-backed strings without copying. This edit is in the local worktree; it is not yet committed or pushed, so I’m leaving the thread open until the fix reaches the PR branch.

davidhewitt davidhewitt commented on Oct 21, 2026 13:49 UTC
Contributor

I wonder whether this would remove the need to reserve the empty string and single-character strings (because representing them as inline values might be as cheap, and possibly lead to less branching)?

davidhewitt davidhewitt commented on Oct 21, 2026 13:50 UTC
Contributor

I wonder also whether this would be strictly better for any "static strings" with size <= 7 ??

jaheba jaheba commented on Oct 21, 2026 16:28 UTC
Author

I wonder also whether this would be strictly better for any "static strings" with size <= 7 ??

Should we do this in a separate PR? This PR is probably already doing too much.

I'm also looking into removing Type::Instance from Builtins, which should allow us to have 15 bytes inline without touching HeapId.

rewitt94 rewitt94 commented on code on Oct 28, 2026 16:58 UTC
Code Review
crates/monty/src/types/bytes.rs:1
@@ -2547,3 +2537,37 @@ pub(crate) fn bytes_contains(container: &[u8], item: &Value, vm: &VM<'_>) -> Run
         None => Err(ExcType::value_error("byte must be in range(0, 256)")),
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use monty_types::{PrintWriter, ResourceTracker};
+
+    use super::*;
+    #[cfg(feature = "ref-count-return")]
+    use crate::heap::ContainsHeap as _;
+    use crate::{
+        exception_private::RunError,
+        heap::HeapReader,
+        run::{Program, SessionTables},
+    };
+
+    #[test]
+    fn fromhex_rejects_bytes_without_retaining_the_argument() {

Should this be a Python fixture ref-count test instead? In general, the repo convention is to use fixture tests.

rewitt94 rewitt94 commented on code on Oct 28, 2026 16:59 UTC
Code Review
crates/monty/src/types/module.rs:1
@@ -165,3 +165,50 @@ impl HeapItem for Module {
         self.attrs.py_dec_ref_ids(stack);
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use monty_types::{PrintWriter, ResourceTracker};
+
+    use super::*;
+    #[cfg(feature = "ref-count-return")]
+    use crate::heap::ContainsHeap as _;
+    use crate::{
+        exception_private::RunError,
+        heap::{Heap, HeapReader},
+        run::{Program, SessionTables},
+        types::str::{allocate_string, allocate_string_on_heap},
+    };
+
+    #[test]
+    fn unknown_runtime_methods_release_their_arguments() {

Should this be a Python fixture instead, e.g. math.missing_method(...) with a short and a >15-byte name?

rewitt94 rewitt94 commented on code on Oct 28, 2026 16:59 UTC
Code Review
crates/monty/src/types/generic_alias.rs:1
@@ -310,4 +316,31 @@ mod tests {
             assert_eq!(minicbor_serde::to_vec(&alias).unwrap(), bytes);
         }
     }
+
+    #[test]
+    fn unknown_runtime_methods_release_their_arguments() {

Should this be a Python fixture instead, e.g. list[int].missing_method(...)?

rewitt94 rewitt94 commented on code on Oct 28, 2026 16:59 UTC
Code Review
crates/monty/src/args/mod.rs:1
@@ -759,3 +761,34 @@ impl ArgExprs {
         Ok(())
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use monty_types::ResourceTracker;
+
+    use super::*;
+    use crate::types::str::allocate_string;
+
+    #[test]
+    fn first_keyword_preserves_runtime_string_names() {

Should this be an inline__argument_errors.py case instead, e.g. f(**{'short': 1}) asserting the exact error message?

rewitt94 rewitt94 commented on code on Oct 28, 2026 16:59 UTC
Code Review
crates/monty/src/bytecode/vm/format.rs:1
@@ -284,5 +290,40 @@ impl VM<'_> {
 /// the mini-language formatter.
 fn str_value_into_string(value: Value, vm: &mut VM<'_>) -> Result<String, RunError> {
     defer_drop!(value, vm);
-    Ok(value.to_str(vm)?.to_owned())
+    Ok(value.try_to_str(vm)?.to_owned())
+}
+
+#[cfg(test)]
+mod tests {
+    use monty_types::{PrintWriter, ResourceTracker};
+
+    use super::*;
+    use crate::{
+        exception_private::ExcType,
+        heap::{Heap, HeapData, HeapReader},
+        run::{Program, SessionTables},
+        types::{Bytes, str::allocate_string_on_heap},
+    };
+
+    #[test]
+    fn string_conversion_releases_owned_values_on_success_and_error() {

Should this be a Python fixture instead, using f-string / format() cases with str and non-str results?

rewitt94 rewitt94 commented on code on Oct 28, 2026 16:59 UTC
Code Review
crates/monty/src/types/csv/dict.rs:1
@@ -665,3 +665,51 @@ fn reader_line_num(reader: &Value, vm: &VM<'_>) -> u64 {
         _ => 0,
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use monty_types::{CompileOptions, PrintWriter, ResourceLimits, ResourceTracker};
+
+    use super::*;
+    use crate::{
+        bytecode::FrameExit,
+        heap::{Heap, HeapReader},
+        run::Executor,
+    };
+
+    #[test]
+    fn extra_key_error_message_respects_the_allocation_budget() {

Should we test this here: large_allocations_are_rejected_before_the_hard_limit (crates/monty-runtime/tests/subprocess.rs)?

rewitt94 rewitt94 commented on code on Oct 28, 2026 16:59 UTC
Code Review
crates/monty/src/value.rs:1
@@ -108,6 +110,89 @@ pub(crate) enum Value {
     Dereferenced,
 }
 
+/// Byte length for an inline UTF-8 string.
+#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
+#[repr(u8)]
+pub(crate) enum InlineLen {

I see @davidhewitt asked whether we could make empty and single-character strings inline too. What was the analysis on that?

I don't think we need to include it in this PR, though; it's already big enough in scope.

rewitt94 rewitt94 commented on code on Oct 28, 2026 17:07 UTC
Code Review
crates/monty/src/types/str.rs:1
@@ -249,6 +283,14 @@ impl<'h> PyTrait<'h> for PyStr<'h> {
                 let text = vm.heap.protect(vm.interns.get_str(*id));
                 call_str_method_impl(&*text, method, args, vm).map(CallResult::Value)
             }
+            Self::Inline { .. } => {
+                let Some(method) = attr.static_string(vm.interns) else {
+                    args.drop_with(vm);
+                    return Err(ExcType::attribute_error(Type::Str, attr.as_str(vm.interns)));
+                };
+                let text = OwnedStrView(self.as_str(vm).to_owned());

Since PyStr::Inline is Copy, could OwnedStrView hold { len, bytes: [u8; 15] } on the stack instead of a String, avoiding an allocation on every index and method call on a short string (possibly the attr_dispatch_minimal regression)?

rewitt94 rewitt94 commented on code on Oct 28, 2026 17:07 UTC
Code Review
crates/monty/src/types/dict.rs:1
@@ -398,6 +398,7 @@ impl Dict {
 fn json_key_string_slice<'a>(key: &'a Value, heap: &'a Heap, interns: &'a Interns) -> Option<&'a str> {
     match key {
         Value::InternString(id) => Some(interns.get_str(*id)),
+        Value::InlineString { .. } => key.inline_str(),

Could we use as_str_heap(heap, interns) instead of a match over every string form? The function is nearly identical.

rewitt94 rewitt94 commented on code on Oct 28, 2026 17:07 UTC
Code Review
crates/monty/src/types/file.rs:1
@@ -1112,15 +1113,24 @@ fn install_buffer<'h>(file: &HeapReadMut<'h, OpenFile>, result: Value, vm: &mut
             } else {
                 text.to_owned()
             };
-            Some(allocate_string_no_interning(text, vm.heap))
+            Some(allocate_string_on_heap(text, vm.heap))
+        }
+        Value::InlineString { .. } => {

Could this arm merge with the InternString one via as_str?

rewitt94 rewitt94 commented on code on Oct 28, 2026 17:25 UTC
Code Review
crates/monty/src/value.rs:1
@@ -68,6 +67,9 @@ pub(crate) enum Value {
     /// To get the actual string content, use `interns.get(string_id)`.
     #[serde(rename = "T")]
     InternString(StringId),
+    /// A short UTF-8 string stored directly in the value slot.
+    #[serde(rename = "S")]
+    InlineString { len: InlineLen, bytes: [u8; 15] },

Should this serialize as a text string of bytes[..len] ({"S": "x-y"}) and rebuild len on load, since today each inline string dumps as {"len": "3", "bytes": [15 ints]}? See CLAUDE.md's single-letter-field and serde_bytes rules.

rewitt94 rewitt94 approved these changes on Oct 28, 2026 18:08 UTC
Approved Reviewer

Some nits to take a look at please - but otherwise this looks good thanks!

Reviewers
Assignees
jaheba jaheba
Labels
risk: low confidence: 93.6% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 71.5% (HIGH) · Higher = larger blast radius
71.5%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 93.6% · Lower = rushed or shallow review
93.6%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 4.6% · Safe to merge
4.6%
Repository