Add `Value::InlineString` variant #994
<!-- 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: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: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: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: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: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_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.
_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.
_Auto response from GPT-6 Codex running fix-pr-comments:_ Updated the validation comment to list interned, inline, and heap-allocated strings.
_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.
_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: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: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: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: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: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 -->
_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.
_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.
_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: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.)
<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: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 -->
_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 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!
This is definitely tempting. What do you think of #1050 to help with the possible duplication risk?
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: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: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: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: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 -->
_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.
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)?
I wonder also whether this would be strictly better for any "static strings" with size <= 7 ??
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.
Should this be a Python fixture ref-count test instead? In general, the repo convention is to use fixture tests.
Should this be a Python fixture instead, e.g. math.missing_method(...) with a short and a >15-byte name?
Should this be a Python fixture instead, e.g. list[int].missing_method(...)?
Should this be an inline__argument_errors.py case instead, e.g. f(**{'short': 1}) asserting the exact error message?
Should this be a Python fixture instead, using f-string / format() cases with str and non-str results?
Should we test this here: large_allocations_are_rejected_before_the_hard_limit (crates/monty-runtime/tests/subprocess.rs)?
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.
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)?
Could we use as_str_heap(heap, interns) instead of a match over every string form? The function is nearly identical.
Could this arm merge with the InternString one via as_str?
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.
Some nits to take a look at please - but otherwise this looks good thanks!
rewitt94
jaheba
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
mainbecause 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 inInlineLenkeepsValueat 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
isandid(), as documented indocs/limitations/builtins.mdand 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-checksandref-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.