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

- 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
preserving other scopes. Unrecognised custom subclasses and module copies
retain delegated tracked-key cleanup and its potentially unbounded history.
Public options, limits, persistent operations and stored formats are unchanged.

- 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
Expand Down
289 changes: 289 additions & 0 deletions benchmarks/memory-namespace-bookkeeping/README.md

Large diffs are not rendered by default.

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 { 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-namespace-cache", enforce: "pre",
load(id) { return id.replaceAll("\\", "/").split("?")[0] === target ? source : null; },
}],
test: { include: ["tests/browser-memory-namespace.test.ts"] },
});
273 changes: 273 additions & 0 deletions benchmarks/memory-namespace-bookkeeping/fixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,273 @@
import type { CachedJsonObject } from "../../src/browser/cache.js";

export type CacheModule = Pick<typeof import("../../src/browser/cache.js"),
"MemoryObjectCache" | "NamespacedMemoryObjectCache" | "TieredObjectCache">;
type Memory = InstanceType<CacheModule["MemoryObjectCache"]>;
type Namespace = InstanceType<CacheModule["NamespacedMemoryObjectCache"]>;
export const scenarios = [
"miss-history", "churn-history", "oversized-history", "other-scope-eviction",
"root-clear-history", "nested-misses", "nested-churn", "same-namespace-peer",
"recreated-wrapper", "ordinary-hot", "ordinary-lru", "scope-isolation",
"prefix-collision", "explicit-delete", "custom-delegate", "custom-delete-failure",
] as const;
export type Scenario = typeof scenarios[number];
export type Encoding = "ascii" | "delimiter-unicode";
export type Policy = "content" | "locations";
export type Lifecycle = "clearMemory" | "setPolicy" | "clearAll" | "destroy";
export const historyScenarios = new Set<string>(scenarios.slice(0, 7));
export const semanticScenarios = new Set<string>(["same-namespace-peer", "recreated-wrapper"]);
export const customScenarios = new Set<string>(["custom-delegate", "custom-delete-failure"]);
const copy = globalThis.structuredClone.bind(globalThis);
const encoder = new TextEncoder();
const equal = (first: unknown, second: unknown) => JSON.stringify(first) === JSON.stringify(second);
export const prefix = (namespace: string) => `${namespace.length}:${namespace}:`;

export function entry(key: string, payload = "kept"): CachedJsonObject {
return {
key, etag: "v1", value: { kind: "branch", revision: 1, payload },
cachedAt: 1, checkedAt: 1, immutable: true,
};
}
function bytes(value: CachedJsonObject) {
return encoder.encode(JSON.stringify(value.value)).byteLength + value.key.length + value.etag.length + 48;
}
export async function digest(value: unknown): Promise<string> {
const hash = await crypto.subtle.digest("SHA-256", encoder.encode(JSON.stringify(value)));
return [...new Uint8Array(hash)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
}
async function describe(values: CachedJsonObject[]) {
return Promise.all(values.map(async (value) => ({
key: value.key, etag: value.etag, bytes: bytes(value), valueSha256: await digest(value.value),
})));
}
function internalEntries(memory: Memory) {
return (memory as unknown as {
entries: Map<string, { entry: CachedJsonObject; bytes: number }>;
}).entries;
}
export function tracked(cache: Namespace): number {
return (cache as unknown as { keys?: Set<string> }).keys?.size ?? 0;
}

export async function runTrial(
classes: CacheModule, scenario: Scenario, maxEntries = 4,
history = 128, encoding: Encoding = "ascii",
) {
const custom = customScenarios.has(scenario);
const maxBytes = maxEntries * 256;
class CustomMemory extends classes.MemoryObjectCache {
readonly backend = new Map<string, CachedJsonObject>();
failKey: string | undefined;
override get(key: string) {
const value = this.backend.get(key);
return value ? copy(value) : null;
}
override set(value: CachedJsonObject) { this.backend.set(value.key, copy(value)); }
override delete(key: string) {
if (key === this.failKey) { this.failKey = undefined; throw new Error("Injected delete failure"); }
this.backend.delete(key);
}
override clear() { this.backend.clear(); }
override stats() {
return { entries: this.backend.size, bytes: [...this.backend.values()].reduce((sum, value) => sum + bytes(value), 0), evictions: 0 };
}
}
const root = custom ? new CustomMemory() : new classes.MemoryObjectCache(maxEntries, maxBytes);
const resident = () => copy(root instanceof CustomMemory
? [...root.backend.values()] : [...internalEntries(root).values()].map((value) => value.entry));
let phase: "work" | "clear" = "work";
const measurements = () => ({
get: 0, set: 0, delete: 0, clear: 0, cloneCalls: 0, cloneInputBytes: 0,
rootKeyVisits: 0, historicalKeyVisits: 0,
trace: [] as Array<Array<string | number>>,
});
const work = measurements(), clearing = measurements();
const current = () => phase === "work" ? work : clearing;
const originalGet = root.get.bind(root), originalSet = root.set.bind(root);
const originalDelete = root.delete.bind(root), originalClear = root.clear.bind(root);
root.get = (key) => { const m = current(); m.get += 1; m.trace.push(["get", key]); return originalGet(key); };
root.set = (value) => {
const m = current(); m.set += 1; m.trace.push(["set", value.key, value.etag, bytes(value)]);
originalSet(value);
};
root.delete = (key) => { const m = current(); m.delete += 1; m.trace.push(["delete", key]); originalDelete(key); };
root.clear = () => { const m = current(); m.clear += 1; m.trace.push(["clear"]); originalClear(); };
const rootMap = internalEntries(root);
const originalKeys = rootMap.keys.bind(rootMap);
rootMap.keys = () => {
const iterator = originalKeys(), next = iterator.next.bind(iterator);
iterator.next = () => {
const result = next();
if (!result.done && phase === "clear") clearing.rootKeyVisits += 1;
return result;
};
return iterator;
};
const wrappers: Array<{ role: string; cache: Namespace }> = [];
function wrap(role: string, namespace: string, delegate: Memory) {
const cache = new classes.NamespacedMemoryObjectCache(namespace, delegate);
wrappers.push({ role, cache });
const keys = (cache as unknown as { keys?: Set<string> }).keys;
if (keys) {
const iterate = keys[Symbol.iterator].bind(keys);
keys[Symbol.iterator] = () => {
const iterator = iterate(), next = iterator.next.bind(iterator);
iterator.next = () => {
const result = next();
if (!result.done && phase === "clear") clearing.historicalKeyVisits += 1;
return result;
};
return iterator;
};
}
return cache;
}
const namespace = encoding === "ascii" ? "scope" : "tenant:one:\ud83d\udca1";
const otherNamespace = `${namespace}:other`;
const nested = scenario === "nested-misses" || scenario === "nested-churn";
const outerNamespace = encoding === "ascii" ? "outer" : "outer:\u00e9";
const outer = nested ? wrap("outer", outerNamespace, root) : null;
const fullPrefix = (nested ? prefix(outerNamespace) : "") + prefix(namespace);
let primary: Namespace;
const other = wrap("other", otherNamespace, root);
const returned: Array<CachedJsonObject | null> = [], expectedReturned: Array<CachedJsonObject | null> = [];
const remember = (cache: Namespace, value: CachedJsonObject) => {
const result = cache.get(value.key);
returned.push(copy(result)); expectedReturned.push(value);
return result;
};
const historyCounts = () => wrappers.map(({ role, cache }) => ({ role, keys: tracked(cache) }));
const previousClone = globalThis.structuredClone;
globalThis.structuredClone = ((value: unknown, options?: StructuredSerializeOptions) => {
const result = copy(value, options);
const m = current(); m.cloneCalls += 1;
m.cloneInputBytes += encoder.encode(JSON.stringify(value)).byteLength;
return result;
}) as typeof structuredClone;
try {
if (scenario === "recreated-wrapper") {
const writer = wrap("writer", namespace, root);
for (let index = 0; index < maxEntries; index += 1) writer.set(entry(`object-${index}/HEAD.json`));
primary = wrap("primary", namespace, root);
} else primary = wrap("primary", namespace, outer ?? root);
if (scenario === "same-namespace-peer") {
const peer = wrap("peer", namespace, root);
for (let index = 0; index < maxEntries; index += 1) peer.set(entry(`object-${index}/HEAD.json`));
} else if (scenario === "miss-history" || scenario === "nested-misses" || custom) {
for (let index = 0; index < history; index += 1) {
returned.push(primary.get(`missing-${index}`)); expectedReturned.push(null);
}
if (custom) {
for (let index = 0; index < maxEntries; index += 1) primary.set(entry(`object-${index}/HEAD.json`));
}
} else if (scenario === "oversized-history") {
const payload = "x".repeat(maxBytes);
for (let index = 0; index < history; index += 1) primary.set(entry(`large-${index}/HEAD.json`, payload));
} else if (scenario === "churn-history" || scenario === "nested-churn" ||
scenario === "other-scope-eviction" || scenario === "root-clear-history") {
for (let index = 0; index < history; index += 1) primary.set(entry(`object-${index}/HEAD.json`));
if (scenario === "other-scope-eviction") {
for (let index = 0; index < maxEntries; index += 1) other.set(entry(`other-${index}/HEAD.json`));
} else if (scenario === "root-clear-history") root.clear();
} else if (scenario === "ordinary-hot" || scenario === "ordinary-lru") {
for (let index = 0; index < maxEntries; index += 1) primary.set(entry(`object-${index}/HEAD.json`));
if (scenario === "ordinary-hot") {
for (let index = 0; index < history; index += 1) {
const value = remember(primary, entry(`object-${index % maxEntries}/HEAD.json`));
if (index === 0 && value) (value.value as { payload: string }).payload = "caller-mutated";
}
} else {
remember(primary, entry("object-0/HEAD.json"));
primary.set(entry("new/HEAD.json"));
}
} else if (scenario === "scope-isolation" || scenario === "prefix-collision" || scenario === "explicit-delete") {
const key = scenario === "prefix-collision" ? `${prefix(otherNamespace)}object/HEAD.json` : "object/HEAD.json";
const first = entry(key, "first"), second = entry("object/HEAD.json", "second");
primary.set(first); other.set(second);
if (scenario === "prefix-collision") root.set(entry("raw/HEAD.json", "raw"));
if (scenario === "explicit-delete") primary.delete(key);
else { remember(primary, first); remember(other, second); }
}
const before = resident(), beforeStats = root.stats(), trackedBefore = historyCounts();
const noClear = scenario === "ordinary-hot" || scenario === "ordinary-lru";
const expected = noClear ? copy(before) : before.filter((value) => !value.key.startsWith(fullPrefix));
let failure: { message: string; retained: CachedJsonObject[]; tracked: ReturnType<typeof historyCounts> } | null = null;
let failureCorrect = scenario !== "custom-delete-failure";
phase = "clear";
if (!noClear) {
if (scenario === "custom-delete-failure" && root instanceof CustomMemory) {
root.failKey = `${fullPrefix}object-1/HEAD.json`;
try { primary.clear(); } catch (error) {
failure = { message: String(error), retained: resident(), tracked: historyCounts() };
}
failureCorrect = failure?.message === "Error: Injected delete failure" &&
equal(failure.tracked, trackedBefore) &&
equal(failure.retained, before.filter((value) => value.key !== `${fullPrefix}object-0/HEAD.json`));
}
primary.clear();
}
const retained = resident(), stats = root.stats(), trackedAfter = historyCounts();
const trackedKeysBefore = trackedBefore.reduce((sum, value) => sum + value.keys, 0);
const trackedKeysAfter = trackedAfter.reduce((sum, value) => sum + value.keys, 0);
const zeroHistory = trackedKeysBefore === 0 && trackedKeysAfter === 0;
const dataCorrect = equal(retained, expected) && equal(returned, expectedReturned) && failureCorrect;
const qualified = dataCorrect && (!historyScenarios.has(scenario) || zeroHistory);
const matching = before.filter((value) => value.key.startsWith(fullPrefix)).length;
const boundedClear = custom || noClear || (
clearing.rootKeyVisits <= before.length && clearing.historicalKeyVisits === 0 &&
clearing.delete === matching && clearing.get === 0 && clearing.set === 0 && clearing.cloneCalls === 0
);
const describeMeasurement = async (m: ReturnType<typeof measurements>) => {
const { trace, ...counts } = m;
return { ...counts, traceSha256: await digest(trace) };
};
return {
scenario, maxEntries, maxBytes, history, encoding, custom, qualified, dataCorrect,
zeroHistory, boundedClear, fullPrefix,
trackedBefore, trackedAfter, trackedKeysBefore, trackedKeysAfter,
before: await describe(before), beforeStats,
retained: await describe(retained), expected: await describe(expected), stats,
returnCount: returned.length, returnedSha256: await digest(returned),
expectedReturnedSha256: await digest(expectedReturned),
failure: failure ? {
message: failure.message, retained: await describe(failure.retained), tracked: failure.tracked,
} : null,
work: await describeMeasurement(work), clearing: await describeMeasurement(clearing),
};
} finally { globalThis.structuredClone = previousClone; }
}

export async function runLifecycle(classes: CacheModule, policy: Policy, operation: Lifecycle) {
const root = new classes.MemoryObjectCache(8, 4096);
const primary = new classes.NamespacedMemoryObjectCache("first", root);
const other = new classes.NamespacedMemoryObjectCache("second", root);
const calls = { get: 0, set: 0, clear: 0, destroy: 0, delete: 0 };
const cache = new classes.TieredObjectCache(primary, {
get: async () => { calls.get += 1; return null; },
set: async () => { calls.set += 1; },
delete: async () => { calls.delete += 1; },
clear: async () => { calls.clear += 1; },
destroy: async () => { calls.destroy += 1; },
}, policy);
await cache.set(entry("object/HEAD.json", "first"));
other.set(entry("object/HEAD.json", "second"));
for (let index = 0; index < 128; index += 1) primary.get(`missing-${index}`);
if (operation === "setPolicy") cache.setPolicy("none");
else await cache[operation]();
const after = primary.get("object/HEAD.json");
const otherValue = other.get("object/HEAD.json");
await cache.setPolicy(policy);
await cache.set(entry("replacement/HEAD.json"));
const reused = await cache.get("replacement/HEAD.json");
return { after, other: otherValue, reused, calls, metrics: cache.metrics(), tracked: tracked(primary) };
}

export function connectionConfig(scopeId: string, policy: Policy, layout: "trie" | "snapshot") {
return {
name: "Namespace fixture", provider: "local", readBaseUrl: "/api/objects",
headTtlMs: 60_000, cachePolicy: policy, collectionLayouts: { notes: layout },
layoutGeneration: "generation-1", csrfToken: "fixture-token",
user: { id: "fixture-user", provider: "dev", roles: [], tenants: [], identities: [] },
scope: { id: scopeId, encrypted: false, keyId: null, keyEndpoint: null },
};
}
Loading