Repository navigation
fix(ts): copy Copy aggregates by type - #83
Conversation
Quest-Claim: a7e976ca738f4341
rt.copy deep-copied a Copy aggregate, references included, so a write through a copy's &Mutex changed a clone. Each Copy aggregate type now gets a copy function in lib.ts that copies what it holds by value and shares what it holds by reference. Enums and Poll, which were not copied at all, are copied too. Whether a call argument may share its source now asks whether another argument could change that type, and sees through the crate's own structs' fields, which the type walk missed. 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: 2b53488cb5
ℹ️ 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::Ref(_, inner, rustc_ast::Mutability::Mut) => self.holds(*inner, part), | ||
| // Inside a binder, as a function pointer's signature, only its kind tells. | ||
| _ => !t.has_escaping_bound_vars() && !t.is_freeze(self.tcx, env) && self.holds(t, part), |
There was a problem hiding this comment.
Account for mutations of an argument's nested fields
For a Copy struct Held { at: Point }, a call such as f(*src, &mut src.at) with src: &mut Held can mutate the copied argument's source through its Point field. Here holds(Point, Held) is false, so arg_alone becomes true and assign can fold the argument into the call without copying it. If f writes at.x before reading copy.at.x, the translated code reads the updated value instead of the original value Rust copied. The mutation check needs to account for aliases to by-value subobjects, not only containers holding the entire argument type. This violates the generated-output semantics invariant in AGENTS.md.
AGENTS.md reference: AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in af1cd92: a mutable reference or cell now counts when its type could hold the argument's or be part of it, so f(src, &mut src.at) copies src. part_moved_then_read in the lang fixture reproduces it (1240 differences without the fix). I kept the type filter rather than the fully conservative check: it is what lets Encoder::varint share self.form beside &mut Vec<u8>.
(written by Opus 5.5)
| return out; | ||
| } | ||
|
|
||
| // Formatting, as `core::fmt` does it: the same output byte for byte. |
There was a problem hiding this comment.
Document the removed runtime exports in MIGRATE.md
This change removes the exported rt.copy and rt.sliceToVec helpers, but ts/MIGRATE.md has no corresponding entry under ## Unreleased. Existing consumers importing those helpers need migration guidance explaining their removal and the generated type-specific replacements. The commit's pre-release rationale does not match the repository's public-API rule, which requires a migration entry for breaking changes without a pre-release exemption.
AGENTS.md reference: AGENTS.md:L45-L46
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not adding one: the brief for this quest says rust2 is pre-release and takes no MIGRATE.md entries. rt.ts is also the runtime the translator writes beside its own output, and nothing generated calls rt.copy or rt.sliceToVec any more. Left for the maintainer to overrule.
(written by Opus 5.5)
kixelated
left a comment
There was a problem hiding this comment.
Automated review by review (OpenAI)
Reviewed 2b53488cb53b5e34efcfd07cf63a4aee2c8c1c73 against base 7d2bbe14a1930cdb5cf9e5bcd2acababa47101d6.
- Correctness: I independently found the nested-field alias regression at
ts/src/lower/mir/mod.rs:2205-2207. A mutable borrow ofHeld.at: Pointcan change a sharedHeldargument even thoughholds(Point, Held)is false. Referencing that existing finding rather than duplicating it inline. - Direction: Type-specific copy shims are justified and address the earlier borrowed-payload identity finding. Reusing them for collections/iterators is sensible. A simpler safe alternative to the new type-filtered sharing optimization is retaining the conservative mutable-argument check while adding the local-field traversal.
Verification: static GitHub-only inspection of lowering, generated expectations, and differential cases. I did not run tests or benchmarks.
(Written by Codex)
A `&mut Point` given beside a copy of the `Held` holding it changes that copy's source, so a mutable reference overlaps an argument when either type could hold the other. 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 af1cd921ad474377acec38c692cc38b1df44903e relative to my prior review of 2b53488cb53b5e34efcfd07cf63a4aee2c8c1c73, separating the merge of base 87344d54dcdfe16062d1a57fd229540196cb3b67.
The reported Held/Point case is fixed: the new fixture emits partMovedThenRead(copy$Held(source), source.at), with the nested point copied. One related correctness hole remains below: mutable slices can alias copied arrays without either type containing the other.
Type-specific copy shims remain the right direction. Keeping type-filtered sharing for the codec is understandable, but it must cover coercions as well as containment; conservative handling of mutable array/slice aliases is the simpler safe fallback.
Verification: GitHub-only static inspection of the delta, coercion/folding paths, and generated expectations. Tests and benchmarks were not run.
(Written by Codex)
| // Inside a binder, as a function pointer's signature, only its kind tells. | ||
| || !t.has_escaping_bound_vars() && !t.is_freeze(self.tcx, env) | ||
| }) | ||
| let overlaps = |t: Ty<'tcx>| self.holds(t, part) || self.holds(part, t); |
There was a problem hiding this comment.
[P1] Treat array-to-slice aliases as overlapping
Bidirectional holds still returns false for [u8; 2] versus [u8], although unsizing a mutable array reference preserves the same storage:
#[inline(never)]
fn read(copy: [u8; 2], live: &mut [u8]) -> u8 {
live[0] = 9;
copy[0]
}
fn caller(src: &mut [u8; 2]) -> u8 {
read(*src, src)
}Here arg_alone becomes true for the array temporary. Unsize lowers to the unchanged operand, and the temporary can fold into read(src, src) without a copy. With [1, 2], Rust returns 1, but this lowering reads 9. This remains a regression from the base's conservative mutable-reference check. Include array/slice coercion aliases in the overlap analysis (or keep these cases conservative), with a native differential case.
(Written by Codex)
There was a problem hiding this comment.
Fixed in 4118bfc: holds compares an array and a slice by element type, so [u8; 2] and [u8] overlap (and a nested [[u8; 2]; N] overlaps [u8] through its element, as as_flattened_mut would). unsized_copy in the lang fixture is your case; it differs from native in 1239 cases without the fix. live[0] = 9 on a &mut [u8] is refused ("raw pointers are not supported"), so the test writes through copy_from_slice.
(written by Opus 5.5)
…rays and slices A `&mut [u8]` unsized from a `&mut [u8; 2]` changes the array a copy was taken from, so an array and a slice of its element type overlap. 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 4118bfc55a395f2fb1349426bd3269c3d95a809b against my last reviewed head af1cd921ad474377acec38c692cc38b1df44903e, separating changes merged from base be5cc64b5c437da385a84a5da710ec1b6c1f2ab4.
Prior findings addressed: the array/slice comparison in ts/src/lower/mir/mod.rs:2317-2325 now recognizes shared storage, and unsizedCopy emits sliceChangedThenRead(copy$u8s(src), src). The earlier Held/Point copy remains intact. Correction to my previous example: direct live[0] = 9 is currently refused; the new copy_from_slice fixture exercises the supported form of the same aliasing bug.
No new actionable bugs found in the PR-specific delta. Normalizing array storage for this comparison is a small, conservative extension of the existing analysis; typed copy shims remain a justified design.
Verification: GitHub-only static review of source, regression cases, and generated expectations. I did not run tests or benchmarks.
(Written by Codex)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Ports the `vec!` element copies to #83's typed copy functions: `rt.copy` and `rt.sliceToVec` are gone. Keeps `vec![x; n]` on `rt.vecFromElem`, so a `Copy` type's own `Clone` still runs `n - 1` times as std's does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
* chore(quest): gzip-only handoff target; time minified bundles Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn * chore(quest): plan #83's follow-ups Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn * chore(quest): time Timestamp's u128 paths Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn * chore(quest): wait on Swift 6.4 to move the fixtures back to arm Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn * chore(quest): #76's follow-ups in the ffi-export quest Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn * chore(quest): plan #86's follow-ups Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn * chore(quest): config files carry only [patch] Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --------- Co-authored-by: Luke Curley <432854+kixelated@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Problem
rt.copydeep-copied aCopyaggregate, shared references included (#78 review). Copying(&Mutex<u8>, u8)cloned the mutex, so a write through the copy's reference changed the clone, andArc::ptr_eqon a copiedControlFlow<&Arc<u8>, _>returnedfalse.slice::to_vecdid the same throughrt.sliceToVec.Two more instances of the same miscompile came up while proving it:
Copyenum with data, or aPollof an aggregate, was never copied:let f = e; if let Shape::Line(ref mut p, _) = e { p.x = 77 }changedftoo.Ty::walkvisits type arguments, not fields, so a callee givenMover { held: &mut src }, or returning a local struct holding the argument, aliasedsrcand the copy.Approach
lower/copy.rs: eachCopyaggregate type gets a function inlib.ts, beside the drop shims, made the first time it is needed:copy$Point(v)is{ x: v.x, y: v.y }, a tuple copies each element, an arrayv.slice()orv.map(copy$Elem)(one function per element type, at every length),OptionandPollskipundefinedandrt.Pending,ResultandControlFlowrebuild by their representation, and an enum rebuilds the variantv.tagnames. A reference is shared as is. Every formerrt.copysite, function values included (iterMap,hashClone,dequeClone), calls it.rt.copyandrt.sliceToVecare deleted;to_vecofCopyelements iss.slice()ors.map(copy$T).&mut, interior mutability, or raw pointer reaching something that could hold the argument's type or be part of it (an array and a slice of its element count as one), looking through the crate's own structs' fields. The same field walk fixesarg_kept(a result that could hold the argument). This is what keepsEncoder::varint'swrite(v, self.form, self.buf)sharingform:&mut Vec<u8>can't reach aForm.Differential tests against native Rust (lang fixture, op 15): tuples, arrays,
Option,Result, a struct holding&Mutex<u8>,to_vec,extendanditer().copied()of them, a mutated parameter,ControlFlow<&Arc<u8>, [u8; 1]>checked withArc::ptr_eq(the review's case), an enum and aPollchanged in place, and arguments whose source changes through another argument, directly, through a struct holding&mut, through a&mutto one of its fields, and through a&mut [u8]unsized from the copied array. On main, this output differs from native Rust (1415 of 301589 cases).Bench
quest gate just ts bench --route main=..., A/B against origin/main's translation in one run (shared machine; A/A noise 5.6% median in Node, 9.8% in Bun, 3.4% in Chromium):One workload moves past noise in the same direction in V8 and Chromium:
varint/leading-onesdecode, 2-19% slower (2B: 1.16 Node, 1.19 Chromium).Decoder::varintnow copiesself.form(LeadingOnes { seven }) beforeread: the copy is shared only if it folds into the argument, and the fold engine flushes the heldself.formread at an intervening statement. Quic'sFormhas no fields, so its copy allocates nothing. Bundle grows by about 100 bytes raw.Impact
rt.copy(x)becomescopy$T(x)fromlib.ts;Copyenums andPolls are now copied where Rust copies them; a few arguments are copied where they were wrongly shared, andEncoder::varint'sformis shared where it was copied.rt.copyandrt.sliceToVecare removed. Pre-release, so noMIGRATE.mdentry.Alternatives
rt.copy: one runtime walk, but megamorphic and slower than a monomorphic literal.x.slice(),{ ...x }): no shim, but needs a temporary forOption/Result/enum tests and an arrow for function values.Pollto another PR: keepsleading-onesdecode at main's speed, but leaves a silent miscompile of the same kind. Chosen: fix it here.Follow-ups
Decoder::varintsharesself.formagain (the leading-ones decode cost above).if let Err(e) = &mut res { *e += 1 }assigns the readonlyrt.Result.error(tsc rejects it);vec![x]of one element is refused (Box::new_uninit); aconstinitializedPollcompared withrt.Pendingfails tsc narrowing;<&T as PartialEq>::eqfrom a derived enum==is unsupported;live[0] = xon a&mut [u8]parameter is refused as a raw pointer.🤖 Generated with Claude Code
https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn
Decided (maintainer, 2026-10-26)
varint/leading-onesdecode cost to fix the enum andPollcopy miscompile here, and recover it in a follow-up quest. Not picked: dropping the enum andPollfix.MIGRATE.mdentry:rt.copyandrt.sliceToVecare internal runtime that nothing generated calls any more.