Skip to content

fix(lynx): serialize cross-thread transport payloads - #885

Merged
trueadm merged 1 commit into
octanejs:mainfrom
Huxpro:fix/lynx-transport-codec
Aug 28, 2026
Merged

trueadm merged 1 commit into
octanejs:mainfrom
Huxpro:fix/lynx-transport-codec

Conversation

@Huxpro

@Huxpro Huxpro commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

On device, a composite sent through Lynx ContextProxy can arrive in LepusNG as a host-backed LEPUS_TAG_LEPUS_REF. The iOS and Android reproduction archived in Huxpro/octane#152 shows the important shape: property reads, spread, and JSON.stringify work, but Reflect.ownKeys throws, Object(value) !== value, and the prototype is null. Before this change, that live bridged composite could reach record() in core/protocol.ts:472; the first Reflect.ownKeys there could therefore terminate the renderer.

The apparent historical success was accidental. The receive path also used Object.getOwnPropertyNames, whose ToObject coercion happened to turn this engine value into something enumerable. That coercion became load-bearing, while the four non-coercing Reflect.ownKeys validators at core/protocol.ts:472, :768, :797, and :1206 exposed the underlying boundary defect. Changing individual reflection calls would only move the crash.

This PR removes the whole failure class: every Octane transport send encodes a string, and every receiver decodes before its first payload read. The native-engine lifecycle entry is the one sender Octane cannot encode, so it is localized immediately on arrival. The resulting invariant is that a LynxValueRef never escapes the transport layer; protocol, lifecycle, and worklet code only see receiver-local LynxStructuredValue data.

The codec is the implementation from Huxpro/octane#164. It round-trips undefined, non-finite numbers, and __proto__-class keys without silent semantic changes; rejects unsupported/cyclic values at the sender; and includes the original type in encoding diagnostics. This deliberately does not include new-lynx validation modes, programs, or adoption work.

Before / after

  • Before: an unencoded bridged composite could reach protocol.ts:472, where the device reproduction throws at Reflect.ownKeys.
  • After: the strict-wire fixture rejects every non-string crossing and decodes every observed string. A real mount, update, teardown, and native-engine lifecycle delivery all round-trip through that fixture. Static conformance tests also pin exactly four encoded send sites and exactly four materializing event.data reads, so a future bypass cannot hide on an unexecuted path.

getOwnPropertyNames site audit

  • Former main-thread.ts:248 (lifecycleTuple): removed. Engine-owned event.data is first passed to localizeLynxHostValue; the resulting JSON materialization is already a dense ordinary array, so the old descriptor walk would be redundant.
  • core/lifecycle-data.ts:109: retained. On the engine path its input descends from the localized lifecycle tuple; on the background path it descends from a decoded lifecycle message. It never receives raw event.data.
  • core/protocol.ts:599: retained. Receive paths decode before validation, while sender self-checks inspect local source-realm values before encoding.
  • core/worklets.ts:152: retained. Transport-delivered worklet descriptors are decoded before worklet validation; compiler-created descriptors are already local values.

The four Reflect.ownKeys sites in core/protocol.ts are intentionally retained for strict schema validation. They now operate only after decode (or on sender-local self-check values), which removes the host-backed receiver object rather than weakening validation.

Validation

  • pnpm format:check
  • pnpm typecheck
  • pnpm test
  • targeted tests:
    • pnpm exec vitest run --project lynx — 27 files, 393 tests
    • ported/integration subset — 12 files, 180 tests
    • node --test benchmarks/lynx-table/stages/*.test.mjs — 15 tests
    • upstream CI test matrix, vitest.ci-sharded.config.js shards 1/4 through 4/4 with the CI excludes — 1,791 files, 21,032 tests passed, 1 skipped
    • pnpm changeset:check
    • pnpm sync (clean; no generated drift)

The CI shards were limited to four workers and used a same-filesystem temporary directory on this host. This avoids unrelated 5-second CLI timeouts, root /tmp exhaustion, and cross-device rename failures without changing the test set or assertions.

Risk / follow-ups

Both realms ship in one bundle, so the internal text envelope does not require wire-version negotiation. The envelope adds a constant four bytes to a clean JSON payload; profiling now measures the exact encoded length and reports encode/decode time separately.

This is Deliverable 1 from Huxpro/octane#232. Standard Lynx performance entries are intentionally a separate PR, and the ART reference-table diagnosis is intentionally an issue without a patch.

Provenance

  • An agent produced this diff (agent-authored)

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.


Note

Medium Risk
This changes every Lynx main/background message path and engine lifecycle materialization; regressions would affect rendering and page lifetime, though conformance tests and broad suite updates narrow that surface.

Overview
Lynx cross-thread traffic is now always a string on the wire, so receiver code never sees host-backed LEPUS_REF composites that break Reflect.ownKeys on device.

A new transport-codec module owns the boundary: outbound messages are encoded (with escapes for undefined and __proto__, refusal of JSON-lossy types, and a [flags, payload] envelope); inbound paths decode before validation. transport.ts, main-thread.ts, and background-lifecycle.ts wire this in at every send/receive site. Native engine lifecycle tuples (__RenderPage, etc.) use localizeLynxHostValue because the engine cannot encode.

Profiling and benchmarks count exact encoded byte length and separate encode/decode time. Tests and fixtures use wire/unwire, plus static conformance checks that pin four encoded send sites and materializing reads of event.data.

Reviewed by Cursor Bugbot for commit 2b24657. Bugbot is set up for automated code reviews on this repo. Configure here.

@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent fix PR: bug fix labels Aug 28, 2026

@cursor cursor 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.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix is ON, but it could not run because the branch was deleted or merged before autofix could start.

Reviewed by Cursor Bugbot for commit 2b24657. Configure here.

path,
`is a ${describeConstructor(composite)}, which JSON would rewrite into something else.`,
);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Encode rejects cross-realm plain objects

Medium Severity

prepare treats a bag as plain only when its prototype is this realm's Object.prototype or null. localizeLynxHostValue feeds that check engine lifecycle records that can carry another realm's Object.prototype. Those records are then refused as rewritten types even though JSON.stringify would keep them, so a valid __RenderPage or __UpdatePage payload is dropped.

Additional Locations (1)
Fix in Cursor Fix in Web

Triggered by learned rule: Lynx cross-thread validators must use hasCrossRealmPlainPrototype — never realm-local identity checks

Reviewed by Cursor Bugbot for commit 2b24657. Configure here.

@trueadm
trueadm marked this pull request as ready for review August 28, 2026 12:59
@trueadm
trueadm merged commit 957b910 into octanejs:main Aug 28, 2026
51 checks passed
trueadm added a commit that referenced this pull request Oct 3, 2026
The lynx-render transport gate failure and the create_1k/create_10k ratio
breaches both trace to #885's JSON-encoded transport and now have an owner
fix. Its branch re-notes those two guards, so this branch drops their waivers
and the suite's allowlist entry instead of editing the same entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 3, 2026
…nd re-judge them (#1646)

* ci(bench): triage the weekly ratio-guard breaches so new ones show

The weekly Bench job (`bench.mjs --quick --ratios`) was red with 81 ratio
breaches, 4 suites that wrote no numbers and 4 harness gate failures, so a new
breach was invisible. Every item is now a fix or a rebaseline.

- Harness drift, fixed. Each harness had stopped producing numbers when runtime
  source it anchors on changed:
  - ssr-final-replay: a second suspended loop since 2026-09-29.
  - root-transactions/contracts: staged-DOM text and attribute journaling since
    2026-09-15.
  - signal-dom-bindings: a second native style Block allocation site since
    2026-09-23.
  - codegen-size: the server runtime's lazy streamed-signals chunk since
    2026-09-16.
  - recursive-context: counted a pure-call annotation and trailing newlines as
    output growth.
- Rebaselined, with numbers in each note: five cross-framework bundle-size
  ratios and the workerd script-size ratio. The absolute app and server-render
  budgets are now the ratchet. Lynx's no-worklet byte caps from 2026-08-17 are
  reset to measured + 32, with the background program pinned exactly.
- Fix pending, with dated waivers that expire 2026-10-24, each with an owner
  task:
  - three exact counters the revived harnesses exposed (one extra closure per
    ssrTry, 128 live text reads per 128 unchanged compiled updates, compiled
    output at 1.295x its source);
  - Lynx create ratios and the re-entrant transport gate;
  - superlinear hydrate boundary preparation;
  - Octane Three versus R3F size and frame dispatch;
  - two timing regressions near the timer floor;
  - ten quick-mode timing guards whose samples are noise-bound;
  - the scoped descriptor shape change.
- bench.mjs supports a guard `waiver` ({ reason, expires }). A waived breach
  prints and does not fail, and fails again once the date passes.
  HARNESS_FAILURE_ALLOWLIST now also covers a suite whose harness writes no
  numbers.

The budget breaches (57) clear when the budget reset lands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(benchmarks): pair and lengthen the timing samples behind waived ratio guards

Twelve timing guards breached in weekly quick runs without a verdict. Their
samples sat near Chromium's 100 µs clock or under two-sample noise, and each
target ran its whole block minutes after the other side of its guard.

- benchmarks/lib/paired.mjs: rotating per-round visit order and a ~20 ms
  sample calibration shared by the harnesses below.
- js-framework-reorder, memo-wall, svg-dashboard, spa-navigation: every
  target's page stays open in one browser and each sample round visits all
  targets; short ops repeat until a sample takes about 20 ms (clicks,
  hook invocations, op batches, and summed navigation legs).
- activity caught-reveal: a sample reveals several independent hidden roots
  in one window, with the small case revealing eight times as many roots so
  both cases do equal work; the cases alternate per round.
- ssr-workerd: an untimed priming spawn per target, then paired cold-spawn
  rounds; quick mode runs six rounds instead of two.
- bench.yml: a `suites` dispatch input to run selected suites.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(benchmarks): collect garbage before every timed spa-navigation leg

The untimed return leg mounts a whole route, and its collection landed
inside the next timed teardown: nav_teardown samples ran at 17-45% rme.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(benchmarks): re-judge the twelve waived timing guards with paired samples

Two quick CI runs of the paired, ~20 ms harness and same-runner A/B runs
against the commits that set each guard decided every waiver:

- Passing, waiver removed: activity reports, ssr-workerd
  cold_spawn_to_first_byte, svg-dashboard pan_zoom, memo-wall
  parent_rerender_equal_A and octane-jsx mount, spa-navigation
  nav_teardown and nav_mount (no Octane change since #674 on one runner).
- Rebaselined: svg-dashboard icon_swap 1.2 -> 1.6, because #983's esbuild
  minification made React 15% faster while Octane stayed flat.
- Confirmed Octane regressions, waiver kept and pointed at the fix:
  js-framework-reorder rotateb (1.41x per click since #639), memo-wall
  one_change_B (1.5x) and ctx_through_wall_B (1.44x), and svg-dashboard
  tooltip_swarm (1.31x since #635).
- The rotateb note claimed React moves every survivor; it moves one. A new
  rotatef guard covers the LIS-vs-lastPlacedIndex differentiator (0.043x).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(benchmarks): rebaseline spa-navigation nav_mount to its CI baseline

The 1.2 ceiling came from a local 0.94x reading. On CI runners #674 itself
measures 1.15x and head 1.09-1.16x, so the ceiling left 3% of quick-mode
headroom; 1.35 keeps a margin while still catching per-node mount growth.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(bench): drop the three weekly waivers that now have fix PRs

The waived guards now have owner PRs: ssr-final-replay try_closures (#1644),
root-transactions equal_reads (#1643) and codegen-size gzip compiled/source
(#1645). #1645 rebaselines the same codegen-size entry, so this branch no
longer edits it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(bench): leave lynx-render to its owner fix

The lynx-render transport gate failure and the create_1k/create_10k ratio
breaches both trace to #885's JSON-encoded transport and now have an owner
fix. Its branch re-notes those two guards, so this branch drops their waivers
and the suite's allowlist entry instead of editing the same entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(bench): keep harness failures unwaivable and leave descriptor shapes to their owner

Waiving a suite that throws before it writes numbers would hide any crash in
that suite, not only the known shape change, and skip all of its guards. The
scoped-descriptor-shapes defect has an owner fix in progress. That fix re-pins
the harness's expected keys, so narrowing the waiver here would edit the same
assertion. HARNESS_FAILURE_ALLOWLIST is empty again, and a thrown suite failure
always fails the job. Dated waivers remain only on individual ratio guards.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(bench): leave the Three guards to their owner fixes

three-renderer frame_1k_subscribers and the two three-bundle-size ratios have
owner PRs (#1651, #1652) that re-note and ratchet those entries, so this branch
drops their waivers instead of editing the same entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(benchmarks): point the four kept timing waivers at their attributed fixes

rotateb and ctx_through_wall_B clear with #1655 and #1656; one_change_B's
per-row remainder and tooltip_swarm's scoped-descriptor accessor reads each
have their own fix task.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(benchmarks): point parent_rerender_equal_A's note at its per-commit journal fix

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 3, 2026
…1641)

* ci(bench): triage the weekly ratio-guard breaches so new ones show

The weekly Bench job (`bench.mjs --quick --ratios`) was red with 81 ratio
breaches, 4 suites that wrote no numbers and 4 harness gate failures, so a new
breach was invisible. Every item is now a fix or a rebaseline.

- Harness drift, fixed. Each harness had stopped producing numbers when runtime
  source it anchors on changed:
  - ssr-final-replay: a second suspended loop since 2026-09-29.
  - root-transactions/contracts: staged-DOM text and attribute journaling since
    2026-09-15.
  - signal-dom-bindings: a second native style Block allocation site since
    2026-09-23.
  - codegen-size: the server runtime's lazy streamed-signals chunk since
    2026-09-16.
  - recursive-context: counted a pure-call annotation and trailing newlines as
    output growth.
- Rebaselined, with numbers in each note: five cross-framework bundle-size
  ratios and the workerd script-size ratio. The absolute app and server-render
  budgets are now the ratchet. Lynx's no-worklet byte caps from 2026-08-17 are
  reset to measured + 32, with the background program pinned exactly.
- Fix pending, with dated waivers that expire 2026-10-24, each with an owner
  task:
  - three exact counters the revived harnesses exposed (one extra closure per
    ssrTry, 128 live text reads per 128 unchanged compiled updates, compiled
    output at 1.295x its source);
  - Lynx create ratios and the re-entrant transport gate;
  - superlinear hydrate boundary preparation;
  - Octane Three versus R3F size and frame dispatch;
  - two timing regressions near the timer floor;
  - ten quick-mode timing guards whose samples are noise-bound;
  - the scoped descriptor shape change.
- bench.mjs supports a guard `waiver` ({ reason, expires }). A waived breach
  prints and does not fail, and fails again once the date passes.
  HARNESS_FAILURE_ALLOWLIST now also covers a suite whose harness writes no
  numbers.

The budget breaches (57) clear when the budget reset lands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(bench): drop the three weekly waivers that now have fix PRs

The waived guards now have owner PRs: ssr-final-replay try_closures (#1644),
root-transactions equal_reads (#1643) and codegen-size gzip compiled/source
(#1645). #1645 rebaselines the same codegen-size entry, so this branch no
longer edits it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(bench): leave lynx-render to its owner fix

The lynx-render transport gate failure and the create_1k/create_10k ratio
breaches both trace to #885's JSON-encoded transport and now have an owner
fix. Its branch re-notes those two guards, so this branch drops their waivers
and the suite's allowlist entry instead of editing the same entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(bench): keep harness failures unwaivable and leave descriptor shapes to their owner

Waiving a suite that throws before it writes numbers would hide any crash in
that suite, not only the known shape change, and skip all of its guards. The
scoped-descriptor-shapes defect has an owner fix in progress. That fix re-pins
the harness's expected keys, so narrowing the waiver here would edit the same
assertion. HARNESS_FAILURE_ALLOWLIST is empty again, and a thrown suite failure
always fails the job. Dated waivers remain only on individual ratio guards.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* ci(bench): leave the Three guards to their owner fixes

three-renderer frame_1k_subscribers and the two three-bundle-size ratios have
owner PRs (#1651, #1652) that re-note and ratchet those entries, so this branch
drops their waivers instead of editing the same entries.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
trueadm added a commit that referenced this pull request Oct 4, 2026
)

Since #885 made the transport JSON-encode every message, the main thread
receives each program run as fresh, mutable data. prepareLynxHostBatch
takes the dense host record store only for a frozen run, so every fresh
root's first mount fell back to staging one record per host. The main
thread now freezes a fresh root's validated compact runs before it
prepares them, as it already did for runs appended after first-screen
adoption.

The lynx-render reentrant pair also broke with #885: runReentrantCommits
still dispatched raw objects, which the receiver rejects, so the pair
measured 0 ms. It now encodes the burst through the transport codec
before the timer starts. A new fixture contract,
benchmarks/lynx-render/workload.test.mjs, runs on every pull request and
in the weekly Bench pre-step, so a wire change cannot strand the workload
again. The build is shared with run.mjs through build.mjs.

Refs #1055

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-authored Diff or issue body substantially produced by an AI agent fix PR: bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants