Skip to content

fix(javascript): stop replaying earlier writes for each object property write - #1444

Merged
N0zoM1z0 merged 3 commits into
morluto:mainfrom
zeynelacikgoez:fix/javascript-repeated-write-complexity
Oct 10, 2026
Merged

N0zoM1z0 merged 3 commits into
morluto:mainfrom
zeynelacikgoez:fix/javascript-repeated-write-complexity

Conversation

@zeynelacikgoez

Copy link
Copy Markdown
Contributor

Summary

Member-mutation collection is still cubic in the number of property writes to a single object on current main. CommonJS/webpack exports objects and minified configuration builders make this pattern common in real bundles. On main (0b9815b6), analyzeJavaScriptSemantics takes 27 s for 2,000 writes to one object and 203 s for 4,000. With this change, those take 0.09 s and 0.16 s.

This is separate from #1401, which 28595276 fixed (factorial growth through reassignment loops). That fix bounds path enumeration. The cost here is in evaluating the written binding.

Problem and expected behavior

Smallest trigger:

export function result() {
  const source = { token: "TOKEN" };
  source.p0 = 0; source.p1 = 1; /* … */ source.p1999 = 1999;
  return [source.token, source.p1999];
}

There are two compounding costs in collectSemanticMemberMutations and evaluateBinding:

  1. Per-write evaluation.
    • Each recorded write calls evaluateSemanticBinding on its target, only to rule out a primitive target, because writes to primitives are ignored.
    • Non-primitive results are not memoized, and each recorded write clears the primitive cache.
    • So the k-th write rebuilds the initializer and replays all k − 1 earlier mutation paths.
  2. Per-path slot copies. Folding binding.mutatedPaths with invalidateSemanticMutationPath copies the whole slot array once per path, so one evaluation costs O(k · slots).

Together that is O(k²·(slots + k)). Expected behavior: cost proportional to the writes, with identical values.

Change and scope

  • First write only (javascriptSemanticMemberMutations.ts).
    • invalidateSemanticMutationPath returns either an object/array or unknown, never a literal/union.
    • So once a binding has one recorded write, it cannot evaluate to a primitive, and the check is needed only for its first write.
    • Capture-point evaluations use separate caches and are unaffected.
  • Single-pass fold (javascriptSemanticMutationValues.ts, javascriptSemanticValues.ts).
    • invalidateSemanticMutationPaths(value, paths) groups paths per slot and recurses once per slot.
    • It reproduces the sequential order-sensitive rules exactly:
      • any null/empty key ⇒ the same root unknown, which subsumes the existing early break;
      • the last array length write resets items;
      • an unmatched exact key appends one unknown-coverage slot;
      • later paths into an added slot are inert;
      • selectors still test every slot.
    • It replaces the single-path function, which had no other callers.

Not included: no caps or truncation, no change to cycle handling from 28595276, and no contract, schema, or catalog change.

Contract and boundary impact

  • Semantic owner and earliest changed stage: src/domain/javascript member-mutation collection and binding evaluation.
  • CLI and MCP/tool-catalog contract: none.
  • Provider, bridge, target-format, or platform compatibility: none.
  • Evidence, artifact, provenance, or reconstruction contract: none. Values are identical (see below).
  • Process execution, authorization, cleanup, or containment impact: none.
  • Generated metadata, package, or installation impact: none.

Evidence and regression coverage

  • Test added: javascriptSemanticAnalysis.member_mutations.test.ts › "records each write to one object without replaying earlier writes".

    • It writes 2,000 properties to one object, then asserts that the untouched slot stays literal and the written slot is unknown, within 2 s.
    • On the base revision it fails after 43 s (expected 42984 to be less than 2000).
  • Base reproduction on Node 24.18.0 / macOS arm64:

    Writes to one object main 0b9815b6 this change
    1,000 3.4 s 0.07 s
    2,000 27.4 s 0.09 s
    4,000 202.9 s 0.16 s
    8,000 — 0.29 s
    • Notion Desktop 7.37.1 bundles: .webpack/main/index.js (4.2 MB) 10.6 s → 8.7 s; .webpack/renderer/activity_monitor/index.js 0.98 s → 0.95 s.
  • Value equivalence:

    • Across all 96 JavaScript files in Notion Desktop 7.37.1's app.asar, all 58,900 binding and return-site values are byte-identical between main and this change.
    • 200,000 randomized value and path sequences (selectors, null keys, length, duplicate names, nesting) fold identically to the sequential per-path reduce.
  • Commands run:

    • npm run check:fast, which passes.
    • npm run test:local -- src/domain/javascript/*.test.ts src/application/javascript/*.test.ts: 55 files, 989 tests, passing.
    • npm run test:focused -- with the 42 JavaScript CLI/MCP/composition test files: 286/290 passed. All 4 failures were 30 s timeouts in tests/acceptance/applications/exportedFunctionBindingsCli.test.ts and tests/acceptance/tools/localToolContracts.test.ts. Run alone, those two files also time out on unmodified main on this machine (5 failures there vs 3 with this change).
  • Real Hopper/Ghidra verification: not applicable; JavaScript-only change.

🤖 Generated with Claude Code

…ty write

Repeated property writes to one object made member-mutation collection
cubic. Each write evaluated its target binding to rule out a primitive,
and every evaluation folded all earlier mutation paths, copying every
slot once per path. 2,000 writes to one object took 27 s and 4,000 took
203 s.

- A recorded write always leaves a non-primitive binding value, so only
  the first write to a binding needs the primitive check.
- Apply mutation paths per slot in one pass with the same ordering
  semantics instead of one full slot copy per path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@N0zoM1z0 N0zoM1z0 added area: domain Domain logic, errors, and pure functions area: tests Test suite and verification bug Something isn't working labels Oct 10, 2026
@N0zoM1z0

N0zoM1z0 commented Oct 10, 2026 •

Copy link
Copy Markdown
Collaborator

Independent review of the final integrated head 439bc1a5d06f6db042161922ea8b1662ffc933a9:

I preserved the contributor commit/history and merged current main into the original contributor branch. The actual original branch ancestor was 0b9815b6, so the initial head did not include #1433 or #1437; the final head also includes the newly merged #1445. Its diff against frozen main e09cfe9b remains exactly the four repeated-write files. Both final-head fork workflows were approved; no reviewers were requested.

  • Traced the first-write primitive guard and batched invalidation through capture caches, aliases, selected/copied slots, duplicate property names, unknown roots and order-sensitive nested array-length resets. No arbitrary traversal cap or sibling-key widening is added.
  • 327 adjacent semantic tests passed on both the initial head and the first main integration. The final integration passes real compiled CLI/SDK stdio acceptance for 24 iteration-alias and 33 stored-slot scenarios, plus actual SDK output-validator reuse. The final push's complete serial typecheck/lint gate passed.
  • 50,000 independently seeded pure value/path differential cases match the old ordered fold, covering duplicate names, root invalidation, nested array resets, exact/selector/excluded keys and prototype-like names. This is diagnostic equivalence evidence, not a substitute for public workflows.
  • Public CLI, source-owned application directories with 1,000/2,000 writes: Evidence and both graph identities match the frozen production baseline. The 2,000-write sample was 29,672 ms before versus 8,007/4,744 ms on the initial candidate. The first 1,000-write candidate invocation was a 20,544-ms outlier and its repeat 3,703 ms; no universal startup/throughput claim. Public stdio MCP also preserves exact identities, full inline text/structured parity when the result fits, and complete retained Evidence with an actionable transport constraint when it does not. Summary, module feature trace, ping, close and expired-reference checks pass.
  • Independently built current main e09cfe9b versus the final integrated runtime on the same real Notion ASAR (SHA-256 97c41bc14fc0ea8c91cd34f502660963dfdf294d5eb35165ccac9d30963069d4): exact same Evidence ev_8b49aebfa361929c6c2b206271260bf2851a55e729884215b8f87fbb4ad8b490. Ordinary 139-tool discovery, bounded transport result, retained summary/module page, trace, distinct-input rejection, ping, close/invalidation and unchanged source bytes pass in both. Main/candidate analysis calls were 95,577/87,763 ms; maximum ping waits 18,172/17,742 ms; peak sampled families 1,847,402,496/1,850,753,024 bytes. Both runs use two CPUs/reduced priority and explicit 210-second client deadlines. These are single paired observations; large-file responsiveness/cancellation under [Feature] Roadmap: improve MCP usability and performance under bounded resources #1065 remains open.

No real Hopper/Ghidra verification was needed for this JavaScript-only fix. Final-head CI is still pending the remaining platform lanes; merge remains conditional on their success.

@N0zoM1z0
N0zoM1z0 merged commit 1ec490f into morluto:main Oct 10, 2026
20 checks passed
@CassieFox23

CassieFox23 commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

TL;DR: #1444 merged as I started, so I tested the merge commit 1ec490f3 against its parent 66863b60. 4,000 writes went from 210 s to 0.24 s. Base and head gave the same answer on all 197 cases.

Speed

Analysis time on Node 24, median of 3. Base at 4,000 ran once.

Writes to one object base head
500 453 ms 72 ms
1,000 3.1 s 100 ms
2,000 24.7 s 156 ms
4,000 210.5 s 239 ms

Five other shapes behave the same way. Head stays under 0.6 s at 4,000 on Node 22, 24 and 26. The output hash matches base at every size.

Soundness

Each case ran through the CLI or analyzeJavaScriptSemantics. I checked each one in real JS.

Case set Cases Right Honest unknown Wrong
#1442 slot stores 24 2 22 0
#1428 for...of 38 8 28 2
#1390 corpus 59 10 34 1
#1445 probes 48 2 40 6
New write probes 28 8 20 0

14 rows in the #1390 set have no real value. Real JS throws on every run there. Base and head match on those too.

The counts are the same on base and head. Head lost no right answer and gained none. The output was byte for byte the same on every case. All 9 wrong rows were wrong on base too. Six are the call-return bug in #1449. This PR leaves them as they were. The new probes cover overwrites, delete, aliases, spread, Object.assign and getters. They also cover array length resets and duplicate keys.

I also fuzzed the new fold against the old one. That was 900,000 random value and path runs. Both gave the same result every time.

Tests

  • The new test passes on Node 22, 24 and 26.
  • On base it fails, as it should. It took 43.8 s against the 2 s limit.
  • All of src/domain/javascript passes on Node 24. That is 722 tests.

Not run

  • check:fast and verify:*. My trees have no git history.
  • The MCP path.
  • The Notion Desktop bundles from the PR body.

Thanks, zeynelacikgoez. The grouped fold is a neat fix, and the notes in the PR made it easy to check.

Speed for all shapes

Median analysis time of 3 runs. Base ran once when a run took over 60 s. A star means the box was busy, so read it as rough.

Shape Writes base 24 head 24 head 22 head 26
Two objects 2,000 5.8 s 151 ms 221 ms * 151 ms *
Two objects 4,000 50.4 s * 259 ms 347 ms * 254 ms *
o["pN"] keys 4,000 207.8 s 242 ms 338 ms * 276 ms *
Writes in a loop body 4,000 213.1 s 260 ms 330 ms * 264 ms *
A read after each write 4,000 235.1 s 435 ms 580 ms * 458 ms *
Webpack comma chain 4,000 223.6 s * 241 ms * 314 ms * 238 ms *
#1401 loop, k=12 24 ms * 24 ms *
#1401 write, k=12 25 ms * 26 ms *
Hermes Desktop (MIT) vendor chunk 1.5 s * 1.4 s *
  • The loop shape puts all the writes in one for body.
  • Unbound dynamic keys (source[k0] = 0) took 0.26 s at 4,000 on both. The object goes unknown, so it is no stress test.
  • Hermes peak memory was about 405 MB on both.
  • All 320 runs exited 0.
The 9 wrong rows (same on base and head)
  • [Bug] Writing through a function's returned object reports a stale literal #1449, six forms. Here is one:

    const shared = { x: 1 };
    const get = () => shared;
    get().x = 2;
    return shared.x; // real 2, both say 1
  • Two copies of one loop case. Real JS gives 2, both say 1:

    const g = { v: 1 }; const c = { m0: g, v: 1 }; const seed = { m0: c };
    let node = seed; let i = 0;
    while (i++ < 2) { node = node.m0; node.v = 2; }
    return g.v;
  • A generator. Real JS gives 2, both say 1:

    const shared = { x: 1 };
    function* gen() { yield shared; }
    for (const t of gen()) t.x = 2;
    return shared.x;
How I checked
  • I ran the CLI cases on Node 22, 24 and 26. That was 600 runs, all exit 0.
  • The file cases ran through analyzeJavaScriptSemantics. That was 582 runs, all exit 0.
  • Real JS ran on all three Nodes. They agreed.
  • No result changed between Node versions.
  • One for...of row is half right. A known key stays right, and the written key is unknown. I count it as right.
  • The fuzz drew random objects and arrays, up to three levels deep. It mixed in duplicate names, length, null keys and selectors.
Test setup
  • Box: Nobara 44 (Fedora 44 base), Linux 7.2.9
  • CPU: AMD Ryzen 9 5900X, 12 cores / 24 threads
  • RAM: 32 GB DDR4-3600
  • Node: 22.23.1, 24.18.0, 26.11.1
  • Head / base: 1ec490f3 (merge of 439bc1a5) / 66863b60

🤖 Generated with Claude Code (Opus 5.5) 🦊

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

Labels

area: domain Domain logic, errors, and pure functions area: tests Test suite and verification bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants