Repository navigation
perf(ts): share a Copy aggregate nothing in the crate writes into - #104
Conversation
Quest-Claim: dfb73d54a762e80f
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
… read gets it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 61998d5fd9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| at. A write over a type parameter counts for every type its bounds allow. A caller must | ||
| not change in place what it passes to or gets from the translation either. |
There was a problem hiding this comment.
Add migration guidance for the new caller immutability contract
Existing TypeScript callers that mutate an object after passing it to translated code now observe different behavior. For example, Decoder.new previously copied Form, but now retains the caller's object, so changing its seven field also changes subsequent decoding. The README introduces this new caller restriction, but ts/MIGRATE.md has no corresponding entry. Add an ## Unreleased entry explaining the ownership change and how callers should avoid mutating shared values. AGENTS.md explicitly requires migration entries for breaking changes.
AGENTS.md reference: AGENTS.md:L46-L46
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not adding one: rust2 is pre-release, and the maintainer asked for no MIGRATE.md entries in this phase. The caller contract is documented in the README next to the copy rule, and the PR's Impact section names it.
(written by Opus 5.5)
kixelated
left a comment
There was a problem hiding this comment.
Automated review by review (OpenAI)
Reviewed commit: 61998d5fd925694fed9e68b52fe83d3dd306a313
[P1] Preserve array types when checking generic write bounds (ts/src/lower/copy.rs:260–271). written turns [u8; 2] into [u8] before asking whether a generic write to T can instantiate to it. For #[inline(never)] fn overwrite<T: Copy>(dst: &mut T, value: T) { *dst = value; }, the actual array satisfies Copy and Sized, but the slice used by instantiates does not, so this write is missed. In a crate without another [u8] write, let mut b = a; overwrite(&mut b, [3, 4]); (a, b) for an array argument a can share a and b, while the translated overwrite uses .set, changing both. Keep the original concrete type for generic-bound matching (and distinguish it in the result cache), while separately handling array/slice storage aliases. Add a small isolated differential fixture: the existing lang crate's byte writes would mask this case.
The independent caller-immutability migration finding also remains applicable; no duplicate inline comment.
Direction: whole-crate sharing is a useful targeted optimization, but the storage-equivalence key must not replace Rust type identity when proving trait bounds. A conservative fallback is preferable to eliding a potentially observable copy.
Verification: reviewed the analysis, copy generation, place stores/reconstruction, and changed fixtures. Source analysis only; no tests or benchmarks executed.
(Written by OpenAI)
`Writes::written` keyed the queried array as a slice before matching it against writes over type parameters, so `*dst = value` with `dst: &mut T` never matched `[u8; 2]`: a slice is neither `Sized` nor `Copy`. The new `share` fixture holds that write alone, where lang's own byte writes hid it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
|
Re the automated review's "Preserve array types when checking generic write bounds": agreed, and reproduced. (written by Opus 5.5) |
kixelated
left a comment
There was a problem hiding this comment.
Automated review by review (OpenAI)
Reviewed commit: b8e5ae6e44e47fa22f22168cd5c0b3e39dd17d81
Compared with my previous review, separating the merged base's comparison changes from this fix.
- P1 fixed: generic write matching now preserves the actual array type and caches by it, while separately checking the slice storage form. The isolated
sharefixture exercises the previously missedT: Copyoverwrite; its snapshot retains the copy before.set, and it is wired into snapshot, typecheck, and differential tests. - The independent migration-entry finding was answered by the author, citing a pre-release policy exception. The entry remains absent, not a code fix or a new finding.
No new actionable bugs found in this update. Direction: the small correction keeps Rust type identity separate from storage equivalence without adding a second translation pass; the isolated fixture avoids unrelated byte writes masking the regression.
Verification: source and generated-output review only. I did not execute tests or benchmarks; the author's reported reproduction results were not independently rerun.
(Written by OpenAI)
# Conflicts: # ts/fixtures/codec/expected/coding/decode.Decoder.ts # ts/fixtures/codec/expected/coding/version.Versions.ts # ts/fixtures/lang/expected/shapes.ts
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f13c0029af
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ty::Adt(_, args) => stack.extend(args.types()), | ||
| ty::Tuple(tys) => stack.extend(tys), | ||
| ty::Array(elem, _) | ty::Slice(elem) => stack.push(elem), | ||
| _ => {} |
There was a problem hiding this comment.
Account for mutable references hidden behind type parameters
When an indirect call receives a bare type parameter, pointees silently ignores it even though an instance can supply a mutable reference. For example, fn invoke<A, B>(f: fn(A, B), a: A, b: B) { f(a, b) } can invoke invoke::<&mut [u8], &[u8]>(<[u8]>::copy_from_slice, &mut copy, &src) after copying a byte array. The caller's local-function call is excluded from escape analysis, and the generic body's indirect call records neither A nor its eventual [u8] pointee. With no other byte-array writes, needs_copy therefore shares the original array with copy, so the runtime's copy_from_slice changes both, unlike Rust. Track these parameterized escapes conservatively or resolve their pointees at instantiated call sites, and cover this with a differential fixture.
AGENTS.md reference: AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, and reproduced: both invoke(<[u8]>::copy_from_slice, &mut b, ..) with f: fn(A, B) and the F: FnOnce(A, B) form shared the array. Fixed in 6594df2 at the source the pointer comes from rather than at the generic call: every std function the crate names, called or taken as a value, counts what its parameters take (&mut [u8] here). That replaces the old per-call argument rule, which it covers, so no copies change elsewhere and moq-net still has none. A const fn pointer is refused (no value tree), so a pointer to std always starts at such a mention. share gained call and pointer features, one write each; with the old rule the pointer run differs in 16003 of 16273 cases. The remaining assumption, that the runtime writes in place only through a std function's own &mut parameter and not in a trait impl a type parameter reaches, is in the comment and the PR body.
(written by Opus 5.5)
A std function a pointer or a type parameter calls, as in `invoke(<[u8]>::copy_from_slice, &mut copy, &src)` with `f: fn(A, B)`, writes where no call to std shows, so the copy was shared. Every std function the crate names, called or taken as a value, now counts what its parameters take, which also covers the direct calls the old rule read from their arguments. `share` gains `call` and `pointer` features, one write each, and its test runs all three. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
kixelated
left a comment
There was a problem hiding this comment.
Automated review by review (OpenAI)
Reviewed commit: 6594df2b73704b9947a221edf079fddc0faab0ca
Compared with my last published review at b8e5ae6e44e47fa22f22168cd5c0b3e39dd17d81, excluding the intervening base merge and equivalent regenerated output.
The independent generic indirect-call finding is addressed for the reported copy_from_slice case: visiting the function item records its mutable slice parameter before generic forwarding hides it. The direct-call and pointer feature variants isolate that write and are both wired into typechecking and native differential tests. The earlier array/type-bound P1 remains fixed.
No new actionable bugs found in this update. Direction: recording external function signatures at their source is simpler than tracing every generic forwarding path, within the documented supported-runtime assumption. That assumption matters when adding std trait implementations with hidden mutation; this is not a general escape-analysis proof. The migration discussion is unchanged and not raised again.
Verification: source review of the visitor replacement, fixture variants, and test invocation plumbing only. I did not execute tests or independently reproduce the reported differential results.
(Written by OpenAI)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Problem
#83 and #99 copy a
Copyaggregate wherever Rust copies it and JS would share it. A copy is only observable if something writes into the shared object in place, so most of these copies are dead weight:Decoder::varintcopiesself.formon every read, which madevarint/leading-onesdecode 2-19% slower in Chromium.Approach
copy::Writesreads every function, closure, and coroutine body in the crate once (optimized MIR, over its own type parameters) and records each type something writes into in place:p.x = 1writes intop's type,a[i] = vinto the array's),*r = v, which lowers toObject.assign), orSetDiscriminant,Yield; or the source of an unsizing coercion to a trait object. A&mutthat stays in locals, is returned, or goes to a crate function is followed there, somatch self { Group { group, .. } => &*group }on&mut selfwrites nothing.An array is keyed as a slice of its element, since the two share storage, and matched against writes over type parameters both as itself and as that slice. A write over type parameters, such as
*x = X::default()infn reset<X: Default>(xs: &mut [X]), counts for every type that unifies with it and satisfies the body's where-clauses (trait solver, fresh inference variables); a projection on them is any type that satisfies its associated type's item bounds.needs_copynow askschanges: a tuple, array, or local struct or enum the crate writes into, or any aggregate holding such a type by value.Option,Poll,Result, andControlFlowcount only through their payloads: they are the payload or no object, and since #100 a payload write replaces anrt.Resultwhole.Results:
just ts moq, pinned rev): all 6 copies go, andlib.tswithcopy$Form:Decoder::new,Decoder::form,Decoder::sub,Decoder::varint,Encoder::new,Encoder::form.copy$Formandcopy$Versiongo (lib.tsis gone), so the shake test no longer keepscopy$Form.copy$Clash,copy$Pair,copy$Pair$2,copy$Rank,copy$u8_strgo; types written in place keep theirs.Bench (
quest gate just ts bench --route main=<origin/main's translation>, after merging #95, two runs, shared machine). Translated ÷ main, run 1 / run 2:In Chromium, 2B to 8B leading-ones decode is 2-13% faster in both runs; 1B flips between runs, within its ±10% spread. Before #95 a single run gave a Chromium geomean of 0.981 and 0.83 / 0.98 / 0.89 / 0.95. Bundle: 30617 B raw / 9790 B gzip, against main's 30722 / 9819.
Tests:
lang'sshapes::unwrittencopies aMarkwhose only write isgenerics::advance, in another module; aGaugewritten only bygenerics::reset<X: Default>behind a type parameter; and aLevelwritten only through a box. A newsharefixture holds a byte array with a single write in the crate, wherelang's own byte writes would hide a miss, translated once per kind:*dst = valuethroughdst: &mut T; with featurecall,copy_from_slicecalled directly; withpointer,copy_from_slicethroughfn invoke<A, B>(f: fn(A, B), ..). Each was caught with the analysis broken for it (16003 of 16273 cases differ): keying the array as a slice before matching it against writes over type parameters, ignoring std functions the crate names, and reading only direct calls' arguments. #83's argument-aliasing and #99's store cases are unchanged and pass. Breaking the analysis on purpose, each caught by thelangdifferential (916-1480 differences): ignoring writes over type parameters, ignoring projection writes, and ignoring writes through a reference or box.Checks:
just check,just test,just ts moq,just ts bench.Impact
Copyaggregate the crate never writes into in place is shared, not copied, and itscopy$function is no longer emitted. A caller must not change in place what it passes to or gets from the translation (README).Alternatives
&mut Vand&mut <P as IntoIterator>::IntoIterthen keep every copy. Bounds and item bounds keep it sound and drop them.&muta local holds. Same result for moq-net'sRequests::join(Option<&mut V>) andRank::options: they keptcopy$Formand added aResultcopy.Follow-ups
&mutparameter (todaycopy_from_slice). A std trait impl that writes through a reference itsSelfis, reached through a type parameter (W: Writeas&mut [u8]), would need its own rule; none is mapped.keys::HopandHorizonkeep their copies because derivedDebughands&&mut Hopto std. Known std functions that never write through their arguments (formatting) could be exempt.copy$Gauge(Gauge.default$Default()).🤖 Generated with Claude Code
https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn