Skip to content

Direct first-screen applier skips the main-thread/background event collision check, silently dropping the main-thread handler #84

Open

Description

@Huxpro

Found by an adversarial audit of the #58 L0–L3 equivalence claims, against stack head 2fe14465f. Counterexample to #65's claim that applyLynxFirstScreenDirect leaves container state indistinguishable from prepareLynxHostBatch + apply.

Not pre-existing — verified against base 6079a6804: git show 6079a6804:packages/lynx/src/core/host-driver.ts | grep -c applyLynxFirstScreenDirect = 0. The direct applier does not exist at base, and the staged path is byte-identical (271 insertions(+), 0 deletions).

Root cause

prepareLynxHostBatch runs assertNoMainThreadEventCollision (defined packages/lynx/src/core/host-driver.ts:1330) over the batch's final host set at :4796; finalIds is populated whenever hasMainThreadProps is true (:4735-4736), so the collision is caught during prepare, before any PAPI call.

applyLynxFirstScreenDirect (:2900-3033) never calls it. Its per-node walk runs applyProps first, which installs the main-thread worklet (:2996), and then installNativeEvent (:2999-3001) overwrites the same native channel with the background token.

Observed

direct : painted
         setEvent view#3 bindEvent:tap worklet(probe.tsrx:tap)
         setEvent view#3 bindEvent:tap token(background)     <- immediately supersedes it
         worklet activation still reported active (1:true) for the painted lifetime
staged : refused, zero PAPI calls
         "main-thread event \"main-thread:bindtap\" conflicts with background event
          \"bindtap\" on the same native channel"

Consumer impact

<view bindtap={onTap} main-thread:bindtap={onTapMT} />

A background handler plus a main-thread handler for immediate feedback — the exact pattern the collision guard was written to reject. Today that page paints, and the main-thread handler silently never fires, because the background token overwrites it on the same channel. Its worklet activation is retained for the page's lifetime.

Worse, the behaviour is inconsistent within one app: the same page hard-fails first-screen paint with a clear conflict error as soon as it contains a native <list>, because firstScreenTreeHasList makes the direct applier decline and packages/lynx/src/main-thread.ts:1906 falls through to the staged path. So whether an authoring mistake is reported or silently swallowed depends on whether an unrelated part of the page uses a list.

Suggested direction

Call assertNoMainThreadEventCollision from applyLynxFirstScreenDirect before mutating, over the same final host set the staged path uses. The direct path has no prepare stage, so this needs an explicit pre-walk — which is the general shape of the problem in #76 as well.

Related

Verification performed

Executed against a registry-backed container — createLynxHostContainer(papi, { root, worklets }) with createLynxMainThreadWorkletRegistry(), a registered worklet definition, and createLynxMainThreadRefDescriptor. Building that container was the blocker that stopped two earlier audit lenses from reaching this surface at all. Base comparison run in a git worktree; the staged half printed the identical refusal there. Adversarial refuter panel had not adjudicated at time of filing.

Activity

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

    @Huxpro
    OwnerAuthor

    Reachability audit: STANDS — and the end state is worse, with a more ordinary sibling defect in the same function

    A dedicated attacker — briefed with the four findings this audit has already withdrawn on reachability grounds — could not refute this one. It is the only finding that survived that scrutiny unqualified.

    Reachable, and it typechecks

    Ordinary authored .tsrx, no exotic construct — immediate main-thread press feedback plus a background state update, the canonical reason both handlers exist:

    export function TapCard() @{
    	const [count, setCount] = useState(0);
    	const pressed = useMainThreadRef(0);
    	const onTapMT = () => { 'main thread'; pressed.current += 1; return pressed.current; };
    	const onTap = () => { setCount((value) => value + 1); };
    	<view id="tap-card" bindtap={onTap} main-thread:bindtap={onTapMT}>
    		<text>{'Count ' + count}</text>
    	</view>
    }

    tsrx-tsc --noEmit with the shipped demo's exact compilerOptions (including skipLibCheck: false): EXIT=0, with a sanity control proving the harness reports real errors. Both bindtap (native-types.ts:203) and main-thread:bindtap (intrinsics.ts:36-38) are declared on the same element type — the type layer permits the collision. The shipped compiler emits both sides and neither rejects nor dedupes.

    This is the axis that withdrew #72, #73, #82 and #83. It does not apply here.

    Correction: the end state is worse than this issue says

    I filed it as "paints with the main-thread handler silently dead." That is only the window between first paint and the background ready handshake. At the handshake the whole native page is destroyed, and background adoption does not repair it — adoption never runs. The #76-mechanism-1 escape hatch (adoption catches the damage) does not apply.

    [A] addEvents: worklet {"_wkltId":"tf_1t2cl5n7uow5h",...,"_owlt":1}, then "octane-lynx:event:1:1:1:1000000:discrete"
    [A] data-main-hit after tap: null          <- main-thread handler genuinely never fires
    [D] control, same component minus bindtap: data-main-hit = "yes"
    

    The <list>-dependent flip reproduced exactly: silent dead handler without a list, hard throw and <page></page> with one.

    Not intentional — the stack asserts the opposite

    Commit 7600bfbaf, .changeset/lynx-direct-first-screen.md, and docs/lynx-specialized-target-l0.md:338-343 all claim container state stays indistinguishable, with "native-list trees keep the staged path" as the only declared exception. And the refusal itself is pinned as intended by packages/lynx/tests/host-driver.test.ts:1861 — "rejects ordinary and main-thread handlers targeting the same PAPI event tuple".

    Neither first-screen-direct.test.ts nor first-screen-applier-acceptance.test.ts exercises any main-thread: prop; grep returns nothing.

    Stack-introduced, with a provenance discriminator

    Base worktree at 6079a6804, logged from the base run itself:

    [X] host-driver exports applyLynxFirstScreenDirect? false
    [X] renderLynxFirstScreen result keys: ["batch","hostCount","logicalCount"]   <- no `nodes`, so base code ran
    

    At base the collision component is refused, never painted, with or without a list:

    Error: Octane Lynx host: main-thread event "main-thread:bindtap" conflicts with
           background event "bindtap" on the same native channel.
      ❯ assertNoMainThreadEventCollision  host-driver.ts:1342
      ❯ prepareLynxHostBatch             host-driver.ts:4619
    

    So the <list>-dependent flip is genuinely new at HEAD.

    A more ordinary sibling defect the maintainers should probably fix first

    The attacker reports that applyLynxFirstScreenDirect:2950 takes node.props raw, skipping the cloneProps unwrap of tagged main-thread callables at :994-1010. The trigger would be main-thread:bindtap alone — no collision — which is the exact shape of the shipped swiper example, and which worked end to end at base.

    I am flagging this rather than filing it, because it partially conflicts with an earlier refuter's finding that the direct path does unwrap tagged callables via planLynxHostPropPatch → decodeMainThreadWorklet → unwrapThreadFunctionDescriptor, with byte-identical PAPI journals on both appliers. The two probes used different fixtures — a bindThreadFunction-tagged callable versus the authored main-thread:bindtap compiled path — so both may be true of different value shapes, with the PAPI patch unwrapping while record.props retains the raw descriptor. That would also explain the collateral below. This needs one probe to settle, and if it holds it is more important than the collision case.

    Collateral worth noting either way

    captureLynxFirstTree accepts the collision tree and reports main-thread:bindtap in the snapshot, so the background is told a main-thread handler is installed on a channel that holds only a background token — and the activated worklet (_owlt: 1) is retained until disposal while unable to ever fire.

    Suggested fix, unchanged in direction

    Route direct-path props through cloneProps, and call assertNoMainThreadEventCollision per host in the direct walk. One change closes both the collision case and the sibling case if the latter confirms.


    Generated by Claude Code

  3. Huxpro commented on Aug 18, 2026

    @Huxpro
    OwnerAuthor

    Panel: unanimous — three independent refuters, none could kill it

    Adding this for confidence weighting, since this audit withdrew four other findings on exactly the axis these refuters attacked.

    Three refuters adjudicated this candidate independently of the reachability audit already reported above. All three returned refuted=false, preExisting=false, intentional=false — four independent confirmations in total.

    Each one rebuilt the repro from authored .tsrx through the real compiler rather than reusing the original probe, because the original hand-built its plan with universalPlan and that was the obvious kill:

    "This was my strongest lead and it failed."

    "I grepped packages/octane/src/compiler/ for conflict/collision validation: zero hits. So there is no build-time rejection standing between a consumer and this divergence."

    Why the compiler admits it

    Pinned precisely across the three:

    • bind* and main-thread:bind* are both in LYNX_STANDARD_PROPS (packages/lynx/src/config.runtime.js:44,52)
    • hostAttributeName (compile-universal.js:1996) accepts the main-thread: namespace under the thread-functions capability
    • main-thread:bindtap does not match the firstScreenEvents globs ['bind*', …], so the worklet is never erased from the main-thread program

    <view class="both" bindtap={props.onTap} main-thread:bindtap={onTapMT} /> compiles clean with no diagnostic, and the divergence reproduces from the compiler's own output on both encodings — target: 'universal' emitting "bindings": [["bindtap",0],["main-thread:bindtap",1]] and target: 'lynx' emitting env.e(n1,"bindtap",values[0]); env.p(n1,"main-thread:bindtap",values[1]). So this is applier-level and independent of #63.

    Route 2 confirmed it through the shipped entry point (installLynxMainThread({firstScreen:true, …}) + firstScreenRoot.render) against the real Lynx testing-environment PAPI, not a fake, with a real registered worklet id:

    setEvent view#3 bindEvent:tap worklet(tf_ok5q6o5eut3o)
    setEvent view#3 bindEvent:tap <background token>      <- immediately supersedes it
    DIRECT worklets still active while painted: ["1:true"]
    

    captureLynxFirstTree also accepts the tree, keying state.nativeEvents by 'bindtap' for the background and 'main-thread:bindtap' for the worklet — so the mismatch is carried into the snapshot rather than caught.

    One qualification, consistent with the audit above

    One refuter summarised it as "core mechanism survives; the consumer story does not" — matching the correction already recorded: the end state is the page being destroyed at the background handshake, not merely painting with a dead handler. The mechanism, reachability, and attribution are settled; the consumer narrative in the original body is the part that was revised.


    Generated by Claude Code

  4. added a commit that references this issue on Aug 19, 2026
  5. Huxpro commented on Aug 21, 2026

    @Huxpro
    OwnerAuthor

    Both halves are fixed on new-lynx, including the sibling this issue flagged but did not file — recommend closing

    The first comment ended on an open question: "This needs one probe to settle, and if it holds it is more important than the collision case." Ran it. It settled the other way — the sibling was fixed too, in its own commit.

    The filed defect

    applyLynxFirstScreenDirect now pre-walks and refuses before any PAPI call, which is this issue's Suggested direction verbatim.

    packages/lynx/src/core/host-driver.ts:3232-3248 — the walk runs only when eventsByHost.size !== 0, so a page with no background listeners skips it, and it calls assertNoMainThreadEventCollisionForTypes (:1382) per host that has one. The in-code comment gives the same reason the issue did: refusing after the walk has begun would leave a half-painted page, which the staged path never produces.

    Landed by a845ec0da "refuse first-screen event-channel collisions before touching PAPI", with e6b289813 "replay prepare-walk diagnostics before declining a first screen" on top. Both are ancestors of new-lynx.

    The sibling defect — the cloneProps unwrap

    Also fixed, and separately: 0210328a2 "journal wire-safe props in the direct first-screen applier".

    host-driver.ts:3309-3310 routes the node's props through cloneProps(node.props, 'first-screen host props') rather than storing them raw, so a tagged main-thread: callable becomes a plain worklet descriptor before it reaches record.props — which is what captureLynxFirstTree snapshots across the ContextProxy wire. That closes the main-thread:bindtap-alone shape the comment worried about, and it is the failure mode the comment correctly judged more important than the collision: a journaled function faults a structured-clone MessagePort for the page's lifetime.

    The comment also noted the two probes might both be true of different value shapes, with the PAPI patch unwrapping while record.props retained the raw descriptor. That reading was right — the fix is specifically on the stored props, not the patch.

    Coverage now exists, and it is not vacuous

    The audit noted neither first-screen suite exercised any main-thread: prop. That gap is closed in first-screen-direct.test.ts:

    • "refuses a main-thread/background event collision before touching PAPI" — the filed case.
    • "does not reject a main-thread handler on a channel no listener shares" — the control that keeps the guard from over-refusing.
    • "produces the identical adoption snapshot, journal, and physical tree as the staged path" asserts the unwrap directly, checking each snapshot value equals {_wkltId: 'first-screen-direct.test:tap', _c: {values: [{step: 8}]}} — a tagged callable fails that — and guards with expect(mtsValues.length).toBeGreaterThan(0) so it cannot pass on an empty set.
    ✓ 9 passed (9)  packages/lynx/tests/first-screen-direct.test.ts
    

    One piece of new evidence worth attaching before this closes

    Measured today on #133: packages/rspeedy-plugin-octane/src/main-thread-entry.js installs the main thread with firstScreen: true unconditionally, so applyLynxFirstScreenDirect is the path every plugin-built app's first screen takes. At 10,000 rows in Chromium the plugin-default build paints entirely through it.

    That retroactively raises what this issue was worth: it was not an edge path. It is worth recording on the function for whoever audits it next, and it is the reason I would treat future divergence between the two appliers as production-severity by default rather than case by case.

    Not closing this myself — that is a maintainer call. But I know of nothing left open on it.


    Generated by Claude Code

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