cultcache-ts update: the legacy-global refusal is one rule at read and write, a store attached mid-apply loses the race, put installs the stamp the store wrote
Some checks failed
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled

Fixes variants:finding:cut-update-with-retry-ts.s1.*: global-key-skips-legacy-refusal,
attach-midflight-blind-push, put-held-storedat-diverges, null-decline-unpinned,
maxattempts-bound-kills-by-hang, storeless-othertype-guard-unpinned, and the
9999-12-31 stamp edge (RangeError, nothing written).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Libby 2026-11-13 16:32:11 +00:00
commit 505b868d90
7 changed files with 145 additions and 19 deletions

View file

@ -12,13 +12,13 @@ All notable changes to `@gamecult/cultcache-ts` are recorded here, following
### Changed
- A write that replaces a record at its key is stored strictly later than it: a supplied `storedAt` not later than the stored one is written one millisecond after it, so a content version that includes `storedAt` never repeats across writes. `push`, `pushAll` and `commitIf` alike; `push` does not report the stamp it was given.
- A write that replaces a record at its key is stored strictly later than it: a supplied `storedAt` not later than the stored one is written one millisecond after it, so a content version that includes `storedAt` never repeats across writes. `push`, `pushAll` and `commitIf` alike; the single-file store's `push` returns the stamp it wrote (`CacheBackingStore.push` may resolve `{ storedAt }`), and `put`, `putGlobal` and `putEnvelope` install that stamp in the cache, so the cache and the file agree after a put over a record stamped at or after now. A stamp that would pass 9999-12-31T23:59:59.999Z is refused with `RangeError` and nothing is written.
- `withStoreWriteLock` looks for a link at the store path again once the lock is held, so a link put at the path while a writer waited on the lock is refused with `StoreLinkedError` and the lock released, instead of being replaced. Pinned by a test that puts the link while another holder owns the lock.
- `CultCache.isWritable` does not look at store paths: a link at a store path is not predicted, and the write refuses it with `StoreLinkedError`. Pinned by a test through a cache attached to a linked store.
### Breaking
- `update` and `updateGlobal` are the conditional golden path and no longer the blind pair. `update(definition, key, apply, options?)` reads the record and its content version from the store, passes `apply` a fresh copy (never the held instance), commits only if the version still holds and runs `apply` again on a lost race, up to `maxAttempts`. `apply` may be async, may return `undefined` to write nothing, and must be free of side effects. It resolves to `{ outcome: "updated" | "declined" | "lostRace", document }` instead of the written value, so a caller reads `result.document`; a lost race that outlasts the attempts is `lostRace`, not a throw. It needs a store with `read` and `commitIf` (the single-file store has them); a cache with no store compares the held entry. `put` and `putGlobal` are the blind writes and are unchanged.
- `update` and `updateGlobal` are the conditional golden path and no longer the blind pair. `update(definition, key, apply, options?)` reads the record and its content version from the store, passes `apply` a fresh copy (never the held instance), commits only if the version still holds and runs `apply` again on a lost race, up to `maxAttempts`. `apply` may be async, may return `undefined` to write nothing, and must be free of side effects. It resolves to `{ outcome: "updated" | "declined" | "lostRace", document }` instead of the written value, so a caller reads `result.document`; a lost race that outlasts the attempts is `lostRace`, not a throw. `apply` returning `undefined` or `null` declines. `maxAttempts` is an integer of at least 1; `undefined` is the default 5 and `null` is refused with `RangeError`. A conditional write over a global loaded from a legacy key is refused wherever it enters (`updateGlobal`, or `update` at `CultCache.GLOBAL_KEY`) and leaves the legacy record untouched; `apply` may have run once before the write is refused. A store attached to a store-less cache while `apply` awaits makes that attempt a lost race. It needs a store with `read` and `commitIf` (the single-file store has them); a cache with no store compares the held entry. `put` and `putGlobal` are the blind writes and are unchanged.
- A write at a single-file store path that is a symbolic link, live or dangling, is refused with the new `StoreLinkedError` (exported from the package entry; `error.path` names the path) before the lock and the replace, and writes nothing: `push`, `pushAll`, `delete` and a soft flush alike. Before, a write at a live link replaced the link with a regular file, a dangling link failed with `ENOENT` (or, for `pushAll`, was replaced), and a soft flush at a link skipped. A caller catching `ENOENT` around a write at a dangling link now catches `StoreLinkedError`; configure the link's target as the store path. Reads through a live link work. An `lstat` failure other than `ENOENT` (`ENOTDIR`, `EACCES`, `ELOOP`) is rethrown as it is.
- `SingleFileMessagePackBackingStore.pushAll` writes the given entries onto the store as it is under the lock, as `push` does: a record under the same key is replaced and no other is removed. It used to replace the whole file with the entries, so `CultMesh.flush()` from a cache that held less than the store (a node created with `pullOnStart: false`, or one whose image was stale) wiped the records it never read. A caller that relied on `pushAll` to reset a store removes the file first. A soft flush is unchanged. `CultCache.storedSnapshot()` is the image as the stores hold it (a global loaded from a legacy key under that key) and is what `CultMesh.flush` persists, so a flush no longer leaves such a global under two keys; `snapshot()` is unchanged.
- A single-file store marked `cultcache.store.v3` (it holds an element id, written by the C# runtime) is read, and a rewrite keeps the mark and the ids; this runtime does not decide when a document carries ids. A runtime from before this change refuses a v3 store by name, so rolling back to an older release after a store has been written as v3 is one-way: there is no carry-back, so restore from a copy taken before upgrading.

View file

@ -598,7 +598,8 @@ export class CultCache {
if (typeof apply !== "function") {
throw new TypeError("CultCache update needs a function to apply.");
}
const maxAttempts = options.maxAttempts ?? 5;
// undefined is the default; anything else must be an integer of at least 1, so null is refused.
const maxAttempts = options.maxAttempts === undefined ? 5 : options.maxAttempts;
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
throw new RangeError(`CultCache update maxAttempts must be an integer of at least 1, not ${String(maxAttempts)}.`);
}
@ -633,11 +634,6 @@ export class CultCache {
options: CultCacheUpdateOptions = {},
): Promise<CultCacheUpdateResult<CultCacheDocumentValue<TDefinition>>> {
this.#requireGlobal(definition);
if (this.#hydrated.legacyGlobals.has(definition.type)) {
throw new Error(
`CultCache global "${definition.type}" was loaded from a legacy key; write it once with putGlobal to retire its legacy key.`,
);
}
return this.update(definition, CultCache.GLOBAL_KEY, apply, options);
}
@ -788,6 +784,7 @@ export class CultCache {
const registered = this.#requireDefinition(definition);
this.#requireGlobalKey(registered, key);
const type = definition.type;
this.#refuseLegacyConditional(type);
const home = this.#homeStore(type);
if (home === undefined) {
const held = this.#hydrated.entries.get(this.#entryId(type, key));
@ -858,8 +855,15 @@ export class CultCache {
const hydrated = this.#admitEntry(this.#hydrated, registered, entry, value, unreadSlots);
this.#refuseIndexSharing(this.#hydrated, entry.type, registered.catalogEntry.schemaName, entry.key, hydrated.lookups);
const legacy = this.#hydrated.legacyGlobals.get(entry.type);
// A conditional write over a legacy global is refused here too (a pull while apply awaited can have loaded one): the condition
// was read from the global's own key, the record sits under its legacy key, and the retire below would delete it unseen.
if (expected !== undefined) {
this.#refuseLegacyConditional(entry.type);
}
if (expected !== undefined && "held" in expected) {
if (this.#hydrated.entries.get(this.#entryId(entry.type, entry.key)) !== expected.held) {
// The condition was fixed at read for a cache with no store. A store attached since has its own record at the key that
// this read never saw, so the held identity no longer judges the write: lose the race and read again.
if (home !== undefined || this.#hydrated.entries.get(this.#entryId(entry.type, entry.key)) !== expected.held) {
return "mismatch";
}
}
@ -873,7 +877,11 @@ export class CultCache {
}
hydrated.storedAt = committed.storedAt;
} else {
await home?.push(entry);
// A store that re-stamps a write (storedAt later than the record it replaces) reports the stamp; the cache holds that one.
const pushed = await home?.push(entry);
if (pushed) {
hydrated.storedAt = pushed.storedAt;
}
}
if (home && legacy) {
await this.#retireLegacyGlobal(home, legacy, entry);
@ -887,6 +895,16 @@ export class CultCache {
return "committed";
}
// The one rule that a conditional write (update, whichever entry reaches it) never touches a global loaded from a legacy key:
// only putGlobal retires that key. Asked before apply runs and again at the write.
#refuseLegacyConditional(type: string): void {
if (this.#hydrated.legacyGlobals.has(type)) {
throw new Error(
`CultCache global "${type}" was loaded from a legacy key; write it once with putGlobal to retire its legacy key.`,
);
}
}
// An envelope of the definition's type at the key, carrying nothing: what the judge asks about a write or a removal by that type.
#probe(registered: RegisteredDefinition, key: string): CultCacheEnvelope {
return {

View file

@ -56,13 +56,14 @@ export class SingleFileMessagePackBackingStore implements CacheBackingStore {
return disk.envelopes;
}
async push(entry: CultCacheEnvelope): Promise<void> {
await this.#enqueue(async () => {
async push(entry: CultCacheEnvelope): Promise<{ storedAt: string }> {
return this.#enqueue(async () => {
const disk = this.#readDisk();
this.#format = disk.format;
const existing = disk.envelopes;
requireOneTypePerKey(this.filePath, [entry], existing);
await this.#writeAll([entry], existing);
const [written] = await this.#writeAll([entry], existing);
return { storedAt: written!.storedAt };
});
}
@ -188,7 +189,14 @@ function laterStoredAt(storedAt: string, prior: string): string {
return storedAt;
}
const storedMs = Date.parse(storedAt);
return Number.isNaN(storedMs) || storedMs <= priorMs ? new Date(priorMs + 1).toISOString() : storedAt;
if (!(Number.isNaN(storedMs) || storedMs <= priorMs)) {
return storedAt;
}
// The stamp is ISO-8601 with a four-digit year; one past 9999-12-31T23:59:59.999Z would print as an extended year.
if (priorMs + 1 > Date.UTC(9999, 11, 31, 23, 59, 59, 999)) {
throw new RangeError(`CultCache cannot stamp a write later than the record it replaces (${prior}): the stamp would leave the four-digit years.`);
}
return new Date(priorMs + 1).toISOString();
}
// A store holds a key once, and the reader refuses a file that holds it twice, so a write that would put a second type under a

View file

@ -125,7 +125,8 @@ export interface PushAllOptions {
export interface CacheBackingStore {
pullAll(): Promise<CultCacheEnvelope[]>;
push(entry: CultCacheEnvelope): Promise<void>;
/** A store that re-stamps the write returns the storedAt it wrote; the cache then holds that stamp, not its own. */
push(entry: CultCacheEnvelope): Promise<void | { storedAt: string }>;
delete(entry: CultCacheEnvelope): Promise<void>;
pushAll?(entries: CultCacheEnvelope[], options?: PushAllOptions): Promise<void>;
/**

View file

@ -129,6 +129,20 @@ test("a write that replaces a record is stored strictly later than it, whatever
}
});
test("a replacing write that would stamp past year 9999 is refused and writes nothing", async () => {
const directory = await scratch();
try {
const store = new SingleFileMessagePackBackingStore(join(directory, "store.cc"));
const last = "9999-12-31T23:59:59.999Z";
await store.push(entry("k", 1, last));
await assert.rejects(() => store.push(entry("k", 2, last)), RangeError);
assert.equal((await store.read("k"))!.envelope.storedAt, last);
assert.deepEqual([...documentPayloadBytes((await store.read("k"))!.envelope.payload)], [0x91, 1]);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test("a write that restores an earlier value does not restore its version", async () => {
const directory = await scratch();
try {

View file

@ -424,7 +424,7 @@ test("a link put while a writer waits on the store lock is refused once it holds
await new SingleFileMessagePackBackingStore(target).push(noteEnvelope("a"));
const before = await readFile(target);
const writes: Array<[string, (store: SingleFileMessagePackBackingStore) => Promise<void>]> = [
["push", (store) => store.push(noteEnvelope("b"))],
["push", async (store) => void (await store.push(noteEnvelope("b")))],
["pushAll", (store) => store.pushAll([noteEnvelope("b")])],
["delete", (store) => store.delete(noteEnvelope("a"))],
];

View file

@ -141,7 +141,7 @@ test("five attempts by default", async () => {
});
});
test("maxAttempts 1 makes one call; invalid values and a non-function reject before any call", async () => {
test("maxAttempts 1 makes one call", async () => {
await withDirectory(async (path) => {
const [cache, rival] = [await open(path), await open(path)];
await cache.put(counterDocument, KEY, { value: 1 });
@ -153,14 +153,76 @@ test("maxAttempts 1 makes one call; invalid values and a non-function reject bef
};
assert.equal((await cache.update(counterDocument, KEY, apply, { maxAttempts: 1 })).outcome, "lostRace");
assert.equal(calls, 1);
for (const maxAttempts of [0, -1, 1.5, Number.NaN]) {
await assert.rejects(() => cache.update(counterDocument, KEY, apply, { maxAttempts }), RangeError);
});
});
// An apply that declines resolves at once whatever the bound, so a validation that lets a bad value through fails the assertion
// below instead of looping: no apply here ever loses a race.
test("invalid maxAttempts (undefined is the default, null is refused) and a non-function reject before any call", async () => {
await withDirectory(async (path) => {
const cache = await open(path);
let calls = 0;
const apply = () => (calls++, undefined);
for (const maxAttempts of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, null as never]) {
await assert.rejects(() => cache.update(counterDocument, KEY, apply, { maxAttempts }), RangeError, `maxAttempts ${String(maxAttempts)}`);
}
await assert.rejects(() => cache.update(counterDocument, KEY, "no" as never), TypeError);
assert.equal(calls, 0);
assert.equal((await cache.update(counterDocument, KEY, apply, { maxAttempts: undefined })).outcome, "declined");
assert.equal(calls, 1);
});
});
test("null from apply declines as undefined does: nothing is written", async () => {
await withDirectory(async (path) => {
const cache = await open(path);
await cache.put(counterDocument, KEY, { value: 1 });
const before = await readFile(path);
const result = await cache.update(counterDocument, KEY, () => null as never);
assert.deepEqual(result, { outcome: "declined", document: cache.get(counterDocument, KEY) });
assert.deepEqual([...(await readFile(path))], [...before]);
});
});
test("a cache with no store refuses a key held as another type before apply runs", async () => {
const cache = CultCache.builder().withRegistry(registry).build();
await cache.put(tallyDocument, KEY, { count: 1 });
let calls = 0;
await assert.rejects(() => cache.update(counterDocument, KEY, () => (calls++, { value: 1 })), /is not a "update.counter"/);
assert.equal(calls, 0);
});
test("a store attached while apply awaits turns the commit into a lost race, never a blind push", async () => {
await withDirectory(async (path) => {
const writer = await open(path);
await writer.put(counterDocument, KEY, { value: 50 });
const cache = CultCache.builder().withRegistry(registry).build();
const seen: Array<number | undefined> = [];
const result = await cache.update(counterDocument, KEY, async (current) => {
seen.push(current?.value);
if (seen.length === 1) cache.addBackingStore(new SingleFileMessagePackBackingStore(path));
return { value: (current?.value ?? 0) + 1 };
});
assert.deepEqual(seen, [undefined, 50], "the second attempt reads the store's record");
assert.equal(result.outcome, "updated");
assert.equal(stored(path), 51);
});
});
test("put installs the storedAt the store stamped, so the cache and the file agree", async () => {
await withDirectory(async (path) => {
const cache = await open(path);
await cache.put(counterDocument, KEY, { value: 1 });
const store = new SingleFileMessagePackBackingStore(path);
const [envelope] = readSingleFileStore(path).envelopes;
await store.push({ ...envelope!, storedAt: "2099-01-01T00:00:00.000Z" });
await cache.put(counterDocument, KEY, { value: 2 });
const onDisk = readSingleFileStore(path).envelopes[0]!.storedAt;
assert.equal(onDisk, "2099-01-01T00:00:00.001Z");
assert.equal(cache.getEnvelope(counterDocument, KEY)!.storedAt, onDisk);
});
});
test("apply gets a fresh copy: changing it changes nothing held, and a lost attempt's change is not seen by the next", async () => {
await withDirectory(async (path) => {
const [cache, rival] = [await open(path), await open(path)];
@ -415,6 +477,11 @@ test("updateGlobal updates the global record and refuses one loaded from a legac
let calls = 0;
await assert.rejects(() => loaded.updateGlobal(settingsDocument, (current) => (calls++, current)), /putGlobal to retire its legacy key/);
assert.equal(calls, 0);
// Every path to the write is refused, the global's own key included, and the legacy record survives.
const before = await readFile(path);
await assert.rejects(() => loaded.update(settingsDocument, CultCache.GLOBAL_KEY, () => ({ theme: "lost" })), /putGlobal to retire its legacy key/);
assert.deepEqual([...(await readFile(path))], [...before]);
assert.deepEqual(readSingleFileStore(path).envelopes.map((e) => e.key), ["old-settings"]);
await loaded.putGlobal(settingsDocument, { theme: "y" });
assert.equal((await loaded.updateGlobal(settingsDocument, (current) => ({ theme: `${current!.theme}z` }))).outcome, "updated");
assert.deepEqual(loaded.getGlobal(settingsDocument), { theme: "yz" });
@ -422,6 +489,24 @@ test("updateGlobal updates the global record and refuses one loaded from a legac
});
});
test("a legacy global that a pull loads while apply awaits is refused at the write, and its legacy record survives", async () => {
await withDirectory(async (path) => {
const settings = defineDocumentRegistry(settingsDocument);
const cache = await open(path, settings);
const legacy = await open(path, defineDocumentRegistry(plainSettingsDocument));
await assert.rejects(
() =>
cache.update(settingsDocument, CultCache.GLOBAL_KEY, async () => {
await legacy.put(plainSettingsDocument, "old-settings", { theme: "x" });
await cache.pullAllBackingStores();
return { theme: "lost" };
}),
/putGlobal to retire its legacy key/,
);
assert.deepEqual(readSingleFileStore(path).envelopes.map((e) => e.key), ["old-settings"]);
});
});
test("the ledger holds under contention: the stored value is the number of updated outcomes", async () => {
await withDirectory(async (path) => {
const caches = await Promise.all([open(path), open(path), open(path)]);