Skip to content
Closed
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

- Fenced late `CachedObjectStore` fills after completed same-key mutations,
existing precondition invalidation, clear or changed policy. Already-running
callers retain their delegate snapshot/error; later probes cannot use those
invalidated fills. Requests remain independent, with unchanged options,
TTL/LRU accounting, metrics and object ownership. Corrected stale hits can
add reads. The optional helper is not used by default authorities and adds
no cross-instance coordination, timeout or transaction guarantee.

- Matched local object listings by lexical key prefix, including partial names,
same-prefix siblings and exact files. Append `/` for directory-boundary
matching. Traversal prunes unrelated subtrees and retains staging-file and
Expand Down
3 changes: 3 additions & 0 deletions benchmarks/node-cache-fill-fences/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.gitattributes text eol=lf
*.mjs text eol=lf
results/*.svg text eol=lf
227 changes: 227 additions & 0 deletions benchmarks/node-cache-fill-fences/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
# Mutation-fenced Node cache fills

Date: 6 December 2026.

Merge-worthiness: 92/100. The local qualification passes. Normal Linux CI
and CodeQL on the publication head remain mandatory before merging.

`CachedObjectStore` can publish an old delegate result after a completed
same-key write, delete or explicit invalidation. The candidate tracks active
read generations and prevents an invalidated generation from filling the
cache. It preserves the result returned to the already-running caller.

This helper is exported by `thimbledb/providers/local` and used by the CLI
benchmark. The checked-in default authorities do not instantiate it.
This is an opt-in helper correctness change, with no measured production
incidence or default-authority benefit.

## Evidence and prospective gates

The [protocol](protocol.json) was published at
[`552966e`](https://github.com/Jason-Doyle/thimble/commit/552966ed2dc96e0469710a001f8d8e3cf317a2ee)
before production edits. The baseline is merged main
[`43255db`](https://github.com/Jason-Doyle/thimble/commit/43255db4bd0db64744ab86f99bea9f87a3e24632).
Its own CI and CodeQL passed before the experiment, and its tree equals the
qualified P27 publication. The frozen implementation, tests, fixture,
collector and independent verifier were published at
[`483ce5b`](https://github.com/Jason-Doyle/thimble/commit/483ce5b92c7e74685ee09362175cdf606e6a40c3)
before the sole scored comparison.

The [original JSON](results/local-2026-12-06.json) is the source of truth.
The [per-trial CSV](results/local-2026-12-06-trials.csv), graphs and
[qualification manifest](results/qualification-2026-12-06.json) retain the
derived counts, source identities and preparation-log identities.
No frozen input or original scored artifact was repaired or recaptured.
P26, P24, P22, P19 and P7 remain parked unchanged.

The fixture runs the actual public Node helper with a recording delegate.
It is a controlled interface experiment, not a filesystem, browser, network
or cloud benchmark. Each arm uses an exact-Git seven-module public API graph
and unmodified standard builtins. The host was Windows with Node 22.22.2,
TypeScript 5.9.3 and esbuild 0.28.2.

Each of 32 specifications combines a trie/snapshot-shaped mutable HEAD key,
`content`/`locations` policy and one of eight schedules. The delegate captures
version 0 before its promise is held. The selected action completes, the old
read is released, and a later cache read probes the resident state.
The five targets are successful same-key put/delete, clear, a changed-policy
round trip and the existing precondition-failure invalidation. Clear,
policy and precondition schedules include a controlled external version 1
update before explicit wrapper invalidation.

Steady state, unrelated-key put and no-op policy assignment supply twelve
complete measured controls. Their delegate payloads/results/errors, public
outcomes, ordered events, backing state, resident/LRU/expiry state and cache
metrics match exactly. Only the separately declared active-token metadata
is excluded from control equality; its lifecycle is checked independently.
The added bookkeeping is not represented as free CPU or allocation work.

`Date.now` is fixed solely for deterministic expiry metadata. Saved real
timers bound driver waits at five seconds. Every trial releases its owned
gate, settles the admitted promise, clears its cache and restores the clock.
Every row retains an own `__proto__` JSON-data sentinel.

## Exact results

| Policy | Historical contracts | Candidate contracts | Complete controls |
| --- | --- | --- | --- |
| content | 6/16 | 16/16 | 6 |
| locations | 6/16 | 16/16 | 6 |
| Total | 12/32 | 32/32 | 12 |

![Desired publication contracts](results/local-2026-12-06-success.svg)

Each schedule has four key/policy combinations. All 32 admitted old reads
in each arm still return version 0.

| Schedule | Historical contracts | Candidate contracts | Historical gets | Candidate gets | Candidate later probe |
| --- | --- | --- | --- | --- | --- |
| put | 0/4 | 4/4 | 4 | 4 | Cached version 1 |
| delete | 0/4 | 4/4 | 4 | 8 | Delegate missing result |
| clear | 0/4 | 4/4 | 4 | 8 | Delegate version 1 |
| policy-roundtrip | 0/4 | 4/4 | 4 | 8 | Delegate version 1 |
| precondition | 0/4 | 4/4 | 4 | 8 | Delegate version 1 |
| steady | 4/4 | 4/4 | 4 | 4 | Cached version 0 |
| other-put | 4/4 | 4/4 | 4 | 4 | Cached version 0 |
| no-op-policy | 4/4 | 4/4 | 4 | 4 | Cached version 0 |

The corrected delete/clear/policy/precondition probes add sixteen delegate
reads instead of returning stale cache hits. Successful same-key puts retain
their write-through cache entry and need no extra read.

| Interface count across 32 trials per arm | Historical | Candidate |
| --- | --- | --- |
| Delegate get starts | 32 | 48 |
| Delegate get completions | 32 | 48 |
| Delegate put starts | 12 | 12 |
| Delegate put completions | 8 | 8 |
| Put payload bytes | 408 | 408 |
| Delegate delete starts | 4 | 4 |
| Delegate delete completions | 4 | 4 |
| Delegate list starts | 0 | 0 |
| Controlled precondition errors | 4 | 4 |
| Recorded events | 404 | 436 |
| Cache hits at final probe, summed | 32 | 16 |
| Cache misses at final probe, summed | 32 | 48 |
| Resident entries at final probe, summed | 36 | 32 |
| Accounted object bytes at final probe, summed | 1224 | 1088 |
| Cache expirations | 0 | 0 |
| Cache evictions | 0 | 0 |

![Delegate read calls](results/local-2026-12-06-work.svg)

Resident totals sum independent trial checkpoints before cleanup. They are
not simultaneous heap usage or allocated/retained memory measurements.
All caches are empty and all active tracking is zero after cleanup.

## Verification

The independent entry point reconciles all 173 frozen inputs, both executable
graphs, all 64 exact observation replays, twenty historical deficiencies and
twelve complete controls. Its separate model checks every ordered delegate
event, condition, payload, outcome, backing/resident state and metric.
It also checks all 1,664 data cells in the CSV and all eight bars, labels and
geometry in the two SVGs. All 32 built `providers/local` probes match the
original candidate observations, including coordination metadata.

The final focused suite passes 45 cases. Additional cases cover rejected
reads, ordinary mutation failure, independent overlapping misses, retired
cleanup versus replacement tokens, reads admitted during unfinished writes,
policy-none bypass, TTL expiry, metric resets and distinct-key quiescence.
Exact historical substitution passes twelve controls and fails twenty
publication targets plus thirteen new tracking assertions. The latter are
not thirteen additional historical public-behaviour deficiencies.

Related regressions pass 222 cases in 23 files with five existing
platform-specific skips. Repository, Studio, Worker and explicit experiment
types, package build, isolated packed consumers and browser isolation pass.
The first preparation attempt exposed strict indexed-array test typing;
the first historical test-oracle attempt incorrectly required candidate-only
coordination capability in unchanged controls. Both diagnostics are retained.
They were corrected before source freeze. The final authoritative protocol,
independent cohort, candidate cases and derivative-format preflight passed
before freezing.

Normal exact-publication-head Linux CI must run all 45 new functional cases,
the supported-Node site build and existing package/browser/integration checks.
This requirement is not replaced by the local controlled comparison.

## Mechanism and limits

Cache misses share only a private active-generation token for their key.
Every caller still makes its own delegate request. A successful same-key
put/delete or the existing `PreconditionFailedError` invalidation retires
that token after the delegate settles. `clear()` and changed policy retire
all active tokens. Ordinary failed mutations, no-op policy assignments,
metric resets and unrelated writes do not retire a token.

A retired read still resolves or rejects with its original delegate outcome.
It cannot publish a cache entry. Matching-token cleanup prevents an old
completion from removing a replacement generation. Quiescent keys leave no
historical version registry. Active tracking follows outstanding current
generations, not the resident entry limit. A hung caller can retain its own
promise, token and eventual value until settlement; there is no new timeout,
cancellation or total-memory bound.

Use this helper when per-instance invalidation of late cache fills is useful
and admitted snapshots are acceptable. It does not provide linearizable
reads, transactions, mutation serialization, durable revocation, coordination
between wrappers/processes or coherence for unobserved direct-delegate writes.
An external writer needs an existing explicit invalidation signal or must
accept the existing TTL behaviour. It cannot change a value already returned
to a caller. Byte/object ownership is unchanged; no defensive-copy guarantee
is introduced.

Policies, options, defaults, public metrics, TTL/LRU/entry/byte accounting,
object formats, provider conditions and local filesystem behaviour are
unchanged. No request coalescing, dependencies, infrastructure or browser
cache changes are included. CPU, allocations, heap, GC, latency, throughput,
physical storage work and production benefit are unmeasured.

## Score and rejection criteria

| Component | Score | Basis |
| --- | --- | --- |
| Correctness and fit | 37/40 | Twenty reproduced stale-publication schedules corrected; opt-in helper and unknown incidence limit reach. |
| Compatibility and work | 22/25 | Admitted snapshots and complete controls preserved; corrected misses add reads and bookkeeping. |
| Reproduction | 19/20 | Prospective freeze, exact graphs/replays, built probes, raw tables and graphs; controlled delegates only. |
| Simplicity | 14/15 | One production module, active-only tokens and no public options or historical registry. |
| Total | 92/100 | Above the 85 threshold only if every hard gate, including publication-head CI, passes. |

Reject promotion if candidate state/cleanup, historical contracts, complete
controls, token retirement, source/artifact identities, required checks or
Linux execution of the new cases fails. Do not waive a failed frozen gate
or alter this series to obtain a better result.

## Reproduce

From a publication checkout with the frozen source commit available in Git:

```powershell
npm ci
node --import tsx benchmarks\node-cache-fill-fences\verify.mjs benchmarks\node-cache-fill-fences\results\local-2026-12-06.json
npx vitest run tests\node-cache-fill-fences.test.ts
npx tsc -p benchmarks\node-cache-fill-fences\tsconfig.json --noEmit
```

For a separate comparison, use a clean, isolated checkout of frozen source
`483ce5b92c7e74685ee09362175cdf606e6a40c3`. The collector requires detached
HEAD and a new filename; never overwrite the originals:

```powershell
git switch --detach 483ce5b92c7e74685ee09362175cdf606e6a40c3
node --import tsx benchmarks\node-cache-fill-fences\run.mjs --output benchmarks\node-cache-fill-fences\results\local-reproduction.json
node --import tsx benchmarks\node-cache-fill-fences\verify.mjs benchmarks\node-cache-fill-fences\results\local-reproduction.json
```

## Industry references

- [Redis client-side caching: avoiding race conditions](https://redis.io/docs/latest/develop/reference/client-side-caching/#avoiding-race-conditions)
describes invalidating an in-progress placeholder before a delayed read
reply can repopulate stale data.
- [Azure Cache-Aside pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/cache-aside)
describes invalidation ordering and the consistency limits of local caches.

Both references were checked on 6 December 2026. They motivate the local
publication fence; they do not establish Redis compatibility, cross-process
coherence or performance benefits for this implementation.
10 changes: 10 additions & 0 deletions benchmarks/node-cache-fill-fences/baseline-vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import {execFileSync} from "node:child_process";
import {readFileSync} from "node:fs";
import path from "node:path";
import {fileURLToPath} from "node:url";
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 file=path.join(root,"src","stores.ts").replaceAll("\\","/");
const source=execFileSync("git",["show",`${baseline}:src/stores.ts`],{cwd:root,encoding:"utf8"});
export default defineConfig({root,plugins:[{name:"exact-node-fill-baseline",enforce:"pre",load(id){return id.replaceAll("\\","/").split("?")[0]===file?source:null}}],test:{include:["tests/node-cache-fill-fences.test.ts"]}});
Loading
Loading