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

## Unreleased

- Ordered admitted persistent-cache mutations within each tiered cache.
Same-key operations wait for predecessors; all-cache clear and destruction
wait for earlier work and fence later admitted mutations. Unrelated keys
remain independently runnable, with immediate memory updates and existing
failure behaviour. This adds promise scheduling and pending-work retention,
not cross-instance ordering, read linearizability or durable logout.
Public options and stored formats are unchanged. Each admitted mutation makes
one adapter call; no entry clone or retry is added.

- Removed unbounded historical-key tracking from recognised concrete built-in
memory namespace chains. Scoped clearing snapshots resident keys and now
includes values written by same-namespace peer or previous wrappers while
Expand All @@ -21,8 +30,8 @@ The format follows Keep a Changelog and the package uses semantic versioning.
- 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
storage calls are unchanged; this does not order pending adapter writes or
provide cross-instance consistency.
storage calls are unchanged; this read-invalidation rule does not provide
cross-instance consistency or cover reads begun during unfinished mutations.

- Isolated mutable browser read results from shared immutable-object reads.
Point reads, scans and queries return independent nested document values.
Expand Down
309 changes: 309 additions & 0 deletions benchmarks/ordered-persistent-cache-mutations/README.md

Large diffs are not rendered by default.

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-mutation-cache", enforce: "pre",
load(id) { return id.replaceAll("\\", "/").split("?")[0] === target ? source : null; },
}],
test: { include: ["tests/browser-cache-mutations.test.ts"] },
});
326 changes: 326 additions & 0 deletions benchmarks/ordered-persistent-cache-mutations/fixtures.ts

Large diffs are not rendered by default.

108 changes: 108 additions & 0 deletions benchmarks/ordered-persistent-cache-mutations/native-fixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { IndexedDbObjectCache, MemoryObjectCache, TieredObjectCache } from "../../src/browser/cache.js";
import {
bounded, deferred, describe, entry, flush, runTrial, type Policy,
} from "./fixtures.js";

export const encryptedScenarios = [
"late-set-newer-set", "late-set-destroy", "late-clear-set",
"late-destroy-set", "multi-key-clear", "unrelated-overlap",
] as const;
async function request<T>(value: IDBRequest<T>): Promise<T> {
return new Promise((resolve, reject) => {
value.onsuccess = () => resolve(value.result);
value.onerror = () => reject(value.error);
});
}
async function inspect(databaseName: string, persistent: IndexedDbObjectCache) {
const database = await request(indexedDB.open(databaseName, 2));
try {
const rows = await request(database.transaction("objects").objectStore("objects")
.index("namespace").getAll(IDBKeyRange.only("p14"))) as Array<{
key: string; iv: ArrayBuffer; ciphertext: ArrayBuffer; value?: unknown;
}>;
const values = await Promise.all(rows.map((row) => persistent.get(row.key)));
const deviceKey = await request(database.transaction("keys").objectStore("keys")
.get("p14:device-cache-key"));
return {
rows: rows.length, decrypted: await describe(values.filter((value) => value !== null)),
missing: values.filter((value) => value === null).length,
encrypted: rows.every((row) => row.iv.byteLength === 12 &&
row.ciphertext.byteLength >= 16 && !("value" in row)),
deviceKeyPresent: Boolean(deviceKey),
};
} finally { database.close(); }
}
async function close(databaseName: string, persistent: IndexedDbObjectCache) {
persistent.close();
await bounded(new Promise<void>((resolve, reject) => {
const deleting = indexedDB.deleteDatabase(databaseName);
deleting.onsuccess = () => resolve();
deleting.onerror = () => reject(deleting.error);
}), "Native database cleanup");
}
export async function runEncryptedScenario(
scenario: typeof encryptedScenarios[number], policy: Policy,
) {
const databaseName = `p14-${crypto.randomUUID()}`;
const boundedAdapter = encryptedScenarios.indexOf(scenario) % 2 === 0;
const persistent = new IndexedDbObjectCache("p14", databaseName,
boundedAdapter ? { maxEntries: 64, maxBytes: 1048576 } : undefined);
try {
const result = await runTrial(TieredObjectCache, scenario, policy, "head", "newest-ready-first", { delegate: persistent });
const stored = await inspect(databaseName, persistent);
return {
result, stored, boundedAdapter,
correct: result.correct && result.ordered && stored.encrypted && stored.missing === 0 &&
JSON.stringify(stored.decrypted) === JSON.stringify(result.expectedPersistent) &&
stored.deviceKeyPresent === (scenario !== "late-set-destroy"),
};
} finally { await close(databaseName, persistent); }
}
export async function runLateCrypto(later: "set" | "delete", policy: Policy) {
const databaseName = `p14-crypto-${crypto.randomUUID()}`;
const boundedAdapter = later === "set";
const persistent = new IndexedDbObjectCache("p14", databaseName,
boundedAdapter ? { maxEntries: 64, maxBytes: 1048576 } : undefined);
const entered = deferred(), release = deferred(), encrypt = crypto.subtle.encrypt;
const pending: Promise<void>[] = [];
let first = true, laterStarted = false, encryptCalls = 0;
try {
await persistent.set(entry("head", 0));
await persistent.delete(entry("head", 0).key);
const set = persistent.set.bind(persistent), remove = persistent.delete.bind(persistent);
persistent.set = (value) => {
if (value.checkedAt === 200) laterStarted = true;
return set(value);
};
persistent.delete = (key) => { laterStarted = true; return remove(key); };
crypto.subtle.encrypt = async (...parameters: Parameters<SubtleCrypto["encrypt"]>) => {
encryptCalls += 1;
if (first) { first = false; entered.resolve(); await release.promise; }
return encrypt.apply(crypto.subtle, parameters);
};
const cache = new TieredObjectCache(new MemoryObjectCache(), persistent, policy);
pending.push(cache.set(entry("head", 1)));
await bounded(entered.promise, "First encryption");
pending.push(later === "set" ? cache.set(entry("head", 2)) : cache.delete(entry("head", 1).key));
await flush();
const laterStartedWhileHeld = laterStarted;
release.resolve();
await bounded(Promise.all(pending), "Late encryption mutations");
crypto.subtle.encrypt = encrypt;
cache.clearMemory();
const returned = await cache.get(entry("head", 1).key);
const actual = returned ? await describe([returned]) : [];
const expected = later === "set" ? await describe([entry("head", 2)]) : [];
const stored = await inspect(databaseName, persistent);
return {
later, policy, boundedAdapter, laterStartedWhileHeld, encryptCalls, actual, expected, stored,
correct: !laterStartedWhileHeld && JSON.stringify(actual) === JSON.stringify(expected) &&
JSON.stringify(stored.decrypted) === JSON.stringify(expected) && stored.missing === 0 &&
stored.encrypted && stored.deviceKeyPresent && encryptCalls === (later === "set" ? 2 : 1),
};
} finally {
release.resolve(); crypto.subtle.encrypt = encrypt;
await bounded(Promise.all(pending), "Crypto fixture cleanup");
await close(databaseName, persistent);
}
}
97 changes: 97 additions & 0 deletions benchmarks/ordered-persistent-cache-mutations/protocol.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
{
"schemaVersion": 1,
"experiment": "P14: ordered persistent cache mutations",
"baseline": "44e0442d3fd1e19da97175b6e8929c377410b29b",
"scope": "Persistent mutations admitted by one TieredObjectCache; no cross-instance or direct-adapter ordering, read linearizability, public option, dependency, format, policy, limit, infrastructure, CI workflow or host runtime change",
"hypothesis": "Serialise admitted same-key persistent mutations and use whole-cache cleanup barriers, while keeping unrelated keys concurrent and immediate memory updates unchanged",
"discovery": "Under both policies an older held set completed after a newer set or delete and restored v1 instead of v2 or a miss. Actual WebCrypto with fake IndexedDB also reproduced v1 overwriting v2 because encryption precedes transaction creation.",
"rules": [
"Admitted set/delete operations for one key start after earlier same-key mutations and the preceding admitted cleanup barrier settle",
"An admitted clearAll/destroy waits for earlier admitted mutations, and later admitted mutations wait for that cleanup to settle",
"Unrelated keys remain independently runnable before a cleanup barrier",
"Memory updates and pending-read invalidation remain immediate at invocation; clearMemory and changed policy do not become persistent barriers",
"Already admitted mutations still attempt their adapter calls if an earlier operation disables persistence; future admissions preserve existing memory-only fallback",
"Set/delete/clear failures retain fallback and metrics; destroy failures still reject; failed predecessors must not poison later admitted work",
"Keep no historical per-key queue entries after settlement; key-queue entries track outstanding admitted keys and barriers can retain dependency snapshots until their slowest predecessor settles",
"Do not add retries, persistence calls, copies, cancellation, timeouts, public configuration, tombstones, IndexedDB schema changes or cross-instance coordination",
"Caller-owned cache entries must remain stable until set settles, as with the existing asynchronous adapter path; no new input snapshot guarantee",
"Reads begun during unfinished persistent mutations, direct adapter use, other cache instances, inaccurate adapter completion promises and durable logout remain outside the guarantee"
],
"matrix": {
"policies": ["content", "locations"],
"shapes": ["head", "branch"],
"releaseOrders": ["oldest-ready-first", "newest-ready-first"],
"replicates": 3,
"unrelatedKeys": 4,
"scenarios": [
"late-set-newer-set",
"late-set-delete",
"late-set-clear",
"late-set-destroy",
"late-delete-set",
"late-clear-set",
"late-destroy-set",
"cascading-sets",
"multi-key-clear",
"barrier-chain",
"unrelated-overlap",
"sequential-lifecycle",
"disabled-policy",
"write-failure",
"destroy-failure",
"memory-only"
],
"conflictingScenarios": [
"late-set-newer-set", "late-set-delete", "late-set-clear",
"late-set-destroy", "late-delete-set", "late-clear-set",
"late-destroy-set", "cascading-sets", "multi-key-clear", "barrier-chain"
],
"safetyControls": [
"unrelated-overlap", "sequential-lifecycle", "disabled-policy",
"write-failure", "destroy-failure", "memory-only"
],
"trialsPerArm": 384,
"memory": { "maxEntries": 64, "maxBytes": 1048576 },
"transport": "No network or actual persistence in the comparative matrix; deterministic gated adapter snapshots and operation completion events; encrypted IndexedDB integration qualified separately",
"ordering": "Fresh cache per trial; alternate baseline/candidate order by scenario, policy, shape, release order and replicate; release the selected ready adapter operation and await its completion before the next release",
"measurement": "Record every admission, adapter start/completion/failure and settlement; expected invocation-order state; actual persistent and immediate-memory values/digests; cold post-settlement read; memory calls/copies; adapter counts; overlap; queue observations and final cleanup; source inventories and every pair gate",
"baselineExpectation": "All controls and oldest-ready-first schedules preserve declared outcomes; newest-ready-first exposes ten conflicting recipes, 120 trials per arm; baseline expected 264/384 and candidate 384/384",
"timers": "Diagnostic deadlines only; no latency, throughput, heap, GC timing, production-frequency or provider-cost inference"
},
"hardGates": [
"Every candidate trial matches invocation-ordered persistent state, immediate memory, declared cold read, errors, fallback and reuse contract",
"Baseline reproduces all 120 declared newest-ready-first conflicts; all benign/control trials remain correct",
"Every admitted mutation makes exactly one matching adapter attempt; action memory operation digests, clone work and metrics match across arms",
"Unrelated-overlap reaches five concurrently started held adapter operations in both arms; same-key work and cleanup barriers are correctly ordered in the candidate",
"Failure controls preserve admitted later work, fallback, destroy rejection and unpoisoned queue cleanup",
"Candidate queue entries and barrier clear at quiescence, do not exceed outstanding admitted work during trials, and retain no history after 1000 sequential distinct-key operations",
"Focused tests cover post-commit promise delay, empty/special/Unicode keys, cleanup chains, reuse and existing read invalidation",
"Chromium, Firefox and WebKit each pass twelve gated real encrypted-IndexedDB cases plus four late-WebCrypto cases under both policies, using selected bounded/unbounded adapters",
"Existing namespace, admission, hydration, ownership, client, connection and publication controls, types, package and canonical documentation pass; full normal CI remains required",
"Publish this protocol before production edits; commit and push source/collector before detached comparative capture; retain all captures without overwrite"
],
"mergeDecision": {
"threshold": 85,
"allHardGatesMandatory": true,
"weights": {
"mutationCorrectness": 40,
"concurrencyAndFailureCompatibility": 25,
"reproducibleEvidence": 20,
"scopeAndSimplicity": 15
},
"benefitCriterion": "Prevent older admitted persistent mutations from overwriting or removing newer state after all operations settle, without globally serialising unrelated keys",
"claimBoundary": "Per-tiered-instance admitted mutation ordering only; same-key and cleanup head-of-line blocking, pending work retention and promise scheduling are real costs; no read linearizability, cross-tab coordination, durability or measured speed benefit"
},
"limits": {
"network": false,
"maximumAdapterCalls": 50000,
"maximumRunMinutes": 5,
"operationDeadlineMilliseconds": 5000,
"overwriteEvidence": false
},
"sources": [
"https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction",
"https://github.com/Jason-Doyle/thimble/blob/44e0442d3fd1e19da97175b6e8929c377410b29b/src/browser/cache.ts",
"https://github.com/Jason-Doyle/thimble/blob/44e0442d3fd1e19da97175b6e8929c377410b29b/docs/BROWSER-CACHE.md"
]
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading