Skip to content

Root cause: the Lynx ContextProxy is a string-only channel; Octane sends live JS values #152

Open

Description

@Huxpro

Root-cause record and fix plan for the native failure investigated in #147 and measured in #149. This issue is the authoritative version; #149 holds the device evidence and #147 holds the surrounding performance and design questions, several of which this resolves.

1. The constraint

Stated authoritatively by the owner, and now the premise of everything below:

The Lynx BTS↔MTS boundary is not only cross-realm, it may also be cross-engine. ContextProxy must therefore be treated as a string-only channel. Whether the string is produced by JSON or by a structured-clone-based codec is an implementation detail.

2. What Octane does

Four call sites hand the ContextProxy a live JS object:

// packages/lynx/src/core/transport.ts:338, :345, :672   (background → main)
// packages/lynx/src/main-thread.ts:659                  (main → background)
context.dispatchEvent({ type: LYNX_BACKGROUND_TO_MAIN_EVENT, data: validated });

The receiving side then interrogates the shape of whatever arrived: main-thread.ts:2489 calls validateLynxBackgroundOutboundMessage(event.data), and packages/lynx/src/core/protocol.ts — 1,988 lines, two exported validators — walks the batch with Reflect.ownKeys, Object.getOwnPropertyDescriptor and Object.getPrototypeOf.

3. This is a contract violation, not a bug — and that reframes #149's bisect

If the channel is string-only, passing an object is not "slow" or "fragile"; it is outside the contract, and what arrives is unspecified. It is undefined behaviour that had not yet been observed.

Therefore octanejs#693 is not the cause. octanejs#693 is the commit that made an existing latent violation observable, by deepening the reflection until the undefined behaviour surfaced. In protocol.ts between f3c4781d and 0fc84da0:

operation before after
Reflect.ownKeys 0 4
Object.getOwnPropertyDescriptor 2 5
Object.getPrototypeOf 0 2

The probe output in #149 confirms the shape of the failure precisely. The message arrives: typeof === "object", ctor === "Object", Object.keys().length === 4. What fails is the inspection, and the error is bare — TypeError: not an object — while every Octane rejection is prefixed (protocol.ts:450):

throw new TypeError(`Octane Lynx transport ${composePath(label, index, field)}: ${message}`);

The validator did not reject the message. The validator crashed while inspecting it, and the throw is the engine's.

Consequence for the fix: reverting or patching octanejs#693 would only restore the "works by luck" state. It is not the fix.

4. The causal chain

Real constraint: ContextProxy is a string-only channel (cross-realm + cross-engine)
        ↓
Octane sends live JS values  ←  a violation from inception; simply had not bitten
        ↓
No environment can observe it — three environments, three different reasons:
  · jsdom                 both threads in one realm; no boundary at all
  · Lynx for Web          cross-realm, but MessageChannel/structured clone
                          re-instantiates in the RECEIVING realm → a local value
  · in-process ContextProxy   one realm
        ↓
#660 (f3c4781d) fixes prototype-identity tests, and records a justification
     that is wrong for the Web path (see §6)
        ↓
#693 deepens reflection under the belief that "cross-realm is handled"
        ↓
Native crash: bare engine `TypeError: not an object`

Every step is a locally reasonable decision. The defect is that a wrong premise was frozen into a comment in the middle of the chain.

5. Why Lynx for Web cannot catch this — and why a Worker-based test cannot either

Cross-realm is a property of the topology; "foreign value" is a property of the marshalling. Structured clone is precisely the mechanism that turns a cross-realm topology into local values: StructuredDeserialize takes a target realm and builds the result with the receiving realm's intrinsics.

topology marshalling value on arrival reflection
Lynx for Web cross-realm MessageChannel → structured clone rebuilt locally ✅ valid
Lynx native cross-realm + cross-engine ContextProxy, no reconstruction foreign ❌ invalid

The Web path is confirmed empirically, not assumed: Huxpro/lynx-js-framework-benchmark docs/METHODOLOGY.md records that on Lynx for Web every BTS↔MTS message crosses one MessageChannel driven by @lynx-js/web-worker-rpc, and its instrument patches MessagePort.prototype.postMessage and the onmessage setter to observe it. protocol.ts:28 notes the native side is the other case: "Named ContextProxy events; this protocol never falls back to postMessage." On Web, web-core happens to implement ContextProxy over MessageChannel, so Octane gets structured-clone semantics for free.

This invalidates an earlier recommendation of mine. A test harness built on a real Worker or a node:vm context would also pass, because postMessage clones and rebuilds locally. No realm-based test can catch this.

The correct gate is a string-only channel conformance transport: a test transport that accepts only strings and fails any attempt to deliver a live object. It encodes the actual contract, and it runs anywhere — including jsdom. It also surfaces the value-domain problem in §7.2 immediately rather than on a device.

6. The comment that became load-bearing

packages/lynx/src/core/plain-object.ts, added by f3c4781d (octanejs#660), states:

on Lynx for Web the background is its own iframe/worker — so a value built on one thread … is a plain object whose prototype is that realm's Object.prototype, never identical to this realm's

This is wrong for a postMessage/MessageChannel path. After StructuredDeserialize the prototype is the receiving realm's Object.prototype, and the identity test passes.

The helper it introduced (hasCrossRealmPlainPrototype, mirrored at universal-core.ts:4211) is harmless and strictly more robust, so the code is fine. The recorded reasoning is what caused harm: it told the team that cross-realm was handled, when the real native constraint is much stronger — the value is not a live local object at all. Three days later octanejs#693 deepened the reflection on that basis.

The fix's changeset should carry §4's chain rather than "octanejs#693 introduced a regression".

7. Severity

dimension assessment
correctness Production native is broken today on upstream/main and on new-lynx. Not slow — broken.
blast radius Everything on this channel: commit batches, acknowledgements, events, first-screen adoption announcements, and worklet runOnBackground/runOnMainThread arguments — all share the same two event types.
detectability Zero. See §5. The test suite cannot fail on it, ever.
not affected Everything above the transport. Plan/slot representation, template-run compaction and destroy-run all measure best-in-class (#147 §3).
locality Two dispatchEvent call sites and two receive handlers.

High severity, low complexity, well localized.

8. Fix — upstream

Order matters: step 1 makes steps 3 and 4 possible.

7.1 Step 1 — the transport owns the encoding

Serialize on send and deserialize on receive, inside transport.ts and main-thread.ts. Not a patch at the call sites — a layer boundary: everything above the transport keeps working with live objects, and the transport is the only thing that knows the channel carries strings.

The load-bearing property: JSON.parse output is by construction local-realm plain data — no accessors, no proxies, no symbols, no class instances, no foreign prototypes. This one change restores the invariant the entire validator was written against, which is exactly why the benchmark's entries/_patches/octane-bench.patch appeared to "fix" the problem.

Caveat to encode in a test: JSON.parse('{"__proto__": …}') creates an own data property named __proto__ rather than assigning a prototype — so it is not prototype pollution, but a downstream Object.assign/spread of a parsed record would promote it. Either strip __proto__ in a reviver, or keep reading parsed records by explicit key.

7.2 Step 2 — fix the value domain

universal-core.ts:380:

UniversalSerializableValue =
  null | undefined | string | number | bigint | boolean | readonly V[] | Readonly<Record<string, V>>

undefined and bigint cannot round-trip JSON ({a: undefined} → {}; [undefined] → [null]; JSON.stringify(1n) throws). Three options:

  • (a) narrow the domain to JSON-safe — cleanest, but a breaking change to the universal ABI;
  • (b) define explicit sentinels in the Lynx transport codec only — keeps the universal ABI unchanged and localises the concession to the platform that needs it;
  • (c) keep the domain and make the encoding pluggable, requiring each codec to declare the domain it supports.

Recommend (b). @octanejs/three is not transported (packages/three/src/core/driver.ts mentions transport only to reject it), so there is no reason to change the universal ABI for this.

Decide aliasing in the same step: cloneSerializableValue rejects cycles but permits DAG sharing (seen.delete(value) in the finally), and JSON expands shared references into copies. sameUniversalHostPropValue has a structural fallback so expansion is probably safe, but it should be an explicit decision with a test, not a silent consequence.

7.3 Step 3 — delete most of the validator

Once step 1 lands, the whole integrity class of validation is provably unnecessary: parsed data cannot contain accessors, proxies, symbols, or foreign prototypes. What remains is schema validation — right op, right arity, right ranges — which is cheap and structural.

A large fraction of protocol.ts's 1,988 lines exists to defend against value shapes JSON.parse cannot produce. Removing it is simultaneously:

The send side has the mirror-image win. cloneSerializableValue (universal-core.ts:6761, 5 call sites) deep-clones into fresh frozen local objects on every render of a transported root. Once the transport serialises, serialisation is the clone. Today the path is:

deep clone → freeze → serialize → parse → deep validate     ← four full traversals of one payload

It can be two: validate while serialising, then schema-check the parsed frame.

Whether this accounts for any of the unexplained device cost in #147 §2 must be measured, not assumed — those numbers were taken with the violation present.

7.4 Step 4 — a string-only conformance transport

Per §5, replacing my earlier Worker/vm suggestion. A test transport that accepts only strings, refuses live objects, and is used by the transport conformance suite. Add a lint rule forbidding reflection on values arriving from the transport.

Without this, step 1's fix erodes: octanejs#660 fixed one layer and octanejs#693 reintroduced the class three days later, not through carelessness but because nothing could catch it.

9. Adjustments for new-lynx

9.1 It inherits the violation and does not fix it. Verified at 62b2631a: transport.ts:338/345/672 still pass objects; main-thread.ts:2492 still revalidates the whole batch reflectively. U1 §7 of #103 keeps both in the shared half, so new-lynx must either take upstream's step 1 or do it itself.

9.2 delta-protocol.ts v2 is already correct by construction. Verified:

check v2
value domain LynxDeltaValue = string | number | boolean | null — already JSON-safe; step 2 is a no-op for v2
value check isLynxDeltaValue — its own comment: "One typeof, never a walk — a hostile getter is never reached."
decoder one Array.isArray, then index-based reads. Zero reflection.

A design justified on wire-cost grounds turns out to be the correctness answer as well. This upgrades v2 on #103 from "performance optimisation" to "the shape the platform requires".

9.3 U1 §7 needs one added sentence. "Replace the background half only" was chosen so the differential test could compare two cores through a shared applier — still a good reason. But the thing that broke shipping lives in the shared half. §7 should state that the shared half has an owner and a correctness contract, not merely that it is shared. Concretely: land step 1 in the shared half before the Block core, so both cores inherit it and the differential test compares two correct cores rather than two broken ones.

9.4 Take the bridge, not the leapfrog. v2 is profiling-only today (deltaCommits/deltaMisses in core/profiling.ts); protocol.ts is what runs. Having v2 take over the wire is a much larger change and should not sit on the critical path of a correctness fix.

9.5 Re-take the device numbers. create@1000 = 12,193 ms was measured at 0fc84da0 with the violation present, through a benchmark patch that worked around it. After step 1 those numbers mean something different. The superlinearity (12.2 s → 103.4 s for 3× the rows) may or may not survive, and it remains unexplained either way.

10. Also in scope, smaller

#693 introduced a second, independent realm-unsafe check that is still live on upstream/main and new-lynx — localPlainPropBag (host-props.ts:430 at the pin, :470 on new-lynx):

const prototype = Object.getPrototypeOf(value);
return prototype === null || prototype === Object.prototype;   // identity test

Every other site in the same commit uses hasCrossRealmPlainPrototype. It gates the class-only prop-patch fast path, so cross-realm it returns false and the optimisation silently never fires. Not a crash — a silent performance loss. After step 1 it becomes correct by accident; it should still be fixed, because the fast path should not depend on the transport's encoding.

11. Evidence status

Verified in source or by the #149 device run: the four dispatchEvent sites; the reflection growth in protocol.ts; fail()'s message prefix; the probe's bare TypeError; the bisect (f3c4781d good, #693 first bad); plain-object.ts's content and origin commit; the Web path being MessageChannel; UniversalSerializableValue's domain; cloneSerializableValue's behaviour and call-site count; v2's value domain, value check and decoder; structuredClone appearing in config.ts's forbiddenGlobals; localPlainPropBag's form and call site.

Inference, not measurement: which specific reflective call throws on device. #149's follow-up (labelled try/catch around each new call site, one device cell) would name the line. The fix does not depend on it, but the regression test does.

Not verified: whether the worklet argument path (runOnBackground / runOnMainThread) is string-safe. It uses the same two event types, so it is in the blast radius, but nobody has checked it. Step 1 is incomplete until someone does.

12. Relationship to other issues

Provenance

  • An agent produced this analysis (agent-authored)

Activity

  1. added
    bug
    on Aug 24, 2026
  2. Huxpro commented on Aug 24, 2026

    @Huxpro
    OwnerAuthor

    Mechanism closed on iOS — and one caveat that narrows the claim

    The #149 follow-up probe ran on iOS 18.5 Simulator and closes §11's open item ("which specific reflective call throws"). It also surfaces a platform caveat that changes what may be concluded from it.

    What the probe established

    On the value delivered to the main thread by ContextProxy:

    operation result
    typeof v "object"
    Object.prototype.toString.call(v) [object Object]
    Object.getPrototypeOf(v) null
    Object.getOwnPropertyNames(v) succeeds
    Reflect.ownKeys(v) throws TypeError: not an object, at the top level ($)

    Control: a local Object.create(null) accepts Reflect.ownKeys normally, so a null prototype is not the discriminator. Main-thread runtime identified as LepusNG 2.3.0 (PrimJS/QuickJS lineage). The value is a ContextProxy bridge exotic value.

    The chain, with the exact operation named

    The only operation that changed on the top-level message between the good and bad commits is in record():

    // f3c4781d (good)
    for (const key of Object.getOwnPropertyNames(value)) {
    // 0fc84da0 (bad)
    for (const key of Reflect.ownKeys(value)) {

    Per spec, Object.getOwnPropertyNames(O) performs ToObject(O) — it coerces; Reflect.ownKeys(target) throws if target is not an Object — it does not coerce.

    So ToObject's implicit coercion was load-bearing for Octane's entire native lifetime, and nobody knew. octanejs#693 did not introduce a defect; it replaced a coercing API with a non-coercing one, removing the accident that had been keeping an already-invalid value usable.

    Everything before that in record() — typeof, Array.isArray, and hasCrossRealmPlainPrototype's double getPrototypeOf — already existed at f3c4781d and passes on device, so none of them is implicated.

    Two corrections to this issue's text

    1. plain-object.ts's comment is wrong about both targets, not just Web. §6 recorded that it is wrong for Lynx for Web (values arrive locally reconstructed, carrying the local Object.prototype). The probe shows it is also wrong for native: the value arrives with a null prototype. Neither target matches the comment's claim of "that realm's Object.prototype". The file's rationale should be replaced outright rather than amended.

    A consequence worth recording: hasCrossRealmPlainPrototype passes on native for the wrong reason — via its prototype === null short-circuit. The guard octanejs#660 added is not protecting anything there; it is accidentally permissive. That is latent fragility independent of this fix.

    2. Retracting a stronger claim I was about to make. I had concluded from the probe that the bridge value "is not a spec-conformant JS object", making this a value-level conformance issue rather than an API-contract issue. That is not supported, because of the caveat below.

    The caveat: the probe ran on the one platform that polyfills Reflect

    Lynx's scripting-runtime documentation states verbatim: "Only injects polyfills on iOS." Reflect appears in that iOS-only polyfill list. (The docs I could read were not consistent about exactly which Reflect methods are listed, so treat "Reflect.ownKeys specifically is polyfilled" as unconfirmed.)

    The probe ran on iOS. So the throw may come from a JS polyfill's guard, not from the engine's object model. A common polyfill shape is:

    if (Object(target) !== target) throw new TypeError('not an object');

    which would throw exactly here if ToObject on the bridge value returns a new wrapper rather than the value itself — and that single hypothesis explains all three observations at once (typeof passes, getOwnPropertyNames succeeds by reading the wrapper, Reflect.ownKeys throws on the identity comparison).

    If that is what is happening, the Lynx-side defect is far narrower and more fixable than "the bridge value is non-conformant": it is the iOS Reflect polyfill's IsObject guard rejecting bridge values.

    What this does and does not change

    Does not change the fix. Whether the throw originates in a polyfill or in the engine, the root cause is unchanged: Octane hands a bridge exotic value to code that reflects on it, over a channel the platform owner has stated is string-only. §8 step 1 fixes it either way — after JSON.parse the value is an ordinary local object and both native and polyfilled Reflect work on it. Steps 2–4 are unaffected.

    Does change two things. §7's severity table said the blast radius covers everything on the channel; that stands. But:

    Two cheap follow-ups, both one line

    1. On iOS, log Function.prototype.toString.call(Reflect.ownKeys). [native code] versus readable JS settles polyfill-versus-engine immediately, and if it is the polyfill its guard can be read directly. Also log Object(v) === v on the arriving value — that tests the hypothesis above outright.
    2. On Android, run Device verification: what actually happens to an object payload at the Lynx ContextProxy boundary #149 Step 1a's unpatched cell that was skipped. It answers whether the mechanism is platform-specific.

    Neither blocks the fix. Both belong in the regression test that ships with it, because a test that pins "the transport never hands a live object to the receiver" is platform-independent, while one that pins "Reflect.ownKeys throws" would only be true on iOS.

    Provenance

    • An agent produced this analysis (agent-authored)

    Generated by Claude Code

  3. Huxpro commented on Aug 24, 2026

    @Huxpro
    OwnerAuthor

    Probe complete on both iOS and Android. Cross-reference: the original regression probe and bisect are in #149, especially #149 (comment).

    Bottom line

    ContextProxy does not deliver an ordinary receiver-realm JavaScript object here. It delivers a PrimJS/LepusNG LEPUS_TAG_LEPUS_REF backed by a Lynx Dictionary/CArray. PrimJS presents that value as typeof === "object" and implements property access, enumeration, identity, coercion, and JSON through bespoke hooks, but its native Reflect.ownKeys accepts only the ordinary LEPUS_TAG_OBJECT tag.

    That closes the #149 failure chain:

    Object.getOwnPropertyNames(event.data) => succeeds
    Reflect.ownKeys(event.data)            => throws TypeError: not an object
    

    This is not iOS-only and is not caused by Octane validation. It reproduces identically on Android. The standards-coverage gap is in PrimJS/LepusNG's handling of LEPUS_REF at the Reflect.ownKeys boundary.

    Cells / provenance

    iOS

    • iPhone17,1 Simulator, iOS 18.5 (device identifier omitted)
    • Lynx Explorer 3.9.0 release, com.lynx.LynxExplorer, app version 1.0 (1), DevTool SDK 1.4.0
    • runtime globals: LepusNG 2.3.0; typeof lepusng_gc === "function"
    • Octane 0fc84da02fd05403ac5e36d2aff631b31168d5ac
    • rspeedy 0.16.0 / Rsbuild 2.1.4 / Rspack 2.1.4, dev mode, NODE_ENV unset, no JSON patch
    • diagnostic bundle SHA-256: bbfa21661c8a2d573041fb456859cd39cfed087ad938766d9f339310794da350
    • timing: not measured

    Android

    • leased physical device aries_10, Android 10 (internal device identifier omitted)
    • Lynx Explorer com.lynx.explorer, versionName 1.0 / versionCode 1
    • runtime globals: LepusNG 2.3.0; typeof lepusng_gc === "function"
    • same Octane and rspeedy/Rsbuild/Rspack versions, no JSON patch
    • diagnostic bundle SHA-256: 55fe6c008a97384130acdd8f026aeff269972d9d5105ba7b9af8c02420b11a14
    • timing: not measured

    The exact PrimJS commit embedded in either Explorer binary was not measured. The source analysis below uses Lynx tag 3.9.0 plus the current public PrimJS source whose control flow and exact error text match the observed runtime.

    A. Required top-level probe, verbatim results

    The actual unpatched main-ready-request value reached the inbound handler as:

    {"protocol":1,"renderer":"lynx","type":"main-ready-request","request":8796093022209}

    The key iOS results (Android was identical) were:

    Function.prototype.toString.call(Reflect.ownKeys) = function ownKeys() {
        [native code]
    }
    Function.prototype.toString.call(Object.getOwnPropertyNames) = function getOwnPropertyNames() {
        [native code]
    }
    Reflect.ownKeys({a:1}) = ["a"]
    Object(v) === v = false
    v === v = true
    v instanceof Object = false
    typeof v = object
    Object.prototype.toString.call(v) = [object Object]
    String(v) = [object Object]
    Array.isArray(v) = false
    Object.getPrototypeOf(v) = null
    Object.getPrototypeOf(Object.getPrototypeOf(v)) throws TypeError: not an object
    Object.keys(v) = ["protocol","renderer","type","request"]
    Object.getOwnPropertyNames(v) = ["protocol","renderer","type","request"]
    Reflect.ownKeys(v) throws TypeError: not an object
    Object.getOwnPropertySymbols(v) = []
    

    The first failing value path is $, i.e. the top-level event.data itself. The second getPrototypeOf failure is expected because the first result is null; it is not the #149 failure.

    Additional cells on the same value all succeeded: for...in, Object.prototype.hasOwnProperty.call, key in v, bracket read, dot read, destructuring, spread, Object.assign, property descriptor lookup, and JSON.stringify.

    Therefore the requested direct answers are:

    • a. Yes. Reflect.ownKeys throws exactly TypeError: not an object.
    • b. Yes. Object.getOwnPropertyNames succeeds on the same value.
    • c. The first failure is at the top level, path $.
    • d. At that node: typeof is object, toString is [object Object], and String is [object Object].
    • e. The main-thread engine identifies itself as LepusNG 2.3.0; both probed built-ins report [native code].

    B/C. Nested capability matrix

    The real validator fails on the first top-level main-ready-request, so an actual commit cannot proceed far enough to supply nested values. To test recursive bridge behavior without normalizing the wire or bypassing validation, I sent a diagnostic-only nested payload from the background side through the same ContextProxy channel, before ready, then let the unchanged validator run.

    Payload shape:

    {
      probe: 'nested-context-proxy-value',
      commands: [{ props: { title: 'card', nested: { enabled: true } } }],
      array: [{ value: 1 }, [2, { value: 3 }]],
      nullPrototype: Object.assign(Object.create(null), { child: { value: 4 } }),
    }

    Each platform produced 269 parsed probe entries for the first sequence. The visited object/array paths were:

    $
    $.commands
    $.commands[0]
    $.commands[0].props
    $.commands[0].props.nested
    $.array
    $.array[0]
    $.array[1]
    $.array[1][1]
    $.nullPrototype
    $.nullPrototype.child
    

    For every object/array node on both platforms:

    • Object(v) === v was false; v === v was true; v instanceof Object was false.
    • Object.getPrototypeOf(v) was null.
    • Object.getOwnPropertyNames(v) succeeded.
    • Reflect.ownKeys(v) threw exactly TypeError: not an object.
    • JSON.stringify(v) succeeded recursively.
    • reads, in, hasOwnProperty.call, descriptors, for...in, spread, and Object.assign succeeded.
    • object tags were [object Object]; array tags were [object Array], and Array.isArray was true.

    Representative exact node, $.commands[0].props:

    Object(v) === v = false
    v === v = true
    v instanceof Object = false
    typeof v = object
    Object.prototype.toString.call(v) = [object Object]
    String(v) = [object Object]
    Array.isArray(v) = false
    Object.getPrototypeOf(v) = null
    Object.getPrototypeOf(Object.getPrototypeOf(v)) throws TypeError: not an object
    Object.keys(v) = ["title","nested"]
    Object.getOwnPropertyNames(v) = ["title","nested"]
    Reflect.ownKeys(v) throws TypeError: not an object
    Object.getOwnPropertySymbols(v) = []
    for...in = ["title","nested"]
    Object.prototype.isPrototypeOf.call(Object.prototype, v) = false
    Object.getOwnPropertyDescriptor(v, "title") = {"value":"card","writable":true,"enumerable":true,"configurable":true}
    Object.prototype.hasOwnProperty.call(v, "title") = true
    "title" in v = true
    v["title"] = card
    v.type = undefined
    ({type} = v).type = undefined
    Object.keys({...v}) = ["title","nested"]
    Object.keys(Object.assign({}, v)) = ["title","nested"]
    JSON.stringify(v) = {"title":"card","nested":{"enabled":true}}
    

    One further nonstandard measured result: Object.getOwnPropertySymbols on bridged arrays, mapped through String, returned numeric-looking values such as ["0"] or ["0","1"] rather than symbols.

    Mutation cells requested for v.__probe = 1/readback and Object.freeze(v) are not measured. The device safety gate rejected mutating/freezing a live captured bridge value after handler return, so I am not substituting inferred results.

    D. Source-level cause and contract

    The source chain is explicit:

    1. Lynx 3.9 ContextProxyInLepus::CreateMessageEvent stores the message as ValueImplLepus: context_proxy_in_lepus.cc L26-L32.
    2. The listener exposes ConvertValueToLepusValue(*message_event->message()) as event.data: lepus_event_listener.cc L51-L60.
    3. DispatchEvent requires the event object/type/data fields, but does not require data to be a string: renderer_functions.cc L1336-L1364. PostMessage likewise transports a generic converted value.
    4. Lynx's QuickContext callbacks read a Dictionary/CArray from LEPUS_REF: quick_context.cc L143-L170, and its conversion callback can materialize ordinary JS objects/arrays: quick_context.cc L223-L248.
    5. In public PrimJS source, LEPUS_REF is a distinct tag; the ordinary-object predicate recognizes only LEPUS_TAG_OBJECT: quickjs.h L557-L563.
    6. Property reads route LEPUS_REF through Lynx callbacks (quickjs.cc L2141-L2187, L7312-L7328); typeof explicitly reports object (L12476-L12491); and Object(v) converts via LEPUS_ToObject (L32713-L32722). This explains Object(v) !== v.
    7. Object.getOwnPropertyNames calls LEPUS_ToObject before enumeration: quickjs.cc L33153-L33243.
    8. JSON.stringify has explicit recursive LEPUS_REF table/array handling: quickjs.cc L41477-L41488, L42389-L42400.
    9. In contrast, native Reflect.ownKeys immediately applies LEPUS_VALUE_IS_NOT_OBJECT(argv[0]) and throws before conversion/enumeration: quickjs.cc L43018-L43025.

    So this is not an ordinary object from a foreign realm, and not an ECMAScript exotic object backed by a JS class. It is a parallel engine tag with operation-specific host hooks. The observed typeof, identity, prototype, coercion, enumeration, JSON, and Reflect behavior follows directly from those separate paths.

    E/F. Wire and ownership conclusions

    • Raw-object wire: not engine-independent. It exposes the receiver to whichever subset of object semantics that engine implemented for LEPUS_REF.
    • JSON string wire + receiver-side parse: supported by the evidence as the robust boundary when the consumer needs ordinary receiver-realm JS object semantics. PrimJS already has dedicated recursive JSON support for LEPUS_REF, while parsing materializes local objects. This is a design conclusion, not an Octane patch proposal here.
    • ContextProxy contract: no source evidence of a string-only contract. The API transports generic lepus::Value, with explicit table/array support. Delivering LEPUS_REF appears to be an intended representation; exposing it as an object while native Reflect.ownKeys rejects it is the PrimJS/LepusNG bug/incompleteness.
    • Platform scope: reproduced on iOS and Android; not an Apple-JS-engine issue.
    • Polyfill phase: skipped because both Reflect.ownKeys and Object.getOwnPropertyNames are native built-ins.
    • History: public PrimJS history is squashed far enough that both the LEPUS_REF JSON special case and current Reflect.ownKeys guard are already present in the first public commit. The original motivation/order is therefore not established; inferring that the JSON path was added specifically for this exact ContextProxy case would overstate the evidence.

    No Octane product files or PR were created for this investigation.

  4. Huxpro commented on Aug 24, 2026

    @Huxpro
    OwnerAuthor

    Decision record: Lynx value semantics, Octane transport choices, and React/Vue benchmark

    This comment consolidates the two probes above with the follow-up source audit and native A/B. It also corrects the issue title/body's original premise: there is no source evidence that ContextProxy is a string-only API. It transports generic Lynx values. The actual constraint is that a composite value may arrive in LepusNG as LEPUS_TAG_LEPUS_REF, which is not an ordinary receiver-realm JavaScript object and does not implement every ordinary-object operation.

    1. What Lynx supports today

    The value layers are:

    lynx_value                 16-byte C ABI tagged value carrier
        ↑ wrapped by
    lepus::Value / LynxValue   runtime-specific ownership, env/ref lifetime, and operations
        ↑ abstracted by
    pub::Value                 backend-neutral facade (Lepus/Piper/NAPI/Java/Darwin/...)
    

    lepus::Value contains lynx_value value_, lynx_api_env env_, and lynx_value_ref value_ref_; public C++ lynx::pub::LynxValue also wraps a lynx_value. This direction is intentional: making the C ABI contain a C++ Lepus value would couple the ABI to C++ layout, destructors, and one runtime backend. Historically, lepus::Value also predates lynx_value; it adopted the C carrier later.

    JSI does define a precise HostObject, and ContextProxyInJS : public HostObject. The delivered event.data is not itself a JSI HostObject. On the Piper side it is carried by a ValueImplPiper; after conversion into LepusNG, tables/arrays can surface as the separate engine tag LEPUS_REF. The most accurate description is host-backed / engine-backed value, not JSI HostObject.

    The iOS and Android probes produced the same capability matrix for bridged object/array nodes:

    operation on LEPUS_REF result
    typeof, toString, String object-like; succeeds
    Array.isArray distinguishes bridged arrays
    Object.getPrototypeOf returns null
    bracket/dot read, in, hasOwnProperty.call succeeds
    Object.keys, for...in, descriptors succeeds
    Object.getOwnPropertyNames succeeds
    spread, Object.assign, destructuring succeeds
    JSON.stringify succeeds recursively through dedicated LEPUS_REF handling
    Reflect.ownKeys throws exactly TypeError: not an object
    Object(v) === v false
    v instanceof Object false
    Object.getOwnPropertySymbols on arrays nonstandard numeric-looking results were observed
    mutation / freezing not measured

    Therefore:

    • Raw generic-value transport is supported by Lynx, but it does not promise ordinary ECMAScript object semantics on the receiving engine.
    • Passing such a value to code that expects a receiver-local ordinary object is unsafe even when basic reads and JSON work.
    • Ordinary-object semantics require an explicit materialization boundary: today JSON stringify/parse is the proven path; a future receiver-local structured-clone codec could provide the same property.
    • The failure in Device verification: what actually happens to an object payload at the Lynx ContextProxy boundary #149 is specifically the replacement of coercing Object.getOwnPropertyNames with non-coercing Reflect.ownKeys, exposing the LEPUS_REF tag distinction.

    Naming recommendation:

    • LynxValue: the generic native value algebra, aligned with lynx_value / LynxValue.
    • LynxValueRef: a JS-visible native-backed composite such as LEPUS_REF.
    • LynxStructuredValue: data materialized into the receiving realm as ordinary arrays/objects.
    • Avoid calling event.data a HostObject; that name already has a specific JSI meaning.

    Source-level mechanism and exact links are in the preceding iOS/Android probe comment.

    2. Octane transport cells

    I built three diagnostic cells from Octane upstream fd6ce69c13daf7aa4eb41b4450382d6370b7993f. All three used the same Octane command graph and native applier; only the Lynx transport policy changed:

    1. raw-safe — pass the live Lynx value/LEPUS_REF, run Octane's deep validator, and return the rich ACK/complete protocol.
    2. json-safe — stringify on send, parse into receiver-local objects, run the same deep validator, and return ACK/complete.
    3. json-unsafe — stringify/parse, skip sender self-check and receiver deep validation, and skip the steady-state ACK. The provisional bootstrap was still acknowledged so the renderer could start. This was an isolation experiment, not the recommended API.

    Measurement:

    • leased physical aries_10, Android 10, LynxExplorer;
    • Create 1,000 rows;
    • five accepted samples per cell, interleaved;
    • every sample completed and exposed exactly 1,000 rows;
    • identical semantic delta: one commit, 33,607 payload bytes;
    • thermal gate ≤40°C; final battery temperature 35°C, thermal status 0;
    • failed DebugRouter/recycle attempts happened before the workload and were not counted.
    cell, n=5 send → apply median (range) encode decode validate prepare native apply ACK round trip
    raw-safe 12,674 ms (12,492–12,712) 0 0 56 429 12,184 335 13,523
    json-safe 11,756 ms (11,625–11,830) 1 7 49 21 11,678 0 11,756
    json-unsafe 11,665 ms (11,613–11,786) 1 7 0 21 11,631 0 n/a — no steady-state ACK

    Interpretation:

    • JSON-safe beats raw-safe by 918 ms at the median. Preserving the raw LEPUS_REF path has no performance case on this engine: raw preparation costs about 408 ms more and the raw ACK path another 335 ms.
    • JSON-safe versus JSON-unsafe differs by 91 ms end to end, but their ranges overlap; that 91 ms is not a defensible causal estimate.
    • The exclusive stage timer does identify the repeatable safety cost: deep validation is 49 ms median (48–51 ms). JSON encode is 1 ms and decode 7 ms in both cells. The JSON completion ACK measures 0 ms at this timer resolution.
    • Current native apply is still approximately 11.6 seconds even after validation and ACK are removed. The main performance cliff is not transport safety.
    • This A/B is Android-only. The semantic failure was measured on both iOS and Android, but the performance cells have not been run on iOS.

    3. What ReactLynx and VueLynx actually pay

    The measured React/Vue implementations are not “raw object + no ACK”:

    renderer BTS → MTS payload receiver completion
    ReactLynx 0.124 JSON.stringify(patchList) inside { data, patchOptions } JSON.parse(data), then snapshot patch apply callLepusMethod(..., callback) retires the commit task
    VueLynx at 28f7acb JSON.stringify(ops) inside { data } JSON.parse(data), then applyOps callback ACK gates nextTick() / flush completion

    They therefore pay JSON localization and a completion callback. What they do not pay is Octane's generic hostile-value integrity walk, full schema proof, or its richer handle/adoption transaction bookkeeping. A better classification is:

    React/Vue use a trusted JSON protocol with completion ACK, not a raw unsafe object protocol.

    4. Whole-renderer native benchmark

    The comparable full-renderer boundary is native-input-handler-to-second-native-frame, Create 1,000 rows, on the same Android device class.

    Same campaign/backfill snapshot (one sample per entry, so directional rather than statistical):

    renderer result
    ReactLynx 188 ms
    Vue Vapor 336 ms
    Vue Vapor IFR 335 ms
    Vue VDOM 368 ms
    Vue VDOM IFR element-template 254 ms
    Octane 0fc84da0 with the required JSON workaround 12,193 ms

    Independent five-sample baselines for the three main competitors were stable:

    renderer, n=5 samples median
    ReactLynx 194, 191, 198, 206, 187 194 ms
    Vue Vapor 331, 337, 323, 322, 337 331 ms
    Vue VDOM 363, 357, 348, 358, 362 358 ms

    This puts the current Octane result roughly 34–65× behind directionally. That must not be attributed to React/Vue being unsafe: the controlled Octane experiment can identify only about 49 ms of deep-validation tax, while the unsafe Octane cell still spends 11,631 ms in native apply. Deleting safety cannot recover an 11-second gap.

    The 49 ms is nevertheless material against a future React-class budget: it is ~25% of 194 ms. It should be removed from the hot path after JSON has already proved the payload is receiver-local ordinary data.

    5. Recommended Octane shape

    Do not fork the universal renderer or maintain two command protocols. Keep one universal batch/transaction model and put the policy in the Lynx adapter:

    validation: 'checked' | 'trusted'

    Both modes should:

    • use JSON (or a future equivalent receiver-local structured codec), never expose raw LEPUS_REF to universal-core reflection;
    • retain protocol/renderer/root/version identity;
    • retain compact completion ACK, backpressure, lifetime, and fault semantics.

    The modes differ only in validation:

    • checked (default): schema-only validation after parse. JSON.parse already proves there are no proxies, accessors, symbols, foreign prototypes, functions, or cycles, so prototype/descriptor/symbol integrity checks should be deleted. Check op discriminants, numeric ranges, lengths, references, and command shape.
    • trusted: for same-bundle internal renderers, skip the production deep schema traversal; retain cheap header/identity checks and development assertions.

    The no-ACK json-unsafe cell was useful only to isolate cost. Since JSON ACK measured at 0 ms and React/Vue both retain a completion callback, removing ACK from the proposed trusted mode would trade away correctness without a measured speed benefit.

    Priority order implied by the data:

    1. Move Octane to receiver-local JSON values and remove the raw-LEPUS_REF compatibility path.
    2. Replace hostile-object validation with schema-only checked validation; add the trusted policy locally in the Lynx adapter.
    3. Keep compact ACK in both modes.
    4. Investigate the native applier/command architecture: it owns ~11.6 s of the current result and dominates everything above.

    No Octane product files or PR were created by this investigation; all transport variants were temporary diagnostic builds.

    Provenance

    • An agent produced this analysis (agent-authored)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent-authoredbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions