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
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

- Coalesced overlapping same-key persistent reads within a tiered cache,
excluding `/HEAD.json` and `/current.json` publication metadata. Waiters
retain independent entries, per-caller metrics and mutation fences; settled
reads are forgotten. Native controlled cases reduce IndexedDB gets and
decryptions while adding explicit ownership copies. Custom hooks share a
snapshot/failure and run per generation rather than per caller. Public
options, defaults, encrypted formats and independent metadata reads are unchanged.

- 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
Expand Down
4 changes: 4 additions & 0 deletions benchmarks/persistent-read-coalescing/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.gitattributes text eol=lf
results/*.svg text eol=lf
results/native-*.json -text -diff
preparation/*.patch -text -diff
304 changes: 304 additions & 0 deletions benchmarks/persistent-read-coalescing/README.md

Large diffs are not rendered by default.

18 changes: 18 additions & 0 deletions benchmarks/persistent-read-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/cache.ts").replaceAll("\\", "/");
const source = execFileSync("git", ["--no-pager", "show", `${baseline}:src/browser/cache.ts`], { cwd: root, encoding: "utf8" });
export default defineConfig({
root,
plugins: [{
name: "exact-baseline-persistent-reads", enforce: "pre",
load(id) { return id.replaceAll("\\", "/").split("?")[0] === filename ? source : null; },
}],
test: { include: ["tests/browser-persistent-reads.test.ts"] },
});
318 changes: 318 additions & 0 deletions benchmarks/persistent-read-coalescing/fixtures.ts

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
diff --git a/src/browser/cache.ts b/src/browser/cache.ts
index 674922e..ce543ff 100644
--- a/src/browser/cache.ts
+++ b/src/browser/cache.ts
@@ -915,7 +915,10 @@ export class TieredObjectCache {
private writes = 0;
private persistentErrors = 0;
private persistentAvailable = true;
- private readonly pendingReads = new Map<string, { readers: number }>();
+ private readonly pendingReads = new Map<string, {
+ readers: number;
+ value?: Promise<CachedJsonObject | null>;
+ }>();
private readonly pendingMutations = new Map<string, Promise<void>>();
private persistentBarrier: Promise<void> | undefined;

@@ -954,13 +957,13 @@ export class TieredObjectCache {
return null;
}

- const pending = this.pendingReads.get(key) ?? { readers: 0 };
+ const pending = this.pendingReads.get(key) ?? { readers: 0, value: undefined };
pending.readers += 1;
this.pendingReads.set(key, pending);
try {
let persisted: CachedJsonObject | null = null;
try {
- persisted = await this.persistent.get(key);
+ persisted = await (pending.value ??= this.persistent.get(key));
} catch {
this.disablePersistent();
}
@@ -973,7 +976,8 @@ export class TieredObjectCache {
} else if (persisted && this.isCacheable(persisted)) {
this.indexedDbHits += 1;
this.memory.set(persisted);
- return persisted;
+ // Earlier waiters must not expose the shared entry to remaining readers.
+ return pending.readers > 1 ? structuredClone(persisted) : persisted;
}

this.misses += 1;
82 changes: 82 additions & 0 deletions benchmarks/persistent-read-coalescing/preparation/replay.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";

const here = path.dirname(fileURLToPath(import.meta.url)), root = path.resolve(here, "..", "..", "..");
const normal = (body) => body.toString().replace(/\r\n/g, "\n");
const sha = (body) => createHash("sha256").update(body).digest("hex");
function applyPatch(source, patch) {
const before = source.split("\n"), after = [];
let cursor = 0, inHunk = false;
for (const line of patch.split("\n")) {
const hunk = /^@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@/.exec(line);
if (hunk) { after.push(...before.slice(cursor, Number(hunk[1]) - 1)); cursor = Number(hunk[1]) - 1; inHunk = true; continue; }
if (!inHunk || line === "") continue;
if (line[0] === " " || line[0] === "-") { assert.equal(before[cursor], line.slice(1)); cursor++; }
if (line[0] === " " || line[0] === "+") after.push(line.slice(1));
}
after.push(...before.slice(cursor)); return after.join("\n");
}
async function observe(api, arm, layout, policy) {
let release, entered, second, reads = 0, sets = 0, cacheGets = 0;
const held = new Promise((resolve) => { release = resolve; }), firstEntered = new Promise((resolve) => { entered = resolve; });
const secondCacheEntered = new Promise((resolve) => { second = resolve; });
const key = `content-${layout}/notes/HEAD.json`, field = layout === "trie" ? "rootHash" : "snapshotHash";
const original = { key, etag: "p21-preparation:1", value: { revision: 1, [field]: "a".repeat(64) }, cachedAt: Date.UTC(2026, 11, 4), checkedAt: Date.UTC(2026, 11, 4), immutable: false };
const newer = { key, etag: "p21-preparation:2", value: { revision: 2, [field]: "b".repeat(64) } }, backing = new Map([[key, original]]);
const persistent = {
async get(key) { const index = ++reads, value = structuredClone(backing.get(key) ?? null); if (index === 1) { entered(); await held; } return value; },
async set(entry) { sets++; backing.set(entry.key, structuredClone(entry)); },
async delete(key) { backing.delete(key); }, async clear() { backing.clear(); }, async destroy() { backing.clear(); },
};
class ObservedCache extends api.TieredObjectCache { get(key) { if (++cacheGets === 2) second(); return super.get(key); } }
const cache = new ObservedCache(new api.MemoryObjectCache(), persistent, policy);
const client = new api.ThimbleClient({ cache, headTtlMs: 60_000, channelName: `p21-preparation-${arm}-${layout}-${policy}`,
collectionLayouts: { notes: layout }, reader: { async get(key) { return { status: "missing", key }; } } });
const reading = cache.get(key);
let publication, publicationCompleted = false;
try {
await firstEntered;
publication = client.applyBundle({ collection: "notes", layout, objects: [newer] }).then(() => { publicationCompleted = true; });
await secondCacheEntered;
await new Promise((resolve) => setImmediate(resolve));
const checkpoint = { firstReadHeld: true, cacheGetCalls: cacheGets, persistentGetCalls: reads, persistentSetCalls: sets,
publicationCompleted, trackedReaders: [...cache.pendingReads.values()].reduce((sum, token) => sum + token.readers, 0) };
release(); const returned = await reading; await publication;
const retained = await cache.get(key);
return { arm, layout, policy, checkpoint, returnedRevision: returned.value.revision, finalRevision: retained.value.revision, finalTrackedKeys: cache.pendingReads.size };
} finally { release(); await Promise.allSettled([reading, publication]); client.close(); await cache.destroy(); }
}
export async function verifyPreparation() {
const retained = JSON.parse(await readFile(path.join(here, "first-prototype.json"), "utf8"));
const patch = normal(await readFile(path.join(here, "first-prototype.patch")));
assert.equal(sha(patch), retained.patchSha256); assert.equal(retained.observations.length, 8);
const require = createRequire(path.join(root, "package.json")), esbuild = require("esbuild"), observations = [];
for (const arm of ["baseline", "first-prototype"]) {
const loaded = new Map();
const built = await esbuild.build({
absWorkingDir: root, stdin: { contents: 'export * from "./src/index.ts";', resolveDir: root, sourcefile: "p21-preparation.ts", loader: "ts" },
bundle: true, platform: "browser", format: "esm", target: "es2022", write: false,
plugins: [{ name: "rebuild-rejected-prototype", setup(build) {
build.onLoad({ filter: /\.ts$/ }, ({ path: filename }) => {
const relative = path.relative(root, filename).replaceAll("\\", "/"); assert.ok(relative.startsWith("src/"));
let contents = normal(execFileSync("git", ["--no-pager", "show", `${retained.baseline}:${relative}`], { cwd: root }));
if (arm === "first-prototype" && relative === "src/browser/cache.ts") contents = applyPatch(contents, patch);
loaded.set(relative, sha(contents)); return { contents, loader: "ts" };
});
} }],
});
const code = built.outputFiles[0].text, executable = retained.executables[arm];
assert.equal(code, executable.code); assert.equal(sha(code), executable.sha256);
assert.deepEqual([...loaded].sort(([a], [b]) => a.localeCompare(b)).map(([path, sha256]) => ({ path, sha256 })), executable.loaded);
const api = await import(`data:text/javascript;base64,${Buffer.from(code).toString("base64")}`);
for (const layout of ["trie", "snapshot"]) for (const policy of ["content", "locations"]) observations.push(await observe(api, arm, layout, policy));
}
assert.deepEqual(observations, retained.observations);
return { verified: true, observations: 8, exactRebuilds: 2, modulesPerArm: 19, patchSha256: sha(patch) };
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) console.log(JSON.stringify(await verifyPreparation()));
Loading