Skip to content

fix: scoped universal component state updates - #578

Merged
leonidaz merged 4 commits into
mainfrom
universal
Aug 5, 2026
Merged

leonidaz merged 4 commits into
mainfrom
universal

Conversation

@leonidaz

@leonidaz leonidaz commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

closes #574


Note

High Risk
Changes core universal scheduling, reconciliation, and commit semantics with many fallback paths; incorrect scoping could break updates, boundaries, or host batches, though benchmarks and tests target the main cases.

Overview
Fixes #574 by making universal setState replay only the owning component subtree instead of the whole root whenever coordination allows, with explicit fallbacks to full-root renders.

Scheduler / replay scope: Hook-driven updates call scheduleOwned and batch into scheduledOwners; resolveScopedTarget hoists anonymous @for item owners and multi-owner event scopes to their nearest shared component ancestor. prepareOwnedUpdate re-renders that owner’s retained range, while schedule() still forces a full root.

When scoped updates apply vs bail: Scoped work is skipped for bridged/transported roots, warm plans, suspense-hidden owners, active boundary episodes (pending thenable or routed error), portals/regions, and cases where shape is unstable without a valid physical frame (scopePhysicalPlacement). Idle @try boundaries stay scoped; render errors/suspense in a scope fall back so an ancestor boundary can handle them. Structural insert/reorder/remove inside a scope commits against the nearest host parent and end anchor so out-of-scope siblings stay put.

Commit path: createPreparedTransaction can reconcile a sub-tree; scoped accepts patch event/local-callback tables in place instead of cloning the whole app. Owner records track componentProps and range for replay; blueprint ranges carry their owner.

Object driver: prepareBatch lazily materializes touched instances and tracks parents instead of cloning the full instance map up front—important for large sibling trees.

Regression coverage: New Node benchmark universal-leaf-update (compiler + native driver) with ratio guards vs 0 siblings; registered in bench.mjs, MCP server, and docs. Broad Vitest scenarios for siblings, keyed lists, boundaries, structural/compact lists, and host rejection.

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

@github-actions github-actions Bot added the fix PR: bug fix label Aug 5, 2026
@leonidaz
leonidaz marked this pull request as ready for review August 5, 2026 18:58

@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.

Autofix Details

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Scoped updates bypass boundary guards
    • resolveScopedTarget now rejects targets when the walk or path from scheduled owners crosses an isBoundary owner, restoring full-root fallback for for-item updates under try/Suspense.

Create PR

Or push these changes by commenting:

@cursor push 7476232cda
Preview (7476232cda)
diff --git a/packages/octane/src/universal-core.ts b/packages/octane/src/universal-core.ts
--- a/packages/octane/src/universal-core.ts
+++ b/packages/octane/src/universal-core.ts
@@ -6717,6 +6717,10 @@
 	// or several owners raised by one event scope) still has one smallest
 	// ancestor whose retained props and range can replay every queued update:
 	// the nearest enclosing component owner of their common ancestor.
+	// The walk must not cross a try/Suspense boundary: context and for-item
+	// owners have component === null, so lifting past isBoundary would select a
+	// parent above boundary coordination that prepareOwnedUpdate only guards on
+	// the target's ancestors.
 	private resolveScopedTarget(): UniversalOwnerRecord | undefined {
 		let scope: UniversalOwnerRecord | null = null;
 		for (const owner of this.scheduledOwners) {
@@ -6724,12 +6728,24 @@
 			scope = scope === null ? owner : commonOwnerAncestor(scope, owner);
 			if (scope === null) return undefined;
 		}
+		let target: UniversalOwnerRecord | undefined;
 		for (let current = scope; current !== null; current = current.parent) {
+			if (current.isBoundary) return undefined;
 			if (current.component !== null && current.componentProps !== null && current.range !== null) {
-				return current;
+				target = current;
+				break;
 			}
 		}
-		return undefined;
+		if (target === undefined) return undefined;
+		// When the common ancestor already sits above a boundary, the upward
+		// walk never visits it. Reject any target that would replay across one.
+		for (const owner of this.scheduledOwners) {
+			if (owner.disposed) continue;
+			for (let current = owner; current !== target; current = current.parent!) {
+				if (current === null || current.isBoundary) return undefined;
+			}
+		}
+		return target;
 	}
 
 	prepare(component: UniversalComponent<any>, props: any): UniversalPreparedAttempt {

diff --git a/packages/octane/tests/universal-event-scope.test.ts b/packages/octane/tests/universal-event-scope.test.ts
--- a/packages/octane/tests/universal-event-scope.test.ts
+++ b/packages/octane/tests/universal-event-scope.test.ts
@@ -11,6 +11,7 @@
 	universalFor,
 	universalPlan,
 	universalProps,
+	universalTry,
 	universalValue,
 	useContext,
 	useLayoutEffect,
@@ -288,6 +289,64 @@
 		root.unmount();
 	});
 
+	it('replays through the root when a keyed list item under a try boundary updates', () => {
+		const container = createObjectContainer();
+		const root = createUniversalRoot(container, createObjectDriver());
+		const rowPlan = universalPlan('object', { kind: 'host', type: 'row', propsSlot: 0 });
+		const shellPlan = universalPlan('object', {
+			kind: 'host',
+			type: 'shell',
+			bindings: [['stamp', 0]],
+		});
+		const log: string[] = [];
+		const Panel = defineUniversalComponent('object', () =>
+			universalTry(
+				() =>
+					universalFor(
+						[1, 2],
+						(id) => id,
+						(id) => {
+							const [count, setCount] = useState(0, 'count');
+							return universalValue(rowPlan, [
+								universalProps([
+									['set', 'value', `${id}:${count}`],
+									['set', 'onPress', () => setCount((value) => value + 1)],
+								]),
+							]);
+						},
+					),
+				() => universalValue(rowPlan, [universalProps([['set', 'value', 'loading']])]),
+			),
+		);
+		const Shell = defineUniversalComponent('object', () => {
+			// deps null: run on every Shell render. A scoped lift above the try
+			// would replay Panel alone and skip this effect; full-root fallback
+			// required for boundary coordination must re-run it.
+			useLayoutEffect(
+				() => {
+					log.push('shell');
+					return () => log.push('shell-clean');
+				},
+				null,
+				'shell-every',
+			);
+			return [universalValue(shellPlan, ['root']), universalComponent('object', Panel)];
+		});
+
+		root.render(Shell, undefined);
+		const shell = container.children[0];
+		const rows = container.children.filter((child) => child.type === 'row');
+		expect(rows.map((row) => row.props.value)).toEqual(['1:0', '2:0']);
+		expect(log).toEqual(['shell']);
+
+		flushUniversalSync(() => container.dispatchEvent(rows[1], 'press', {}));
+		expect(container.children[0]).toBe(shell);
+		expect(container.children.filter((child) => child.type === 'row')).toEqual(rows);
+		expect(rows.map((row) => row.props.value)).toEqual(['1:0', '2:1']);
+		expect(log).toEqual(['shell', 'shell-clean', 'shell']);
+		root.unmount();
+	});
+
 	it('applies parent and child state raised by one event in a single commit', () => {
 		const container = createObjectContainer();
 		const root = createUniversalRoot(container, createObjectDriver());

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

Comment thread packages/octane/src/universal-core.ts Resolved

@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

Done

Create PR

Or push these changes by commenting:

@cursor push 3a2bef87e9
Preview (3a2bef87e9)
diff --git a/packages/octane/src/universal-core.ts b/packages/octane/src/universal-core.ts
--- a/packages/octane/src/universal-core.ts
+++ b/packages/octane/src/universal-core.ts
@@ -6755,8 +6755,9 @@
 		let endAnchor: number | null = null;
 		let current = scope;
 		for (let parent = current.parent; parent !== null; current = parent, parent = current.parent) {
-			if (parent.kind === 'host') return { parent: parent.id, endAnchor };
-			if (parent.kind !== 'range') return null;
+			if (parent.kind !== 'host' && parent.kind !== 'range') return null;
+			// Host and range parents both keep out-of-scope later siblings; the
+			// first physical host after the scope is the append/move fence.
 			if (endAnchor === null) {
 				const siblings = parent.children;
 				for (let index = siblings.indexOf(current) + 1; index < siblings.length; index++) {
@@ -6767,6 +6768,7 @@
 					}
 				}
 			}
+			if (parent.kind === 'host') return { parent: parent.id, endAnchor };
 			if (parent === this.rootRecord) return { parent: null, endAnchor };
 		}
 		return null;

diff --git a/packages/octane/tests/universal-event-scope.test.ts b/packages/octane/tests/universal-event-scope.test.ts
--- a/packages/octane/tests/universal-event-scope.test.ts
+++ b/packages/octane/tests/universal-event-scope.test.ts
@@ -460,6 +460,64 @@
 		root.unmount();
 	});
 
+	it('anchors scoped inserts and reorders before later siblings of a host parent', () => {
+		const container = createObjectContainer();
+		const root = createUniversalRoot(container, createObjectDriver());
+		const rowPlan = universalPlan('object', {
+			kind: 'host',
+			type: 'row',
+			bindings: [['label', 0]],
+		});
+		const siblingPlan = universalPlan('object', {
+			kind: 'host',
+			type: 'sibling',
+			bindings: [['value', 0]],
+		});
+		const viewPlan = universalPlan('object', {
+			kind: 'host',
+			type: 'view',
+			children: [
+				{ kind: 'slot', slot: 0 },
+				{ kind: 'slot', slot: 1 },
+			],
+		});
+		let apply!: (ids: string[]) => void;
+		const Rows = defineUniversalComponent('object', () => {
+			const [ids, setIds] = useState(['a', 'b'], 'ids');
+			apply = (next) => setIds(next);
+			return ids.map((id) => universalValue(rowPlan, [id], id));
+		});
+		const Shell = defineUniversalComponent('object', () =>
+			universalValue(viewPlan, [
+				universalComponent('object', Rows),
+				universalValue(siblingPlan, ['sib']),
+			]),
+		);
+
+		root.render(Shell, undefined);
+		const view = container.children[0];
+		expect(view.children.map((child) => child.type)).toEqual(['row', 'row', 'sibling']);
+		const rowA = view.children[0];
+		const rowB = view.children[1];
+		const sibling = view.children[2];
+
+		// Host parents own the scope plus later siblings; appends and trailing
+		// moves must stay before that untouched sibling, not after it.
+		flushUniversalSync(() => apply(['b', 'a', 'c']));
+		expect(view.children[0]).toBe(rowB);
+		expect(view.children[1]).toBe(rowA);
+		expect(view.children[2].type).toBe('row');
+		expect(view.children[2].props.label).toBe('c');
+		const rowC = view.children[2];
+		expect(view.children[3]).toBe(sibling);
+
+		flushUniversalSync(() => apply(['c']));
+		expect(view.children.map((child) => child.type)).toEqual(['row', 'sibling']);
+		expect(view.children[0]).toBe(rowC);
+		expect(view.children[1]).toBe(sibling);
+		root.unmount();
+	});
+
 	it('updates compact leaf rows from list state without disturbing row identity', () => {
 		const container = createObjectContainer();
 		const base = createObjectDriver();

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

Reviewed by Cursor Bugbot for commit f028dcf. Configure here.

Comment thread packages/octane/src/universal-core.ts Resolved
@leonidaz
leonidaz marked this pull request as draft August 5, 2026 20:43
@leonidaz
leonidaz marked this pull request as ready for review August 5, 2026 20:46
@leonidaz
leonidaz merged commit 48e2397 into main Aug 5, 2026
50 checks passed
@leonidaz
leonidaz deleted the universal branch August 5, 2026 20:55
doodlewind added a commit to pocket-nexus/pocketjs that referenced this pull request Aug 6, 2026
…k XMB covers (#227)

* feat(framework): add Octane as the third first-class framework

Octane (React's programming model, compiled) joins Solid and Vue Vapor:
universal-driver renderer over the native tree, full 15-component surface,
use-prefixed frame hooks, app.octane.tsx variants for all 8 demos, playground
in-browser compilation, byte-exact PPSSPP goldens, and a three-framework
PPSSPP benchmark (docs/bench/) per the PR #6 methodology. The PSP host gains
an arena-pressure GC; framework=octane builds stub octane/profiling to dodge
a WeakMap pinning pathology in the pinned QuickJS.

Co-Authored-By: Claude Fable 5 <[email protected]>

* perf(octane): move continuous motion onto native channels; fix silently -O0 QuickJS builds

Real-hardware testing showed hero-octane under 1 fps. Two root causes:

1. Every PSP QuickJS build was -O0: CRATE_CC_NO_DEFAULTS=1 drops the cc
   crate's synthesized flags including build.rs opt_level(), and the pin
   predated quickjs-rs PR #6 anyway. -O2 now lives in TARGET_CFLAGS and
   libquickjs-sys is repinned to master (ba5bdd0d) registry-wide
   (psp + vita Cargo, psp/symbian toolchain manifests, pin tests).

2. An Octane state commit replays the whole root regardless of where the
   state lives (~2-4ms desktop, engine-bound on PSP), so per-frame state is
   unaffordable there. Continuous motion now rides the native channels:
   sprite atlases (hero/gallery/library spinners via sprites.json + a new
   spinner-atlas.svg), baked keyframe timelines (music equalizer,
   apps/music/pocket.config.ts), animate()/jump() one-shots (stats systems
   reveal), ref-based phase timers (notifications, library loading), and a
   new setTextContent() escape hatch - the text-shaped sibling of animate() -
   for count-ups and percentages (stats tiles, music progress).

useSpriteAnimation also stops committing state on ticks that do not change
the visible sprite frame.

PPSSPP avg frame work, before -> after (budget 16.7ms):
hero 387.8 -> 6.5ms, stats 279.9 -> 9.2ms, music 282.7 -> 12.9ms,
notifications 271.2 -> 13.8ms, library 50.8 -> 4.9ms, settings 27.4 ->
14.5ms, cards 9.7 -> 6.6ms. All three frameworks' e2e suites pass; only
the six goldens whose pixels legitimately changed were re-baselined.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(psp): XMB cover art for all eight showcase demos; refresh bench + blog to post-fix numbers

- tools/gen-demo-covers.ts bakes the pocket app-family cover convention for
  every showcase demo: ICON0 as a geometry-drawn family tile, PIC1 as a real
  sim-pumped frame of the app with the XMB legibility dim. apps/<demo>/psp/
  fragments apply to every framework build of that demo.
- docs/bench: archive the 2026-07-30 post-optimization dataset (geomean
  avg_work octane 1.66x vs solid, was 15.58x; all 21 cells inside the 16.7ms
  budget) alongside the pre-fix 07-29 dataset.
- blog: add "The hardware said no" chapter (the -O0-since-2021 discovery,
  replay-scope-independence, the native-channel rule, per-demo before/after),
  refresh the benchmark section to the new dataset with a linear-scale chart,
  and re-count byte-identical goldens (14/23).
- playground compiler-entry merges the music demo's equalizer keyframes into
  the playground-wide animation theme.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(blog): rewrite the Octane post's index blurb for outside readers

No repo-internal references, leads with the machine and the three findings;
post dated to its publish day.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(compiler): hard-error on <g transform> in bake-svg; flatten the spinner atlas

The svg baker scans shapes flat, so the spinner atlas's per-cell
<g transform="translate(...)"> was silently dropped - all eight frames baked
into cell 0 and cells 1-7 shipped blank. On hardware the spinner sat
invisible and "flashed" once per cycle when the frame index wrapped through
the one painted cell; the golden re-baseline had baked the bug in.

The atlas now carries absolute per-cell circle coordinates (no groups), and
bake-svg refuses <g transform> loudly instead of mis-baking. All four
affected goldens re-baked and visually verified: the spinner is present at a
distinct phase in every capture.

Co-Authored-By: Claude Fable 5 <[email protected]>

* docs(blog): record the hardware confirmation and the blank-atlas incident

The post-fix builds are verified on the same physical PSP that failed the
first run; the sprite-cycling bullet now carries the honest beat about the
<g transform> atlas bake and the golden re-baseline that hid it.

Co-Authored-By: Claude Fable 5 <[email protected]>

* perf(octane): upgrade to 0.1.26 scoped updates, move hero's count off the root

octanejs/octane#578 (shipped in 0.1.26) makes a universal setState replay only
the owning component's subtree instead of the whole root. It landed the day
after we filed #574 with a repro, and our repro is now their regression
benchmark (benchmarks/universal-leaf-update).

The upgrade alone changes nothing on device: all 23 psp-octane goldens stay
byte-exact, and every bench app's press cost is unmoved. The reason is on our
side — octane scopes a replay to the nearest owner holding a committed range,
and a root component has none, so state that lives in the root component still
replays everything. Every demo keeps its interactive state in the root.

Hero now demonstrates the shape the fix rewards: the counter moves into a
CounterRow leaf, and the underline it also drives leaves the render path for
the native jump() channel. Output is unchanged to the byte (all 23 goldens
pass), while on PPSSPP:

  hero octane   avg work 6.53 -> 3.64 ms   max work 176.89 -> 37.80 ms
  hero solid    avg work 3.66 ms           max work 31.47 ms

That is press-latency parity with Solid, from a 4.7x drop in the worst frame.
The other six demos are unconverted; several of them hold state at the root
legitimately (library's screen, stats' tab switch whole views) and need
per-app judgement rather than a blanket refactor.

Verified: full suite 8 groups 0 fail, tsc clean, 23/23 psp-octane goldens
byte-exact, solid control unchanged (+0%) across the same bench run.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(psp): per-framework XMB covers — the Octane twins name themselves

A demo's framework twins were indistinguishable on a memory stick: both the
Solid and the Octane build of `hero` packed the same icon and the same
"PocketJS Hero" title, so the XMB gave you no way to tell which one you were
about to launch.

gen-demo-covers.ts grows --framework=<fw>, which bakes a variant set into
apps/<demo>/psp/<fw>/ instead of the shared directory: the framework's name
under the accent rule on the 144x80 tile, an accent-bordered badge in the
PIC1 corner, and "(Octane)" appended to the PARAM.SFO title. PIC1 is rendered
from that framework's own bundle. tools/psp.ts prefers <app>/psp/<framework>/
when it exists and otherwise keeps using the shared fragment, so default
builds are untouched.

All eight Octane demos get the variant set. Verified by unpacking the built
PBPs: every one carries its Octane icon0/pic1 and an "(Octane)" SFO title.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fix PR: bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Universal target: one leaf setState replays the whole root — update cost scales with total tree size, not update scope

1 participant