Skip to content
Merged
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ The format follows Keep a Changelog and the package uses semantic versioning.

## Unreleased

- Fixed an empty raw memory-cache key blocking LRU eviction when eldest.
Entry/byte budgets now evict it normally; empty keys remain supported.
Direct raw caches and shared roots containing such a key are affected.
Factory-generated encoded keys are nonempty. Correct enforcement can add
eviction work and later cache misses. Public options, accounting, defaults
and persistent-cache policy are unchanged.

- Coordinated custom-persistent namespace wrappers sharing the same immediate
delegate object and encoded namespace within one loaded module. Registry
updates no longer lose settled peer writes; complete same-key mutations and
Expand Down
252 changes: 252 additions & 0 deletions benchmarks/empty-key-memory-eviction/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,252 @@
# Empty-key memory eviction qualification

The candidate restores the memory-cache budget contract when the eldest raw
key is an empty string. All 384 candidate trials pass. The historical module
passes 216/384; its nine declared controls remain unchanged. The production
change is one explicit exhaustion comparison in `MemoryObjectCache`.

Merge recommendation: 93/100, above the prospective 85/100 threshold.
All protocol hard gates, including exact-publication-head CI and CodeQL,
remain mandatory. The score is an engineering judgement, not a probability.

## Input boundary and implementation

`MemoryObjectCache` is publicly exported and already accepts `""` in its
set/get/delete methods. Its eviction loop read the first insertion-ordered
Map key, then treated any falsy value as exhaustion. An empty eldest key
therefore stopped eviction while further fitting entries accumulated.

The candidate changes `if (!oldest)` to `if (oldest === undefined)`. It retains
the current admission, cloning, byte accounting, recency and virtual deletion
paths. It neither rejects empty keys nor adds a special pinned-key policy.
The [historical implementation](https://github.com/Jason-Doyle/thimble/blob/7184ef9b760b86200210ea521c2bd9615db18b57/src/browser/cache.ts#L70-L157)
and [candidate implementation](https://github.com/Jason-Doyle/thimble/blob/de8da5b264b477bdb869ec016e01044b4dd79d5f/src/browser/cache.ts#L140-L157)
bound the comparison.

This affects direct raw-cache use and shared roots containing an unrelated
raw empty key. Normal factory-generated memory keys have nonempty encoded
namespace prefixes. An empty logical key through that namespace is also
nonempty at the root and already evicts correctly. No production incidence
or ordinary factory-workload benefit has been measured.

The rationale uses established
[Map insertion-order semantics](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys)
and the [iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols).
It requires no new language feature or dependency.

## Prospective protocol and capture

The [protocol](protocol.json) was published at
`acf16c3e963e0780a55670b62150fb7c28658f87`, before production edits.
Source, fixtures, collector, verifier and tests were frozen and pushed at
`de8da5b264b477bdb869ec016e01044b4dd79d5f`. The sole comparative invocation
ran detached at that commit, against the complete exact historical cache
module at `7184ef9b760b86200210ea521c2bd9615db18b57`.

The matrix has 16 recipes, two independent pressure modes, ASCII/multibyte
payloads, capacities 1/8 and three deterministic replicates: 384 matched
pairs, 768 raw rows. Fitting entries each charge 256 bytes. Entry-pressure
cases use the selected entry capacity and 16,384 bytes; byte-pressure cases
use 128 entries and `capacity * 256` bytes. The burst's non-target limit does
not bind. Exact-fit and oversized controls deliberately vary entry size.
Replicates demonstrate repeatability, not statistical independence.

Every declared command, root call/return, successful production clone,
resident value/order, accounted byte count, eviction count and later probe is
retained. Fixture copying and non-mutating inspection are excluded from
production clone counters. The matrix performs no network, IndexedDB,
persistent-adapter or WebCrypto operations.

The separate [verifier](verify.mjs) imports neither fixtures nor collector.
It reconstructs recipes, checks an independent array LRU model, replays all
root/clone events through a second state ledger, checks all 384 pairs and
81 frozen input digests, and reproduces every CSV cell and both SVGs.
The capture contains 12,648 commands/probes, 20,676 root calls and 10,140
successful production clones across both arms and both phases.

## Contract results

Each recipe has 24 trials per arm. A contract requires every work and probe
state, return, LRU order, accounting value and clone expectation to match.
The selected budget must hold after every completed command.

| Recipe | Historical contracts | Candidate contracts | Historical peak residents | Candidate peak residents |
| --- | ---: | ---: | ---: | ---: |
| Empty eldest under pressure | 0/24 | 24/24 | 9 | 8 |
| Empty-eldest burst | 0/24 | 24/24 | 33 | 8 |
| Empty becomes eldest after hits | 0/24 | 24/24 | 9 | 8 |
| Empty hit, then renewed pressure | 0/24 | 24/24 | 9 | 8 |
| Empty replacement, then pressure | 0/24 | 24/24 | 9 | 8 |
| Shared namespaces over raw empty seed | 0/24 | 24/24 | 11 | 8 |
| Namespace clear and reuse | 0/24 | 24/24 | 11 | 8 |
| Oversized empty-key replacement | 24/24 | 24/24 | 8 | 8 |
| Ordinary eldest under pressure | 24/24 | 24/24 | 8 | 8 |
| Empty key without pressure | 24/24 | 24/24 | 8 | 8 |
| Explicit empty-key deletion | 24/24 | 24/24 | 8 | 8 |
| Root clear and reuse | 24/24 | 24/24 | 8 | 8 |
| Oversized new key | 24/24 | 24/24 | 8 | 8 |
| Exact byte fit | 24/24 | 24/24 | 1 | 1 |
| Same-key replacement | 24/24 | 24/24 | 1 | 1 |
| Encoded empty logical key | 24/24 | 24/24 | 8 | 8 |
| Total | 216/384 | 384/384 | 33 | 8 |

These are deliberately constructed input-boundary cases. Their pass ratio
does not estimate application prevalence. The nine controls have exactly
equal full work/probe observations between arms, including root events,
values, recency, accounting and copy work.

![Contract passes for every declared recipe](results/local-2026-12-03-contracts.svg)

In the prospectively selected capacity-eight burst, the historical root ends
with 33 objects after 33 fitting sets, including the empty seed. The candidate
retains eight. Under byte pressure the same 33 objects charge 8,448 bytes
against a 2,048-byte budget; the candidate retains 2,048 accounted bytes.
The graph below uses the declared entry-pressure/ASCII/replicate-zero pair.

![Logical resident growth and the eight-entry budget](results/local-2026-12-03-growth.svg)

## Work and costs

Primary work ends before later verification reads. Every matched pair has
equal accepted-set clone events and equal total work-phase clone counts and
logical input bytes.

| Measurement across 384 trials per arm | Historical | Candidate |
| --- | ---: | ---: |
| Declared work commands | 3,336 | 3,336 |
| Later verification reads | 2,988 | 2,988 |
| Work-phase root calls | 7,056 | 7,644 |
| All root calls, including probes | 10,044 | 10,632 |
| Work-phase production clones | 3,216 | 3,216 |
| Work-phase logical clone-input bytes | 1,317,168 | 1,317,168 |
| All production clones, including probes | 5,364 | 4,776 |
| Budget-eviction deletes | 528 | 1,140 |
| Namespace-clear deletes | 132 | 108 |
| Persistent/network operations in matrix | 0 | 0 |

Correct enforcement adds 612 eviction deletes. Clearing subsequently visits
24 fewer resident namespace keys, giving a net 588 additional root calls.
The historical over-budget cache also serves 588 extra probe hits and clones;
the candidate correctly misses on those evicted objects. Those differences
are consequences of restoring the budget, not timing or allocation results.

Applications can incur more persistent or authorised remote reads after
correct eviction. A bounded cache cannot retain the previous invalid
over-budget working set. No latency, throughput, heap, GC timing, hit-rate or
provider-cost benefit is established. Accounted bytes retain UTF-8 JSON value
size, JavaScript key/ETag lengths and the existing 48-byte allowance.

## Compatibility qualification

| Qualification | Outcome |
| --- | --- |
| Exact historical initial focused suite | 78 pass, 65 expected failures / 143 |
| Exact historical with factory cases | 80 pass, 67 expected failures / 147 |
| Exact historical final focused suite | 80 pass, 69 expected failures / 149 |
| Candidate final focused suite | 149/149 |
| Existing browser cache/client/factory controls | 496/496 |
| Native selected memory recipes | 24/24 |
| Native shared-root factory cases | 12/12 |
| Built public-entrypoint probes | 4/4 |
| Repository, Studio, Worker and experiment types | Pass |
| Package, isolated consumers and browser isolation | Pass |

The focused suite includes 1,000 bounded fitting writes after an empty seed,
multiple byte evictions after removing that seed, virtual delete dispatch,
input/return ownership, and other ordinary string keys. Under both content
and locations policies, eviction preserves persistent writes and correct
post-eviction hydration or existing failure fallback. Memory-only and
disabled-policy behaviour remain covered.

Each native engine ran eight memory cases and four connection-factory cases.
Factory cases use `persistentCache: false`, both policies and a shared root
with/without a raw empty seed. They exercise synthetic snapshot configuration,
not a revised collection protocol or a new encrypted-IndexedDB workload.

The unchanged Windows x64 host uses Node 22.22.2 and TypeScript 5.9.3.
Playwright 1.63.0 ran Chromium 153.0.8010.12, Firefox 155.0 and WebKit 26.6.
Windows WebKit does not qualify Apple Safari. The supported-Node public-site
build remains part of normal CI; the shared host was not upgraded.

All six local focused-suite invocations and the one native invocation are
retained by identity in the qualification artifact. Initial candidate suites
passed 639/639 and 643/643 before the final two multi-eviction cases brought
the total to 645/645. The first verifier syntax check found a redundant
closing parenthesis, corrected before source freeze. It executed no
comparative trial. There was one successful comparative capture and one
successful native invocation.

The native helper began with absent data and free ports. Its three generated
paths were checked by timestamp and attributes and removed non-recursively
after all listeners stopped, without reading the generated key.

## Decision and rejection criteria

| Criterion | Score | Basis |
| --- | ---: | --- |
| Budget correctness and fit | 35/40 | All declared states pass; supported raw-empty boundary, with unknown production incidence |
| Compatibility and work | 24/25 | Controls, fallback and native integration pass; intended extra eviction work and misses remain |
| Reproducible evidence | 19/20 | Frozen paired ledgers, independent replay and three Windows engines; no production or Apple-device campaign |
| Scope and simplicity | 15/15 | One guard change; no option, dependency, format, policy or runtime change |
| Total | 93/100 | Threshold 85/100, all hard gates mandatory |

Reject the candidate if a declared control changes, a candidate state violates
either budget, a copy is added to admission, or a root event fails replay.
Also reject claims of general performance gains from these constructed
cases. Code using empty keys as pinned sentinels must keep that state outside
the bounded LRU. Invalid/non-finite constructor limits, arbitrary subclass
storage/deletion overrides, cross-instance consistency and durable logout
remain outside this qualification.

## Evidence and reproduction

| Artifact | Contents |
| --- | --- |
| [Complete raw ledger, lossless gzip](results/local-2026-12-03.json.gz) | All 768 rows and every command/state/event |
| [Trial CSV](results/local-2026-12-03-trials.csv) | Exact per-arm trial measurements |
| [Contract graph](results/local-2026-12-03-contracts.svg) | All declared recipe contract counts |
| [Resident-growth graph](results/local-2026-12-03-growth.svg) | Prospectively selected finite burst |
| [Native observations](results/native-2026-12-03.json) | All 36 observations, versions, runner digest and cleanup metadata |
| [Qualification manifest](results/qualification-2026-12-03.json) | Historical failures, local checks, source and retained-run identities |

The full expanded JSON is 135,574,132 bytes. It is published as a 1,624,035-byte
gzip because it exceeds [GitHub's per-file limit](https://docs.github.com/en/repositories/working-with-files/managing-large-files/about-large-files-on-github).
Compression was a transport-only post-capture step: no rows or fields were
removed, no comparative trial was rerun, and the frozen collector/verifier
remain unchanged.

Archive SHA256:
`d7789df9e74c4408aae075bf2317036cb705ab3861735e8124e6192950744f5f`.
Expanded JSON SHA256:
`7672c016eb7c5831f828f3f3215a5bfccb288a6a675e1f15f1bdfb5bae7d87aa`.
The original expanded bytes are also retained locally.

From a publication checkout with dependencies installed and both historical
Git objects available, expand the archive once and verify it in PowerShell:

```powershell
node --input-type=module -e "import fs from 'node:fs'; import z from 'node:zlib'; import path from 'node:path'; const f=path.join('benchmarks','empty-key-memory-eviction','results','local-2026-12-03.json'); fs.writeFileSync(f,z.gunzipSync(fs.readFileSync(f+'.gz')),{flag:'wx'});"
node benchmarks\empty-key-memory-eviction\verify.mjs benchmarks\empty-key-memory-eviction\results\local-2026-12-03.json --native benchmarks\empty-key-memory-eviction\results\native-2026-12-03.json
```

In a separate clean checkout, detach at the frozen source and use an unused
output name for a new comparison:

```powershell
git switch --detach de8da5b264b477bdb869ec016e01044b4dd79d5f
node --import tsx benchmarks\empty-key-memory-eviction\run.ts --output benchmarks\empty-key-memory-eviction\results\replication.json
node benchmarks\empty-key-memory-eviction\verify.mjs benchmarks\empty-key-memory-eviction\results\replication.json
npx --no-install vitest run tests/browser
npx --no-install tsc -p benchmarks\empty-key-memory-eviction\tsconfig.json
```

Native qualification uses the existing local helper. First confirm that
`.thimble-e2e` is absent and ports 5173/8787/8790 are free; the helper clears
that named test-data path on startup:

```powershell
npx --no-install playwright test 'cache-empty-key\.spec\.ts'
```

No cloud campaign, provisioning, infrastructure change, deployment or
shared-host runtime upgrade is required.
17 changes: 17 additions & 0 deletions benchmarks/empty-key-memory-eviction/baseline-vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { defineConfig } from "vitest/config";

const root = fileURLToPath(new URL("../../", import.meta.url));
const target = fileURLToPath(new URL("../../src/browser/cache.ts", import.meta.url)).replaceAll("\\", "/");
const { baseline } = JSON.parse(readFileSync(new URL("./protocol.json", import.meta.url), "utf8"));
const source = execFileSync("git", ["--no-pager", "show", `${baseline}:src/browser/cache.ts`], { cwd: root, encoding: "utf8" });
export default defineConfig({
root,
plugins: [{
name: "exact-baseline-empty-key-memory", enforce: "pre",
load(id) { return id.replaceAll("\\", "/").split("?")[0] === target ? source : null; },
}],
test: { include: ["tests/browser-memory-empty-key.test.ts"] },
});
58 changes: 58 additions & 0 deletions benchmarks/empty-key-memory-eviction/factory-fixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { MemoryObjectCache } from "../../src/browser/cache.js";
import { createThimbleConnection } from "../../src/browser/connect.js";
import { equal, LruReference, prefix, sizedEntry, snapshot } from "./fixtures.js";

export async function runFactoryCase(policy: "content" | "locations", rawEmptySeed: boolean) {
const root = new MemoryObjectCache(2, 8192), model = new LruReference({ maxEntries: 2, maxBytes: 8192 });
const connections: Awaited<ReturnType<typeof createThimbleConnection>>[] = [];
const configurationRequests: string[] = [], channel = `p17-factory-${crypto.randomUUID()}`;
const namespace = (scope: string) => `local:https://p17.example.test:/api/objects:${scope}`;
const scopes = ["p17-one", "p17-two"];
try {
for (const scope of scopes) {
connections.push(await createThimbleConnection({
configurationUrl: "https://p17.example.test/api/config",
memoryCache: root, persistentCache: false, channelName: channel,
fetchImplementation: async input => {
const url = String(input); configurationRequests.push(url);
if (url !== "https://p17.example.test/api/config") throw new Error("Unexpected factory fetch");
return Response.json({
name: "ThimbleDB", provider: "local", readBaseUrl: "/api/objects",
headTtlMs: 10_000, cachePolicy: policy, collectionLayouts: { notes: "snapshot" },
layoutGeneration: "generation-1", csrfToken: "fixture",
user: { id: "fixture", provider: "dev", roles: [], tenants: [], identities: [] },
scope: { id: scope, encrypted: false, keyId: null, keyEndpoint: null },
});
},
}));
}
const seed = rawEmptySeed ? sizedEntry("", 256, "multibyte") : null;
if (seed) { root.set(seed); model.apply({ kind: "set", target: "root", entry: seed }); }
const initial = { actual: snapshot(root), expected: model.snapshot() };
const values = Array.from({ length: 6 }, (_, index) => ({
connection: index % 2, entry: sizedEntry(`item-${index}/HEAD.json`, 256, "multibyte", index + 1),
}));
const steps = [];
for (const value of values) {
await connections[value.connection]!.cache.set(value.entry);
const key = `${prefix(namespace(scopes[value.connection]!))}${value.entry.key}`;
const expected = model.apply({ kind: "set", target: "root", entry: { ...value.entry, key } }).snapshot;
const actual = snapshot(root);
steps.push({ ...value, actual, expected, correct: equal(actual, expected) });
}
const verification = [];
for (const value of values) {
const key = `${prefix(namespace(scopes[value.connection]!))}${value.entry.key}`;
const expectedResult = model.apply({ kind: "get", target: "root", key });
const expectedReturned = expectedResult.returned ? { ...expectedResult.returned, key: value.entry.key } : null;
const returned = await connections[value.connection]!.cache.get(value.entry.key), actual = snapshot(root);
verification.push({ ...value, returned, expectedReturned, actual, expected: expectedResult.snapshot,
correct: equal(returned, expectedReturned) && equal(actual, expectedResult.snapshot) });
}
const metrics = connections.map(connection => connection.cache.metrics());
const correct = equal(initial.actual, initial.expected) && steps.every(step => step.correct) &&
verification.every(step => step.correct) && configurationRequests.length === 2 &&
metrics.every(value => !value.persistentAvailable && value.persistentErrors === 0 && value.writes === 3);
return { policy, rawEmptySeed, seed, initial, configurationRequests, steps, verification, metrics, correct };
} finally { for (const connection of connections) connection.client.close(); }
}
Loading