Skip to content

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

Closed

Description

@doodlewind

Summary: on the universal target, a setState in one leaf component replays from the root — the cost of updating a single component scales with the total number of components in the tree, not with the size of the update. In the repro below, the same one-leaf state change goes from 0.024 ms with no siblings to 23 ms with 4,000 untouched siblings (~1,000×). On desktop this hides inside the frame budget; on the 333 MHz MIPS handheld we ship on it's a 150–250 ms hitch per button press.

(Following up from the X exchange — thanks for the quick response. Context: we ported octane's universal target to the Sony PSP as one of PocketJS's three frameworks; writeup: https://pocketjs.dev/blog/octane-on-psp/. Everything below reproduces on plain Node with stock octane — no PSP required.)

Repro

octane 0.1.25 (same shape on 0.1.18), Node v24.15.0, macOS arm64. Four files, then npm install && node bench.mjs.

package.json

{
  "name": "octane-universal-replay-repro",
  "private": true,
  "type": "module",
  "dependencies": {
    "octane": "^0.1.25"
  }
}

runtime.mjs

// The renderer module the compiled output imports from — for this repro it is
// just the stock universal native runtime, re-exported.
export * from "octane/universal/native";

app.jsx

// One stateful leaf (Counter) next to `size` stateless leaf siblings.
// Pressing the button updates ONLY the Counter's own useState value.
import { useState } from "octane";

function Leaf({ index }) {
  return <view label={"leaf-" + index} />;
}

function Counter() {
  const [count, setCount] = useState(0);
  return <view focusable={true} onPress={() => setCount((v) => v + 1)} label={"count-" + count} />;
}

export default function App({ size }) {
  return (
    <view>
      <Counter />
      {Array.from({ length: size }, (_, index) => (
        <Leaf key={index} index={index} />
      ))}
    </view>
  );
}

bench.mjs

// Measures the cost of ONE leaf setState as a function of how many OTHER
// (stateless, untouched) components exist in the tree.
//
//   node bench.mjs
//
// Uses only public octane APIs: octane/compiler + the universal native
// target's object driver.
import { compile } from "octane/compiler";
import { readFileSync, writeFileSync } from "node:fs";
import { performance } from "node:perf_hooks";

const RENDERER = {
  id: "object",
  module: "./runtime.mjs",
  target: "universal",
  server: "unsupported",
  text: "host",
  capabilities: [],
};

const src = readFileSync(new URL("./app.jsx", import.meta.url), "utf8");
const compiled = compile(src, "app.jsx", { mode: "client", renderer: RENDERER });
if (compiled.diagnostics?.length) {
  console.error(compiled.diagnostics);
  process.exit(1);
}
writeFileSync(new URL("./app.compiled.mjs", import.meta.url), compiled.code);

const { createUniversalRoot, createObjectContainer, createObjectDriver, flushUniversalSync } =
  await import("octane/universal/native");
const { default: App } = await import("./app.compiled.mjs");

function findCounter(children) {
  for (const child of children) {
    if (String(child.props?.label ?? "").startsWith("count-")) return child;
    const nested = findCounter(child.children ?? []);
    if (nested) return nested;
  }
  return null;
}

function pressCost(size) {
  const container = createObjectContainer("object");
  const root = createUniversalRoot(container, createObjectDriver("object"));
  flushUniversalSync(() => root.render(App, { size }));
  const counter = findCounter(container.children);
  if (!counter) throw new Error("counter instance not found");

  const press = () => flushUniversalSync(() => container.dispatchEvent(counter, "press", {}));
  for (let i = 0; i < 30; i++) press(); // warmup

  const ROUNDS = 5;
  const PRESSES = 100;
  let best = Infinity;
  for (let round = 0; round < ROUNDS; round++) {
    const t0 = performance.now();
    for (let i = 0; i < PRESSES; i++) press();
    best = Math.min(best, (performance.now() - t0) / PRESSES);
  }

  const label = String(counter.props?.label ?? "");
  const instances = container.instanceCount;
  root.unmount();
  return { best, label, instances };
}

console.log("| stateless siblings | host instances | ms per leaf setState |");
console.log("| --- | --- | --- |");
for (const size of [0, 500, 1000, 2000, 4000]) {
  const { best, label, instances } = pressCost(size);
  if (label !== "count-530") throw new Error(`updates did not apply: ${label}`);
  console.log(`| ${size} | ${instances} | ${best.toFixed(3)} |`);
}

Results on my machine (best-of-5 average over 100 presses each; only the counter's own state changes, siblings receive nothing):

stateless siblings host instances ms per leaf setState
0 2 0.024
500 502 2.249
1000 1002 4.270
2000 2002 9.793
4000 4002 22.955

Expected: per-press cost roughly independent of the untouched sibling count.

Where the time goes

node --cpu-prof over the same run, self-time:

 20.4%  (garbage collector)
 13.0%  (anon)                     universal-core.js
  6.3%  writeOwnerIdentity         universal-core.js
  5.4%  prepareBatch               universal-core.js   <- object-driver harness, see note
  5.2%  claimChildOwner            universal-core.js
  4.8%  readOwnerIdentity          universal-core.js
  4.7%  materializeComponentValue  universal-core.js
  3.3%  draftOwner                 universal-core.js
  3.1%  universalProps             universal-core.js
  2.8%  materializeNode            universal-core.js
  2.8%  childOwnerBucket           universal-core.js
  2.8%  executeOwner               universal-core.js

Reading universal-core.js, this matches the code shape:

  • Every hook update ends in owner.root.schedule() (scheduleOwner, the useState/useReducer update paths) — replay is always root-scoped.
  • The replay re-drafts the owner tree from the root (draftOwner / executeOwner / materializeComponentValue), so bookkeeping runs for every owner even when its output is unchanged.
  • Child claiming walks the owner-identity index with each owner's full identity path, several times per owner per replay (childOwnerBucket, claimChildOwner, plus the ordinal and cursor reads/writes through readOwnerIdentity/writeOwnerIdentity — each one a segment-by-segment chain of Map lookups starting from the component root). In our real app a function counter measured ~13,000 ownerIdentityMapKey invocations per replay. These paths are stable across replays, so they look cacheable.
  • The 20% GC line is the per-replay draft allocation (draftOwner clones hooks/context/update maps for every owner in the tree).

Two honesty notes about the repro itself:

  • The object driver's prepareBatch clones its whole instance map per commit, which is also O(tree) — but it accounts for only ~5% of self-time, so it is not the source of the scaling. Our production driver prepares batches in O(commands) and shows the same wall-time scaling on device.
  • Wrapping the static siblings in memo() changes nothing measurable — as far as we can tell component render bodies already skip; the cost is the replay machinery itself, not user render code.

Why it bites us

The PSP is a 333 MHz single-issue MIPS core running QuickJS. One replay of our (fairly small) demo app costs 150–250 ms of press-to-response latency there, while all continuous animation holds 60 fps because we routed it around setState entirely. The same replay is 2–4 ms on an M-series laptop — invisible on desktop, dominant on low-end hardware.

Caching the identity-path lookups and/or scoping replay to the scheduling owner's subtree would presumably collapse most of this, but you know the constraints better than we do. Happy to run candidate patches on real hardware and report numbers.

Activity

  1. self-assigned this
    on Aug 5, 2026
  2. leonidaz commented on Aug 5, 2026

    @leonidaz
    Collaborator

    Thanks for reporting! Got this fixed and a few others that got identified - #578

    Going to merge and ship a release right after.

    Give it a try and let us know if you find any more issues. Happy to fix asap!

  3. doodlewind commented on Aug 6, 2026

    @doodlewind
    Author

    Fixed — thank you, that was a fast turnaround. Confirming with the same repro from the issue, 0.1.25 → 0.1.26:

    stateless siblings 0.1.25 0.1.26
    0 0.024 ms 0.020 ms
    1000 4.270 ms 0.011 ms
    4000 22.955 ms 0.010 ms

    Flat instead of linear in tree size, and the correctness assertions in the bench (final counter value, exact host-instance count) still pass. Nice touch turning it into a permanent regression benchmark with the ratio guard.

    One field note from adopting it, in case it is useful to other host integrations. On our side the upgrade was initially inert: every demo's press cost was unchanged on device. Probing showed all the scheduling preconditions passing (scheduledPreparationDepth 1, scheduledUrgent, !scheduledFullRoot, scheduledOwners.size 1) but resolveScopedTarget() returning undefined — it walks up looking for an owner with a committed range, and our state lived in the root component, which has none. That is reasonable behaviour (there is nothing smaller to scope to), it just meant the win was gated on an app-shape change we had not realised we needed. Moving the state one level down into a leaf component was enough.

    What that was worth on our target — a 333 MHz MIPS PSP running QuickJS, measured under PPSSPP's deterministic software renderer, same input tape, rendering byte-identical before and after:

    hero demo avg frame work worst frame (the press)
    octane 0.1.18, state in root 6.53 ms 176.89 ms
    octane 0.1.26, state in leaf 3.64 ms 37.80 ms
    Solid, same app and tape 3.66 ms 31.47 ms

    So the 150–250 ms press stall I described is now ~38 ms, and octane sits at parity with Solid on this app. Confirmed on physical hardware too — the button feels immediate now, where before every press visibly hitched.

    If you ever wanted the root component itself to carry a range, that would close the gap for the "small app, state at the top" shape without app changes — but it is entirely reasonable to say that shape should just push state down.

  4. leonidaz commented on Aug 6, 2026

    @leonidaz
    Collaborator

    ok, got something for you.

    the root component now participates in scoped updates like any other component, so the "state at the top" shape gets all of this without restructuring your app.

    Give it a try and let me know how it went: [email protected] which should be on npm in a few minutes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions