Skip to content

perf(signals): allocate optional scope capabilities on first use - #1288

Merged
trueadm merged 1 commit into
mainfrom
perf/lazy-scope-capabilities
Sep 23, 2026
Merged

trueadm merged 1 commit into
mainfrom
perf/lazy-scope-capabilities

Conversation

@trueadm

@trueadm trueadm commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Every signal scope eagerly allocated eleven collections, for requests, query definitions, resources, the four streamed-result maps, derived bindings, adoption leases, seeds and trace events. It also carried the streamed-result methods on ScopeImpl. These now allocate only when the feature is used.
  • Streamed selections move into a ScopeStreams capability that only the existing stream ingress functions create. Stream-free consumers stop retaining that code.
  • A useSignal$ hook scope retains 785 instead of 2,649 bytes (−70%), and stream-free signals entries are ~700 B gzip smaller (−3.7% to −5%).

Refs #1284 (proposal 1; triage in this comment).

Changes

  • signals/scope-streams.ts (new): ScopeStreams holds the selection, result, failure and waiter maps and their operations. They were moved from ScopeImpl unchanged, apart from the owner prefix. The capability participates explicitly in the owner lifecycle:
    • suspend: expire unfinished channels;
    • resume: rebind refreshed resources;
    • flush: deliver results received before the declaration ran;
    • clear: on dispose.
  • signals/engine.ts:
    • requests, queryDefinitions, resources, derivedBindings, frames, seedEntries and events start as undefined and allocate on first write. They are initialized in the class body, so the object shape stays stable.
    • Suspend, resume and dispose run in the same order as before: producers stop before channels clear, and adoption leases release before the graph retires.
    • bindScopeStreamedSelection is the only function that creates the capability. Accept and fail keep their liveness check and return false when nothing was bound.
  • signals/requests.ts and signals/facade.ts use the lazy maps and the capability. There are no public API or type changes.

Measurements

Baseline is main @ afc0bee88, archived. The candidate is this branch. The repo's own run-bundles.mjs comparison reports every boundary check and export smoke test as passed.

Entry (run-bundles.mjs) Baseline raw / gz / br Candidate raw / gz / br gzip delta
engine (createScope, query) 47,565 / 14,522 / 13,144 44,064 / 13,794 / 12,478 −728 (−5.0%)
native-client (useSignal$) 50,381 / 15,916 / 14,383 46,880 / 15,185 / 13,713 −731 (−4.6%)
native-server (useSignal$) 50,273 / 15,841 / 14,318 46,744 / 15,099 / 13,641 −742 (−4.7%)
compiled-plain-signals 70,147 / 20,664 / 18,677 66,793 / 19,992 / 18,091 −672 (−3.3%)
streamed-signals-bootstrap 76,389 / 23,673 / 21,216 76,400 / 23,886 / 21,388 +213 (+0.9%)
streamed-signal-results-bootstrap 70,291 / 21,636 / 19,421 70,302 / 21,858 / 19,563 +222 (+1.0%)
ordinary-client, ordinary-server, binding-* — byte-identical 0

Stream-using entries are +11 raw bytes, but gzip +213/+222. Moving the stream code out of ScopeImpl costs some compression locality; no work was added. That is the tradeoff against −670 to −740 B for every stream-free consumer.

Retained heap: Node 24, 50,000 scopes kept alive, post-GC heapUsed delta, deterministic across runs:

Scope Baseline Candidate
useSignal$ shape: local scope + one signal$ 2,649 B 785 B (−70%)
Shared scope: two signal$, one derived$, one subscription 3,827 B 1,962 B (−49%)

Timing (one process, both builds alternating, 10 samples after 2 warmups):

  • Lifecycle: a local scope, plus a shared scope with a derived value and a subscription, created, read and disposed. 5,600 → 4,155 ns per cycle (−26%).
  • Scalar read/write: set, then read a derived value with one subscriber. 153 vs 156 ns, overlapping ranges (151–162 vs 154–160). That code path is unchanged.

Validation

  • New test in signals-streams.test.ts. On a scope with live ordinary signals, it activates a streamed selection (results buffered before the declaration), then a resource, an adoption lease and tracing. It checks that:

    • ordinary signals and their subscriptions keep working;
    • the resource receives the streamed value without fetching;
    • dispose() is idempotent and clears every capability;
    • stream ingress on the retired scope is refused.

    The test passes on both the baseline and the candidate: it pins preserved behavior.

  • Mutation checks on the new code. Caught:

    • adoption leases not tracked: 54 failures;
    • trace events not stored: 4;
    • stream suspension skipped: 1;
    • derived bindings not recorded: 2;
    • resources never recorded: tests hang.

    Four mutants survive, all equivalent through the public API:

    • re-reading the request map before resume, since selection starts its own request;
    • the pre-declaration flush, since selectionReady flushes the same results;
    • the ingress liveness check, since the facade drops retired owners first;
    • clearing stream state on dispose, which only affects retention.
  • New bundle guard in bundle-boundaries.mjs/.test.mjs (runs in ci:workflow:test). engine, native-client, native-server and compiled-plain-signals must emit zero bytes from scope-streams.ts. This covers a synthetic negative case and the real engine and native-client closures. Making every scope create the capability eagerly fails it.

  • All four signal projects (node, dev, prod, strong): 814 passed across 51 files.

  • Stream, hydration and behavior suites in dev and prod (streamed cancellation, automatic signal streams, document lifecycle, stream receiver/delivery, streamed query hydrate, signal instance/owner identity, early handoff/intent, fetched regions/history, universal transport, behavior roots): 852 passed across 30 files.

  • benchmarks/scoped-signals CI tests (bundle boundaries, workloads, async retainers, deferred/split boundaries): 57 passed.

  • pnpm typecheck:files on changed files, tsgo -p packages/octane/typetests/signals-engine-node, pnpm format:files:check, pnpm changeset:check and pnpm sync.

  • pnpm test, pnpm typecheck and pnpm format:check (repo-wide): left to CI.

Risk / follow-ups

  • Lifecycle order is the main risk. Suspend, resume and dispose keep the original sequence; the capability test and the existing document-lifecycle and retirement suites cover it.
  • observers and nodes stay eager. Nearly every scope uses them, and observers is on the subscription path.
  • Proposals 2 and 3 in Reduce runtime reachability for scoped signals and fixed-node bindings #1284 are unchanged. See the triage comment.

Provenance

  • An agent produced this diff (agent-authored)

🤖 Generated with Claude Code


View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.


Note

Medium Risk
Touches core scope lifecycle (suspend/resume/dispose) and streamed-result delivery order; behavior is heavily tested but mistakes in lazy init could affect queries and hydration.

Overview
Signal scopes no longer eagerly create maps and bookkeeping for requests, resources, derived bindings, adoption frames, trace events, or streamed results. Those structures are allocated on first use, which cuts retained memory for simple hook scopes (e.g. useSignal$) and shrinks stream-free bundles by roughly 700 B gzip.

Streamed selections are refactored into a new ScopeStreams capability (scope-streams.ts). Stream ingress (bindScopeStreamedSelection / attachStreamedSignalResult) is the only path that creates it; accept/fail stay no-ops until a selection is bound. Suspend, resume, flush, and dispose behavior is preserved on the capability.

Bundle guards assert that engine, native-client, native-server, and compiled-plain-signals emit zero bytes from scope-streams.ts when they never bind streams. A new integration test verifies late activation of streams, resources, adoption, and tracing on a scope that already has ordinary signals.

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

A ScopeImpl eagerly allocated eleven collections for requests, query
definitions, resources, streamed selections/results/failures/waiters,
derived bindings, adoption leases, seeds and trace events, and kept the
streamed-result methods on the class, so every scope paid for them.

Streamed selections now live in a ScopeStreams capability that only the
existing stream ingress functions create. The other optional collections
allocate on first use. Lifecycle order is unchanged: producers stop before
channels clear, and adoption leases release before the graph retires.

A useSignal$ hook scope retains 785 instead of 2,649 bytes, stream-free
signal entries are about 700 bytes smaller after gzip, and a bundle guard
keeps the capability out of those entries.

Refs #1284 (proposal 1).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@trueadm
trueadm marked this pull request as ready for review September 23, 2026 20:02
@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent perf PR: performance work labels Sep 23, 2026
@trueadm
trueadm merged commit 701b8c3 into main Sep 23, 2026
46 of 49 checks passed
@trueadm
trueadm deleted the perf/lazy-scope-capabilities branch September 23, 2026 20:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-authored Diff or issue body substantially produced by an AI agent perf PR: performance work

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant