Repository navigation
Description
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
- 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-facadederived$API, which also supports asynchronous values and streams. - 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.
- 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.
- 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
- Establish real internal boundaries first, potentially through proposal 1. A barrel that re-exports the current
createScoperetains the same implementation and does not establish a smaller closure. - 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.
- 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. - 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
- Separate ordinary publication, scalar staging/read visibility, and transition-specific preparation in a dependency inventory.
scope.actionis a synchronous batching wrapper; renderer Actions have a separate transactional contract. Keep that distinction explicit. - 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.
- 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. - 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
- Start with public compiled
adoptBindings/mountBindingsfixtures 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. - 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.
- 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.
- 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
trueadm commentedon Sep 23, 2026
Agent-authored triage (Claude Code, at the maintainer's request).
I measured each proposal's resolved graph on
main @ d9ed0f446before choosing an order. Every bundle uses esbuild 0.28.1 withminify,treeShaking, ESM, browser platform and a productionNODE_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.PrimaryAction/ atitle+ text fixture throughadoptBindingscreateScope+signal$+ syncderived$+ subscribe/batch/disposeuseSignal$scopeProposal 4
In the fixed-node scalar fixtures,
__adoptBindingsaccounts 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 onlyattr/boolean/aria/textuses 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_CONSUMERpresentation, 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__adoptBindingstoday (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.tsalready tree-shakes to zero bytes for acreateScope-only consumer. What stays is the stream-selection methods onScopeImpland seven collections allocated per scope.useSignal$creates a fullScopeImplper 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 onesignal$). Stream state can attach through the existing ingress functions (bindScopeStreamedSelection,acceptScopeStreamedResult,failScopeStreamedResult) and resource state throughcreateResourceDeclaration. Neither needs a process-global registry.Proposal 3
transition-action.tsandtransition-coordinator.tstogether are 14,520 raw bytes in the standalone engine, and removing their registration fromgraph.tssaves 4,387 gzip. They cannot move. Every plainexport { createRoot } from 'octane'closure already retainsnativeCandidateForAction. 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
Scopesaves nothing beyond proposals 1 and 3. A narrower contract withoutserialize,beginAdoptionandinspectsaves 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.
perf(bindings): select a scalar-only adopter for fixed-node DOM bindi…
perf(signals): allocate optional scope capabilities on first use (#1288)
trueadm commentedon Sep 23, 2026
Agent-authored audit (Claude Code, at the maintainer's request).
Can today's islands activate without the renderer?
Scope: every independent
<Hydrate>island outsidepackages/octane/tests, plus one route root. That is nine islands in the conversation-streaming benchmark,examples/signal-chatand the vite-plugin fixture app, plus that fixture'sConversationApp. Measured onmain @ a95c2dc47, after #1286, #1288 and #1289.Method:
'use dom bindings'view (client, production).1. Correctness bug:
.get()in a binding view compiles but never updatesThis compiles with no diagnostic. Adopted from real SSR output, the text stays at
1aftercount$.set(7). The same view written with the handle,<p>{count$}</p>, adopts and updates to7. 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.
.get()/.latest()reads@try/@pending/@catchComposerreadyflagBody@forover a signal-derived listHistory@forover a signal-derived listHistoryrecordActivationToolsrecordActivationConversationrecordActivation@catch (error, reset), localTranscriptchildComposerready+recordActivationMetricsuseState+ intervalComposercond ? draftA$ : draftB$ConversationApp(route root)readyflagThe probes show these already compile:
{count$},value={draft$});@foritem;@forand@ifover props;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:
x$.get()andx$.latest(fallback)in setup and templates, includingconst frame = x$.get()feeding@forand attributes, need to become subscribed projections. This also closes the bug in section 1.useLayoutEffect(() => recordActivation(...), [])anduseState(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.@try,@pendingand@catch.@catch (error, reset), a control bound to a conditionally selected handle, and genuineuseStateUI (chatMetrics).3. The renderer is loaded by the shell, not the islands
Real production Vite builds (gzip-9 per chunk):
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 indocs/hydration-islands-plan.md.Appshell has no hooks, only static markup and a form. OnlyMetricstruly needs component state.readyflag.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
Metricsrewritten 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: theStateandfacadechunks are about 25 KB.Suggested sequence
.get()/.latest()in binding views with a diagnostic, closing the section 1 bug.@try/@pending/@catchin binding programs.Steps 1–5 each make more islands eligible. Only step 6 removes bytes from a real page.
trueadm commentedon Oct 1, 2026
Agent-authored re-measurement (Claude Code, at the maintainer's request).
Re-measured on
main @ da9b1e46cSame method as the first triage: esbuild 0.28.1,
minify+treeShaking, ESM, browser, productionNODE_ENV, gzip-9. The baseline is an archive ofd9ed0f446. It reproduces the triage's and the PRs' baseline figures to within 3–52 raw bytes.benchmarks/scoped-signals/bundle-boundaries.test.mjspasses 30/30 on main.Shipped items all hold
d9ed0f446mainPrimaryActionviaadoptBindingstitle+ text view, adopt / adopt + mountcreateScope+queryentryuseSignal$-shaped scope / shared scope.tsrxsignal state + handle view viaadoptBindings{count$.get()}view adopted from real SSR1afterset(7)#308at activationcreateScopeconsumerDecisions on what remains
runtime.tsis the only caller of both the Action frame and coordinator factories, and everycreateRootreachesnativeCandidateForAction, so a renderer-side import would add about 4.3 KB to every app.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.seedoption,serialize,beginAdoption,inspectand native-read serialization: class methods never tree-shake, and the seed constructor path retainsdata-encoding. Keeping seeds leaves −855 gz. Islands, the main renderer-free consumer, need seeds and adoption, so the narrow entry would not serve them.scope-streams.tsemits 0 bytes in stream-free entries, guarded in CI.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 includingjavascript: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
numberin a binding text hole cannot adopt its own SSR output (#318). The bug predates perf(bindings): select a scalar-only adopter for fixed-node DOM bindings #1286.@tryarms, islands-only route mode), steps 2–6 of the island audit above, re-verified on main.perf(bindings): adopt URL channels with the scalar adopter (#1525)