Skip to content

Read a record copy's mutable fields before overrides that can assign them - #9425

Draft
illusionalsagacity wants to merge 3 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-record-copy-order
Draft

illusionalsagacity wants to merge 3 commits into
rescript-lang:masterfrom
illusionalsagacity:fix-record-copy-order

Conversation

@illusionalsagacity

@illusionalsagacity illusionalsagacity commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Part of #9398 (item 32). Found while reviewing the fixes for it.

Problem

A spread of a record with fewer than 20 fields and no optional field reads the fields of the base one by one, in declaration order. A mutable field declared after an override was read after that override had run, so an assignment in the override showed up in the copy.

type s = {a1: int, mutable b1: int}
let f = (base: s) => {...base, a1: {base.b1 = 100; 5}}

Before:

function f(base) {
  return {
    a1: (base.b1 = 100, 5),
    b1: base.b1
  };
}

After:

function f(base) {
  let b1 = base.b1;
  return {
    a1: (base.b1 = 100, 5),
    b1: b1
  };
}

A JSX spread of such props had the same bug.

Fix

A mutable field that follows an override with side effects is bound before all the overrides. Immutable fields, mutable fields declared before every such override, and copies whose overrides have no side effects compile as before.

no_side_effects moves unchanged from Lam_analysis to the new Lambda_effects in compiler/typing, where the translation to Lambda can use it.

Trade-offs

  • Any unknown call counts as a side effect, so {...state, a: f()} gets extra lets for later mutable fields even if f is pure.
  • A base coerced from a type where the field is mutable can still change under a field that is immutable in its own type. Those reads stay in place.

Tests

record_copy_order_test.res: 9 of its 11 cases fail without the change, the other 2 are controls. ounit_record_copy_tests.ml checks the raw Lambda: which fields get a let before the record is built, and in what order, across two overrides and mutable fields before and after them; 2 of its 4 cases fail without the change, the other 2 are controls. One existing output changes, mario_game.mjs, where four mutable fields follow a call.

12.x

12.x has the same bug: 9 of the 11 tests in record_copy_order_test fail there. I'll backport once this one is reviewed.

The fix was written by Claude.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 83.33333% with 29 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.26%. Comparing base (ccfc979) to head (5bbbc18).

Files with missing lines Patch % Lines
compiler/typing/lambda_effects.ml 68.11% 22 Missing ⚠️
tests/ounit_tests/ounit_record_copy_tests.ml 87.50% 7 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #9425      +/-   ##
==========================================
+ Coverage   82.25%   82.26%   +0.01%     
==========================================
  Files         462      464       +2     
  Lines       65672    65749      +77     
==========================================
+ Hits        54016    54088      +72     
- Misses      11656    11661       +5     
Files with missing lines Coverage Δ
compiler/backend/lam_analysis.ml 67.20% <ø> (-0.33%) ⬇️
compiler/typing/translcore.ml 88.60% <100.00%> (+0.31%) ⬆️
tests/ounit_tests/ounit_tests_main.ml 100.00% <ø> (ø)
tests/ounit_tests/ounit_record_copy_tests.ml 87.50% <87.50%> (ø)
compiler/typing/lambda_effects.ml 68.11% <68.11%> (ø)

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Changelog

🐛 Bug fix

  • Fix a record spread {...base, field: value}, or a JSX spread <C {...base} field={value} />, copying a mutable field of base after value was evaluated, so that an assignment made by value showed up in the copy.

Semantic Diff

3 commits · Full page

Read a record copy's mutable fields before overrides that can assign them

78fcd7b · illusionalsagacity · Nov 25, 2026, 19:36 UTC

Why

A record spread {...base, a: e} of a record with fewer than 20 fields and no optional field, or of an array record, reads the fields of base one by one. The values were evaluated in the order the type declares the fields, so a mutable field declared after a was read after e had run, and an assignment in e, or while it awaited, showed up in the copy. A JSX spread of such props did the same. A mutable field that follows an override with side effects is now bound before all the overrides. Immutable fields, mutable fields declared before every such override, and copies whose overrides have no side effects compile as before. no_side_effects moves unchanged from Lam_analysis to Lambda_effects in compiler/typing, where the translation to Lambda can use it.

JS modified (record spread copied field by field)

type s = {a1: int, mutable b1: int}
let f = (base: s) => {...base, a1: {base.b1 = 100; 5}}

js

 function f(base) {
+  let b1 = base.b1;
   return {
     a1: (base.b1 = 100, 5),
-    b1: base.b1
+    b1: b1
   };
 }

JS modified (JSX spread of props copied field by field)

@@config({flags: ["-bs-jsx", "4"]})
@inline(never) let id = x => x
type props = {className: string, mutable title: string}
module C = {
  @react.componentWithProps
  let make = (props: props) => React.string(props.title)
}
let jsxProps = (base: props) =>
  <C {...base} className={base.title = "changed"; id("c")} />

js

 function jsxProps(base) {
+  let title = base.title;
   return JsxRuntime.jsx(Record_copy$C, {
     className: (base.title = "changed", id("c")),
-    title: base.title
+    title: title
   });
 }

Review

  • Why bind only some fields? A field read before the overrides in the literal already has the right value, and an immutable field can't be assigned through its own type, so binding them would only add variables to the output. A base coerced from a type where the field is mutable can still change under an immutable field; such reads stay in place.
  • Which checked-in outputs change? mario_game.mjs, where vpt is overridden by a call and four mutable fields follow it.
Test the binding of copied mutable fields in Lambda

e3d01e0 · illusionalsagacity · Nov 26, 2026, 22:04 UTC

The record spread fix had only an end-to-end test, as Codex pointed out. A unit test now translates record spreads to raw Lambda and checks which fields are bound before the record is built and in what order: mutable fields after two calls, a mutable field before the first call, overrides without side effects, and immutable fields after a call. The first two fail without the fix; the other two are controls.

Check which variable a copied field is read from in the Lambda test

5bbbc18 · illusionalsagacity · Nov 27, 2026, 00:04 UTC

The record spread unit test mapped a field read on any variable to the same value, so it couldn't tell a field read from the copied base from one read from the base before the copy, and it took the last binding named copy rather than the outermost one. It now records the variable of each read, checks the value each let binds, so a bound copy must read init, and stops at the first, outermost binding. An override that reads base itself is checked to read base. The two tests that failed without the fix still do.

@pkg-pr-new

pkg-pr-new Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

rescript

npm i https://pkg.pr.new/rescript@9425

@rescript/belt

npm i https://pkg.pr.new/@rescript/belt@9425

@rescript/darwin-arm64

npm i https://pkg.pr.new/@rescript/darwin-arm64@9425

@rescript/linux-arm64

npm i https://pkg.pr.new/@rescript/linux-arm64@9425

@rescript/linux-x64

npm i https://pkg.pr.new/@rescript/linux-x64@9425

@rescript/runtime

npm i https://pkg.pr.new/@rescript/runtime@9425

@rescript/win32-x64

npm i https://pkg.pr.new/@rescript/win32-x64@9425

commit: 5bbbc18

@cknitt

cknitt commented Nov 26, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T20:56:19.876496Z 5bbbc18 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 248ff9d709

ℹ️ 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".

[None] to leave the field out, and [read] reads a label of [init]. The
values are evaluated in position order, so a mutable field after an override
that can assign it is bound first. *)
let copied_fields fields ~transl ~read =

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Add the required syntax and Lambda regression coverage

This commit adds only the end-to-end fixture and generated JavaScript under tests/tests/src; it adds no syntax fixtures or Lambda/OUnit coverage for the new copied_fields transformation. This does not meet compiler/AGENTS.md's explicit requirement to test syntax, Lambda, and end-to-end behavior. Add the missing syntax and Lambda-level regression cases, including binding order across multiple overrides and mutable fields, so the intermediate transformation is checked independently of backend optimizations.

AGENTS.md reference: compiler/AGENTS.md:L16-L16

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point about Lambda. There's no syntax change, so there are no syntax fixtures to add. The OUnit suite already turns source into raw Lambda (ounit_partial_application_tests.ml does it), so 635a89a adds tests/ounit_tests/ounit_record_copy_tests.ml the same way. It translates record spreads and checks which fields get a let before the record is built, and in what order:

  • {...base, second: f(), fourth: g()} over {mutable first, second, mutable third, fourth, mutable fifth} binds third and then fifth, and reads first in place.
  • {...base, second: 2, fourth: g()} binds only fifth. third comes before the first override with side effects, so it's read in place.
  • An override with no side effects (second: base.first) binds nothing.
  • Immutable fields after a call are read in place.

With the previous translcore.ml, the first two cases fail (expected: init, third, fifth but got: init). The other two are controls.

Investigated by Claude.

match init with
| None -> lam
| Some init -> let_ Strict init_id init lam
| Some init -> let_ Strict init_id init (bind_strict defs lam)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Evaluate the JSX tag before binding copied prop values

For a direct React.jsx call with an effectful tag expression, these new bindings read the copied fields before jsx_tag, even though the tag is the first argument of Pjsx. With the props type in the new test, React.jsx({base.title = "new"; Jsx.make}, {...base, className: id("c")}) now snapshots the old title before the assignment; the previous code and normal left-to-right call evaluation copy "new". Evaluate and protect the tag before taking the prop snapshots so fixing override ordering does not reverse effects from an earlier argument.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I couldn't reproduce this. A direct React.jsx(tag, {...base, className: id("c")}) call never goes through transl_jsx_element. Pjsx is only built for applications with transformed_jsx = true, and only the JSX PPX sets that (Exp.apply ~transformed_jsx:true in jsx_v4.ml). A hand-written call is an ordinary external call, and its props literal goes through transl_record, which puts the let inside the argument, after the tag. With the branch's compiler, the example from the review compiles to

base.title = "new";
let title = base.title;
return JsxRuntime.jsx(Repro$C, { className: id("c"), title: title });

and the copied title is "new", the same as before. Calling an effectful function as the tag gives the same result.

On the path that does build Pjsx, the PPX makes the tag itself: a string constant for a lowercase tag, an identifier or module path such as C.make for an uppercase or qualified tag, or jsxFragment. None of these runs code, so nothing can be observed between the tag and the snapshot of the props. The spread base was already evaluated before the tag on master (let init = ... in Pjsx(tag, ...)), and this PR doesn't change that.

Investigated by Claude.

…them

Why:
    A record spread `{...base, a: e}` of a record with fewer than 20 fields
    and no optional field, or of an array record, reads the fields of `base`
    one by one. The values were evaluated in the order the type declares the
    fields, so a mutable field declared after `a` was read after `e` had run,
    and an assignment in `e`, or while it awaited, showed up in the copy. A
    JSX spread of such props did the same. A mutable field that follows an
    override with side effects is now bound before all the overrides.
    Immutable fields, mutable fields declared before every such override, and
    copies whose overrides have no side effects compile as before.
    `no_side_effects` moves unchanged from `Lam_analysis` to `Lambda_effects`
    in compiler/typing, where the translation to Lambda can use it.

JS modified (record spread copied field by field):
Example:
    type s = {a1: int, mutable b1: int}
    let f = (base: s) => {...base, a1: {base.b1 = 100; 5}}
Before (js):
    function f(base) {
      return {
        a1: (base.b1 = 100, 5),
        b1: base.b1
      };
    }
After (js):
    function f(base) {
      let b1 = base.b1;
      return {
        a1: (base.b1 = 100, 5),
        b1: b1
      };
    }

JS modified (JSX spread of props copied field by field):
Example:
    @@config({flags: ["-bs-jsx", "4"]})
    @inline(never) let id = x => x
    type props = {className: string, mutable title: string}
    module C = {
      @react.componentWithProps
      let make = (props: props) => React.string(props.title)
    }
    let jsxProps = (base: props) =>
      <C {...base} className={base.title = "changed"; id("c")} />
Before (js):
    function jsxProps(base) {
      return JsxRuntime.jsx(Record_copy$C, {
        className: (base.title = "changed", id("c")),
        title: base.title
      });
    }
After (js):
    function jsxProps(base) {
      let title = base.title;
      return JsxRuntime.jsx(Record_copy$C, {
        className: (base.title = "changed", id("c")),
        title: title
      });
    }

Review: Why bind only some fields? A field read before the overrides in the
    literal already has the right value, and an immutable field can't be
    assigned through its own type, so binding them would only add variables
    to the output. A base coerced from a type where the field is mutable can
    still change under an immutable field; such reads stay in place.
Review: Which checked-in outputs change? mario_game.mjs, where `vpt` is
    overridden by a call and four mutable fields follow it.

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
The record spread fix had only an end-to-end test, as Codex pointed out.
A unit test now translates record spreads to raw Lambda and checks which
fields are bound before the record is built and in what order: mutable
fields after two calls, a mutable field before the first call, overrides
without side effects, and immutable fields after a call. The first two
fail without the fix; the other two are controls.

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
The record spread unit test mapped a field read on any variable to the
same value, so it couldn't tell a field read from the copied base from
one read from the base before the copy, and it took the last binding
named `copy` rather than the outermost one. It now records the variable
of each read, checks the value each `let` binds, so a bound copy must
read `init`, and stops at the first, outermost binding. An override that
reads `base` itself is checked to read `base`. The two tests that failed
without the fix still do.

Signed-off-by: Rob <illusionalsagacity@users.noreply.github.com>
@cknitt

cknitt commented Nov 27, 2026

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 5bbbc1838e

ℹ️ 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".

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants