From 1f442f3345d6f02a9539abd2308018f77022c12e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 14 Sep 2026 00:57:09 +0200 Subject: [PATCH] Refuse duplicate global records while staging a pull A load is all-or-nothing. TypeScript checked for a second record of a global type inside #applyHydratedEntry, which runs after #resetHydratedState, so a refused pull left the cache cleared and partly reloaded. The check now runs in the staging pass beside the home check, before anything is cleared; the apply step's pull-only branch is gone. Python already validated before swapping, but its check only fired when the __global__ record arrived second, so a store holding __global__ then another key of a global type loaded both. Any second record of a global type is now refused regardless of order. Rust has no global document types and replaces its entry map only after staging; it had neither flaw. pullWithDuplicateGlobalLeavesCacheUnchanged (TS) and test_pull_with_duplicate_global_leaves_cache_unchanged (Python) fail on 9ab1706 and pass here. Co-Authored-By: Claude Opus 5 --- .../cultcache-py/src/cultcache_py/cache.py | 2 +- packages/cultcache-py/tests/test_cultcache.py | 29 ++++++++++++++++++- packages/cultcache-ts/src/cult-cache.ts | 20 ++++++++----- packages/cultcache-ts/test/cult-cache.test.ts | 27 +++++++++++++++++ 4 files changed, 69 insertions(+), 9 deletions(-) diff --git a/packages/cultcache-py/src/cultcache_py/cache.py b/packages/cultcache-py/src/cultcache_py/cache.py index e4329233..5644b5d1 100644 --- a/packages/cultcache-py/src/cultcache_py/cache.py +++ b/packages/cultcache-py/src/cultcache_py/cache.py @@ -176,7 +176,7 @@ class CultCache: f"but its home is {self._describe(home, routes, generic)}" ) if document.global_document: - if envelope.type in seen_globals and envelope.key == GLOBAL_KEY: + if envelope.type in seen_globals: raise CultCacheError(f"Duplicate global document for type: {envelope.type}") seen_globals.add(envelope.type) value = document.decode_payload(envelope.payload) diff --git a/packages/cultcache-py/tests/test_cultcache.py b/packages/cultcache-py/tests/test_cultcache.py index e56d2dca..2636458e 100644 --- a/packages/cultcache-py/tests/test_cultcache.py +++ b/packages/cultcache-py/tests/test_cultcache.py @@ -2,7 +2,7 @@ from __future__ import annotations import tempfile import unittest -from dataclasses import asdict, dataclass +from dataclasses import asdict, dataclass, replace from pathlib import Path from cultcache_py.cache import CultCacheError from cultcache_py import ( @@ -341,6 +341,33 @@ class CultCacheTests(unittest.TestCase): self.assertEqual(generic_path.read_bytes(), generic_bytes) self.assertFalse(settings_path.exists()) + def test_pull_with_duplicate_global_leaves_cache_unchanged(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + item = item_doc() + settings = define_document_type("settings", global_document=True) + store_path = Path(tmp) / "generic.cc" + cache = ( + CultCache.builder() + .register_document_type(item) + .register_document_type(settings) + .add_generic_store(SingleFileMessagePackBackingStore(store_path)) + .build() + ) + cache.put(item, "item:potion", Item(name="Potion", category="Consumable", value=50)) + cache.put_global(settings, {"theme": "ash"}) + before = cache.snapshot_envelopes() + + # A second record of the global type lands in the store file behind the cache's back. + stray = replace(cache.get_required_envelope(settings, CultCache.GLOBAL_KEY), key="stray") + SingleFileMessagePackBackingStore(store_path).push(stray) + + with self.assertRaisesRegex(CultCacheError, "Duplicate global document for type: settings"): + cache.pull_all_backing_stores() + self.assertEqual(cache.snapshot_envelopes(), before) + self.assertEqual(cache.get_required(item, "item:potion").value, 50) + self.assertEqual(cache.get_key_by_name(item, "Potion"), "item:potion") + self.assertEqual(cache.get_required_global(settings)["theme"], "ash") + def test_attach_with_empty_type_list_is_the_generic_store(self) -> None: with tempfile.TemporaryDirectory() as tmp: settings = define_database_entry_type("settings", [("theme", 0)]) diff --git a/packages/cultcache-ts/src/cult-cache.ts b/packages/cultcache-ts/src/cult-cache.ts index b83cec63..d4dcc37e 100644 --- a/packages/cultcache-ts/src/cult-cache.ts +++ b/packages/cultcache-ts/src/cult-cache.ts @@ -209,6 +209,7 @@ export class CultCache { // the cache's view is replaced, so a refused load admits nothing. async pullAllBackingStores(): Promise { const loaded: Array<{ registered: RegisteredDefinition; entry: CultCacheEnvelope; value: unknown }> = []; + const globalKeys = new Map(); for (const registration of this.#stores) { const entries = await registration.store.pullAll(); @@ -232,6 +233,14 @@ export class CultCache { ); } + if (registered.global) { + const globalKey = globalKeys.get(type); + if (globalKey !== undefined && globalKey !== entry.key) { + throw new Error(`CultCache global document type "${type}" has multiple persisted entries.`); + } + globalKeys.set(type, entry.key); + } + const payload = this.#cloneBytes(entry.payload); const value = registered.formatter.decode(payload); loaded.push({ registered, entry: { ...entry, type, payload }, value }); @@ -240,7 +249,7 @@ export class CultCache { this.#resetHydratedState(); for (const { registered, entry, value } of loaded) { - this.#applyHydratedEntry(registered, entry, value, "pull"); + this.#applyHydratedEntry(registered, entry, value); } } @@ -422,7 +431,7 @@ export class CultCache { } await home?.push(entry); - this.#applyHydratedEntry(registered, entry, parsed, "put"); + this.#applyHydratedEntry(registered, entry, parsed); return parsed; } @@ -464,7 +473,7 @@ export class CultCache { } await home?.push(entry); - this.#applyHydratedEntry(registered, entry, parsed, "put"); + this.#applyHydratedEntry(registered, entry, parsed); return parsed; } @@ -705,7 +714,6 @@ export class CultCache { registered: RegisteredDefinition, entry: CultCacheEnvelope, value: unknown, - source: "pull" | "put", ): void { const entryId = this.#entryId(entry.type, entry.key); const existing = this.#entries.get(entryId); @@ -717,9 +725,7 @@ export class CultCache { const currentGlobalKey = this.#globalKeys.get(entry.type); if (currentGlobalKey && currentGlobalKey !== entry.key) { throw new Error( - source === "pull" - ? `CultCache global document type "${entry.type}" has multiple persisted entries.` - : `CultCache global document type "${entry.type}" already has a different key "${currentGlobalKey}".`, + `CultCache global document type "${entry.type}" already has a different key "${currentGlobalKey}".`, ); } } diff --git a/packages/cultcache-ts/test/cult-cache.test.ts b/packages/cultcache-ts/test/cult-cache.test.ts index d289806c..04dfb159 100644 --- a/packages/cultcache-ts/test/cult-cache.test.ts +++ b/packages/cultcache-ts/test/cult-cache.test.ts @@ -639,6 +639,33 @@ test("CultCache refuses at load a record delivered by a store that is not its ho assert.equal(existsSync(settingsPath), false); }); +test("pullWithDuplicateGlobalLeavesCacheUnchanged", async () => { + const itemDocument = defineDocumentType({ type: "item", schema: z.object({ name: z.string() }) }); + const settingsDocument = defineDocumentType({ + type: "settings", + schema: z.object({ theme: z.string() }), + global: true, + }); + const tempDir = await mkdtemp(join(tmpdir(), "cultcache-duplicate-global-")); + const storePath = join(tempDir, "generic.cc"); + const cache = CultCache.builder() + .withRegistry(defineDocumentRegistry(itemDocument, settingsDocument)) + .withGenericStore(new SingleFileMessagePackBackingStore(storePath)) + .build(); + await cache.put(itemDocument, "potion", { name: "Potion" }); + await cache.putGlobal(settingsDocument, { theme: "ash" }); + const before = cache.snapshot(); + + // A second record of the global type lands in the store file behind the cache's back. + const stray = cache.getRequiredEnvelope(settingsDocument, CultCache.GLOBAL_KEY); + await new SingleFileMessagePackBackingStore(storePath).push({ ...stray, key: "stray" }); + + await assert.rejects(cache.pullAllBackingStores(), /has multiple persisted entries/u); + assert.deepEqual(cache.snapshot(), before); + assert.deepEqual(cache.getRequired(itemDocument, "potion"), { name: "Potion" }); + assert.deepEqual(cache.getRequiredGlobal(settingsDocument), { theme: "ash" }); +}); + 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();