Skip to content

Reduce runtime reachability for scoped signals and fixed-node bindings #1284

Closed

Description

@domgan-oai

Goal

Investigate four related improvements to reduce the code reachable from simple scoped-signal and compiled DOM-binding consumers, while preserving the performance and semantics of the existing APIs.

This is an enhancement proposal based on public source at 0185cb2. It does not assert a measured size saving or runtime regression. Octane already separates resource/computation modules and selects several binding capabilities at compile time; the proposals below extend those boundaries. Each change should demonstrate an actual reduction in the resolved consumer graph before introducing another supported entry or runtime abstraction.

1. Extract optional resource, stream, and asynchronous-computation capabilities from the scope owner

Opportunity

ScopeImpl owns writable/synchronous signal state alongside request, resource, streamed-selection, streamed-frame, readiness/failure, and derived-binding state. Resource construction already has a useful seam: createResource(scope, key, describe) passes an initializer into the owner, and the engine imports resource implementation types rather than its runtime implementation. The remaining question is whether optional state and its lifecycle code can move out of the core owner's reachable implementation.

Sources: scope-owned state, resource initializer seam, documented signal semantics.

Suggested approach

  1. Inventory the owner operations required by writable signals and synchronous Scope.derived$: graph publication, equality, guards, batching, ownership, and disposal. Distinguish these from the declaration-facade derived$ API, which also supports asynchronous values and streams.
  2. Extract typed, scope-owned capability objects for genuinely optional features. Allocate their maps and producer bookkeeping only when the existing resource/computation/stream API is used. Start with one capability, keeping the public API unchanged, before generalizing the design.
  3. Give each capability explicit participation in serialization, adoption, cancellation, and disposal. Attach it deterministically through existing API calls and any seed, adoption, or receiver ingress that needs it. Avoid a mutable process-global feature registry or a requirement that users import modules in a particular order.
  4. Keep scalar reads/writes and synchronous derivation on their current direct path where possible. A universal capability dispatcher that adds allocations or lookups to every write could trade smaller output for worse hot-path performance.

Risks and validation

The state is connected through lifecycle ordering, rather than being four independent collections. Disposal must invalidate the owner and stale producers before cleanup can invoke user code. Extraction must preserve stream-attempt identity, stale-result fencing, abort propagation, iterator closure, post-await dependency handling, seed/request metadata, serialization, historical leases, and adoption guards.

Use the existing signal state, serialization, hydration, and asynchronous lifecycle tests as controls. Add focused coverage for activating an optional capability after ordinary signals already exist, multiple capabilities on one owner, and idempotent cleanup. Compare both the emitted graph and per-scope allocation/lifetime costs. Moving code to another file is insufficient if the core still retains it through imports or method references.

2. Provide a supported smaller scoped-signal entry backed by the same canonical core

Opportunity

A consumer may need only createScope, writable signals, synchronous derivation, reads/writes, subscription, batching, and disposal. A documented entry for that use case could make the intended dependency boundary explicit. At this revision there is no public octane/signals/sync entry; its name and exact contract should be designed upstream.

Sources: current scope contract, signals exports, package entry points, canonical owner checks.

Suggested approach

  1. Establish real internal boundaries first, potentially through proposal 1. A barrel that re-exports the current createScope retains the same implementation and does not establish a smaller closure.
  2. Reuse one canonical owner/node implementation, graph state, native-read protocol, scheduler/publication state, and lifetime identity across the supported entries within the same module graph. Do not copy the scalar engine into a second entry.
  3. Choose the contract explicitly. If the entry returns the existing full Scope, every documented method must remain valid and optional capabilities must activate deterministically. If a genuinely narrower contract is necessary, expose an honest narrower type and document feature interoperability and limitations. Do not type a reduced implementation as the full interface.
  4. Publish the entry through package exports and declarations, and verify the supported resolver conditions and distributed artifacts. Compiler-generated code and deferred chunks must resolve the same core. Decide whether this new public surface is still worthwhile if the ordinary entry becomes sufficiently small through internal extraction.

Risks and validation

Duplicate cores can cause cross-entry handles to fail owner checks, split scheduling state, or lose adoption/transition interoperability. A global singleton should not conceal independently installed package instances. Changes to export conditions can also make source-tree tests pass while packaged consumers fail.

Test mixed imports from the ordinary and smaller entries, cross-entry handles, optional resource activation, deferred chunks, renderer bindings, disposal, and any explicitly supported loading configuration. Build packaged consumer fixtures as well as source fixtures. Report the smaller entry alone and both entries combined, including deduplicated chunks and any newly deferred bytes. Treat public-surface maintenance and compatibility as costs alongside the byte saving.

3. Investigate a smaller transaction/transition boundary without weakening Actions

Opportunity

The signal graph currently imports and registers an Action frame factory and transition coordinator. It is worth investigating whether ordinary synchronous graph publication can retain a small canonical transaction protocol while more specialized transition preparation lives behind a deliberate capability boundary.

Sources: graph registration, live registration contract, renderer acquisition, transaction semantics and limits.

Suggested approach

  1. Separate ordinary publication, scalar staging/read visibility, and transition-specific preparation in a dependency inventory. scope.action is a synchronous batching wrapper; renderer Actions have a separate transactional contract. Keep that distinction explicit.
  2. Preserve the existing factories and live lookup initially. The source deliberately supports signals first loaded after an Action has already awaited, including handles passed through opaque props without a local signal import. Those cases define the minimum interoperability kernel.
  3. Only move heavier coordination when the renderer can acquire the complete capability synchronously and deterministically at the existing boundary. Do not put registration solely in action$, assume a signal import is visible at the call site, annotate required initialization away, or dynamically import support during the first synchronous write.
  4. Keep this investigation separate from resource-state extraction. If preserving the contract retains most of the code or adds costly dispatch, keep the current boundary and document the finding.

Risks and validation

A superficially successful bundle split can silently publish model state before prepared native presentation, expose candidate values to committed reads, or miss frame acquisition after an await. Preserve atomic acceptance, functional-update chronology, urgent updates, cancellation, supersession, errors, retirement, and cleanup. Preserve the documented rejection of receiver-owned server streams and historical adoption frames as transition candidates; this proposal does not extend those combinations.

Use Action lifecycle coverage, especially late-loaded signals and opaque handles, plus mixed-entry and code-split cases. Compare publication counts, committed/candidate visibility, scheduling work, and native presentation alongside output size. This is the highest semantic-risk proposal and should proceed only with a demonstrated useful boundary.

4. Extend compiler-selected specialization for fixed-node DOM bindings

Opportunity

The compiler already selects optional projection, style, control, signal, class, and other binding capabilities, and emits lean binding programs. The further opportunity is to audit the residual runtime retained by eligible fixed-node scalar templates and select only the claim, writer, source-subscription, and cleanup operations they actually require.

Sources: binding source and lifetime contract, existing compiler capability imports, experimental compiler-backed API.

Suggested approach

  1. Start with public compiled adoptBindings/mountBindings fixtures containing fixed nodes and scalar text/attributes. Record their complete resolved dependencies and identify which general adoption/program helpers remain reachable. Do not infer the retained graph from helper names alone.
  2. Extend the compiler's existing plan/IR and capability selection to choose specialized helpers where it has proof. Share canonical claim, signal, and ownership machinery. Avoid a second renderer, copied engine, handwritten application DOM mutations, or text rewriting of emitted code.
  3. Retain a conservative fallback for templates requiring structure, controls, projections, class groups, signal reads, or other richer semantics. An opaque value can contain a signal handle at runtime; absence of a local signals import is not proof that native-read support is unnecessary.
  4. Keep generated helper exports and compiler/runtime versions consistent. Helpers can be an internal compiler contract without becoming a new authoring API. Expand eligibility incrementally, after each class of template has semantic and graph controls.

Risks and validation

Binding behavior includes ownership and handoff, not just setting text. Preserve immutable synchronous BindingSource snapshots, safe notification during subscription, returned cleanup, refresh/dispose behavior, existing-node identity, claim diagnostics, SSR hydration handoff, externally owned handlers, and restoration of owned styles. Controls need their own focused-value and selection rules.

Use binding handoff tests, signal/DOM binding tests, and compiler artifact tests, including opaque values that become signal handles. Test both adoption and fresh mounting with the same compiled inputs. Measure publication/subscription work and cleanup as well as bytes; a smaller helper is not sufficient evidence of equivalent batching or faster updates.

Related work

#1135 documents the tradeoff between ordinary-root reachability and the standalone signal-engine closure when changing Action registration. #1139 preserves live coordination for props-only and post-await Actions. Proposal 3 should build on those constraints. #1226 already adds opt-in fixed primitive child-prop folding; proposal 4 concerns further binding-runtime reachability rather than repeating that compiler optimization.

Measurement and delivery plan

Use Octane's public scoped-signal benchmark methodology and small public consumer fixtures. Keep toolchain, production conditions, compiler options, minification, and consumer behavior matched between baseline and candidate. Report raw, gzip, and Brotli output separately, with resolved-module graphs for isolated and combined entries. Include any bytes or work moved into deferred chunks.

Pair bundle results with semantic counters and lifetime/allocation controls. For timing claims, repeat runs and report variability. A raw module size, a disabled feature, or a consumer with fewer semantics is not a valid saving for an equivalent supported API.

Suggested delivery: extract one optional capability first; evaluate whether a smaller supported entry adds value once the core boundary exists; investigate transitions independently with the late-loading controls; extend fixed-node binding specialization in a separate change. Each step should be independently reviewable and should record both achieved savings and any runtime or compatibility tradeoff.

Activity

  1. added
    enhancement
    agent-authored
    on Sep 23, 2026
  2. trueadm commented on Sep 23, 2026

    @trueadm
    Collaborator

    Agent-authored triage (Claude Code, at the maintainer's request).

    I measured each proposal's resolved graph on main @ d9ed0f446 before choosing an order. Every bundle uses esbuild 0.28.1 with minify, treeShaking, ESM, browser platform and a production NODE_ENV, with gzip level 9. Most "ceiling" numbers come from scratch copies with the feature removed. They are upper bounds, not savings for an equivalent API. The proposal 4 figure is the exception, because it keeps the full scalar semantics.

    Proposal Consumer Today (gzip) Ceiling Verdict
    4. Fixed-node binding specialization docs PrimaryAction / a title + text fixture through adoptBindings 5,793 −2,851 (−49%) Do first
    1. Optional resource/stream capability createScope + signal$ + sync derived$ + subscribe/batch/dispose 14,401 −999; −49% heap per useSignal$ scope Do second
    3. Smaller transaction boundary same consumer 14,401 −4,387 (−30%) Keep the current boundary
    2. Smaller scoped-signal entry same consumer 14,401 −2,518, only with a narrower contract Defer

    Proposal 4

    In the fixed-node scalar fixtures, __adoptBindings accounts for 12,652 of 15,202 raw bytes. It contains the projection, control, class-group, style-restoration, host-handoff and addressed-node integrations, and a template that binds only attr/boolean/aria/text uses none of them. A scalar-only adopter measured 2,942 gzip in a scratch copy, and a happy-dom smoke test showed the same DOM updates and teardown. That adopter keeps the signal connector, preview/NATIVE_TRANSITION_CONSUMER presentation, legacy claim publication, snapshot validation and cleanup ordering. The compiler knows every one of these facts about the descriptor (binding kinds, handoff, addressed, connected capabilities), and it always imports __adoptBindings today (compiler/dom-bindings.js ~L1698). Structural programs already have the lean/selected split this would follow. Claim ownership must stay shared with the general adopter and programs.

    Proposal 1

    The code saving is small because requests.ts already tree-shakes to zero bytes for a createScope-only consumer. What stays is the stream-selection methods on ScopeImpl and seven collections allocated per scope. useSignal$ creates a full ScopeImpl per component slot. Not allocating those seven collections up front took Node 24 post-GC heap from 2,649 to 1,361 bytes per local scope (100k scopes, each with one signal$). Stream state can attach through the existing ingress functions (bindScopeStreamedSelection, acceptScopeStreamedResult, failScopeStreamedResult) and resource state through createResourceDeclaration. Neither needs a process-global registry.

    Proposal 3

    transition-action.ts and transition-coordinator.ts together are 14,520 raw bytes in the standalone engine, and removing their registration from graph.ts saves 4,387 gzip. They cannot move. Every plain export { createRoot } from 'octane' closure already retains nativeCandidateForAction. A renderer-side import would therefore restore about 4.4 KB to every application, which is the regression #1135/#1139 recovered. A static module graph cannot express "renderer and signals both loaded". Dynamic loading and import-name gating are excluded for the late-loaded and opaque-handle cases. I suggest documenting this finding and treating any smaller implementation of those two modules as the only remaining lever.

    Proposal 2

    An entry that returns the full Scope saves nothing beyond proposals 1 and 3. A narrower contract without serialize, beginAdoption and inspect saves 2,518 gzip. It still has to share the canonical graph, and therefore the Action registration. I don't think that justifies a new public surface now.

    Starting proposal 4 as a separate PR.

  3. trueadm commented on Sep 23, 2026

    @trueadm
    Collaborator

    Agent-authored audit (Claude Code, at the maintainer's request).

    Can today's islands activate without the renderer?

    Scope: every independent <Hydrate> island outside packages/octane/tests, plus one route root. That is nine islands in the conversation-streaming benchmark, examples/signal-chat and the vite-plugin fixture app, plus that fixture's ConversationApp. Measured on main @ a95c2dc47, after #1286, #1288 and #1289.

    Method:

    • Compile gate: each island compiled as a 'use dom bindings' view (client, production).
    • Construct probes: small views to separate what the binding compiler accepts from what it rejects.
    • Runtime check: one view run in happy-dom from real SSR output.
    • Real production Vite builds of two apps, measuring each island's static chunk closure.

    1. Correctness bug: .get() in a binding view compiles but never updates

    export function ReadView(props: {}) @{ 'use dom bindings'; <p>{count$.get() as number}</p> }
    

    This compiles with no diagnostic. Adopted from real SSR output, the text stays at 1 after count$.set(7). The same view written with the handle, <p>{count$}</p>, adopts and updates to 7. The compiler already rejects "hooks or live accessors" in bindings, but a member call on an imported handle passes as a "pure projection". It should be rejected, or lowered to a handle binding (item 2 below). This is the first thing to fix.

    2. Every island is rejected, and for which reasons

    The compiler reports only the first rejection, so the table combines it with a manual read of each source.

    Island Zero-arg view .get()/.latest() reads Mount-only hooks @try/@pending/@catch Real component state Other
    bench Composer ✗ ✗ ready flag
    bench Body ✗ ✗ ✗ @for over a signal-derived list
    bench History ✗ ✗ ✗ @for over a signal-derived list
    chat History ✗ ✗ ✗ recordActivation ✗
    chat Tools ✗ ✗ ✗ recordActivation ✗
    chat Conversation ✗ ✗ ✗ recordActivation ✗ @catch (error, reset), local Transcript child
    chat Composer ✗ ✗ ready + recordActivation
    chat Metrics ✗ ✗ ✗ ✗ ✗ useState + interval should stay on the renderer, or move its state to signals
    fixture Composer ✗ ✗ a control bound to cond ? draftA$ : draftB$
    fixture ConversationApp (route root) ✗ ✗ ✗ ready flag ✗ nested independent island

    The probes show these already compile:

    • module-scope handles in text and in control values ({count$}, value={draft$});
    • imported and inline event handlers, including handlers that capture a @for item;
    • @for and @if over props;
    • local child components.

    The ones checked at runtime are handle text holes (adopted and updated from SSR). The handler and local-child cases were checked at compile level only. What is rejected: zero-argument views, @try (unsupported binding program construct TryStatement), and any setup statement other than a pure const alias, which includes hooks.

    Ranked by how many of the ten each blocks:

    1. Zero-argument views: 10/10. Islands take their state from module-scope signals, not props. This is mostly a gate relaxation.
    2. Lowering signal reads: 8/10. x$.get() and x$.latest(fallback) in setup and templates, including const frame = x$.get() feeding @for and attributes, need to become subscribed projections. This also closes the bug in section 1.
    3. Mount-only effects: 7/10. useLayoutEffect(() => recordActivation(...), []) and useState(false) + useLayoutEffect(() => setReady(true), []). They are activation markers or instrumentation, not rendering state. They need an activation/cleanup equivalent for binding views, or should leave the examples.
    4. Async arms: 7/10. Binding programs need @try, @pending and @catch.
    5. Long tail, 1/10 each: @catch (error, reset), a control bound to a conditionally selected handle, and genuine useState UI (chat Metrics).

    3. The renderer is loaded by the shell, not the islands

    Real production Vite builds (gzip-9 per chunk):

    App All client JS Renderer chunk Each island's closure Island-specific chunk
    conversation-streaming 147.8 KB 94.0 KB (64%) 132.0–132.4 KB 1.0–1.4 KB
    signal-chat 153.5 KB 92.4 KB (60%) 131.0–132.2 KB 1.3–2.5 KB

    In both apps the generated client entry statically imports the renderer, because the route shell is always hydrated with hydrateRoot. So making islands renderer-free saves nothing on its own. The renderer only drops out when the shell stops hydrating too: the islands-only route mode in docs/hydration-islands-plan.md.

    • signal-chat is the natural first target. Its App shell has no hooks, only static markup and a form. Only Metrics truly needs component state.
    • The benchmark shell needs an item-3 replacement for its ready flag.

    For signal-chat, the resulting estimate is roughly 153 → ~65 KB gzip. It removes the renderer, entry and shell chunks and adds the ~10.5 KB structural binding runtime, with Metrics rewritten on signals. This is an estimate built from measured parts, not a measurement of a built result. What remains is dominated by the signals code: the State and facade chunks are about 25 KB.

    Suggested sequence

    1. Reject .get()/.latest() in binding views with a diagnostic, closing the section 1 bug.
    2. Allow zero-argument views.
    3. Lower signal reads into subscribed projections, replacing the diagnostic from step 1 where proven.
    4. Mount-only effects as binding activation/cleanup.
    5. @try/@pending/@catch in binding programs.
    6. Renderer-free island activation, plus an islands-only route mode, piloted on signal-chat.

    Steps 1–5 each make more islands eligible. Only step 6 removes bytes from a real page.

  4. trueadm commented on Oct 1, 2026

    @trueadm
    Collaborator

    Agent-authored re-measurement (Claude Code, at the maintainer's request).

    Re-measured on main @ da9b1e46c

    Same method as the first triage: esbuild 0.28.1, minify + treeShaking, ESM, browser, production NODE_ENV, gzip-9. The baseline is an archive of d9ed0f446. It reproduces the triage's and the PRs' baseline figures to within 3–52 raw bytes. benchmarks/scoped-signals/bundle-boundaries.test.mjs passes 30/30 on main.

    Shipped items all hold

    PR Consumer d9ed0f446 main
    #1286 (proposal 4) docs PrimaryAction via adoptBindings 5,862 gz 3,403 (−41.9%)
    title + text view, adopt / adopt + mount 5,783 / 13,411 3,327 (−42.5%) / 11,446 (−14.7%)
    #1288 (proposal 1) createScope + query entry 14,522 13,351 (−8.1%, includes #1356)
    retained heap per useSignal$-shaped scope / shared scope 2,680 / 3,840 B 816 (−70%) / 1,978 B (−48%)
    #1289 .tsrx signal state + handle view via adoptBindings 51,267, renderer bundled 25,431, no renderer
    #1304 {count$.get()} view adopted from real SSR text stuck at 1 after set(7) throws #308 at activation
    #1356 sync createScope consumer 14,433 13,283 (−8.0%, with #1288)

    Decisions on what remains

    • Proposal 3 (transaction boundary): keep. The ceiling is still −4,310 gz (−32% of the sync consumer). It is still forced: runtime.ts is the only caller of both the Action frame and coordinator factories, and every createRoot reaches nativeCandidateForAction, so a renderer-side import would add about 4.3 KB to every app.
    • Shrinking transition-action.ts / transition-coordinator.ts: deferred. They are 14.2 KB raw of renderer-only code in every signals consumer, with an upper bound of −4,310 gz. No concrete lever was found, and this is the highest-risk transaction code. Reopen only with a specific design.
    • Proposal 2 (smaller entry): dropped. A narrower contract now saves −2,332 gz (−17.6%). That only works if it also drops the seed option, serialize, beginAdoption, inspect and native-read serialization: class methods never tree-shake, and the seed constructor path retains data-encoding. Keeping seeds leaves −855 gz. Islands, the main renderer-free consumer, need seeds and adoption, so the narrow entry would not serve them.
    • Proposal 1: complete. scope-streams.ts emits 0 bytes in stream-free entries, guarded in CI.
    • Proposal 4, last increment: in progress. URL channels (href, src, …) on the scalar adopter. A scratch version takes a URL view from 5,747 to 3,603 gz (−37%), with identical DOM traces including javascript: blocking. Done naively it adds +260 gz to URL-free views, so the sanitizer has to arrive only with URL descriptors. That PR will close this issue.

    Split out

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    agent-authoredenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions