Repository navigation
perf: trap-free entity snapshot, and skip unchanged entities - #59
Merged
Merged
Conversation
abedell-phantom
force-pushed
the
perf/entity-snapshot-fast-path
branch
2 times, most recently
from
September 10, 2026 04:31
fcfb441 to
c4b87fc
Compare
abedell-phantom
commented
Sep 10, 2026
|
|
||
| /** | ||
| * Snapshot a raw field value. Nested entity proxies go back to Signalium so | ||
| * they consume their own notifier. The array and object walks mirror |
Contributor
Author
There was a problem hiding this comment.
Probably best to just export from Signalium before merging this
abedell-phantom
force-pushed
the
perf/entity-snapshot-fast-path
branch
2 times, most recently
from
September 10, 2026 15:50
8e43915 to
1ceeb0a
Compare
`useQuery` deep-snapshots its result through `useReactive` on every dependency change, and the entity snapshot handler walked the proxy to do it. `Object.keys` triggers a `getOwnPropertyDescriptor` trap per key, that trap calls `handler.get` to produce the value it reports, and nested plain data came back as the read-only wrapper proxies the `get` trap returns, which the snapshot then walked through more traps. Every field was read twice per snapshot and each read allocated a descriptor. Each proxy now registers an `EntitySnapshotSource`: consume the notifier and activate the entity relay once, list the enumerable own keys, read a field's raw value. The handler walks nested plain data itself, unwrapping `WRAPPED_VALUE` holders and handing nested entity proxies back to Signalium so they still consume their own notifiers. The value half of the `get` trap moved into `readField` so the trap and the snapshot share one reader. On top of that, `EntityInstance` carries a `version` bumped in `notify()`. A snapshot records the source id, version and key list it came from, so re-snapshotting an entity still at that version re-reads only its dynamic fields: child entities, live collections, and a query's attached getters. `isStaticFieldDef` decides that per shape, recognising only the def shapes `getEntityDef` validates against and treating everything else as dynamic, so an unfamiliar def costs a read rather than serving a stale value. Array items are paired with the snapshot they produced themselves rather than with whatever sat at the same index. Signalium diffs arrays by position, so a front insert handed every entity its neighbour's snapshot and every memoized row re-rendered. The pairing index is built from the consumer's own previous array, so two consumers keep independent trees, and only when a mispairing is detected, so appends don't pay for it. Guarding the result, since none of this is observable from behavior: - Dev builds re-read the fields the fast path skipped and throw if one moved. That catches both a merge that changes `data` without notifying and a field wrongly judged static — the two ways a snapshot could go permanently stale — at the point it happens rather than in a render. It costs dev builds the read the fast path saved. - `__debug_snapshotFullWalks` / `__debug_snapshotFieldReads` let tests assert the fast path is taken. A regression that quietly routes every snapshot through the full walk leaves every behavioral test green. - `src/__benchmarks__/snapshot.bench.ts` and `npm run bench` measure the paths this touches, built with `IS_DEV: false` so the dev guard doesn't skew them. Two smaller behavior notes: - `getOwnPropertyDescriptor` answers from the enumerable key list rather than `prop in shapeFields`. `shapeFields` is an object literal, so `in` was true for inherited names and the trap reported `toString` as an enumerable own property with value `undefined`. It now returns `undefined`. `Object.keys(proxy)` was never affected — it filters `ownKeys`, which never listed inherited names. - The `Entity`-without-a-snapshot-source fallback is gone. Its own properties are the shape's type defs, so walking one produced a plausible-looking object of `t.string`/`t.number` values rather than data. Falling through returns the instance untouched, which is what Signalium does for any class it has no handler for. Costs, measured: the production `QueryClient` chunk grows 80,581 -> 83,781 raw and 21,597 -> 22,647 gzipped (+1,050, +4.9%) for the per-shape key metadata, the static-field analysis and the origin bookkeeping. Dev-only code is fully eliminated — the invariant check and the debug counters appear in no emitted production JS. The snapshot origin holds the source's id rather than the proxy: a snapshot outlives the entity it came from, and a strong reference would have made the entity graph reachable from a detached snapshot tree. Ids are per proxy, which `PROXY_ID` is not — an entity has one proxy per shape and they share a key. Output is otherwise unchanged: same key set, same structural sharing, same reactive dependencies, no public API change. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
abedell-phantom
force-pushed
the
perf/entity-snapshot-fast-path
branch
from
September 10, 2026 16:18
1ceeb0a to
b352ece
Compare
jimmy-phantom
approved these changes
Sep 10, 2026
abedell-phantom
added a commit
that referenced
this pull request
Sep 29, 2026
This was referenced Sep 29, 2026
abedell-phantom
added a commit
that referenced
this pull request
Oct 8, 2026
* perf(fetchium): snapshot entities without walking their proxies (#59) `useQuery` deep-snapshots its result through `useReactive` on every dependency change, and the entity snapshot handler walked the proxy to do it. `Object.keys` triggers a `getOwnPropertyDescriptor` trap per key, that trap calls `handler.get` to produce the value it reports, and nested plain data came back as the read-only wrapper proxies the `get` trap returns, which the snapshot then walked through more traps. Every field was read twice per snapshot and each read allocated a descriptor. Each proxy now registers an `EntitySnapshotSource`: consume the notifier and activate the entity relay once, list the enumerable own keys, read a field's raw value. The handler walks nested plain data itself, unwrapping `WRAPPED_VALUE` holders and handing nested entity proxies back to Signalium so they still consume their own notifiers. The value half of the `get` trap moved into `readField` so the trap and the snapshot share one reader. On top of that, `EntityInstance` carries a `version` bumped in `notify()`. A snapshot records the source id, version and key list it came from, so re-snapshotting an entity still at that version re-reads only its dynamic fields: child entities, live collections, and a query's attached getters. `isStaticFieldDef` decides that per shape, recognising only the def shapes `getEntityDef` validates against and treating everything else as dynamic, so an unfamiliar def costs a read rather than serving a stale value. Array items are paired with the snapshot they produced themselves rather than with whatever sat at the same index. Signalium diffs arrays by position, so a front insert handed every entity its neighbour's snapshot and every memoized row re-rendered. The pairing index is built from the consumer's own previous array, so two consumers keep independent trees, and only when a mispairing is detected, so appends don't pay for it. Guarding the result, since none of this is observable from behavior: - Dev builds re-read the fields the fast path skipped and throw if one moved. That catches both a merge that changes `data` without notifying and a field wrongly judged static — the two ways a snapshot could go permanently stale — at the point it happens rather than in a render. It costs dev builds the read the fast path saved. - `__debug_snapshotFullWalks` / `__debug_snapshotFieldReads` let tests assert the fast path is taken. A regression that quietly routes every snapshot through the full walk leaves every behavioral test green. - `src/__benchmarks__/snapshot.bench.ts` and `npm run bench` measure the paths this touches, built with `IS_DEV: false` so the dev guard doesn't skew them. Two smaller behavior notes: - `getOwnPropertyDescriptor` answers from the enumerable key list rather than `prop in shapeFields`. `shapeFields` is an object literal, so `in` was true for inherited names and the trap reported `toString` as an enumerable own property with value `undefined`. It now returns `undefined`. `Object.keys(proxy)` was never affected — it filters `ownKeys`, which never listed inherited names. - The `Entity`-without-a-snapshot-source fallback is gone. Its own properties are the shape's type defs, so walking one produced a plausible-looking object of `t.string`/`t.number` values rather than data. Falling through returns the instance untouched, which is what Signalium does for any class it has no handler for. Costs, measured: the production `QueryClient` chunk grows 80,581 -> 83,781 raw and 21,597 -> 22,647 gzipped (+1,050, +4.9%) for the per-shape key metadata, the static-field analysis and the origin bookkeeping. Dev-only code is fully eliminated — the invariant check and the debug counters appear in no emitted production JS. The snapshot origin holds the source's id rather than the proxy: a snapshot outlives the entity it came from, and a strong reference would have made the entity graph reachable from a detached snapshot tree. Ids are per proxy, which `PROXY_ID` is not — an entity has one proxy per shape and they share a key. Output is otherwise unchanged: same key set, same structural sharing, same reactive dependencies, no public API change. Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> * perf: don't notify or persist when applied data is unchanged (#60) * perf(fetchium): don't notify or persist when applied data is unchanged `applyEntity` called `notify()` and persisted on every update, whether or not the data differed from what the entity already held. A refetch or poll returning identical data produced one notify per entity, a consumer recompute for each, a full re-snapshot and one store write per entity, to arrive back where it started. `mergeFields` now reports whether it changed anything and `applyEntity` acts on that. Comparison is by value: identical scalars, formatted values built from the same raw input, arrays and plain objects element by element, entities by proxy identity. Anything it cannot compare confidently — a Date, a typed array, a class instance — counts as different, so the failure mode is an unnecessary notify, not a dropped update. Live collections report the same, and `LiveInstance.reset`/ `append` return a boolean for it. A field that compares equal keeps its existing value, so nested objects and arrays hold their identity. Two pre-existing bugs this reaches, both fixed here: - Record fields never applied an update. A record def's `shape` is its value type — a bare Mask for `t.record(t.string)` — and the merge recursed into it as though it were a set of field defs, iterated nothing, then restored the old value. An update, addition or removal inside a record was silently dropped. Nested field records are now recognised by shape, and records fall through to the value comparison. - The persist decision no longer assumes an unchanged entity is already in the store. `persist` is caller-supplied and the cache-hydrate path passes `false`, so hydrate-then-fetch-identical could have skipped an entity's only write. `EntityInstance._persisted` makes that explicit. `sameRefs` compares the ref key set rather than counts, matching what the store persists and what `setChildRefs` acts on; comparing counts forced writes that produced byte-identical bytes. `sameValue` uses `Object.hasOwn` rather than `in`, which reached the prototype and could compare a missing key against `Object.prototype`'s answer. Tests: 11 integration cases in `entity-change-detection.test.ts`, 10 of which fail against main, plus 34 table-driven cases covering `sameValue` and `sameRefs` directly — every branch, and the fail-safe direction for each type they cannot compare. The identity assertions use `toBe`; `toEqual` cannot observe the property being claimed and passes on main. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor(fetchium): address review feedback Comments: cut the `needsPersist` rationale to the one non-obvious line, the `_persisted` field doc to its first sentence, and made `sameMembers` read declaratively. Dropped the throwaway const around the live reset/append call. Fixed a misplaced JSDoc: the block describing structural field equality sat above `sameKeys`, which only compares key sets. Moved it to `sameValue` and gave `sameKeys` its own one-liner. Tests: `sameKeys` is now exported and covered like `sameValue` and `sameRefs` (own-keys-only, added/removed keys, a key holding undefined). Added two change-detection cases — a live-array member's own field changing, which must notify the member and leave the list quiet, and a mutation event carrying a nested entity, which must notify only the entity that actually moved. Both fail without the change detection in this branch. Hoisted the `Item`/`List`/`GetList` declarations to module scope with a `list()` data helper; the same block had been copy-pasted into three tests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(fetchium): assert the nested entity's merged value, not just its notify The nested-entity change-detection case pinned which entity notified but never what the data became, so a notify that fired without the merge landing would have passed. Reads the child instance back and asserts its field after both events — including the unchanged one, where skipping the notify must not skip the merge. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(fetchium): assert merged values in the mutation-event cases The unchanged-fields case pinned which entity notified but never what the data became, the same gap just closed for the nested-entity case. Reads the instance back and asserts its field after both events. Also corrects the comment on both: for an event that carries the current value there is nothing to merge, so the assertion guards against the no-op path damaging the value rather than against a skipped merge. The changed event is what pins the merge landing. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(fetchium): name the mutation-event case for both directions it asserts The name covered only the unchanged half, but the test also applies a real change and asserts the notify and the merged value. That second event is the positive control: without it, the empty-notify assertion above would pass just as happily if the recorder never fired. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(fetchium): rewrite this change's changesets for React developers Lead with what changes for an app using useQuery or fetchQuery, keep migration notes to a line or two, and drop internal detail. No source change. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): re-read formatted fields in the snapshot fast path A formatted value's snapshot can go through a custom snapshot handler that reads another signal, such as a locale. Classifying t.format fields as static skipped them, so the handler's signal stopped being tracked: dev threw the stale-snapshot guard and prod kept the old value. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(fetchium): tighten comments Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(fetchium): cut and shorten comments Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Two related changes to the entity snapshot path, skipping proxy traps and re-reading an entity whose data hasn't changed.
Read entity fields directly instead of walking the proxy
Object.keys(proxy)triggers agetOwnPropertyDescriptortrap per key, and that trap callshandler.getto produce the value it reports. So every field was read twice per snapshot, each read allocated a descriptor, and nested plain data arrived as the read-only wrapper proxies thegettrap returns, which the snapshot then walked through more traps.Each proxy registers an
EntitySnapshotSource: consume the notifier and activate the entity relay once, list the enumerable own keys, read a field's raw value. The value half of thegettrap moved intoreadField, so the trap and the snapshot share one reader instead of drifting apart.Skip re-reading an entity whose data hasn't changed
EntityInstancecarries aversion, bumped innotify(). A snapshot records the source id, version and key list it came from; re-snapshotting an entity still at that version re-reads only its dynamic fields — child entities, live collections, and a query's attached getters.isStaticFieldDefdecides that per shape, recognising only the def shapesgetEntityDefvalidates against and treating everything else as dynamic.Array items are paired with the snapshot they produced themselves rather than with whatever sat at the same index. Signalium diffs arrays by position, so a front insert handed every entity its neighbour's snapshot and every memoized row re-rendered. The pairing index comes from the consumer's own previous array, so two consumers keep independent trees, and it's built only when a mispairing is detected, so appends don't pay for it.
Measured
npm run bench(src/__benchmarks__/snapshot.bench.ts, Node 24,IS_DEV: false). Mean per streamed event — apply plus the snapshot a mounted consumer pulls:Reproduce either side with
git checkout main -- packages/fetchium/src/EntityInstance.tsand re-running. These rows sit under ±2.3% rme.The bench's cold-query group is deliberately not in the table: it times client construction, fetch, parse, apply and the first snapshot together, and swings ±10-20% rme. An earlier revision of this description quoted 11.5 → 8.0 ms from it, which doesn't reproduce.
Out-of-repo, on a 1,000-row React screen (react-dom 19.2.8, jsdom): event to flushed commit 7.17 → 4.26 ms median.
Twenty front-inserts into a 200-row sorted live array: 4190/4190 existing rows lost snapshot identity → 0/4190. That figure is for an array reached through an entity field, which is what this handler walks. An array Signalium walks itself is still paired by position, so a front insert there still gives every row a new snapshot — it just no longer blends two entities' data, because a foreign
previs discarded rather than diffed against.Costs
readFieldframe can't inline. A read on a directly held entity proxy is faster (16 → 11 ns).QueryClientchunk grows 21,597 → 22,647 bytes gzipped (+1,050, +4.9%; 80,581 → 83,781 raw) for the per-shape key metadata, the static-field analysis and the origin bookkeeping — paid by every consumer whether or not they useuseQuery. Dev-only code is fully eliminated; neither the invariant check nor the debug counters reach any emitted production JS.What keeps this from silently regressing
None of the above is observable from output, so behavioral tests can't defend it:
dataonly changes through anotify()that bumpsversion, and that every field outside the dynamic list is a pure function ofdata. Dev builds re-read the skipped fields and throw if one moved, naming the entity and field. That covers both failure modes — a merge that mutates without notifying, and a field wrongly judged static — at the point it happens.__debug_snapshotFullWalks/__debug_snapshotFieldReads. A test asserts that changing one token in a 20-token list produces exactly one full walk. Losing the fast path leaves every other test green.Tests
15 in
entity-snapshot.test.ts. Againstmain, 11 pass and 4 fail. The 11 pin behavior this must not change: key set, proxy-free output, structural sharing, nested-entity propagation through wrappers/objects/arrays, formatted values, live-array membership, independent snapshot trees. Two of the failures are the array-identity change; the other two fail only because the counters aren't exported and the dev check doesn't exist there.So no test fails on
mainbecause of the version fast path, and none can — its output is identical by design. What defends that half is the counter test and the dev check.NOTE, SOME DUPLICATED CODE FROM SIGNALIUM UTILS
Snapshot code should be exported from signalium/utils and used directly, once done drop the test asserting they're the same. Requires Signalium PR: Signalium/signalium#250