Keep cultcache-ts record homes stable and refuse strays at load

Conform cultcache-ts to the store-composition contract, following C#:

- addBackingStore refuses, attaching nothing, when the new store would
  move the home of any record type the cache already holds (for example a
  store routed to "settings" attached after settings:app landed in the
  generic store).
- pullAllBackingStores reads, decodes and home-checks every record before
  replacing the cache's view. A record delivered by a store that is not
  its home throws naming the key and both stores; nothing is admitted and
  no store is written.
- A cache with zero stores is in memory: put, putEnvelope and delete no
  longer throw. Once any store is attached, a type with no home still
  throws.

Tests for each rule fail on 6bb41f3.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-14 00:50:07 +02:00
commit 6b117def62
2 changed files with 122 additions and 26 deletions

View file

@ -185,15 +185,30 @@ export class CultCache {
throw new Error(`CultCache type "${type}" is already routed to another backing store; it cannot also route to this one.`);
}
}
this.#stores.push({ store, types: claimed });
const candidate: CultCacheStoreRegistration = { store, types: claimed };
for (const type of this.#typeEntryIds.keys()) {
const before = this.#resolveRegistration(type);
this.#stores.push(candidate);
const after = this.#resolveRegistration(type);
this.#stores.pop();
if (before !== after) {
throw new Error(
`Attaching this backing store would move "${type}" from ${this.#describe(before)} to ${this.#describe(after)}; ` +
"attach routed stores before the generic store.",
);
}
}
this.#stores.push(candidate);
}
addGenericBackingStore(store: CacheBackingStore): void {
this.addBackingStore(store);
}
// Every store is read and every record resolved, decoded and checked against its home before
// the cache's view is replaced, so a refused load admits nothing.
async pullAllBackingStores(): Promise<void> {
this.#resetHydratedState();
const loaded: Array<{ registered: RegisteredDefinition; entry: CultCacheEnvelope; value: unknown }> = [];
for (const registration of this.#stores) {
const entries = await registration.store.pullAll();
@ -208,15 +223,25 @@ export class CultCache {
);
}
const type = registered.definition.type;
const home = this.#resolveRegistration(type);
if (home?.store !== registration.store) {
throw new Error(
`CultCache "${type}" record "${entry.key}" was loaded from ${this.#describe(registration)}, ` +
`but its home is ${this.#describe(home)}.`,
);
}
const payload = this.#cloneBytes(entry.payload);
const value = registered.formatter.decode(payload);
this.#applyHydratedEntry(registered, {
...entry,
type: registered.definition.type,
payload,
}, value, "pull");
loaded.push({ registered, entry: { ...entry, type, payload }, value });
}
}
this.#resetHydratedState();
for (const { registered, entry, value } of loaded) {
this.#applyHydratedEntry(registered, entry, value, "pull");
}
}
get<TDefinition extends AnyCultCacheDocumentDefinition>(
@ -387,10 +412,7 @@ export class CultCache {
catalogEntry: registered.catalogEntry,
};
const home = this.#resolveRoute(definition.type);
if (!home) {
throw new Error(`No backing store is registered for document type "${definition.type}".`);
}
const home = this.#homeStore(definition.type);
if (registered.global) {
const existingGlobalKey = this.#globalKeys.get(definition.type);
@ -399,7 +421,7 @@ export class CultCache {
}
}
await home.push(entry);
await home?.push(entry);
this.#applyHydratedEntry(registered, entry, parsed, "put");
return parsed;
}
@ -432,10 +454,7 @@ export class CultCache {
catalogEntry: envelope.catalogEntry ?? registered.catalogEntry,
};
const home = this.#resolveRoute(definition.type);
if (!home) {
throw new Error(`No backing store is registered for document type "${definition.type}".`);
}
const home = this.#homeStore(definition.type);
if (registered.global) {
const existingGlobalKey = this.#globalKeys.get(definition.type);
@ -444,7 +463,7 @@ export class CultCache {
}
}
await home.push(entry);
await home?.push(entry);
this.#applyHydratedEntry(registered, entry, parsed, "put");
return parsed;
}
@ -492,13 +511,10 @@ export class CultCache {
return false;
}
const home = this.#resolveRoute(definition.type);
if (!home) {
throw new Error(`No backing store is registered for document type "${definition.type}".`);
}
const home = this.#homeStore(definition.type);
const envelope = this.#toEnvelope(entry);
await home.delete(envelope);
await home?.delete(envelope);
this.#removeHydratedEntry(registered, entry);
return true;
}
@ -658,10 +674,31 @@ export class CultCache {
return this.#schemaNameDefinitions.get(entry.type) ?? this.#definitions.get(entry.type);
}
// The store that claims the type, else the generic store. Registration guarantees at most one of each.
#resolveRoute(type: string): CacheBackingStore | undefined {
return (this.#stores.find((registration) => registration.types.includes(type))
?? this.#stores.find((registration) => registration.types.length === 0))?.store;
// The registration that claims the type, else the generic one. Registration guarantees at most one of each.
#resolveRegistration(type: string): CultCacheStoreRegistration | undefined {
return this.#stores.find((registration) => registration.types.includes(type))
?? this.#stores.find((registration) => registration.types.length === 0);
}
// A cache with no stores is in memory: undefined. Once any store is attached, a type with no home is an error.
#homeStore(type: string): CacheBackingStore | undefined {
if (this.#stores.length === 0) {
return undefined;
}
const home = this.#resolveRegistration(type);
if (!home) {
throw new Error(`No backing store is registered for document type "${type}".`);
}
return home.store;
}
#describe(registration: CultCacheStoreRegistration | undefined): string {
if (!registration) {
return "memory";
}
return registration.types.length === 0
? "the generic store"
: `the store routed to ${registration.types.join(", ")}`;
}
#applyHydratedEntry(

View file

@ -589,6 +589,65 @@ test("CultCache routes each type to its home store", async () => {
assert.equal(reloaded.get(settingsDocument, "app"), undefined);
});
test("CultCache refuses an attach that would move a held record's home", async () => {
const settingsDocument = defineDocumentType({ type: "settings", schema: z.object({ theme: z.string() }) });
const tempDir = await mkdtemp(join(tmpdir(), "cultcache-home-move-"));
const genericPath = join(tempDir, "generic.cc");
const settingsPath = join(tempDir, "settings.cc");
const cache = CultCache.builder()
.withRegistry(defineDocumentRegistry(settingsDocument))
.withGenericStore(new SingleFileMessagePackBackingStore(genericPath))
.build();
await cache.put(settingsDocument, "app", { theme: "v1-generic" });
assert.throws(
() => cache.addBackingStore(new SingleFileMessagePackBackingStore(settingsPath), settingsDocument),
/would move "settings" from the generic store to the store routed to settings/u,
);
// Nothing attached: the next write still lands in the generic store, and the refused store stays untouched.
await cache.put(settingsDocument, "app", { theme: "v2-generic" });
const keysIn = async (path: string) =>
(await new SingleFileMessagePackBackingStore(path).pullAll()).map((entry) => `${entry.type}:${entry.key}`);
assert.deepEqual(await keysIn(genericPath), ["settings:app"]);
assert.equal(existsSync(settingsPath), false);
});
test("CultCache refuses at load a record delivered by a store that is not its home", async () => {
const settingsDocument = defineDocumentType({ type: "settings", schema: z.object({ theme: z.string() }) });
const tempDir = await mkdtemp(join(tmpdir(), "cultcache-load-home-"));
const genericPath = join(tempDir, "generic.cc");
const settingsPath = join(tempDir, "settings.cc");
const writer = CultCache.builder()
.withRegistry(defineDocumentRegistry(settingsDocument))
.withGenericStore(new SingleFileMessagePackBackingStore(genericPath))
.build();
await writer.put(settingsDocument, "app", { theme: "stray" });
const genericBytes = await readFile(genericPath);
const cache = CultCache.builder()
.withRegistry(defineDocumentRegistry(settingsDocument))
.withBackingStore(new SingleFileMessagePackBackingStore(settingsPath), settingsDocument)
.withGenericStore(new SingleFileMessagePackBackingStore(genericPath))
.build();
await assert.rejects(
cache.pullAllBackingStores(),
/"settings" record "app" was loaded from the generic store, but its home is the store routed to settings/u,
);
assert.equal(cache.get(settingsDocument, "app"), undefined);
assert.deepEqual(cache.snapshot(), []);
assert.deepEqual(await readFile(genericPath), genericBytes);
assert.equal(existsSync(settingsPath), false);
});
test("CultCache with zero stores writes and deletes in memory", async () => {
const settingsDocument = defineDocumentType({ type: "settings", schema: z.object({ theme: z.string() }) });
const cache = CultCache.builder().withRegistry(defineDocumentRegistry(settingsDocument)).build();
await cache.put(settingsDocument, "x", { theme: "mem" });
assert.deepEqual(cache.getRequired(settingsDocument, "x"), { theme: "mem" });
assert.equal(await cache.delete(settingsDocument, "x"), true);
assert.equal(cache.get(settingsDocument, "x"), undefined);
});
test("CultCache v1 MessagePack stores are readable across TS, Rust, C#, and Python", async () => {
await buildInteropPeers();
const tempDir = await mkdtemp(join(tmpdir(), "cultcache-interop-"));