Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ The format follows Keep a Changelog and the package uses semantic versioning.

## Unreleased

- Extended same-client immutable-read coalescing through lifecycle-checked
cache publication for snapshots, secondary indexes and trie nodes. Followers
no longer duplicate fetches during the publication gap or publish the same
overlapping fetch separately. Cache lookup still precedes joining, settled
fills are forgotten, and caller ownership, policies, remote errors and independent
keys/clients are preserved. Pending values and waiters remain live until
publication settles. Public options, defaults and stored formats are unchanged.

- Fixed query comparisons, ordering and projections reading inherited
JavaScript properties as document data. Missing optional fields such as
`toString` no longer cause clone/sort errors, and absent `__proto__` fields
Expand Down
1 change: 1 addition & 0 deletions benchmarks/immutable-fill-coalescing/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
results/*.svg text eol=lf
270 changes: 270 additions & 0 deletions benchmarks/immutable-fill-coalescing/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
# Immutable fill coalescing through cache publication

## Decision

Merge-worthiness: 93/100. Recommend the scoped change once CI and CodeQL pass
on the pull request's current head. Every mandatory gate remains required,
regardless of the score.

This change reduces duplicate work when callers miss the same immutable
object within one `ThimbleClient`. The historical implementation already
returns correct, independently owned documents in these workloads. The
experiment establishes structural work reductions under controlled overlap,
without measuring production incidence, latency, throughput, heap or disk use.

Already warm, sequential-cold, unrelated-key and independent-client workloads
show no work reduction. Applications dominated by those patterns have no
demonstrated benefit from this change.

## Source and mechanism

| Boundary | Revision |
| --- | --- |
| Historical main baseline | `257ed4ac0b809aa196e5f3789aafe14b18c2fd7b` |
| Protocol published before production edits | `3095439a690c0b8dcbb568ab6773388fa623cc39` |
| Frozen implementation, fixtures, tests, collector and verifier | `299a298937e1ce5e20e9254b529e4834e607cd2e` |

Only `src/browser/client.ts` changes in production: 15 insertions and
16 deletions. The existing per-client, per-key pending promise now covers the
remote read and lifecycle-checked cache publication. Snapshot pages,
secondary-index pages and trie nodes use that complete fill.

Previously, the promise was removed after the remote read settled. Each
waiting caller then published separately. A follower arriving before
publication could miss the cache and start another remote read. The new
boundary suppresses that fetch gap and duplicate publications.

Cache lookup still precedes joining a fill. An eligible cache hit can return
while persistence finishes. Settled fills are forgotten on success or
failure; this adds no retained-value cache, negative caching, timeout,
dependency, option or storage format. Mutable HEAD publication and point-read
bundles retain their separate paths. Public document results remain owned by
each caller. Different keys and different client instances remain independent.
Waiters share the fill's publication outcome, including rejection from a custom
cache hook; hook invocation counts follow fills rather than waiting callers.

The branch starts from the P18 main merge. It does not contain or requalify
the separately parked range-candidate predicate change.

## Method and evidence

The [prospective protocol](protocol.json) fixes eight recipes, three immutable
reader paths, two payloads, fanouts two/eight and forward/reverse caller
orders: 192 trials per arm, 384 rows. The clock is fixed and restored.

Actual `TieredObjectCache` and `MemoryObjectCache` instances use a recording
in-memory persistent delegate and a synthetic JSON reader. HEAD and trie
ancestors start warm; the selected immutable target starts cold, except in
the warm-hit control. Covering queries use a one-entry equality index,
explicit `label` projection and a one-candidate budget.

The publication-gap recipes hold the actual client lifecycle lock before its
generation check and cache publication. Followers launch after the first
remote result has completed. Remote-overlap recipes instead hold the reader
response. Driver deadlines and a zero-delay host-task drain control
scheduling; they are not latency samples.

One comparative capture ran from detached frozen source, from
05:39:32.408Z to 05:39:37.519Z on 4 December 2026. Node 22.22.2,
TypeScript 5.9.3 and esbuild 0.28.2 ran on Windows x64 10.0.26200. Node used
the declared queued exclusive-lock compatibility model. The raw capture is
24,849,291 bytes, below the 64 MiB limit.

Both complete 19-module public-entrypoint executable graphs are retained.
The independent verifier reconstructs fixtures and references without the
production read predicates, rebuilds both exact-Git graphs, replays all
384 observations, checks 83 frozen inputs, and verifies every CSV cell and
SVG bar. It validates entry metadata, reader/delegate/cache/lock events,
metrics and every clone input/output. All 120 control pairs preserve complete
normalised observations.

Normalisation removes event sequence numbers and global ordering for
multiset comparison. Phase, operation, key, owner, metadata, errors, payloads,
clone inputs/outputs and scalar costs remain. Original ordering is retained
in the raw data. Native checks do not impose cross-runtime scheduling-order
equality.

| Evidence | Contents |
| --- | --- |
| [Scored raw capture](results/local-2026-12-04.json) | Every row, reference, fixture, outcome, ownership probe, event, clone, metric and both executable graphs |
| [Per-trial CSV](results/local-2026-12-04-trials.csv) | All 384 rows and exercise/all/phase costs |
| [Remote-attempt graph](results/local-2026-12-04-remote-attempts.svg) | All recipes and both arms |
| [Publication graph](results/local-2026-12-04-publications.svg) | All recipes and both arms |
| [Original native capture](results/native-2026-12-04.json) | All original attachments from one zero-retry invocation |
| [Qualification manifest](results/qualification-2026-12-04.json) | Artifact/log identities, test results, independent audits and native attachment digests |

## Exercise results

Each recipe has 24 trials per arm. Reader attempts include the deliberate
503 in failure/retry cases. Publications count completed cache writes;
persistent set calls match publications in this content-policy fixture.

| Recipe | Historical reads | Candidate reads | Historical publications | Candidate publications |
| --- | ---: | ---: | ---: | ---: |
| Publication gap | 120 | 24 | 120 | 24 |
| Remote overlap | 24 | 24 | 120 | 24 |
| Sequential cold | 120 | 120 | 120 | 120 |
| Warm hit | 0 | 0 | 0 | 0 |
| Different keys | 120 | 120 | 120 | 120 |
| Different clients | 120 | 120 | 120 | 120 |
| Remote failure/retry | 48 | 48 | 24 | 24 |
| Logout during fill | 120 | 24 | 0 | 0 |
| Total | 672 | 480 | 624 | 432 |

![Immutable target remote attempts](results/local-2026-12-04-remote-attempts.svg)

![Immutable cache publications](results/local-2026-12-04-publications.svg)

The fixed mix removes 192 reader attempts and 192 publications. These
aggregate reductions depend on the chosen recipe weights. In a publication
gap, `N` callers make one fetch/publication instead of `N`. With an overlapping
remote response, the historical fetch was already shared; only duplicate
publication work disappears.

Both arms have 984 caller outcomes: 744 successful results and 240 expected
rejections. All results, plans, errors and inputs match their independent
references. Each arm completes 744 nested-mutation/re-query ownership probes.
Failure/retry cases permit a fresh successful read after the shared 503.
Logout cases reject every caller and publish nothing after cancellation.

## Complete fixture costs

Values below are historical/candidate totals. No setup, misses, ownership
re-queries or cleanup work is removed. Delegate calls include get, set,
delete and destroy. These are counts of the instrumented fixture, excluding
compiler, server-startup and test-runner overhead.

| Phase | Reader attempts | Publications/sets | Delegate calls | Cache gets | Clone calls | Events |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| Setup | 0/0 | 664/664 | 664/664 | 0/0 | 1,584/1,584 | 1,992/1,992 |
| Exercise | 672/480 | 624/432 | 1,632/1,440 | 2,624/2,624 | 4,896/4,320 | 12,344/10,520 |
| Ownership | 0/0 | 0/0 | 0/0 | 1,984/1,984 | 3,224/3,224 | 4,216/4,216 |
| Cleanup | 0/0 | 0/0 | 288/288 | 0/0 | 0/0 | 576/576 |
| All | 672/480 | 1,288/1,096 | 2,584/2,392 | 4,608/4,608 | 9,704/9,128 | 19,128/17,304 |

Every successful clone preserves its JSON input. The counts do not measure
physical allocations, CPU time, ciphertext bytes, IndexedDB transactions
or storage-provider requests.

## Native-browser qualification

One invocation ran 144 tests with zero retries, unexpected failures, flakes
or skips. Each test loads both retained exact-revision bundles. There are
48 pairs per engine, using the multibyte payload, both fanouts and forward
caller order. All 288 observations pass independent semantic/state,
per-arm work and event validation. All 90 same-engine control pairs preserve
complete normalised observations.

| Engine | Version | Pairs | Reader attempts, historical/candidate | Publications, historical/candidate | Delegate calls, historical/candidate |
| --- | --- | ---: | ---: | ---: | ---: |
| Chromium | 153.0.8010.12 | 48 | 168/120 | 156/108 | 408/360 |
| Firefox | 155.0 | 48 | 168/120 | 156/108 | 408/360 |
| WebKit | 26.6 | 48 | 168/120 | 156/108 | 408/360 |

All three use their actual Web Locks manager. Windows WebKit does not
qualify Apple Safari. The native fixture also uses the recording JSON reader
and in-memory delegate; this is not encrypted IndexedDB or network
performance evidence. The archived native capture is not replaced by
subsequent normal CI test execution.

## Other qualification

| Check | Result |
| --- | --- |
| Focused candidate cases | 28/28 pass |
| Exact-historical focused substitution | 19 pass; nine predeclared failures across the three targeted schedules and three paths |
| Focused plus related regressions | 800/800 pass across 18 files, including the 28 focused cases |
| Candidate-only pre-freeze preflight | 48/48 independently verified; both 19-module graphs build |
| Repository, Studio, Worker and explicit fixture/native types | Pass |
| Package build and isolated packed consumers | Pass; browser isolation, optional providers and exports preserved |
| Built public-entrypoint probes | 48/48 pass; complete normalised JSON observations match retained candidate rows |
| Canonical documentation and repository/site links | Checked with the repository's existing validators |
| Supported-Node site build, full CI and CodeQL | Required on the current pull request head |

Before source freeze, covering-query fixture validation required the query
version and the Web Locks wrapper needed a precise generic return type.
An initial related run passed 766/772 cases; six ownership schedules waited
for a second publication removed by this optimisation. Those schedules now
hold the single shared write, require all callers to wait, and retain the
independent-result and cache-isolation assertions. The final 800-case run
passes.

An additional package probe initially compared JavaScript object prototypes
with JSON-reloaded observations. Index projections use null-prototype
dictionaries. The external probe now applies the same JSON serialisation as
the retained capture before comparing complete observations. Its initial
failure is retained in the qualification identities. No frozen source,
protocol, scored capture, native attachment or independent verifier was
changed after collection, and no failed capture was rerun.

## Costs, limits and rejection criteria

The fill promise remains live until cache publication settles, retaining its
remote value and waiters for longer than the historical remote-only promise.
A slow or hung custom cache operation can retain this work indefinitely;
resident-cache limits do not bound pending promises or caller concurrency.
Cold fills also add promise scheduling and lifecycle checking whose CPU and
latency costs are unmeasured.

This is per-client coordination. It does not deduplicate across clients,
tabs, module copies or authorities, coordinate different keys, establish read
linearizability, or add durable logout. It does not change authorisation,
cache policy, HEAD freshness, format, planner, options or defaults. A cache
policy or admission decision that does not retain the target can still
require a later remote read.

Reject promotion if any semantic, ownership, lifecycle, policy or isolation
contract fails; if any declared count/control changes unexpectedly; if a
settled fill is reused; if independent/native verification fails; or if
publication-head checks fail. Unmeasured production benefit is not a reason
to relax those gates.

| Score component | Score | Basis |
| --- | ---: | --- |
| Semantic correctness and fit | 36/40 | Exact contracts pass; benefit is limited to controlled same-key overlap with unknown production incidence |
| Compatibility and work | 24/25 | Policies, failures, isolation, formats and complete controls preserved; scheduling/retention costs remain |
| Reproduction | 19/20 | Exact-Git rebuild/replay, raw ledgers and paired native controls; one local host and no Safari qualification |
| Simplicity | 14/15 | Existing map and lifecycle helper reused in one production module; no API or dependency |
| Total | 93/100 | Threshold 85 plus every mandatory gate |

## Reproduce

Use the locked dependencies. To audit the published observations, rebuild
both historical/candidate graphs, replay all rows and verify native evidence:

```powershell
node benchmarks\immutable-fill-coalescing\verify.mjs benchmarks\immutable-fill-coalescing\results\local-2026-12-04.json benchmarks\immutable-fill-coalescing\results\native-2026-12-04.json
npx vitest run tests\browser-immutable-fills.test.ts tests\browser-read-ownership.test.ts
npx tsc --project benchmarks\immutable-fill-coalescing\tsconfig.json --noEmit
```

The historical substitution deliberately exits nonzero with exactly nine
focused failures:

```powershell
npx vitest run --config benchmarks\immutable-fill-coalescing\baseline-vitest.config.ts
```

For a new comparative capture, use an isolated checkout detached at the
frozen source revision and choose an unused `results` JSON filename.
`run.mjs --preflight` runs candidate-only preparation; collection refuses
existing evidence paths and uncommitted frozen inputs. Do not overwrite
the published observations.

Native validation uses `tests/e2e/immutable-fills.spec.ts`, the retained
bundles and a minimal routed page. The existing helper deletes
`.thimble-e2e` at startup: verify it is absent and ports 5173/8787/8790
are free before invoking Playwright. Keep any new validation output separate
from the archived capture.

## Primary research

- [Go singleflight](https://pkg.go.dev/golang.org/x/sync/singleflight):
per-key duplicate suppression covers one complete function and shares its
outcome, including errors.
- [Microsoft HybridCache](https://learn.microsoft.com/en-us/aspnet/core/performance/caching/hybrid?view=aspnetcore-10.0):
same-instance get/create coordination includes storing the fetched value.

Both were checked on 4 December 2026. They motivate the fill boundary,
without adding either dependency or supporting distributed-coordination
claims.
18 changes: 18 additions & 0 deletions benchmarks/immutable-fill-coalescing/baseline-vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { resolve } from "node:path";
import { defineConfig } from "vitest/config";

const root = fileURLToPath(new URL("../../", import.meta.url));
const { baseline } = JSON.parse(readFileSync(new URL("./protocol.json", import.meta.url), "utf8")) as { baseline: string };
const filename = resolve(root, "src/browser/client.ts").replaceAll("\\", "/");
const source = execFileSync("git", ["--no-pager", "show", `${baseline}:src/browser/client.ts`], { cwd: root, encoding: "utf8" });
export default defineConfig({
root,
plugins: [{
name: "exact-baseline-immutable-fills", enforce: "pre",
load(id) { return id.replaceAll("\\", "/").split("?")[0] === filename ? source : null; },
}],
test: { include: ["tests/browser-immutable-fills.test.ts"] },
});
Loading