Repository navigation
feat(lynx): the transport owns encoding, so nothing live crosses a thread - #164
Merged
Merged
Conversation
`ContextProxy` transports generic Lynx values, not strings, so a composite sent through it can arrive in LepusNG as `LEPUS_TAG_LEPUS_REF` — a host-backed value that answers reads and `Object.keys` but is not an ordinary receiver-realm object. Octane read those with the coercing `Object.getOwnPropertyNames`, which quietly made them usable for the package's whole native lifetime; swapping in `Reflect.ownKeys` removed the accident and broke the renderer on device. This adds the module that ends that class of defect by making the transport the only layer that materializes a value. Nothing is wired yet. It owns exactly the cases where JSON silently changes meaning: - `undefined` travels as a sentinel rather than dropping the key, which is what a worklet closure capture holds before its first assignment. - `NaN`, the infinities, bigints, functions, and symbols are refused at the sender with a message naming the path, because the sender is the last place that still knows what the value was. - `Date`, `Map`, `Set`, and class instances are refused for the same reason: they have no own enumerable keys to walk, so they would pass the escape pass untouched and then be rewritten by `JSON.stringify` alone. - a `__proto__` key is restored as an own data property via `defineProperty`, matching the precedent `main-renderer.ts` already sets, rather than whatever the receiving engine's `JSON.parse` decides. Both escapes key on `U+0000` with a doubling ladder, so a payload that spells a sentinel round-trips as itself. The wire form is `[flags, payload]`: a payload that escaped nothing decodes in a single `JSON.parse` with no walk of its own, and its bytes are its own JSON unchanged. A `null` prototype is the one lossiness accepted rather than refused — JSON cannot express it, and `host-props.ts` already treats it and `Object.prototype` as the same ordinary bag. Every one of the 20 tests is red-verified: 17 deliberate breaks of the implementation, each caught, with no test left that nothing can fail. Co-Authored-By: Claude <[email protected]> Claude-Session: https://claude.ai/code/session_019RsC3U39kUuLKajZANeTVy
`ContextProxy` transports generic Lynx values, not strings, so every `dispatchEvent` handed the receiver a live composite built on the sending thread. On device that composite can arrive as a `LEPUS_TAG_LEPUS_REF`: reads work, `Object.keys` works, `JSON.stringify` works, but `Reflect.ownKeys` throws and `Object(v) !== v`. Octane's own history is the proof that this is load-bearing rather than theoretical — `record()` read props with the coercing `Object.getOwnPropertyNames` until it switched to the non-coercing `Reflect.ownKeys`, and `ToObject`'s implicit conversion had been quietly keeping an already-invalid value usable for the framework's entire native lifetime. Encoding at the four send sites and decoding at the three receive sites moves that from an accident to a rule: a string cannot be a host-backed reference on any engine, so the receiver is handed receiver-local ordinary data by construction. `transport-codec.ts` owns the value domain — `undefined` via a sentinel, `__proto__` as an own data property either way, `bigint`, non-finite numbers, functions, symbols, and `Date`/`Map`/class instances refused at the sender, which is the last place that still knows what the value was. The conformance transport is the gate. Its static half reads every `dispatchEvent` in `src` and counts four; its dynamic half runs a real mount, update, and teardown through a proxy that throws on anything but this codec's output. The suite's own harness now puts strings on the wire and takes strings off it, so each of the 63 sends and 82 reads is also a boundary assertion. Two consequences surfaced rather than papered over. `background-lifecycle.ts` shares its inbound channel with the transport's receiver, so an inbound message decodes twice — acknowledged in a comment, and cheap because the heavy direction has a single receiver. And the null prototype and frozen-ness that two tests asserted on cross-thread payloads were same-realm harness artifacts that no real wire could have carried; they now assert what a receiver can actually observe. `profile.bytes` is the encoded length, which is the wire length, so the profiler no longer stringifies a second time to estimate it. Co-Authored-By: Claude <[email protected]> Claude-Session: https://claude.ai/code/session_019RsC3U39kUuLKajZANeTVy
`__RenderPage`, `__UpdatePage`, and `__UpdateGlobalProps` arrive on the same `ContextProxy` machinery as a transport message, but their sender is the native engine, which cannot be asked to encode. That left them the one inbound payload nothing had materialized, and everything downstream — `Array.isArray`, `Object.getOwnPropertyNames`, descriptor reads, the clone in `lifecycle-data.ts` — is written for ordinary local data. Those particular calls happen to coerce a host-backed reference into something usable, which is exactly the accident that kept `record()` working until it swapped one reflection call for another. The invariant that a `LynxValueRef` never escapes the transport layer cannot be claimed with that entry open. `lifecycleTuple` is the single funnel for all three, so it materializes there, through the same codec the transport uses rather than a bare stringify/parse: `undefined` survives, `__proto__` lands as an own data property on every engine instead of whichever one `JSON.parse` happens to produce, and a value the domain cannot carry is named where it entered. That last part is the behavior worth reading twice. A `bigint` in engine page data used to be copied straight through the clone and only refused at the send site — and a throw there is a failure to deliver an engine lifecycle update, which tears down the page lifetime. One malformed record killed the page. It is now one dropped record with a diagnostic naming the field. Materializing also moves the line on hostile shapes, in the direction this issue is committing to everywhere: a shape the codec can express becomes ordinary local data and the update proceeds, and only what cannot be expressed is refused. Two cases that used to be rejected now normalize. A symbol-keyed extra field on the tuple, which nothing downstream could ever read, is dropped. And an accessor in an options bag is read — copying a value means reading it, so the getter runs, once, here, inside the boundary's own try/catch, rather than at whatever later moment a lazy descriptor read happened to fall on. The rewritten test says both out loud. The conformance transport grows the receiving half of its rule: every `event.data` in `src` must be the argument of a materializer, and there are exactly four. Its dynamic half now drives the engine entry too, so what the engine handed in is watched all the way out across the strict wire. Co-Authored-By: Claude <[email protected]> Claude-Session: https://claude.ai/code/session_019RsC3U39kUuLKajZANeTVy
Two of the questions #156 asked, answered with tests rather than claims. The worklet argument path is string-safe end to end, and not by a separate arrangement: `runOnMainThread` reaches `transport.callMain`, `runOnBackground` reaches the controller's `callBackground`, and both funnel into the same `dispatch` as every other message — so arguments, results, and cancellations ride the four encoded send sites in both directions. The new scenario drives a real bidirectional call through the strict proxy, which refuses anything that is not the codec's output, and mutates the argument object the instant the call is made so a wire that passed the live object would report the later value. The other is `localPlainPropBag`, the gate on the prop-patch fast path. That fast path reads only own enumerable keys, so it is allowed only for a bag whose prototype is this realm's `Object.prototype` or none — the proof that there is nothing else to read. Decoding props on the receiving thread puts every bag on the permissive side of that gate, where before the wire they carried the sending realm's prototype and never qualified. What has to stay true afterwards is that nothing in a bag's own contents can put it back on the other side. `__proto__` is the case that could. The renderer defines it as data when it composes props and the codec restores it as data when it decodes them; either end using assignment instead makes the object it names the bag's prototype, and the slow path then reads an `id` and a `style` off it and applies them to a node nobody styled. Swapping the codec's `defineProperty` for an assignment produces exactly that: `id: "injected"`, `inlineStyles: "width:99px"`. The test pins the bag ordinary and the patch free of both. Co-Authored-By: Claude <[email protected]> Claude-Session: https://claude.ai/code/session_019RsC3U39kUuLKajZANeTVy
The deterministic wire-cost gates read `event.data` directly, so once the transport encoded, they stopped seeing anything. The failure was silent and looked like a result: `lynx-table` reported every swap message as `<unknown>` with no command ops and a null `wireRegime`, and `lynx-render` skipped every message outright — zero commands, zero acknowledgements — because its guard was `typeof event.data !== 'object'`. Both now decode, the same as the receiver does, which also makes each observer a boundary assertion: a message that reached the wire unencoded throws here rather than being counted. With the observers reading again, every deterministic count matches the base exactly — commands, command ops, message types, render counts, selector installs, and `wireRegime`. The swap byte figures, which are the payload without the envelope, are unchanged to the byte in both directions. The stage harness patches framework sources by string anchor, and two of its anchors were in the lines this branch rewrote. Both are repaired against the current text with their instrumentation intact. Its two hand-written profile literals also needed the new `encodeMs`/`decodeMs` bands: `lynxWireProfile()` returns whichever record already exists, so a literal missing a band left the runtime accumulating onto `undefined`, and the frame snapshot arrived as `NaN` where `analyze.mjs` requires a finite number. That is the hazard the file's own comment warns about, now with two more fields to keep in step. Co-Authored-By: Claude <[email protected]> Claude-Session: https://claude.ai/code/session_019RsC3U39kUuLKajZANeTVy
1 task done
`prepare` recurses, so a cycle is unbounded depth from its point of view and it ran the stack out before `JSON.stringify` could refuse it — a `RangeError` carrying no path, which is a worse diagnostic than the named `TypeError` plain JSON would have produced, and worse than the "contains a cycle" the receive-boundary validator used to give. An on-path `Set` would separate a true cycle from deep nesting, but it costs an add and a delete per composite on the first-screen walk this codec exists to keep cheap. A depth counter costs one integer compare, names the path where it gave up, and is reached only by a payload no receiver could use. `restore` takes the same cap for the same reason: it recurses too, and `JSON.parse` will hand back a structure deeper than the stack. Co-Authored-By: Claude <[email protected]> Claude-Session: https://claude.ai/code/session_019RsC3U39kUuLKajZANeTVy
This was referenced Aug 24, 2026
…rt-json-boundary # Conflicts: # benchmarks/lynx-table/stages/instrument-source.mjs
…order The merge with new-lynx took the lynxWireProfile() single-authority probes, whose anchors predate this branch's transport rewrite; the profiling.ts commands anchor and the two transport selfcheck anchors now match the encoded-dispatch shapes, keeping bytes counted from the wire string the transport actually sends. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YHfFsy9CLaRovTFH8pTGyY
…made - restore() renamed keys in place, so a record carrying both a literal proto-family key and a real __proto__ lost one of them and restored the other twice — the exact round-trip the codec header promises. Rebuilding into a fresh record is order-independent because the escape is injective; red-verified with the adversarial ordering. - lifecycleTuple's dense-tuple/extra-field/symbol/descriptor checks were unreachable after materialization (JSON output is always a dense ordinary array) and read as rigor the boundary already provides; the reachable contract — an exact-length array — stays. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YHfFsy9CLaRovTFH8pTGyY
Huxpro
marked this pull request as ready for review
August 25, 2026 10:10
Huxpro
added a commit
that referenced
this pull request
Aug 27, 2026
…iants The train forked from the pre-#164 baseline, so the merge re-integrates the transport codec and the C-gate fixes into a heavily refactored tree. Textual merging alone reintroduced three behavioral regressions, each caught by a red-verified regression the train's own suite never carried: - The renderer's result literal dropped `programs`, so main-thread's program-decline check read undefined and every direct-apply decline — list defects included — silently declined instead of reaching the staged fallback that reports them. - The announcement walk reverted to table-before-members order, which renumbers member handlers relative to the interpreted arm and routes taps to the wrong listeners. The walk announces in merged pre-order again; the mount's run cursor now skips a member's binding by the block's ascending-id invariant, and the run guard is restated as membership (own bindings claimed) rather than exhaustion. - The comparator's program branch lost the hidden-description refusal; re-grafted after the D2-era ownership comment. D7's lifecycle-marker tests dispatch raw objects; the wire now carries codec text, so they encode with the shared wire() fixture. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YHfFsy9CLaRovTFH8pTGyY
This was referenced Aug 28, 2026
Huxpro
pushed a commit
that referenced
this pull request
Aug 29, 2026
…test wire Two corrections to the merge resolution, caught by the full run: - The react-parity audit records were resolved to the train side, but the sync regenerated them against upstream v0.1.47 — the tree the merge actually contains — so the parity contract tests read stale execution records (tsconfig lanes pointing at pre-sync paths). Restored the sync side for every conflicted audit and restamped lockfileSha256 against the merged lockfile. - The new first-screen wire and compact-ack tests were written against the pre-codec fork base and put raw objects on the ContextProxy; since the transport owns encoding (#164), such a message never decodes and the reply never fires. They now wire/unwire through the shared fixture, and the reply-cost budgets measure the encoded string that actually crosses instead of a re-print. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01YHfFsy9CLaRovTFH8pTGyY
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The first slice of #156: the Lynx transport owns encoding, so nothing live crosses a thread.
Every
ContextProxysend site nowJSON.stringifys and every paired receive siteJSON.parses, which means the receiver is handed its own ordinary local data by construction rather than a composite built on the other thread. On device that composite can arrive as aLEPUS_TAG_LEPUS_REF: reads,Object.keys, spread andJSON.stringifyall work, butReflect.ownKeysthrowsTypeError: not an object,Object(v) !== v, and the prototype isnull. A string cannot be a host-backed reference on any engine, so the invariant — aLynxValueRefnever escapes the transport layer — holds by construction rather than by inspection.Why
Octane's
record()moved fromObject.getOwnPropertyNames(value)toReflect.ownKeys(value)betweenf3c4781dand0fc84da0.ToObject's implicit coercion inside the first had been silently keeping an already-invalid value usable for Octane's entire native lifetime. Nothing about the value changed; the accident that hid it did. Fixing individual reflection sites would just re-hire the same accident under a different name, so the boundary — not the reader — is where this has to be closed.Changes
packages/lynx/src/core/transport-codec.ts(new)LynxValue/LynxValueRef/LynxStructuredValueper #152's naming, plusencodeLynxTransportValue/decodeLynxTransportValue/localizeLynxHostValue. The codec owns the value domain (#156 §3, option b from #152 §8), in the Lynx codec only — the universal command ABI is untouched:undefinedundefinedbigint, non-finite number$[0].count is a bigint)Date,Map, class instanceObject.keys(new Date())is[], so an own-enumerable walk would pass aDatethrough and letJSON.stringifysilently rewrite it as an ISO string__proto__main-renderer.ts's existing precedent, on both encode and decodeat $.self.self nests deeper than 512 levels)__proto__is engine-independent here rather than "whatever thisJSON.parsedoes", andrestore()usesObject.definePropertydeliberately:Object.assign({}, p)goes throughSet, triggers the accessor, and replaces the prototype — measured, not assumed.Sentinel collision safety (gatekeeper addition 1): a payload that literally contains the sentinel encoding round-trips unchanged. The escape is a NUL-prefixed family, and the round-trip is proved over a generator that includes the sentinel strings themselves, nested.
Cycles (commit
488f704e8): the codec's walk is recursive, so a cycle is unbounded depth from its point of view. Without a limit it exhausts the stack — aRangeErrorcarrying no path, which is a worse diagnostic than theTypeErrorplainJSON.stringifywould have produced, and worse than the "contains a cycle" theprotocol.tswalk gives today. Bothprepareandrestorecarry a depth counter capped at 512. An on-pathSetwould distinguish a true cycle from deep nesting, but it costs an add and a delete per composite on the first-screen path — the one walk this codec exists to keep cheap — where an integer compare costs nothing and still names where it gave up. Nothing Octane sends nests past single digits; 500 levels round-trips, 512 is refused.This one was surfaced by slice 2 rather than by inspection: deleting
protocol.ts'sseencycleSetleft the codec as the only thing standing between a cyclic payload and the stack, and it was not standing.The four send sites and their receivers
core/transport.ts×3 (background→main) andmain-thread.ts×1 (main→background).context.dispatchEventappears exactly four times insrc, so everycommit,call-main,call-background,call-*-result,call-*-error,cancel-*andterminal-disposeis encoded.core/background-lifecycle.tsshares the main→background channel with the transport's own receiver, so it decodes independently and stays silent on a payload it cannot read rather than doubling every diagnostic on the channel.The engine lifecycle entry (gatekeeper ruling, separate commit
67ddb6a23)__RenderPage/__UpdatePage/__UpdateGlobalPropsarrive on the sameContextProxymachinery, but their sender is the native engine, which cannot be asked to encode. They are the one inbound payload nobody encoded, and the invariant would be false with that entry open.lifecycleTuple— the single funnel for all three — now materializes throughlocalizeLynxHostValuebefore anything reflects on the record.Materializing through the codec rather than a bare
JSON.parse(JSON.stringify(v))is deliberate: one value domain,undefinedpreserved (matching whatcloneLifecycleValuealready did),__proto__engine-independent, and — decisively — abigintis named at the entry instead of throwing later at the send site that would have carried it, whereterminateLifecycleDeliveryturns a throw intoonNativeDestroy(), tearing down the whole page lifetime. One dropped record with a diagnostic, not a dead page.The conformance transport (the gate)
tests/_fixtures/lynx-wire.tswraps aContextProxyso that nothing can cross it except this codec's output. The pinned proposition is platform-independent — the transport hands the receiver only receiver-local ordinary values — not "Reflect.ownKeysthrows", which is one engine's symptom, reproducible only on a device, and a harness that simulated it would be asserting the symptom rather than the rule.tests/transport-conformance.test.tsruns both halves:dispatchEventsend sites, each encoding; exactly fourevent.datareads, each as the direct argument to a materializer. A fifth site, or a dropped encode, is what this notices. (Comment lines are dropped whole — a trailing comment on a code line is still scanned, the conservative direction.)The whole
--project lynxsuite runs through the conforming proxy via the shared fixture, so the boundary is asserted by most of the suite rather than by one test.Regressions asked for by #156 §2, §4 and §5
__proto__on encode and decode, red-verified both directions.runOnBackground's main→background args do ride themain-thread.tssend site (callBackground→sendBackgroundCall→dispatch);runOnMainThreadridestransport.callMain→dispatch. Pinned end to end inthread-calls.test.tswith a mutation-after-send to prove the argument was snapshotted, in both directions.localPlainPropBag(core/host-props.ts:470): a decoded bag stays ordinary, so an injected__proto__carryingid/stylelands as an attribute and never becomes a channel. Red-verified against the realistic break —restore()using assignment instead ofdefineProperty— which producesid: "injected"andwidth:99pxon a node nobody styled.Benchmark harnesses
benchmarks/lynx-table/workload.tsandbenchmarks/lynx-render/workload.tsreadevent.datadirectly and were silently blinded by the encode:wireRegime: null, every message typed<unknown>,commandOps: {}, and byte counts inflated by JSON string escaping — a measurement that looks like a result. Both now decode the same way the receiver does.stages/instrument-source.mjsanchors were repaired against the rewritten lines, and its two hand-written profile literals gainedencodeMs/decodeMs(without them,profile.decodeMs += xproducesNaN— exactly the hazard that file's own comment warns about).Wire measurement
Base
6bf6703a4vs. head, same window, deterministic gates only:wireRegime,messageTypes,commandOps, command counts, render counts and selector installs are identical to base. The payload is byte-identical to the message's own JSON; encoding adds a constant 4-byte envelope per message, and nothing in these workloads needed escaping (the flag stays0). At 10k create that is 0.0012%.Absolute byte counts are deterministic and comparable here; no wall-clock number is reported, per
benchmarks/lynx-table/README.md.Validation
pnpm format:check— clean.pnpm typecheck— clean (all 276 workspace projects).pnpm test— 21,179 passed, 5 failed, 74 skipped across 2,210 files. Every failure is accounted for below; none is inpackages/lynx, and none is caused by this diff.--project lynx— 40 files, 573 tests, all green.tsrx-tsc --noEmitclean forpackages/lynx/tsconfig.jsonandtsconfig.testing.json.pnpm syncclean.The ten failing files in the full run
The container has 4 CPUs and the root Vitest run fans out to 15 workers, so the
browser, SSR and bundler suites time out under contention. Each failure was
classified by re-running it, not by inspection:
website/tests/ssr-hydration.e2e.test.ts(2 suites)website vite build did not finish within 300000mswebsite/tests/ssr-smoke.test.tspackages/octane/tests/react-hosted/web3-island.test.tsbeforeAllhook timed out at 10 s building a hydration fixturepackages/aria/tests/hydration.test.tspackages/aria/tests/package-boundary.test.tspackages/adapter-vercel/tests/adapt.test.tspackages/dropzone/tests/probes/hydration.test.ts6bf6703a4packages/octane/tests/browser/suspense-hydration/suspense-hydration.test.tspackages/drei/tests/browser/upstream-e2e.browser.test.tspackages/rspeedy-plugin-octane/tests/native-demo.test.tsNone of the ten imports
@octanejs/lynx. (website/tests/ssr-smoke.test.tsmentions
bench-lynx, which is a DOM id on a benchmark page, and that testnever reached the assertion.) Every failure is a timeout; not one is an
assertion about behavior this diff changes.
Red-verified regressions
Each was seen failing and then restored:
localizeLynxHostValue(event.data)→event.data— both lifecycle tests fail; thebigintcase reportspage-destroyinstead ofpage-data.event.datarule fails.main-thread.tsdispatchstops encoding — 3 of 4 conformance tests fail.transport.tsplain-branchdispatchstops encoding — the worklet test fails on the strict wire's type guard.localizeLynxHostValuereturnsvalue— the disjointness test fails.restore()uses assignment instead ofdefineProperty— the prop-bag test fails.MAX_PREPARE_DEPTHraised to1_000_000— the cycle test fails withMaximum call stack size exceededinstead of the named path, which is exactly the diagnostic the guard exists to prevent.Risk / follow-ups
validation: 'checked' | 'trusted', deleting the hostile-object integrity walk fromprotocol.ts— that walk exists to survive a hostile composite, and after this slice the receiver never sees one. It is started without waiting for this to merge.core: 'block' | 'universal'switch.checkedmode should not re-derive v2's own shape checks.benchmarks/lynx-table/web/driver-client.mjsinstruments web-core's ownMessagePort, not Octane'sContextProxy, and its genericsizeOfcounts a string payload in JSON-escaped form. ReactLynx and VueLynx also shipJSON.stringifypayloads (Root cause: the Lynx ContextProxy is a string-only channel; Octane sends live JS values #152), so all three are counted the same way — but the absolute web numbers are inflated for every framework and should not be compared to the native byte counts above.background-lifecycle.tsdecodes a second time on the main→background channel. That is one extraJSON.parseper inbound message, not per node, on the light direction; a follow-up can share one decode if measurement ever shows it matters.encodeLynxNativeEventTokenis now callerless — filed as a separate cleanup rather than widened into this diff.mainport is a follow-up, per Lynx transport: receiver-local JSON values, checked|trusted validation, conformance transport #156.Provenance
agent-authored)