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

## Unreleased

- Rejected oversized memory-cache entries before cloning or insertion, rather
than evicting unrelated residents to make room for an object that cannot fit.
Oversized replacements still remove their old same-key value. Returned
values, persistent operations, cache policies and default limits are unchanged.

- Prevented pending persistent-cache reads from restoring memory values
invalidated by an intervening local write, delete, clear or policy change.
Invalidated reads use current memory or return a miss. Unrelated keys and
Expand Down
242 changes: 242 additions & 0 deletions benchmarks/oversized-memory-admission/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
# Oversized memory-cache admission

Date: 3 December 2026 (UTC).

Recommendation: merge the scoped admission change, subject to normal repository
CI and review. Score: 94/100 against the prospective 85/100 threshold. This is
an engineering assessment, not a probability.

An object that cannot fit in the memory byte budget should not evict unrelated
resident objects. The candidate rejects that admission before cloning or
insertion. It still removes an older value for the same key. Returned
application values, persistent operations, policies, default limits, public
interfaces and stored formats are unchanged.

## Motivation and scope

The merged baseline inserted and cloned every incoming object, then evicted
oldest entries until both memory limits held. An object larger than the entire
byte budget therefore removed the working set and finally itself. Discovery
with a 512-byte budget reduced two hot entries, occupying 142 accounted bytes,
to zero entries and recorded three evictions.

This is an established admission technique, not a new browser capability.
The [primary lru-cache source](https://github.com/isaacs/node-lru-cache/blob/2056b03da35a12d3a234ce1984202de6e3cadbf3/src/index.ts)
documents rejection of oversized entries without evicting others, while
removing an existing same-key value. It motivates the policy; this experiment
does not install, compare against or benchmark that package.

The only production difference is a three-line guard in
[`MemoryObjectCache.set`](https://github.com/Jason-Doyle/thimble/blob/ba6079bf81557daa297bacce9888f03276a61b70/src/browser/cache.ts#L87-L100),
after existing same-key deletion and size estimation. No new option, retry,
queue, timer, request, schema or dependency is introduced. Existing namespaced
memory caches and tiered persistent hydration use the same guard.

## Prospective method

The [protocol](protocol.json) was published at
[`3af1d4c8e12e602ec83add3899fad8c09eaab601`](https://github.com/Jason-Doyle/thimble/commit/3af1d4c8e12e602ec83add3899fad8c09eaab601)
before production edits. It fixes 16 schedules, 512/2,048-byte budgets, ASCII
and four-byte UTF-8 payloads, content/locations policies, and three replicates:
384 trials per arm. The matrix uses fresh memory and a counting, snapshotting
persistent fixture per trial, with no network.

The baseline cache module is transpiled directly from merged main
`8691d8623689c16c9ac4cc7e10df57b7a8fb2175`. Other source and dependencies are
shared between arms. Arm order alternates by case and replicate. Sizes at the
boundary include the existing key, ETag and metadata accounting; exact-fit and
one-byte-over fixtures check the boundary under both payload encodings.

Source, collector and tests were committed and pushed at
`ba6079bf81557daa297bacce9888f03276a61b70` before capture. The single complete
capture ran from an actual detached checkout of that commit, then restored the
owning branch. All 768 rows and 384 pair gates passed. No failed capture was
discarded or replaced.

Rows retain input metadata/value digests, exact resident keys and value
digests in LRU order, expected states, returned values, persistence state,
cache metrics, memory operations and production copy work. Source inventories
are checked against committed blobs before collection and against the working
files again afterwards. The collector refuses output overwrite and caps the
matrix at five minutes and 10,000 persistent calls. Capture timestamps are
diagnostic, not latency measurements.

## Results

Each row below represents 24 trials per arm. Retained entries are totals across
those independent caches, not the contents of one enlarged cache.

| Schedule | Baseline correct | Candidate correct | Baseline retained entries | Candidate retained entries |
| --- | ---: | ---: | ---: | ---: |
| oversized-new | 0/24 | 24/24 | 0 | 48 |
| oversized-replacement | 0/24 | 24/24 | 0 | 24 |
| repeated-oversized | 0/24 | 24/24 | 0 | 48 |
| oversized-after-hit | 0/24 | 24/24 | 24 | 48 |
| oversized-key | 0/24 | 24/24 | 0 | 48 |
| oversized-etag | 0/24 | 24/24 | 0 | 48 |
| one-byte-over | 0/24 | 24/24 | 0 | 48 |
| persistent-hydration | 0/24 | 24/24 | 0 | 48 |
| persistent-failure | 0/24 | 24/24 | 0 | 48 |
| shared-namespaces | 0/24 | 24/24 | 0 | 48 |
| exact-byte-fit | 24/24 | 24/24 | 24 | 24 |
| ordinary-byte-pressure | 24/24 | 24/24 | 48 | 48 |
| ordinary-entry-pressure | 24/24 | 24/24 | 48 | 48 |
| warm-hit-copy | 24/24 | 24/24 | 48 | 48 |
| replacement-only | 24/24 | 24/24 | 0 | 0 |
| disabled-policy | 24/24 | 24/24 | 48 | 48 |
| Total | 144/384 | 384/384 | 240 | 672 |

![Retained entries by schedule, with exact totals across 24 trials per arm](results/local-2026-12-03-retention.svg)

The candidate fixes all 240 affected trials. In the replacement schedules it
removes the old same-key object; it does not preserve stale data. The
after-hit schedule checks retained order before a later fitting insertion,
then verifies that insertion still evicts the correct LRU object.
`replacement-only` is a safety control: both arms remove the sole old value,
but the candidate avoids cloning and immediately evicting its replacement.

| Action-phase counter, per arm | Baseline | Candidate |
| --- | ---: | ---: |
| Persistent get | 24 | 24 |
| Persistent set attempts | 408 | 408 |
| Persistent delete/clear/destroy | 0 | 0 |
| Total persistent calls | 432 | 432 |
| Memory get | 72 | 72 |
| Memory set attempts | 432 | 432 |
| Memory delete, including internal eviction | 1,320 | 552 |
| Memory evictions | 888 | 120 |
| Instrumented cache-entry clones | 480 | 144 |
| Clones of oversized inputs | 336 | 0 |
| Logical clone-input JSON bytes | 584,880 | 73,272 |

Persistent operations, stored values and application read results match in
every pair. Persistent set counts include the 24 injected failed attempts.
The five ordinary-work controls, 120 trials per arm, preserve identical
memory operations, cache metrics and clone work. Disabled-policy fixtures
seed the shared memory directly before constructing the disabled tier; reads
still miss and no persistent operation occurs.

Copy instrumentation covers successful `structuredClone` calls made by the
production memory cache. Fixture persistence snapshots, verification and
digest preparation use the original clone function and are excluded. Setup
is also excluded from the action counters. The candidate removes 336 clones
and 511,608 logical input bytes in this deliberately selected matrix. These
are not physical allocation sizes or an estimate of production savings.

## Qualification

| Check | Observation |
| --- | --- |
| Exact historical-cache focused suite | 6 passed, 15 expected failures, 21 total |
| Candidate focused suite | 21 passed |
| Existing cache, hydration, ownership, client, connection and publication controls | 221 passed |
| Chromium / Firefox / WebKit | 14 passed in each engine; 42 total; no failures, skips or flaky cases |
| Root, Studio, Worker and collector type checks | Passed |
| Package build, isolated consumer and export verification | Passed |

Native coverage comprises 24 direct admission cases, six actual encrypted
IndexedDB hydrations and 12 connection-factory cases. Hydration returns the
complete oversized object and retains persistence while preserving two hot
memory entries. Factory cases configure both layouts and policies, share one
memory cache between scopes, and check isolation and scoped clearing. They
qualify cache wiring, not end-to-end database read or bundle performance.

Local observations used Node 22.22.2 on a shared Windows x64 host without a
runtime upgrade. Native tests used the existing loopback helper; no provider
campaign or infrastructure change ran. Windows WebKit does not qualify Safari
on Apple hardware. Supported-Node website and full repository qualification
remain the normal CI gate.

The [qualification observations](results/qualification-2026-12-03.json)
separate test-runner counts and digests from the comparative raw rows. Full
runner reports contain machine-local paths and are retained locally.

## Cost, limitations and rejection criteria

Every memory set adds one size comparison and conditional branch after the
existing byte estimate. Oversized values still pay for that JSON size
estimate, normal persistence/encryption and any public result copies. Values
read from persistence are still decrypted and parsed before admission.

An oversized object remains absent from memory, just as on the baseline.
Repeated reads can still require persistent or authorised remote work. A
fitting but large object can still evict smaller hot objects under ordinary
LRU. This is not a frequency-based admission policy or a larger working set.

`evictions` no longer counts an oversized object that was never admitted, or
unrelated entries that it previously displaced. Accepted tiered write
attempts still increment `writes` and attempt persistence. There is no new
memory-rejection metric. Consumers interpreting eviction counts should retain
this distinction.

Memory accounting remains UTF-8 JSON value bytes plus JavaScript string
lengths for the stored key and ETag, plus a 48-byte allowance. Namespaced keys
include their prefix. This does not account for physical heap, temporary
serialization, auxiliary namespace-key history or browser implementation
overhead. In particular, this change does not fix or bound that auxiliary
key bookkeeping.

No latency, throughput, heap, allocation-size, production-frequency,
network-saving, cloud-cost, logout or cross-tab guarantee is established.
The 512/2,048-byte matrix tests admission boundaries, not a production workload
at the default 16 MiB limit. Existing entry and byte limits are unchanged.

Reject the candidate if it retains an obsolete same-key value, changes normal
LRU or exact-fit behaviour, changes application/persistent values, adds
persistent calls, changes the ordinary-work controls, or fails native or
repository qualification. The local mandatory gates pass. Normal CI and human
review are still required before merge.

## Merge-worthiness assessment

| Category | Score | Basis |
| --- | ---: | --- |
| Correctness and working-set retention | 34/35 | All 240 affected trials fixed; same-key, LRU, boundary and policy controls pass; finite fixtures are not exhaustive |
| Bounded storage and local work | 19/20 | No extra persistent work; rejected clones eliminated; comparison and JSON-estimate costs remain |
| Reproducible evidence | 18/20 | Published prospective protocol, detached frozen-source capture, all rows and source digests; one observed host |
| Compatibility and scope | 14/15 | No option/interface/format change; returned values and persistence match; eviction accounting intentionally changes |
| Operational simplicity | 9/10 | Three-line guard reuses existing accounting; no lifecycle or configuration state |
| Total | 94/100 | Above 85/100, with all local mandatory gates passing |

## Evidence and reproduction

The raw artifact is authoritative:

- [Raw paired rows and source inventory](results/local-2026-12-03.json)
- [Derived trial CSV](results/local-2026-12-03-trials.csv)
- [Derived retention graph](results/local-2026-12-03-retention.svg)
- [Derived qualification observations](results/qualification-2026-12-03.json)
- [Collector](run.ts), [fixtures](fixtures.ts) and [prospective protocol](protocol.json)

| Provenance item | SHA256 |
| --- | --- |
| Raw JSON, 4,905,218 bytes | `42da376775304eb00a1241851816be9d3c9ef3384c657d41728978669d285a3d` |
| Protocol, LF-normalised | `d9e97c575be5ffde5c650d9a926b095199dba797625113b9e15382c65669efff` |
| Baseline cache source, LF-normalised | `032aedb99fa6e9419216c2c2b42ad7b17b73522e78a0858f9a95482dbc7b8d8b` |
| Candidate cache source, LF-normalised | `bae973215a9789cb05b7132bb21e16527313d8e4517592b03d2cbc32a299d082` |

Capture ran from `2026-12-03T04:36:42.255Z` to
`2026-12-03T04:36:42.458Z`. All 78 recorded inputs matched committed source
and remained unchanged.

Use the repository's locked dependencies and installed Playwright browsers.
Start from the frozen source, with the baseline commit available locally:

```powershell
git switch --detach ba6079bf81557daa297bacce9888f03276a61b70
npm ci
npm test -- --config benchmarks\oversized-memory-admission\baseline-vitest.config.ts
npm test -- tests\browser-memory-admission.test.ts tests\browser-cache-hydration.test.ts tests\browser-cache-limits.test.ts tests\browser-cache-failure.test.ts tests\browser-client.test.ts tests\browser-connect.test.ts tests\browser-head-publication.test.ts tests\browser-read-ownership.test.ts
npm run check
npx tsc -p benchmarks\oversized-memory-admission\tsconfig.json --noEmit
npm run test:e2e -- 'memory-admission\.spec\.ts'
node --import tsx benchmarks\oversized-memory-admission\run.ts --output benchmarks\oversized-memory-admission\results\local-reproduction.json
```

The historical-cache command is expected to exit non-zero with the 15 declared
failures. The final collector command requires a new output filename and
creates raw JSON, CSV and SVG without changing branches or refs. It does not
require a live remote branch tip; historical source and committed inputs are
required. Reproduced timestamps and environment metadata can differ; compare
the rows and declared gates rather than expecting an identical whole-file
digest across runs.
24 changes: 24 additions & 0 deletions benchmarks/oversized-memory-admission/baseline-vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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", ["show", `${baseline}:src/browser/cache.ts`], {
cwd: root, encoding: "utf8",
});

export default defineConfig({
root,
plugins: [{
name: "exact-baseline-memory-admission",
enforce: "pre",
load(id) {
return id.replaceAll("\\", "/").split("?")[0] === target ? source : null;
},
}],
test: { include: ["tests/browser-memory-admission.test.ts"] },
});
Loading