Python: one registered document carries each schema id; a second claimant is refused typed
register_document_type refuses a document whose own or compatible ids overlap another registered document's, raising SchemaConflictError (empty record key, both schema names, a message naming both document types), as TypeScript does. Before, the record resolved to whichever document the dict held first (Soul F4). With one carrier per id, resolution by id is a single pass. SchemaConflictError takes an optional message for this use. The test that pinned owner-over-lister resolution inside one cache becomes a refusal test in both orders; shared compatible ids and a shared own id (neither declaring its own) are refused in both orders. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4182c2502b
commit
abb922cd57
3 changed files with 63 additions and 27 deletions
|
|
@ -7,6 +7,7 @@ from typing import Any, Callable, Generic, TypeVar
|
|||
|
||||
from .backing_store import BackingStore, CultCacheEnvelope
|
||||
from .documents import DocumentDefinition, extract_value
|
||||
from .stores import SchemaConflictError
|
||||
|
||||
T = TypeVar("T")
|
||||
F = TypeVar("F", bound=Callable[..., Any])
|
||||
|
|
@ -140,9 +141,23 @@ class CultCache:
|
|||
def _register_document_type(self, document: DocumentDefinition[Any]) -> None:
|
||||
if document.type in self._state.documents:
|
||||
raise CultCacheError(f"Document type already registered: {document.type}")
|
||||
schema_name = document.catalog_entry().schema_name
|
||||
entry = document.catalog_entry()
|
||||
schema_name = entry.schema_name
|
||||
if schema_name in self._state.documents_by_schema_name:
|
||||
raise CultCacheError(f"Document schema name already registered: {schema_name}")
|
||||
# One document carries each schema id, its own or declared compatible, so which document a record resolves to never
|
||||
# depends on the order documents were registered in.
|
||||
for registered in self._state.documents.values():
|
||||
other = registered.catalog_entry()
|
||||
shared = sorted(({entry.schema_id, *entry.compatible_schema_ids}) & ({other.schema_id, *other.compatible_schema_ids}))
|
||||
if shared:
|
||||
raise SchemaConflictError(
|
||||
shared[0],
|
||||
[other.schema_name, schema_name],
|
||||
"",
|
||||
message=f"Schema id {shared[0]!r} is already carried by document type {registered.type!r} and cannot also be "
|
||||
f"claimed by {document.type!r}. A schema id, owned or declared compatible, belongs to one registered document.",
|
||||
)
|
||||
name_extractors = dict(self._state.name_extractors)
|
||||
index_extractors = {type: dict(indexes) for type, indexes in self._state.index_extractors.items()}
|
||||
if document.name is not None:
|
||||
|
|
@ -592,16 +607,13 @@ class CultCache:
|
|||
raise CultCacheError(f"Document type is not global: {document.type}")
|
||||
|
||||
def _resolve_document_for_envelope(self, envelope: CultCacheEnvelope) -> DocumentDefinition[Any] | None:
|
||||
"""A record resolves by its schema id: the document that owns the id, else one that lists it as compatible. The name
|
||||
its catalog carries is metadata; it names a document only when the id names none (a store from a runtime whose
|
||||
schema ids this one cannot know)."""
|
||||
"""A record resolves by its schema id: the one document that owns the id or lists it as compatible. The name its
|
||||
catalog carries is metadata; it names a document only when the id names none (a store from a runtime whose schema
|
||||
ids this one cannot know)."""
|
||||
if envelope.schema_id:
|
||||
catalogs = [(document, document.catalog_entry()) for document in self._state.documents.values()]
|
||||
for document, entry in catalogs:
|
||||
if entry.schema_id == envelope.schema_id:
|
||||
return document
|
||||
for document, entry in catalogs:
|
||||
if envelope.schema_id in entry.compatible_schema_ids:
|
||||
for document in self._state.documents.values():
|
||||
entry = document.catalog_entry()
|
||||
if entry.schema_id == envelope.schema_id or envelope.schema_id in entry.compatible_schema_ids:
|
||||
return document
|
||||
document = self._state.documents.get(envelope.type)
|
||||
if document is not None:
|
||||
|
|
|
|||
|
|
@ -36,11 +36,13 @@ class StoreUnreadableError(ValueError):
|
|||
class SchemaConflictError(ValueError):
|
||||
"""A write the catalog cannot describe: records of different types under one schema id, two arrived schemas that share an id
|
||||
and disagree on the schema name, or a record no chosen entry publishes. Nothing is written. It names the id, the names
|
||||
involved (`schema_names`) and a record key (`record_key`)."""
|
||||
involved (`schema_names`) and a record key (`record_key`). A cache raises it too, with an empty record key, when a
|
||||
document registers a schema id another registered document already carries."""
|
||||
|
||||
def __init__(self, schema_id: str, schema_names: list[str], record_key: str) -> None:
|
||||
def __init__(self, schema_id: str, schema_names: list[str], record_key: str, *, message: str | None = None) -> None:
|
||||
super().__init__(
|
||||
f"Schema id {schema_id!r} cannot describe record {record_key!r}: {', '.join(repr(name) for name in schema_names)}"
|
||||
message
|
||||
or f"Schema id {schema_id!r} cannot describe record {record_key!r}: {', '.join(repr(name) for name in schema_names)}"
|
||||
)
|
||||
self.schema_id = schema_id
|
||||
self.schema_names = schema_names
|
||||
|
|
|
|||
|
|
@ -628,25 +628,47 @@ class CultCacheTests(unittest.TestCase):
|
|||
self.assertEqual(cache.get_required(second, "k")["name"], "k", schema_id)
|
||||
self.assertIsNone(cache.get(first, "k"), schema_id)
|
||||
|
||||
def test_an_id_a_document_owns_names_that_document_not_one_registered_earlier_that_lists_it(self) -> None:
|
||||
def _assert_second_claim_refused(self, first, second, schema_id: str) -> None:
|
||||
"""One document carries each schema id, owned or declared compatible, whichever order the documents register in: a
|
||||
second claimant is refused, typed, naming both, and the cache keeps what it had."""
|
||||
from cultcache_py import SchemaConflictError
|
||||
|
||||
cache = CultCache()
|
||||
cache.register_document_type(first)
|
||||
with self.assertRaises(SchemaConflictError) as refused:
|
||||
cache.register_document_type(second)
|
||||
self.assertEqual(refused.exception.schema_id, schema_id)
|
||||
self.assertEqual(refused.exception.schema_names, [first.catalog_entry().schema_name, second.catalog_entry().schema_name])
|
||||
self.assertIn(first.type, str(refused.exception))
|
||||
self.assertIn(second.type, str(refused.exception))
|
||||
with self.assertRaisesRegex(CultCacheError, "not registered"):
|
||||
cache.put(second, "k", {"name": "k"})
|
||||
|
||||
def test_a_document_listing_an_id_another_document_owns_is_refused_in_either_order(self) -> None:
|
||||
lister = define_database_entry_type(
|
||||
"tests.lister", [("name", 0)], schema_id="id.lister", schema_name="tests.lister", schema_version="tests.lister.v1",
|
||||
compatible_schema_ids=["id.lister", "id.owned"],
|
||||
)
|
||||
owner = define_database_entry_type("tests.owner", [("name", 0)], schema_id="id.owned", schema_name="tests.owner", schema_version="tests.owner.v1")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = Path(tmp) / "store.msgpack"
|
||||
self._store_of(
|
||||
path,
|
||||
[["id.owned", "tests.lister", "tests.owner.v1", "h", "", ["id.owned"], []]],
|
||||
[["k", "id.owned", "2026-09-30T00:00:00Z", owner.encode_payload({"name": "k"})]],
|
||||
)
|
||||
cache = CultCache.builder().register_document_type(lister).register_document_type(owner).add_generic_store(
|
||||
SingleFileMessagePackBackingStore(path)
|
||||
).build()
|
||||
cache.pull_all_backing_stores()
|
||||
self.assertEqual(cache.get_required(owner, "k")["name"], "k")
|
||||
self.assertIsNone(cache.get(lister, "k"))
|
||||
self._assert_second_claim_refused(lister, owner, "id.owned")
|
||||
self._assert_second_claim_refused(owner, lister, "id.owned")
|
||||
|
||||
def test_two_documents_listing_one_compatible_id_are_refused_in_either_order(self) -> None:
|
||||
a = define_database_entry_type(
|
||||
"tests.list-a", [("name", 0)], schema_id="id.a", schema_name="tests.list-a", compatible_schema_ids=["id.a", "id.shared"],
|
||||
)
|
||||
b = define_database_entry_type(
|
||||
"tests.list-b", [("name", 0)], schema_id="id.b", schema_name="tests.list-b", compatible_schema_ids=["id.b", "id.shared"],
|
||||
)
|
||||
self._assert_second_claim_refused(a, b, "id.shared")
|
||||
self._assert_second_claim_refused(b, a, "id.shared")
|
||||
|
||||
def test_two_documents_owning_one_schema_id_are_refused_in_either_order(self) -> None:
|
||||
# Each declares an older id and not its own, so the id they share is only ever their own.
|
||||
a = define_database_entry_type("tests.own-a", [("name", 0)], schema_id="id.same", schema_name="tests.own-a", compatible_schema_ids=["id.a-older"])
|
||||
b = define_database_entry_type("tests.own-b", [("name", 0)], schema_id="id.same", schema_name="tests.own-b", compatible_schema_ids=["id.b-older"])
|
||||
self._assert_second_claim_refused(a, b, "id.same")
|
||||
self._assert_second_claim_refused(b, a, "id.same")
|
||||
|
||||
def test_interop_cli_helpers_round_trip_v1_store(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
|
|
|
|||
Loading…
Reference in a new issue