Repository navigation
fix(lynx): deliver native events to background handlers and halve render cost - #346
Merged
Merged
Conversation
…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]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
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.
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.
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]>
22 of 29 tasks
This branch was previously deployed
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
Two defects Xuan Huang (
Huxpro) hit while adding Octane to the Vue-Lynx unified benchmark matrix:__AddEventinstalled Octane's listener tokens correctly, but nothing on the background thread received them, so click-driven benchmark operations could not run.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 callinglynxCoreInject.tt.publishEventon the background thread. It never routes an ordinary background event through main-thread JavaScript. Octane only hadLynxMainThreadController.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.mdhad already flagged it: "__AddEventpublicly installs tokens, but production native delivery still depends on the privatelynxCoreInject.tt.publishEventreceiver".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
NodesRefquery binding, aWeakMapstate 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): installspublishEvent/publicComponentEventon 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.UniversalTransportEventMessagewithout 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.lynxCoreInjectis 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
apply()publishes it, and rollback drops it outright.exactKeysno longer rescans, leaf props skip the wire walk and its cycle set, and nodes withoutdata-*ormain-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 reportshandler DID NOT RUNand fails.Validation
Baseline vs candidate, same command (
node benchmarks/lynx-render/run.mjs 5), same machine: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:checkpnpm typecheckpnpm test— 14,564 passed / 1,430 filesvitest run --project lynx(259 tests),node benchmarks/bench.mjs --quick lynx-renderRisk / follow-ups
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.host-driver.test.tspins it either way.benchmarks/lynx-renderjoins 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 privatelynxCoreInject.tt.publishEventon 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 emitUniversalTransportEventMessagewithout 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
LynxHandleEntryrecords with lazy public facade,NodesRefbinding, 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-rendersuite (empty startup, 1k/10k keyed rows, native-click gate) and end-to-end tests that drivepublishEventlike 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.