Skip to content

fix(lynx): deliver native events to background handlers and halve render cost - #346

Merged
trueadm merged 2 commits into
mainfrom
fix/lynx-events-and-perf
Jul 28, 2026
Merged

trueadm merged 2 commits into
mainfrom
fix/lynx-events-and-perf

Conversation

@trueadm

@trueadm trueadm commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Two defects Xuan Huang (Huxpro) hit while adding Octane to the Vue-Lynx unified benchmark matrix:

  1. Native clicks never reached handlers. __AddEvent installed Octane's listener tokens correctly, but nothing on the background thread received them, so click-driven benchmark operations could not run.
  2. Render cost was well above Vue VDOM+IFR and Vapor+IFR. 433ms vs 233/251ms for 1,000 rows; 3,228ms vs 2,141/2,252ms for 10,000.

Both are fixed, and both now have a benchmark that fails if they regress.

Why

The Lynx engine resolves a background bind*/catch* token by calling lynxCoreInject.tt.publishEvent on the background thread. It never routes an ordinary background event through main-thread JavaScript. Octane only had LynxMainThreadController.dispatchNativeEvent, a main-thread bridge, and every existing event test drove that bridge — which is exactly why the gap survived to a third-party evaluation. docs/lynx-native-renderer-plan.md had already flagged it: "__AddEvent publicly installs tokens, but production native delivery still depends on the private lynxCoreInject.tt.publishEvent receiver".

On the performance side, profiling the real dual-thread path showed roughly half the mount was bookkeeping no application had asked for: a frozen public handle, a NodesRef query binding, a WeakMap state entry, and a deep frozen snapshot clone per accepted host node, plus a full structural walk of every command and every prop on both the send and the receive side of each message.

Changes

Event path

  • packages/lynx/src/core/native-event-receiver.ts (new): installs publishEvent/publicComponentEvent on the engine's private injection. It chains any previously installed handler, declines tokens it does not own, contains its own errors, and coalesces the synchronous burst the engine makes while walking one propagation path into a single Octane event scope.
  • A tap can land between main applying a commit — which is when it installs the tokens, so the element becomes tappable — and the background accepting that commit's acknowledgement. Ownership is therefore claimed on the root the transport has served since its first commit, and a delivery whose host is not yet published is held for the one acknowledgement it can be racing rather than dropped. (Raised by Bugbot; fixed in 9d147e8.)
  • The listener priority now travels inside the token, so the background can build a valid UniversalTransportEventMessage without a round trip to main. A token whose host is stale, detached, or foreign is dropped with a diagnostic — the background-side equivalent of main's host-tree check.
  • createLynxRoot() installs and releases the receiver with the root's lifetime. lynxCoreInject is resolved ambiently (explicit host → wrapper lexical binding → global), because under the official Rspeedy wrapper the root's background globals are a synthetic object.

Render cost

  • Public handles became compact entries: identity plus mutable acknowledgement state in one monomorphic object, with the frozen facade, the query binding, and the snapshot clone built on first use. Refs, queries, and portals reach a handful of nodes in a real screen.
  • A handle created by a preparation is written directly instead of staged — it is unreachable until apply() publishes it, and rollback drops it outright.
  • Outbound messages are self-checked in development only. The receiving thread validates every inbound message regardless, so the trust boundary is unchanged; what goes away is re-walking a message you just built.
  • Receive-side validation and prop diffing no longer allocate on the success path: message paths are composed only on failure, exactKeys no longer rescans, leaf props skip the wire walk and its cycle set, and nodes without data-* or main-thread: props share frozen empties.

Benchmark

  • benchmarks/lynx-render (new): drives the real background root, transport, main receiver, and host driver over an in-process ContextProxy pair with a cheap fake Element PAPI, so the milliseconds are Octane's own per-node CPU cost. It also gates that a native tap reaches its handler through the engine receiver — a build without it reports handler DID NOT RUN and fails.

Validation

Baseline vs candidate, same command (node benchmarks/lynx-render/run.mjs 5), same machine:

main this branch
create 1,000 rows 111.1ms 72.0ms (−35%)
create 10,000 rows 1292.5ms 730.5ms (−43%)
native click handler DID NOT RUN handler ran

The six new end-to-end event tests fail 4/6 on main with the receiver removed, so they carry credible pre-fix failure evidence. The pre-ACK race test fails independently for each half of its fix. They dispatch on the elements the official Element PAPI created, so delivery runs through the engine's own publishEvent, not the test bridge.

  • pnpm format:check
  • pnpm typecheck
  • pnpm test — 14,564 passed / 1,430 files
  • targeted: vitest run --project lynx (259 tests), node benchmarks/bench.mjs --quick lynx-render

Risk / follow-ups

  • The receiver rides lynxCoreInject, a private core injection. That is the only path the engine offers today and it is what ReactLynx uses, but it is not a public API contract. The Milestone 3/4 gate on a public native event receiver stays open, and the plan doc has been updated to say the receiver is implemented and covered in the official JavaScript environment while carrying no device evidence.
  • Timing here is Node with a cheap fake PAPI. It is the right oracle for framework CPU cost and the wrong one for native paint, layout, or adoption; the Android/iOS gates are unchanged.
  • A priority change for the same listener id now rebinds natively, because the token carries priority. The Lynx renderer derives priority from the event name, so this cannot happen through the compiler; host-driver.test.ts pins it either way.
  • benchmarks/lynx-render joins the pnpm workspace, so the eval corpus lockfile digest was regenerated.

🤖 Generated with Claude Code


Note

Medium Risk
Touches core dual-thread event delivery via a private engine injection and changes handle/transport hot paths; behavior is heavily tested but device-native evidence is still absent.

Overview
Native background events — The Lynx engine resolves bind*/catch* tokens via private lynxCoreInject.tt.publishEvent on the background thread; Octane previously never listened there, so installed tokens were dropped and clicks did nothing. A new receiver chains prior hooks, routes owned tokens into the transport as a single coalesced propagation scope, and encodes listener priority in the token so the background can emit UniversalTransportEventMessage without asking main. createLynxRoot() installs it for the root lifetime; taps that arrive after main applies tokens but before the background ACK are held and flushed once handles are published.

Render CPU — Accepted host nodes use compact LynxHandleEntry records with lazy public facade, NodesRef binding, and snapshot clone; acknowledgement prep avoids extra staging for brand-new handles. Outbound messages are structurally self-checked only in development; inbound validation and prop/dataset paths avoid allocations on the hot success path.

Regression coverage — New Node benchmarks/lynx-render suite (empty startup, 1k/10k keyed rows, native-click gate) and end-to-end tests that drive publishEvent like the engine, not the main-thread test bridge. Plan/changeset docs updated accordingly.

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

…der cost

`__AddEvent` installed Octane's listener tokens correctly, but nothing
received them. The engine resolves a background `bind*`/`catch*` token by
calling `lynxCoreInject.tt.publishEvent` on the background thread and never
routes an ordinary background event through main-thread JavaScript, so every
tap was dropped and click-driven interaction did not work in a real app. Every
existing event test drove the main-thread `dispatchNativeEvent` bridge, which
is why the gap survived.

The background root now installs that receiver, chaining any previously
installed handler, declining tokens it does not own, and containing its own
errors. Listener priority travels inside the token so the background can build
a valid transported event message without a round trip to main, and one native
propagation path is delivered as a single Octane event scope.

Mount cost is down about a third to a half:

- Public handles for accepted host nodes are compact entries whose frozen
  facade, NodesRef query binding, and defensive snapshot clone are built on
  first use instead of once per node.
- Outbound transport messages are self-checked in development only; the
  receiving thread validates every inbound message regardless.
- Per-node validation and prop diffing no longer allocate message paths,
  descriptor objects, or empty dataset and event-name bags on success.

Adds `benchmarks/lynx-render`, which drives the real dual-thread path through a
cheap fake Element PAPI and gates that a native tap reaches its handler.

Co-Authored-By: Claude Opus 5 <[email protected]>
@vercel

vercel Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
octane-website Ready Ready Preview, Comment Jul 28, 2026 2:39pm
octane-website-mcp Ready Ready Preview, Comment Jul 28, 2026 2:39pm

Request Review

@vercel
vercel Bot temporarily deployed to Preview – octane-website-mcp July 28, 2026 14:15 Inactive
@vercel
vercel Bot temporarily deployed to Preview – octane-website July 28, 2026 14:16 Inactive

@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 prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Pre-ACK native taps silently dropped
    • Changed claims() to use transportRoot (set at commit-apply time) instead of acceptedIdentity (set at ACK time), and added a pre-ACK event buffer that is drained after the ACK applies handles, closing the race window where native taps were silently dropped.

Create PR

Or push these changes by commenting:

@cursor push 90c8ed3857
Preview (90c8ed3857)
diff --git a/packages/lynx/src/core/transport.ts b/packages/lynx/src/core/transport.ts
--- a/packages/lynx/src/core/transport.ts
+++ b/packages/lynx/src/core/transport.ts
@@ -79,6 +79,8 @@
 	/** Bind logical background cleanup to the native page lifetime broadcast. */
 	bindPageDestroy(handler: () => void | Promise<void>): void;
 	acceptedIdentity(): UniversalTransportIdentity | null;
+	/** Whether this transport owns the given root id (true as soon as a commit is applied). */
+	claimsRoot(root: number): boolean;
 	/** Cancel commits that have not crossed the readiness/send boundary. */
 	cancelPendingBeforeReady(reason?: unknown): Promise<boolean>;
 	/** Internal facade state used to classify teardown without probing the host. */
@@ -277,6 +279,7 @@
 	let pageDestroyReceived = false;
 	let pageDestroyHandler: (() => void | Promise<void>) | null = null;
 	let pageDestroyHandlerInvoked = false;
+	let preAckEventBuffer: (readonly LynxBackgroundNativeEventDelivery[])[] | null = null;
 	const finalizedWorkletBatches = new WeakSet<object>();
 
 	const report = (error: unknown, fallback = 'Octane Lynx transport protocol error.') => {
@@ -555,6 +558,7 @@
 		notifyMain = true,
 	): boolean => {
 		if (closedError !== null) return false;
+		preAckEventBuffer = null;
 		closeThreadCalls(error, notifyMain);
 		closedError = error;
 		readyDeferred.reject(error);
@@ -767,7 +771,8 @@
 				return;
 			}
 		}
-		publishAcknowledgementMainCalls(message);
+		if (!publishAcknowledgementMainCalls(message)) return;
+		drainPreAckEvents();
 	};
 
 	const settleCommitResponse = (entry: PendingCommit, message: CommitSettlement): void => {
@@ -863,6 +868,53 @@
 		}
 	};
 
+	const processNativeEventBatch = (
+		deliveries: readonly LynxBackgroundNativeEventDelivery[],
+	): void => {
+		if (accepted === null) return;
+		const priority = deliveries[0]!.identity.priority;
+		const transported: UniversalTransportEventDelivery[] = [];
+		for (const delivery of deliveries) {
+			const { identity } = delivery;
+			if (identity.root !== accepted.root) {
+				report(new Error(`Octane Lynx received a foreign native event for root ${identity.root}.`));
+				return;
+			}
+			if (identity.priority !== priority) {
+				report(new Error('Octane Lynx native event batch mixes listener priorities.'));
+				return;
+			}
+			if (!isLynxClientEventTarget(container, identity.root, identity.id, identity.generation)) {
+				report(
+					new Error(
+						`Octane Lynx received a stale native event for host ${identity.id}:${identity.generation}.`,
+					),
+				);
+				return;
+			}
+			transported.push({ listener: identity.listener, payload: delivery.payload });
+		}
+		handleEvent({
+			protocol: LYNX_TRANSPORT_PROTOCOL_VERSION,
+			renderer: LYNX_TRANSPORT_RENDERER,
+			root: accepted.root,
+			version: accepted.version,
+			type: 'event',
+			priority,
+			deliveries: Object.freeze(transported),
+		});
+	};
+
+	const drainPreAckEvents = (): void => {
+		const buffer = preAckEventBuffer;
+		preAckEventBuffer = null;
+		if (buffer === null || buffer.length === 0 || accepted === null) return;
+		for (const deliveries of buffer) {
+			if (closedError !== null) return;
+			processNativeEventBatch(deliveries);
+		}
+	};
+
 	const handleHostAttachment = (message: LynxHostAttachmentMessage): void => {
 		if (accepted === null || !sameLynxTransportIdentity(accepted, message)) {
 			report(
@@ -1389,6 +1441,9 @@
 		acceptedIdentity() {
 			return accepted;
 		},
+		claimsRoot(root) {
+			return transportRoot === root;
+		},
 		dispatchNativeEventBatch(deliveries) {
 			if (deliveries.length === 0) return;
 			if (closedError !== null) {
@@ -1396,45 +1451,14 @@
 				return;
 			}
 			if (accepted === null) {
+				if (transportRoot !== null) {
+					(preAckEventBuffer ??= []).push(deliveries);
+					return;
+				}
 				report(new Error('Octane Lynx received a native event before a commit was accepted.'));
 				return;
 			}
-			const priority = deliveries[0]!.identity.priority;
-			const transported: UniversalTransportEventDelivery[] = [];
-			for (const delivery of deliveries) {
-				const { identity } = delivery;
-				if (identity.root !== accepted.root) {
-					report(
-						new Error(`Octane Lynx received a foreign native event for root ${identity.root}.`),
-					);
-					return;
-				}
-				if (identity.priority !== priority) {
-					report(new Error('Octane Lynx native event batch mixes listener priorities.'));
-					return;
-				}
-				// The background owns the listener table but main owns the physical
-				// tree, so the generation and attachment recorded at acknowledgement
-				// are what prove this token still names a live, mounted host.
-				if (!isLynxClientEventTarget(container, identity.root, identity.id, identity.generation)) {
-					report(
-						new Error(
-							`Octane Lynx received a stale native event for host ${identity.id}:${identity.generation}.`,
-						),
-					);
-					return;
-				}
-				transported.push({ listener: identity.listener, payload: delivery.payload });
-			}
-			handleEvent({
-				protocol: LYNX_TRANSPORT_PROTOCOL_VERSION,
-				renderer: LYNX_TRANSPORT_RENDERER,
-				root: accepted.root,
-				version: accepted.version,
-				type: 'event',
-				priority,
-				deliveries: Object.freeze(transported),
-			});
+			processNativeEventBatch(deliveries);
 		},
 		async cancelPendingBeforeReady(reason) {
 			if (closedError !== null || accepted !== null || pending.size === 0) return false;

diff --git a/packages/lynx/src/root.ts b/packages/lynx/src/root.ts
--- a/packages/lynx/src/root.ts
+++ b/packages/lynx/src/root.ts
@@ -307,7 +307,7 @@
 	try {
 		uninstallNativeEvents = installLynxNativeEventReceiver(target as object, {
 			claims(root) {
-				return transport.acceptedIdentity()?.root === root;
+				return transport.claimsRoot(root);
 			},
 			deliver(deliveries) {
 				transport.dispatchNativeEventBatch(deliveries);

You can send follow-ups to the cloud agent here.

Reviewed by Cursor Bugbot for commit 62641b2. Configure here.

Comment thread packages/lynx/src/root.ts Resolved
Main installs `__AddEvent` tokens while it applies a commit, so an element is
tappable the moment that apply lands. The acknowledgement that teaches the
background the host's generation and attachment is still in flight, and a tap
is an engine call rather than a ContextProxy message, so it can overtake it.

Two problems in that window. `claims()` recognized a root only once
`acceptedIdentity()` was set, so before the first acknowledgement no sink
claimed the token and the tap was dropped with no diagnostic at all — the
first-paint case. And a delivery whose host was not yet published was reported
as stale, when it names a host that genuinely exists on main.

The receiver now claims on the root the transport has served since its first
commit, which is necessarily earlier than main installing a token for it, and
an unresolved delivery is held for the one acknowledgement it can be racing
before being dispatched or diagnosed. The queue is bounded and is failed on
transport close.

Found by Cursor Bugbot on #346. The synchronous ContextProxy the tests used
always settled past the acknowledgement first, so the new regression test gates
main-to-background delivery to reproduce the window.

Co-Authored-By: Claude Opus 5 <[email protected]>
@vercel
vercel Bot temporarily deployed to Preview – octane-website-mcp July 28, 2026 14:38 Inactive
@vercel
vercel Bot temporarily deployed to Preview – octane-website July 28, 2026 14:39 Inactive
@trueadm
trueadm merged commit 6600353 into main Jul 28, 2026
25 of 26 checks passed
@trueadm
trueadm deleted the fix/lynx-events-and-perf branch July 28, 2026 14:48

This branch was previously deployed

2 inactive deployments
Preview – octane-website — 9d147e8f Deployed Jul 28, 2026 by vercel[bot]
Preview – octane-website-mcp — 9d147e8f Deployed Jul 28, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant