2026-06-13 20:35:58 +01:00
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
2026-09-14 12:03:45 +02:00
|
|
|
|
import functools
|
2026-11-11 06:59:08 +00:00
|
|
|
|
import math
|
2026-09-14 12:03:45 +02:00
|
|
|
|
import threading
|
2026-11-11 06:59:08 +00:00
|
|
|
|
from decimal import Decimal
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
from dataclasses import dataclass, field, replace
|
2026-11-11 06:59:08 +00:00
|
|
|
|
from typing import Any, Callable, Generic, Iterable, TypeVar
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
|
|
|
|
|
from .backing_store import BackingStore, CultCacheEnvelope
|
2026-11-12 04:24:07 +00:00
|
|
|
|
from .documents import DocumentDefinition, UnreadSlots, extract_value
|
2026-11-12 00:45:11 +00:00
|
|
|
|
from .stores import SchemaConflictError, retyped, written_owns
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
|
|
|
|
|
T = TypeVar("T")
|
2026-09-14 12:03:45 +02:00
|
|
|
|
F = TypeVar("F", bound=Callable[..., Any])
|
2026-06-13 20:35:58 +01:00
|
|
|
|
GLOBAL_KEY = "__global__"
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-09-14 12:03:45 +02:00
|
|
|
|
def _locked(method: F) -> F:
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
"""Runs a read holding the cache's lock. Reads are reentrant and may run inside a mutation."""
|
2026-09-14 12:03:45 +02:00
|
|
|
|
|
|
|
|
|
|
@functools.wraps(method)
|
|
|
|
|
|
def wrapper(self: "CultCache", *args: Any, **kwargs: Any) -> Any:
|
|
|
|
|
|
with self._lock:
|
|
|
|
|
|
return method(self, *args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
return wrapper # type: ignore[return-value]
|
|
|
|
|
|
|
|
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
def _mutating(method: F) -> F:
|
|
|
|
|
|
"""Runs an attach, pull, registration, write or delete holding the cache's lock, so its validation,
|
|
|
|
|
|
store I/O and apply cannot interleave with another thread's. One started on a thread that is already
|
|
|
|
|
|
inside a mutation of this cache (from a store call, decoder, encoder, extractor or updater) raises
|
|
|
|
|
|
before touching anything."""
|
|
|
|
|
|
|
|
|
|
|
|
@functools.wraps(method)
|
|
|
|
|
|
def wrapper(self: "CultCache", *args: Any, **kwargs: Any) -> Any:
|
|
|
|
|
|
if self._mutating_thread == threading.get_ident():
|
|
|
|
|
|
raise CultCacheError(
|
|
|
|
|
|
f"CultCache refuses a re-entrant {method.__name__}: a mutation cannot start from inside a store call, "
|
|
|
|
|
|
"decoder, encoder, extractor or updater of another mutation on the same cache"
|
|
|
|
|
|
)
|
|
|
|
|
|
with self._lock:
|
|
|
|
|
|
self._mutating_thread = threading.get_ident()
|
|
|
|
|
|
try:
|
|
|
|
|
|
return method(self, *args, **kwargs)
|
|
|
|
|
|
finally:
|
|
|
|
|
|
self._mutating_thread = None
|
|
|
|
|
|
|
|
|
|
|
|
return wrapper # type: ignore[return-value]
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-06-13 20:35:58 +01:00
|
|
|
|
class CultCacheError(RuntimeError):
|
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-11 06:59:08 +00:00
|
|
|
|
# Blank is no value: empty or only C# White_Space characters (the 25 chars string.IsNullOrWhiteSpace is true for).
|
|
|
|
|
|
# An explicit set, not str.isspace(): Python also counts U+001C-001F, which C# does not, and omits nothing C# counts.
|
|
|
|
|
|
_BLANK_INDEX_CHARS = frozenset(
|
|
|
|
|
|
chr(code)
|
|
|
|
|
|
for code in (
|
|
|
|
|
|
*range(0x09, 0x0E),
|
|
|
|
|
|
0x20,
|
|
|
|
|
|
0x85,
|
|
|
|
|
|
0xA0,
|
|
|
|
|
|
0x1680,
|
|
|
|
|
|
*range(0x2000, 0x200B),
|
|
|
|
|
|
0x2028,
|
|
|
|
|
|
0x2029,
|
|
|
|
|
|
0x202F,
|
|
|
|
|
|
0x205F,
|
|
|
|
|
|
0x3000,
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _utf16_order(text: str) -> bytes:
|
|
|
|
|
|
"""Sorts as C# StringComparer.Ordinal does: by UTF-16 code unit, not code point."""
|
|
|
|
|
|
return text.encode("utf-16-be", "surrogatepass")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def index_text(value: Any) -> str | None:
|
|
|
|
|
|
"""The canonical text of an index value, as C# IndexValue and RenderCanonicalNumber, or None when it names no
|
|
|
|
|
|
value: a string is as is (never trimmed), a boolean is `True`/`False`, an integer is its digits, a non-integral
|
|
|
|
|
|
finite float is its exact decimal expansion, NaN and infinities and blank strings are no value."""
|
|
|
|
|
|
if value is None:
|
|
|
|
|
|
return None
|
|
|
|
|
|
if isinstance(value, bool): # before int: bool is an int subclass
|
|
|
|
|
|
return "True" if value else "False"
|
|
|
|
|
|
if isinstance(value, int):
|
|
|
|
|
|
return str(value)
|
|
|
|
|
|
if isinstance(value, float):
|
|
|
|
|
|
if not math.isfinite(value):
|
|
|
|
|
|
return None
|
|
|
|
|
|
if value.is_integer():
|
|
|
|
|
|
return str(int(value)) # -0.0 is 0
|
|
|
|
|
|
text = format(Decimal(value), "f") # Decimal(float) is exact
|
|
|
|
|
|
return text.rstrip("0").rstrip(".") if "." in text else text
|
|
|
|
|
|
text = value if isinstance(value, str) else str(value)
|
|
|
|
|
|
return None if all(char in _BLANK_INDEX_CHARS for char in text) else text
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-06-13 20:35:58 +01:00
|
|
|
|
@dataclass
|
|
|
|
|
|
class _State:
|
|
|
|
|
|
documents: dict[str, DocumentDefinition[Any]] = field(default_factory=dict)
|
2026-06-27 14:34:53 +01:00
|
|
|
|
documents_by_schema_name: dict[str, DocumentDefinition[Any]] = field(default_factory=dict)
|
2026-06-14 15:12:40 +01:00
|
|
|
|
values: dict[str, dict[str, Any]] = field(default_factory=dict)
|
|
|
|
|
|
envelopes: dict[str, dict[str, CultCacheEnvelope]] = field(default_factory=dict)
|
2026-09-14 00:37:31 +02:00
|
|
|
|
stores_by_type: dict[str, BackingStore] = field(default_factory=dict)
|
|
|
|
|
|
generic_store: BackingStore | None = None
|
2026-06-13 20:35:58 +01:00
|
|
|
|
name_extractors: dict[str, str | Any] = field(default_factory=dict)
|
|
|
|
|
|
index_extractors: dict[str, dict[str, str | Any]] = field(default_factory=dict)
|
|
|
|
|
|
names: dict[tuple[str, str], str] = field(default_factory=dict)
|
|
|
|
|
|
indexes: dict[tuple[str, str, str], str] = field(default_factory=dict)
|
2026-09-14 11:48:59 +02:00
|
|
|
|
# The name and index values each held record produced when it was admitted. Removing a
|
|
|
|
|
|
# record reads these and runs no extractor, so removal has no fallible step.
|
|
|
|
|
|
lookup_keys: dict[str, dict[str, "_LookupKeys"]] = field(default_factory=dict)
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
# Load compatibility shim: a global persisted under a key other than GLOBAL_KEY is held as that
|
|
|
|
|
|
# type's global under GLOBAL_KEY, and its persisted key is kept here so the first write or delete
|
|
|
|
|
|
# of that global removes it from the home store. Remove once no store holds a global under a key
|
|
|
|
|
|
# other than GLOBAL_KEY.
|
|
|
|
|
|
legacy_global_keys: dict[str, str] = field(default_factory=dict)
|
2026-11-12 00:45:11 +00:00
|
|
|
|
# The records the last pull read that no registered type claims, sorted by key. Derived from the pull and swapped with the
|
|
|
|
|
|
# rest of the state, written nowhere else; it decides only refusals at its keys. A store keeps their bytes.
|
|
|
|
|
|
foreign: list["ForeignRecord"] = field(default_factory=list)
|
2026-11-12 04:24:07 +00:00
|
|
|
|
# The records held read-only, by key (a key holds one record) with the type that holds it: the payload carried slots past the
|
|
|
|
|
|
# declared ones and nothing consents to the loss. Derived from the load or the write that admitted the record and swapped with
|
|
|
|
|
|
# the rest of the state; it decides only refusals at its keys, and any other key is absent.
|
|
|
|
|
|
unread: dict[str, tuple[str, UnreadSlots]] = field(default_factory=dict)
|
2026-11-12 00:45:11 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
|
|
|
|
class ForeignRecord:
|
|
|
|
|
|
"""A record a store holds that no registered type claims: the cache does not serve it, refuses a write or a removal at its
|
|
|
|
|
|
key, and a store keeps its bytes. Registering a type that declares its schema id claims it at the next load."""
|
|
|
|
|
|
|
|
|
|
|
|
key: str
|
|
|
|
|
|
schema_id: str
|
|
|
|
|
|
schema_name: str
|
|
|
|
|
|
stored_at: str
|
2026-09-14 11:48:59 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
|
|
|
|
class _LookupKeys:
|
|
|
|
|
|
name: str | None
|
|
|
|
|
|
indexes: dict[str, str]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_Names = dict[tuple[str, str], str]
|
|
|
|
|
|
_Indexes = dict[tuple[str, str, str], str]
|
|
|
|
|
|
_LookupKeysByType = dict[str, dict[str, _LookupKeys]]
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CultCacheBuilder:
|
|
|
|
|
|
def __init__(self) -> None:
|
|
|
|
|
|
self._cache = CultCache()
|
|
|
|
|
|
|
|
|
|
|
|
def register_document_type(self, document: DocumentDefinition[Any]) -> "CultCacheBuilder":
|
|
|
|
|
|
self._cache.register_document_type(document)
|
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
|
|
def register_registry(self, documents: list[DocumentDefinition[Any]] | tuple[DocumentDefinition[Any], ...]) -> "CultCacheBuilder":
|
|
|
|
|
|
self._cache.register_registry(documents)
|
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
|
|
def register_name_lookup(self, document: DocumentDefinition[Any], extractor: str | Any) -> "CultCacheBuilder":
|
|
|
|
|
|
self._cache.register_name_lookup(document, extractor)
|
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
|
|
def register_index(self, document: DocumentDefinition[Any], index: str, extractor: str | Any) -> "CultCacheBuilder":
|
|
|
|
|
|
self._cache.register_index(document, index, extractor)
|
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
|
|
def add_backing_store(self, store: BackingStore, types: list[str] | tuple[str, ...] | set[str]) -> "CultCacheBuilder":
|
|
|
|
|
|
self._cache.add_backing_store(store, types)
|
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
|
|
def add_generic_store(self, store: BackingStore) -> "CultCacheBuilder":
|
|
|
|
|
|
self._cache.add_generic_store(store)
|
|
|
|
|
|
return self
|
|
|
|
|
|
|
|
|
|
|
|
def build(self) -> "CultCache":
|
|
|
|
|
|
return self._cache
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CultCache:
|
|
|
|
|
|
GLOBAL_KEY = GLOBAL_KEY
|
|
|
|
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
|
|
def builder(cls) -> CultCacheBuilder:
|
|
|
|
|
|
return CultCacheBuilder()
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self) -> None:
|
|
|
|
|
|
self._state = _State()
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
# Mutations hold this lock and refuse to start on the thread already inside one (see _mutating).
|
|
|
|
|
|
# It is reentrant so a mutation's extractors, decoders and updaters may still read the cache.
|
|
|
|
|
|
# Single-structure reads (get, get_all, get_envelope, key lookups) stay unlocked. The guarantee is
|
|
|
|
|
|
# per call: each reads one dict under the GIL and sees it wholly before or after a write's install.
|
|
|
|
|
|
# Two unlocked calls can straddle a write or pull, and see different states.
|
2026-09-14 12:03:45 +02:00
|
|
|
|
self._lock = threading.RLock()
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
self._mutating_thread: int | None = None
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def register_document_type(self, document: DocumentDefinition[Any]) -> None:
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
self._register_document_type(document)
|
|
|
|
|
|
|
|
|
|
|
|
def _register_document_type(self, document: DocumentDefinition[Any]) -> None:
|
Python: a document listing an id registers beside the one owning it; registration refuses typed
Owner beats lister, as in C#. A document owns its schema id; others may list it
as compatible beside its owner, in either registration order (batch 9 refused
any overlap, which forbade keeping v1 beside a v2 that declares v1's id; Soul
F8). A record resolves to the document owning its id, else to the one document
listing it. Several listers and no owner name no single document, and the load
is refused with SchemaConflictError naming the id, the record key and the
listers: refusing at registration would depend on whether the owner had
registered yet.
Every registration refusal is now SchemaConflictError (Soul F10): a second owner
of one schema id, a second document with one schema name, and a second
definition of one document type. Each names the new document's id and both
schema names and document types. Before, the last two raised CultCacheError.
Tests: an owner and a lister register in both orders and each reads its own
records, and a lister alone reads the owner's id; two listers register in both
orders, a record under their id is refused typed without its owner and is the
owner's with it, registered before or after them; two owners, one schema name
and one document type twice are each refused as a schema conflict.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:31:25 +02:00
|
|
|
|
# Every registration refusal is a SchemaConflictError naming the new document's schema id and both schema names.
|
2026-09-30 12:35:52 +02:00
|
|
|
|
entry = document.catalog_entry()
|
|
|
|
|
|
schema_name = entry.schema_name
|
Python: a document listing an id registers beside the one owning it; registration refuses typed
Owner beats lister, as in C#. A document owns its schema id; others may list it
as compatible beside its owner, in either registration order (batch 9 refused
any overlap, which forbade keeping v1 beside a v2 that declares v1's id; Soul
F8). A record resolves to the document owning its id, else to the one document
listing it. Several listers and no owner name no single document, and the load
is refused with SchemaConflictError naming the id, the record key and the
listers: refusing at registration would depend on whether the owner had
registered yet.
Every registration refusal is now SchemaConflictError (Soul F10): a second owner
of one schema id, a second document with one schema name, and a second
definition of one document type. Each names the new document's id and both
schema names and document types. Before, the last two raised CultCacheError.
Tests: an owner and a lister register in both orders and each reads its own
records, and a lister alone reads the owner's id; two listers register in both
orders, a record under their id is refused typed without its owner and is the
owner's with it, registered before or after them; two owners, one schema name
and one document type twice are each refused as a schema conflict.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:31:25 +02:00
|
|
|
|
|
|
|
|
|
|
def refuse(registered: DocumentDefinition[Any], what: str) -> SchemaConflictError:
|
|
|
|
|
|
return SchemaConflictError(
|
|
|
|
|
|
entry.schema_id,
|
|
|
|
|
|
[registered.catalog_entry().schema_name, schema_name],
|
|
|
|
|
|
"",
|
|
|
|
|
|
message=f"{what} is already registered to document type {registered.type!r} and cannot also be claimed by "
|
|
|
|
|
|
f"{document.type!r}.",
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
if document.type in self._state.documents:
|
|
|
|
|
|
raise refuse(self._state.documents[document.type], f"Document type {document.type!r}")
|
2026-06-27 14:34:53 +01:00
|
|
|
|
if schema_name in self._state.documents_by_schema_name:
|
Python: a document listing an id registers beside the one owning it; registration refuses typed
Owner beats lister, as in C#. A document owns its schema id; others may list it
as compatible beside its owner, in either registration order (batch 9 refused
any overlap, which forbade keeping v1 beside a v2 that declares v1's id; Soul
F8). A record resolves to the document owning its id, else to the one document
listing it. Several listers and no owner name no single document, and the load
is refused with SchemaConflictError naming the id, the record key and the
listers: refusing at registration would depend on whether the owner had
registered yet.
Every registration refusal is now SchemaConflictError (Soul F10): a second owner
of one schema id, a second document with one schema name, and a second
definition of one document type. Each names the new document's id and both
schema names and document types. Before, the last two raised CultCacheError.
Tests: an owner and a lister register in both orders and each reads its own
records, and a lister alone reads the owner's id; two listers register in both
orders, a record under their id is refused typed without its owner and is the
owner's with it, registered before or after them; two owners, one schema name
and one document type twice are each refused as a schema conflict.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:31:25 +02:00
|
|
|
|
raise refuse(self._state.documents_by_schema_name[schema_name], f"Schema name {schema_name!r}")
|
|
|
|
|
|
# One document owns each schema id. Others may list it as compatible beside its owner: a record under the id resolves to
|
|
|
|
|
|
# its owner, and to a lister only when nothing owns it. Neither depends on the order documents were registered in.
|
2026-09-30 12:35:52 +02:00
|
|
|
|
for registered in self._state.documents.values():
|
Python: a document listing an id registers beside the one owning it; registration refuses typed
Owner beats lister, as in C#. A document owns its schema id; others may list it
as compatible beside its owner, in either registration order (batch 9 refused
any overlap, which forbade keeping v1 beside a v2 that declares v1's id; Soul
F8). A record resolves to the document owning its id, else to the one document
listing it. Several listers and no owner name no single document, and the load
is refused with SchemaConflictError naming the id, the record key and the
listers: refusing at registration would depend on whether the owner had
registered yet.
Every registration refusal is now SchemaConflictError (Soul F10): a second owner
of one schema id, a second document with one schema name, and a second
definition of one document type. Each names the new document's id and both
schema names and document types. Before, the last two raised CultCacheError.
Tests: an owner and a lister register in both orders and each reads its own
records, and a lister alone reads the owner's id; two listers register in both
orders, a record under their id is refused typed without its owner and is the
owner's with it, registered before or after them; two owners, one schema name
and one document type twice are each refused as a schema conflict.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:31:25 +02:00
|
|
|
|
if registered.catalog_entry().schema_id == entry.schema_id:
|
|
|
|
|
|
raise refuse(registered, f"Schema id {entry.schema_id!r}")
|
2026-09-14 11:48:59 +02:00
|
|
|
|
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:
|
|
|
|
|
|
name_extractors[document.type] = document.name
|
|
|
|
|
|
if document.indexes:
|
|
|
|
|
|
index_extractors.setdefault(document.type, {}).update(document.indexes)
|
|
|
|
|
|
self._install_lookups(name_extractors, index_extractors)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
self._state.documents[document.type] = document
|
2026-06-27 14:34:53 +01:00
|
|
|
|
self._state.documents_by_schema_name[schema_name] = document
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def register_registry(self, documents: list[DocumentDefinition[Any]] | tuple[DocumentDefinition[Any], ...]) -> None:
|
|
|
|
|
|
for document in documents:
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
self._register_document_type(document)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def register_name_lookup(self, document: DocumentDefinition[Any], extractor: str | Any) -> None:
|
|
|
|
|
|
self._assert_registered(document)
|
2026-09-14 11:48:59 +02:00
|
|
|
|
name_extractors = dict(self._state.name_extractors)
|
|
|
|
|
|
name_extractors[document.type] = extractor
|
|
|
|
|
|
self._install_lookups(name_extractors, self._state.index_extractors)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def register_index(self, document: DocumentDefinition[Any], index: str, extractor: str | Any) -> None:
|
|
|
|
|
|
self._assert_registered(document)
|
2026-11-11 08:05:39 +00:00
|
|
|
|
if index in document.roles:
|
|
|
|
|
|
raise CultCacheError(f"Index '{index}' of {document.type} is declared as a role; a role is never a unique index.")
|
2026-09-14 11:48:59 +02:00
|
|
|
|
index_extractors = {type: dict(indexes) for type, indexes in self._state.index_extractors.items()}
|
|
|
|
|
|
index_extractors.setdefault(document.type, {})[index] = extractor
|
|
|
|
|
|
self._install_lookups(self._state.name_extractors, index_extractors)
|
|
|
|
|
|
|
|
|
|
|
|
def _install_lookups(
|
|
|
|
|
|
self, name_extractors: dict[str, str | Any], index_extractors: dict[str, dict[str, str | Any]]
|
|
|
|
|
|
) -> None:
|
|
|
|
|
|
"""Derives every lookup under the candidate extractors, then installs extractors and lookups
|
|
|
|
|
|
together. An extractor that raises on a held value installs nothing."""
|
2026-11-11 08:05:39 +00:00
|
|
|
|
names, indexes, lookup_keys = self._derive_lookups(
|
|
|
|
|
|
[(type, key, value) for type, values in self._state.values.items() for key, value in values.items()],
|
|
|
|
|
|
name_extractors,
|
|
|
|
|
|
index_extractors,
|
|
|
|
|
|
)
|
2026-09-14 11:48:59 +02:00
|
|
|
|
(
|
|
|
|
|
|
self._state.name_extractors,
|
|
|
|
|
|
self._state.index_extractors,
|
|
|
|
|
|
self._state.names,
|
|
|
|
|
|
self._state.indexes,
|
|
|
|
|
|
self._state.lookup_keys,
|
|
|
|
|
|
) = (name_extractors, index_extractors, names, indexes, lookup_keys)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def add_backing_store(self, store: BackingStore, types: list[str] | tuple[str, ...] | set[str]) -> None:
|
2026-09-14 00:50:48 +02:00
|
|
|
|
"""Makes the store home to the given types, or the generic store when there are none.
|
|
|
|
|
|
|
|
|
|
|
|
A type has exactly one home store, and attaching cannot move the home of a record the cache holds.
|
|
|
|
|
|
"""
|
|
|
|
|
|
types = list(types)
|
|
|
|
|
|
if not types:
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
self._add_generic_store(store)
|
2026-09-14 00:50:48 +02:00
|
|
|
|
return
|
2026-06-13 20:35:58 +01:00
|
|
|
|
for type in types:
|
2026-09-14 00:37:31 +02:00
|
|
|
|
if type in self._state.stores_by_type:
|
|
|
|
|
|
raise CultCacheError(
|
|
|
|
|
|
f"Document type {type} is already routed to another backing store; it cannot also route to this one"
|
|
|
|
|
|
)
|
2026-09-14 00:50:48 +02:00
|
|
|
|
routes = dict(self._state.stores_by_type)
|
|
|
|
|
|
routes.update({type: store for type in types})
|
|
|
|
|
|
self._refuse_home_moves(routes, self._state.generic_store)
|
|
|
|
|
|
self._state.stores_by_type = routes
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def add_generic_store(self, store: BackingStore) -> None:
|
2026-09-14 00:37:31 +02:00
|
|
|
|
"""Makes the store home to every type no other store claims. A cache has at most one."""
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
self._add_generic_store(store)
|
|
|
|
|
|
|
|
|
|
|
|
def _add_generic_store(self, store: BackingStore) -> None:
|
2026-09-14 00:37:31 +02:00
|
|
|
|
if self._state.generic_store is not None:
|
|
|
|
|
|
raise CultCacheError(
|
|
|
|
|
|
"Backing store would be a second generic store; name the types it is home to"
|
|
|
|
|
|
)
|
2026-09-14 00:50:48 +02:00
|
|
|
|
self._refuse_home_moves(self._state.stores_by_type, store)
|
2026-09-14 00:37:31 +02:00
|
|
|
|
self._state.generic_store = store
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
2026-09-14 00:50:48 +02:00
|
|
|
|
def _refuse_home_moves(self, routes: dict[str, BackingStore], generic: BackingStore | None) -> None:
|
|
|
|
|
|
for type, values in self._state.values.items():
|
|
|
|
|
|
if not values:
|
|
|
|
|
|
continue
|
|
|
|
|
|
before = self._state.stores_by_type.get(type, self._state.generic_store)
|
|
|
|
|
|
after = routes.get(type, generic)
|
|
|
|
|
|
if before is not after:
|
|
|
|
|
|
raise CultCacheError(
|
|
|
|
|
|
f"Attaching this backing store would move {type} from {self._describe(before, routes, generic)} "
|
|
|
|
|
|
f"to {self._describe(after, routes, generic)}; attach routed stores before the generic store"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _describe(store: BackingStore | None, routes: dict[str, BackingStore], generic: BackingStore | None) -> str:
|
|
|
|
|
|
if store is None:
|
|
|
|
|
|
return "memory"
|
|
|
|
|
|
if store is generic:
|
|
|
|
|
|
return "the generic store"
|
|
|
|
|
|
return "the store routed to " + ", ".join(sorted(type for type, routed in routes.items() if routed is store))
|
|
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def pull_all_backing_stores(self) -> None:
|
Build the whole next state before a pull swaps it in
A pull is all-or-nothing, but TS cleared the cache and then ran user name and
index accessors while re-applying entries, and Python swapped values in and
then rebuilt lookups. An accessor that threw left the cache partly loaded.
TS: the hydrated maps (entries, type entry ids, name and index lookups, global
keys) are one HydratedState. The pull builds a fresh one, running every check
and accessor, and replaces #hydrated in one assignment at the end. The
reset-then-apply sequence, #resetHydratedState, the staged global-key map and
the three per-map getOrCreate helpers are deleted; apply/remove take the
target state. The duplicate-global check now lives only in apply. Name and
index lookup rebuilds build a local map before assigning.
Python: the pull derives names and indexes into local dicts and assigns
values, envelopes, names and indexes together; _rebuild_indexes delegates to
the same pure _derive_lookups.
Rust already stages into a local map and assigns self.entries last, with no
derived lookups; unchanged.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 01:03:30 +02:00
|
|
|
|
"""Builds the complete next state (values, envelopes, name and index lookups) in local
|
|
|
|
|
|
structures, running every check and every user extractor; the cache's state is replaced
|
|
|
|
|
|
only once that build finishes, so a refused load admits nothing."""
|
2026-09-14 00:50:48 +02:00
|
|
|
|
loaded_values: dict[str, dict[str, Any]] = {}
|
2026-11-11 11:48:38 +00:00
|
|
|
|
read_values: dict[tuple[str, str], Any] = {} # (type, key) -> value, one per key, the last read wins; the judge is order-free
|
2026-09-14 00:50:48 +02:00
|
|
|
|
loaded_envelopes: dict[str, dict[str, CultCacheEnvelope]] = {}
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
loaded_legacy_global_keys: dict[str, str] = {}
|
2026-09-14 00:50:48 +02:00
|
|
|
|
routes, generic = self._state.stores_by_type, self._state.generic_store
|
2026-06-13 20:35:58 +01:00
|
|
|
|
seen_globals: set[str] = set()
|
2026-11-12 00:45:11 +00:00
|
|
|
|
foreign: list[ForeignRecord] = []
|
2026-11-12 04:24:07 +00:00
|
|
|
|
loaded_unread: dict[str, tuple[str, UnreadSlots]] = {}
|
2026-11-12 00:45:11 +00:00
|
|
|
|
type_at_key: dict[str, tuple[str, int]] = {} # one record per key across every store: its type (or schema name) and store
|
2026-09-14 00:37:31 +02:00
|
|
|
|
stores: list[BackingStore] = []
|
|
|
|
|
|
for candidate in [*self._state.stores_by_type.values(), self._state.generic_store]:
|
|
|
|
|
|
if candidate is not None and all(candidate is not store for store in stores):
|
|
|
|
|
|
stores.append(candidate)
|
2026-11-12 00:45:11 +00:00
|
|
|
|
for position, store in enumerate(stores):
|
2026-06-13 20:35:58 +01:00
|
|
|
|
for envelope in store.pull_all():
|
2026-06-27 14:34:53 +01:00
|
|
|
|
document = self._resolve_document_for_envelope(envelope)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
if document is None:
|
2026-11-12 00:45:11 +00:00
|
|
|
|
entry = envelope.catalog_entry
|
|
|
|
|
|
held_name = entry.schema_name if entry is not None else envelope.type
|
|
|
|
|
|
self._claim_key(type_at_key, envelope.key, held_name, position)
|
|
|
|
|
|
foreign.append(
|
|
|
|
|
|
ForeignRecord(envelope.key, envelope.schema_id or envelope.type, held_name, envelope.stored_at)
|
|
|
|
|
|
)
|
|
|
|
|
|
continue
|
2026-06-27 14:34:53 +01:00
|
|
|
|
if envelope.type != document.type:
|
|
|
|
|
|
envelope = CultCacheEnvelope(
|
|
|
|
|
|
key=envelope.key,
|
|
|
|
|
|
type=document.type,
|
|
|
|
|
|
payload=envelope.payload,
|
|
|
|
|
|
stored_at=envelope.stored_at,
|
|
|
|
|
|
schema_id=envelope.schema_id,
|
|
|
|
|
|
catalog_entry=envelope.catalog_entry,
|
|
|
|
|
|
)
|
2026-09-14 00:50:48 +02:00
|
|
|
|
home = routes.get(envelope.type, generic)
|
|
|
|
|
|
if home is not store:
|
|
|
|
|
|
raise CultCacheError(
|
|
|
|
|
|
f"{envelope.type} record {envelope.key} was loaded from {self._describe(store, routes, generic)}, "
|
|
|
|
|
|
f"but its home is {self._describe(home, routes, generic)}"
|
|
|
|
|
|
)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
if document.global_document:
|
2026-09-14 00:57:09 +02:00
|
|
|
|
if envelope.type in seen_globals:
|
2026-06-13 20:35:58 +01:00
|
|
|
|
raise CultCacheError(f"Duplicate global document for type: {envelope.type}")
|
|
|
|
|
|
seen_globals.add(envelope.type)
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
if envelope.key != GLOBAL_KEY:
|
|
|
|
|
|
loaded_legacy_global_keys[envelope.type] = envelope.key
|
|
|
|
|
|
envelope = replace(envelope, key=GLOBAL_KEY)
|
2026-11-12 00:45:11 +00:00
|
|
|
|
self._claim_key(type_at_key, envelope.key, envelope.type, position)
|
2026-11-12 04:24:07 +00:00
|
|
|
|
arrived, envelope = envelope, self._stamped(document, envelope)
|
|
|
|
|
|
value, unread = self._decode_marked(document, arrived)
|
|
|
|
|
|
if unread is not None:
|
|
|
|
|
|
loaded_unread[envelope.key] = (envelope.type, unread)
|
2026-09-14 00:50:48 +02:00
|
|
|
|
loaded_values.setdefault(envelope.type, {})[envelope.key] = value
|
2026-11-11 11:48:38 +00:00
|
|
|
|
read_values[(envelope.type, envelope.key)] = value
|
2026-09-14 00:50:48 +02:00
|
|
|
|
loaded_envelopes.setdefault(envelope.type, {})[envelope.key] = envelope
|
2026-09-14 11:48:59 +02:00
|
|
|
|
loaded_names, loaded_indexes, loaded_lookup_keys = self._derive_lookups(
|
2026-11-11 11:48:38 +00:00
|
|
|
|
[(type, key, value) for (type, key), value in read_values.items()], self._state.name_extractors, self._state.index_extractors
|
2026-09-14 11:48:59 +02:00
|
|
|
|
)
|
Build the whole next state before a pull swaps it in
A pull is all-or-nothing, but TS cleared the cache and then ran user name and
index accessors while re-applying entries, and Python swapped values in and
then rebuilt lookups. An accessor that threw left the cache partly loaded.
TS: the hydrated maps (entries, type entry ids, name and index lookups, global
keys) are one HydratedState. The pull builds a fresh one, running every check
and accessor, and replaces #hydrated in one assignment at the end. The
reset-then-apply sequence, #resetHydratedState, the staged global-key map and
the three per-map getOrCreate helpers are deleted; apply/remove take the
target state. The duplicate-global check now lives only in apply. Name and
index lookup rebuilds build a local map before assigning.
Python: the pull derives names and indexes into local dicts and assigns
values, envelopes, names and indexes together; _rebuild_indexes delegates to
the same pure _derive_lookups.
Rust already stages into a local map and assigns self.entries last, with no
derived lookups; unchanged.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 01:03:30 +02:00
|
|
|
|
# Plain attribute assignments: nothing fallible runs once the swap begins.
|
|
|
|
|
|
(
|
|
|
|
|
|
self._state.values,
|
|
|
|
|
|
self._state.envelopes,
|
|
|
|
|
|
self._state.names,
|
|
|
|
|
|
self._state.indexes,
|
2026-09-14 11:48:59 +02:00
|
|
|
|
self._state.lookup_keys,
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
self._state.legacy_global_keys,
|
2026-11-12 00:45:11 +00:00
|
|
|
|
self._state.foreign,
|
2026-11-12 04:24:07 +00:00
|
|
|
|
self._state.unread,
|
2026-11-12 00:45:11 +00:00
|
|
|
|
) = (
|
|
|
|
|
|
loaded_values,
|
|
|
|
|
|
loaded_envelopes,
|
|
|
|
|
|
loaded_names,
|
|
|
|
|
|
loaded_indexes,
|
|
|
|
|
|
loaded_lookup_keys,
|
|
|
|
|
|
loaded_legacy_global_keys,
|
|
|
|
|
|
sorted(foreign, key=lambda record: _utf16_order(record.key)),
|
2026-11-12 04:24:07 +00:00
|
|
|
|
loaded_unread,
|
2026-11-12 00:45:11 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _claim_key(type_at_key: dict[str, tuple[str, int]], key: str, type: str, store: int) -> None:
|
|
|
|
|
|
"""A key holds one record whatever its type, across every store a load reads. The refusal names the key and both types,
|
|
|
|
|
|
never a payload."""
|
|
|
|
|
|
held, held_store = type_at_key.setdefault(key, (type, store))
|
|
|
|
|
|
if held != type or held_store != store:
|
|
|
|
|
|
raise CultCacheError(f"Record {key!r} is held by both {held} and {type}: a key holds one record; the load admitted nothing.")
|
|
|
|
|
|
|
|
|
|
|
|
def foreign_records(self) -> list[ForeignRecord]:
|
|
|
|
|
|
"""The records the last load read that no registered type claims, sorted by key (UTF-16 code-unit order)."""
|
|
|
|
|
|
return list(self._state.foreign)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
|
|
|
|
|
def get(self, document: DocumentDefinition[T], key: str) -> T | None:
|
|
|
|
|
|
self._assert_registered(document)
|
2026-06-14 15:12:40 +01:00
|
|
|
|
values = self._state.values.get(document.type)
|
|
|
|
|
|
return None if values is None else values.get(key)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
|
|
|
|
|
def get_required(self, document: DocumentDefinition[T], key: str) -> T:
|
|
|
|
|
|
value = self.get(document, key)
|
|
|
|
|
|
if value is None:
|
|
|
|
|
|
raise CultCacheError(f"Missing {document.type}:{key}")
|
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
def get_all(self, document: DocumentDefinition[T]) -> list[T]:
|
|
|
|
|
|
self._assert_registered(document)
|
2026-06-14 15:12:40 +01:00
|
|
|
|
return list(self._state.values.get(document.type, {}).values())
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
|
|
|
|
|
def get_envelope(self, document: DocumentDefinition[Any], key: str) -> CultCacheEnvelope | None:
|
|
|
|
|
|
self._assert_registered(document)
|
2026-06-14 15:12:40 +01:00
|
|
|
|
envelopes = self._state.envelopes.get(document.type)
|
|
|
|
|
|
return None if envelopes is None else envelopes.get(key)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
|
|
|
|
|
def get_required_envelope(self, document: DocumentDefinition[Any], key: str) -> CultCacheEnvelope:
|
|
|
|
|
|
envelope = self.get_envelope(document, key)
|
|
|
|
|
|
if envelope is None:
|
|
|
|
|
|
raise CultCacheError(f"Missing envelope {document.type}:{key}")
|
|
|
|
|
|
return envelope
|
|
|
|
|
|
|
|
|
|
|
|
def get_global(self, document: DocumentDefinition[T]) -> T | None:
|
|
|
|
|
|
self._assert_global(document)
|
|
|
|
|
|
return self.get(document, GLOBAL_KEY)
|
|
|
|
|
|
|
|
|
|
|
|
def get_required_global(self, document: DocumentDefinition[T]) -> T:
|
|
|
|
|
|
self._assert_global(document)
|
|
|
|
|
|
return self.get_required(document, GLOBAL_KEY)
|
|
|
|
|
|
|
|
|
|
|
|
def get_key_by_name(self, document: DocumentDefinition[Any], name: str) -> str | None:
|
|
|
|
|
|
self._assert_registered(document)
|
|
|
|
|
|
return self._state.names.get((document.type, name))
|
|
|
|
|
|
|
2026-09-14 12:03:45 +02:00
|
|
|
|
# Name and index resolution read the lookup and then the values, two structures a pull swaps and a
|
|
|
|
|
|
# write updates in sequence, so they hold the lock to resolve a key and its value from one state.
|
|
|
|
|
|
@_locked
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def get_by_name(self, document: DocumentDefinition[T], name: str) -> T | None:
|
|
|
|
|
|
key = self.get_key_by_name(document, name)
|
|
|
|
|
|
return None if key is None else self.get(document, key)
|
|
|
|
|
|
|
|
|
|
|
|
def get_key_by_index(self, document: DocumentDefinition[Any], index: str, value: str) -> str | None:
|
|
|
|
|
|
self._assert_registered(document)
|
|
|
|
|
|
return self._state.indexes.get((document.type, index, value))
|
|
|
|
|
|
|
2026-09-14 12:03:45 +02:00
|
|
|
|
@_locked
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def get_by_index(self, document: DocumentDefinition[T], index: str, value: str) -> T | None:
|
|
|
|
|
|
key = self.get_key_by_index(document, index, value)
|
|
|
|
|
|
return None if key is None else self.get(document, key)
|
|
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def put(self, document: DocumentDefinition[T], key: str, value: T) -> None:
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
self._put(document, key, value)
|
|
|
|
|
|
|
|
|
|
|
|
def _put(self, document: DocumentDefinition[T], key: str, value: T) -> None:
|
2026-06-13 20:35:58 +01:00
|
|
|
|
self._assert_registered(document)
|
|
|
|
|
|
if document.global_document and key != GLOBAL_KEY:
|
|
|
|
|
|
raise CultCacheError(f"Global document {document.type} must use key {GLOBAL_KEY}")
|
|
|
|
|
|
catalog_entry = document.catalog_entry()
|
|
|
|
|
|
envelope = CultCacheEnvelope.create(
|
|
|
|
|
|
key=key,
|
|
|
|
|
|
type=document.type,
|
|
|
|
|
|
payload=document.encode_payload(value),
|
|
|
|
|
|
schema_id=catalog_entry.schema_id,
|
|
|
|
|
|
catalog_entry=catalog_entry,
|
|
|
|
|
|
)
|
2026-09-14 11:48:59 +02:00
|
|
|
|
self._write(document, [(envelope, value)], batch=False)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def put_envelope(self, document: DocumentDefinition[T], envelope: CultCacheEnvelope) -> T:
|
|
|
|
|
|
self._assert_registered(document)
|
2026-09-14 11:48:59 +02:00
|
|
|
|
self._check_envelope(document, envelope)
|
2026-11-12 04:24:07 +00:00
|
|
|
|
arrived, envelope = envelope, self._stamped(document, envelope)
|
|
|
|
|
|
value, unread = self._decode_marked(document, envelope)
|
|
|
|
|
|
self._write(document, [(envelope, value)], batch=False, unread={envelope.key: unread})
|
2026-06-13 20:35:58 +01:00
|
|
|
|
return value
|
|
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 23:40:53 +01:00
|
|
|
|
def put_envelopes(self, document: DocumentDefinition[T], envelopes: list[CultCacheEnvelope]) -> list[T]:
|
|
|
|
|
|
self._assert_registered(document)
|
|
|
|
|
|
values: list[T] = []
|
2026-09-30 06:54:18 +02:00
|
|
|
|
stamped: list[CultCacheEnvelope] = []
|
2026-11-12 04:24:07 +00:00
|
|
|
|
unread: dict[str, UnreadSlots | None] = {}
|
2026-06-13 23:40:53 +01:00
|
|
|
|
for envelope in envelopes:
|
2026-09-14 11:48:59 +02:00
|
|
|
|
self._check_envelope(document, envelope)
|
2026-09-30 06:54:18 +02:00
|
|
|
|
stamped.append(self._stamped(document, envelope))
|
2026-11-12 04:24:07 +00:00
|
|
|
|
value, unread[envelope.key] = self._decode_marked(document, stamped[-1])
|
|
|
|
|
|
values.append(value)
|
|
|
|
|
|
self._write(document, list(zip(stamped, values)), batch=True, unread=unread)
|
2026-09-14 11:48:59 +02:00
|
|
|
|
return values
|
2026-06-13 23:40:53 +01:00
|
|
|
|
|
2026-11-12 04:24:07 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _decode_marked(document: DocumentDefinition[Any], held_as: CultCacheEnvelope) -> tuple[Any, UnreadSlots | None]:
|
|
|
|
|
|
"""The payload decoded under the document, with the mark of any slot it carried past the declared ones, or no mark when the
|
|
|
|
|
|
loss is consented. `held_as` is the envelope under the id the record is stored under: a load's arrival, a write's stamped
|
|
|
|
|
|
envelope, so a key is writable in memory exactly when it is after a reload. A depth-0 mark is consented only when that id is
|
|
|
|
|
|
one the document lists compatible and its catalog entry has slots past the document's that cover the mark's slot count (the
|
|
|
|
|
|
loss a compatible-id declaration consents to, cultlib-gaps:ruling:slot-mark-consent). Any other mark keeps the record read-only."""
|
|
|
|
|
|
value, slots = document.decode_payload_marked(held_as.payload)
|
|
|
|
|
|
if slots is None:
|
|
|
|
|
|
return value, None
|
|
|
|
|
|
entry, stored = document.catalog_entry(), held_as.catalog_entry
|
|
|
|
|
|
if slots.depth0_only and stored is not None and held_as.schema_id in entry.compatible_schema_ids and held_as.schema_id != entry.schema_id:
|
|
|
|
|
|
declared = {member.slot for member in entry.members}
|
|
|
|
|
|
reported = [member.slot for member in stored.members if member.slot not in declared]
|
|
|
|
|
|
if reported and slots.slot_count <= max(reported) + 1:
|
|
|
|
|
|
return value, None
|
|
|
|
|
|
return value, slots
|
|
|
|
|
|
|
2026-09-30 06:54:18 +02:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _stamped(document: DocumentDefinition[Any], envelope: CultCacheEnvelope) -> CultCacheEnvelope:
|
|
|
|
|
|
"""The record under its registered schema's id, whatever id the envelope arrived under, so the catalog entry a store
|
|
|
|
|
|
writes is the one its schema id names."""
|
|
|
|
|
|
entry = document.catalog_entry()
|
|
|
|
|
|
return replace(envelope, schema_id=entry.schema_id, catalog_entry=entry)
|
|
|
|
|
|
|
2026-09-14 11:48:59 +02:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _check_envelope(document: DocumentDefinition[Any], envelope: CultCacheEnvelope) -> None:
|
|
|
|
|
|
if envelope.type != document.type:
|
|
|
|
|
|
raise CultCacheError(
|
|
|
|
|
|
f"Envelope type {envelope.type} does not match document type {document.type}"
|
|
|
|
|
|
)
|
|
|
|
|
|
if not envelope.key or not envelope.key.strip():
|
|
|
|
|
|
raise CultCacheError(f"Envelope key for document type {document.type} must be non-empty")
|
|
|
|
|
|
if document.global_document and envelope.key != GLOBAL_KEY:
|
|
|
|
|
|
raise CultCacheError(f"Global document {document.type} must use key {GLOBAL_KEY}")
|
|
|
|
|
|
|
|
|
|
|
|
def _write(
|
2026-11-12 04:24:07 +00:00
|
|
|
|
self,
|
|
|
|
|
|
document: DocumentDefinition[Any],
|
|
|
|
|
|
records: list[tuple[CultCacheEnvelope, Any]],
|
|
|
|
|
|
*,
|
|
|
|
|
|
batch: bool,
|
|
|
|
|
|
unread: dict[str, UnreadSlots | None] | None = None,
|
2026-09-14 11:48:59 +02:00
|
|
|
|
) -> None:
|
|
|
|
|
|
"""Validates every record (home and name and index extractors included) before the store is
|
|
|
|
|
|
touched; once the store accepts, applying to the cache has no fallible step."""
|
|
|
|
|
|
type = document.type
|
2026-11-11 06:59:08 +00:00
|
|
|
|
# A batch naming a key twice lands the last record for it, as C# CultCacheBatch stages one operation per key. The
|
|
|
|
|
|
# judge, the store and the apply all read this one list.
|
|
|
|
|
|
records = list({envelope.key: (envelope, value) for envelope, value in records}.values())
|
2026-11-12 04:24:07 +00:00
|
|
|
|
self._refuse_unread([envelope.key for envelope, _ in records])
|
2026-09-14 11:48:59 +02:00
|
|
|
|
name_extractor = self._state.name_extractors.get(type)
|
|
|
|
|
|
index_extractors = self._state.index_extractors.get(type, {})
|
|
|
|
|
|
admitted = [
|
|
|
|
|
|
(envelope, value, self._lookup_keys_for(value, name_extractor, index_extractors))
|
|
|
|
|
|
for envelope, value in records
|
|
|
|
|
|
]
|
2026-11-12 00:45:11 +00:00
|
|
|
|
displaced = self._refuse_retype(document, [envelope for envelope, _ in records])
|
2026-11-11 06:59:08 +00:00
|
|
|
|
self._refuse_index_sharing(
|
|
|
|
|
|
[(type, envelope.key, keys) for envelope, _, keys in admitted],
|
|
|
|
|
|
self._state.indexes,
|
|
|
|
|
|
{(type, envelope.key) for envelope, _ in records},
|
|
|
|
|
|
)
|
2026-09-14 11:48:59 +02:00
|
|
|
|
store = self._store_for_type(type)
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
legacy_key = self._state.legacy_global_keys.get(type)
|
2026-09-14 00:37:31 +02:00
|
|
|
|
if store is not None:
|
2026-09-14 11:48:59 +02:00
|
|
|
|
if batch:
|
|
|
|
|
|
store.push_all([envelope for envelope, _ in records])
|
|
|
|
|
|
else:
|
|
|
|
|
|
store.push(records[0][0])
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
if legacy_key is not None:
|
|
|
|
|
|
self._retire_legacy_global(store, type, legacy_key)
|
|
|
|
|
|
self._state.legacy_global_keys.pop(type, None)
|
2026-09-14 11:48:59 +02:00
|
|
|
|
values = self._state.values.setdefault(type, {})
|
|
|
|
|
|
envelopes = self._state.envelopes.setdefault(type, {})
|
|
|
|
|
|
lookup_keys = self._state.lookup_keys.setdefault(type, {})
|
2026-11-12 00:45:11 +00:00
|
|
|
|
for other, key in displaced:
|
|
|
|
|
|
self._drop(other, key)
|
2026-09-14 11:48:59 +02:00
|
|
|
|
for envelope, value, keys in admitted:
|
|
|
|
|
|
self._remove_lookups(type, envelope.key)
|
|
|
|
|
|
values[envelope.key] = value
|
|
|
|
|
|
envelopes[envelope.key] = envelope
|
2026-11-12 04:24:07 +00:00
|
|
|
|
# A held mark refused this write above, so a key reaching here carries none to clear.
|
|
|
|
|
|
if (mark := (unread or {}).get(envelope.key)) is not None:
|
|
|
|
|
|
self._state.unread[envelope.key] = (type, mark)
|
2026-09-14 11:48:59 +02:00
|
|
|
|
lookup_keys[envelope.key] = keys
|
|
|
|
|
|
if keys.name is not None:
|
|
|
|
|
|
self._state.names[(type, keys.name)] = envelope.key
|
|
|
|
|
|
for index, index_value in keys.indexes.items():
|
|
|
|
|
|
self._state.indexes[(type, index, index_value)] = envelope.key
|
2026-06-13 23:40:53 +01:00
|
|
|
|
|
2026-11-12 00:45:11 +00:00
|
|
|
|
def _refuse_retype(self, document: DocumentDefinition[Any], written: list[CultCacheEnvelope]) -> list[tuple[str, str]]:
|
|
|
|
|
|
"""The one key-identity judge (variants:ruling:cache-refuses-retype): a key holds one record whatever its type, so a write
|
|
|
|
|
|
may not land at a key this cache holds another type's record at, unless the written type owns that record's schema id
|
|
|
|
|
|
(the single-file store's commit guard asks the same question of the file), and may not land at a key a store carries
|
|
|
|
|
|
foreign. Returns the (type, key) records an owning write replaces; refuses, changing nothing, otherwise."""
|
|
|
|
|
|
replaced: list[tuple[str, str]] = []
|
|
|
|
|
|
foreign = {record.key: record for record in self._state.foreign}
|
|
|
|
|
|
for envelope in written:
|
|
|
|
|
|
carried = foreign.get(envelope.key)
|
|
|
|
|
|
if carried is not None:
|
|
|
|
|
|
raise self._foreign_refusal(carried)
|
|
|
|
|
|
for other, held_envelopes in self._state.envelopes.items():
|
|
|
|
|
|
held = held_envelopes.get(envelope.key)
|
|
|
|
|
|
if other == document.type or held is None:
|
|
|
|
|
|
continue
|
|
|
|
|
|
if not written_owns(held, envelope) or self._store_for_type(other) is not self._store_for_type(document.type):
|
|
|
|
|
|
raise retyped(held, envelope)
|
|
|
|
|
|
replaced.append((other, envelope.key))
|
|
|
|
|
|
return replaced
|
|
|
|
|
|
|
2026-11-12 04:24:07 +00:00
|
|
|
|
@_locked
|
|
|
|
|
|
def is_writable(self, document: DocumentDefinition[Any], key: str) -> bool:
|
|
|
|
|
|
"""Whether a write or removal of the key by this document would pass the judges that run before any store is touched: False for
|
|
|
|
|
|
a record held read-only (its payload carried slots past the declared ones, at any depth, and nothing consents to the loss, so
|
|
|
|
|
|
writing it would drop data a newer writer stored), for a key a store carries foreign, and for a key held as another type's
|
|
|
|
|
|
record this document does not own. Advisory (the write still decides): it answers at call time, and a key nothing holds is
|
|
|
|
|
|
writable."""
|
|
|
|
|
|
self._assert_registered(document)
|
|
|
|
|
|
try:
|
|
|
|
|
|
self._refuse_at(document, key)
|
|
|
|
|
|
except (SchemaConflictError, CultCacheError):
|
|
|
|
|
|
return False
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
|
|
def _refuse_at(self, document: DocumentDefinition[Any], key: str) -> list[tuple[str, str]]:
|
|
|
|
|
|
"""The judges a write or removal of the key by this document passes before any store is touched, asked by `is_writable` and
|
|
|
|
|
|
by `delete`: a global document writes only its global key, a record held read-only is never replaced, and a key held as
|
|
|
|
|
|
another type's record or carried foreign is refused (`_refuse_retype`)."""
|
|
|
|
|
|
if document.global_document and key != GLOBAL_KEY:
|
|
|
|
|
|
raise CultCacheError(f"Global document {document.type} must use key {GLOBAL_KEY}")
|
|
|
|
|
|
self._refuse_unread([key])
|
|
|
|
|
|
entry = document.catalog_entry()
|
|
|
|
|
|
probe = CultCacheEnvelope.create(key=key, type=document.type, payload=b"", schema_id=entry.schema_id, catalog_entry=entry)
|
|
|
|
|
|
return self._refuse_retype(document, [probe])
|
|
|
|
|
|
|
|
|
|
|
|
def _refuse_unread(self, keys: list[str]) -> None:
|
|
|
|
|
|
"""The one check every write and removal asks before any store is touched."""
|
|
|
|
|
|
for key in keys:
|
|
|
|
|
|
held = self._state.unread.get(key)
|
|
|
|
|
|
if held is None:
|
|
|
|
|
|
continue
|
|
|
|
|
|
type, slots = held
|
|
|
|
|
|
raise SchemaConflictError(
|
|
|
|
|
|
self._state.envelopes[type][key].schema_id or type,
|
|
|
|
|
|
[self._state.documents[type].catalog_entry().schema_name],
|
|
|
|
|
|
key,
|
|
|
|
|
|
message=(
|
|
|
|
|
|
f"{self._state.documents[type].catalog_entry().schema_name} record {key} is read-only: {slots.type_name} was read with "
|
|
|
|
|
|
f"{slots.slot_count} slots where this build declares {slots.declared_count} ({slots.occurrences} object(s) in the "
|
|
|
|
|
|
"record). Writing it would drop data a newer writer stored; read it with types that declare those slots, or "
|
|
|
|
|
|
"write it from that build."
|
|
|
|
|
|
),
|
|
|
|
|
|
unread_slots=slots,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2026-11-12 00:45:11 +00:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _foreign_refusal(record: ForeignRecord) -> SchemaConflictError:
|
|
|
|
|
|
return SchemaConflictError(
|
|
|
|
|
|
record.schema_id,
|
|
|
|
|
|
[record.schema_name],
|
|
|
|
|
|
record.key,
|
|
|
|
|
|
message=(
|
|
|
|
|
|
f"Record {record.key!r} is held by the store as a {record.schema_name} (schema id {record.schema_id!r}) that no "
|
|
|
|
|
|
"registered type claims; a write or removal there would replace what this cache cannot read. Register the type "
|
|
|
|
|
|
"that owns the schema id, or remove the record with the runtime that wrote it."
|
|
|
|
|
|
),
|
|
|
|
|
|
)
|
|
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _retire_legacy_global(store: BackingStore, type: str, legacy_key: str) -> None:
|
|
|
|
|
|
"""The first write of a global loaded from a legacy key removes that record in the same write. If
|
|
|
|
|
|
the removal fails, the new record is taken back out, so the store keeps only the legacy record."""
|
|
|
|
|
|
try:
|
|
|
|
|
|
store.delete(type, legacy_key)
|
|
|
|
|
|
except BaseException:
|
|
|
|
|
|
try:
|
|
|
|
|
|
store.delete(type, GLOBAL_KEY)
|
|
|
|
|
|
except Exception: # noqa: BLE001 - the removal failure is the error reported
|
|
|
|
|
|
pass
|
|
|
|
|
|
raise
|
|
|
|
|
|
|
|
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def put_global(self, document: DocumentDefinition[T], value: T) -> None:
|
|
|
|
|
|
self._assert_global(document)
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
self._put(document, GLOBAL_KEY, value)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def update(self, document: DocumentDefinition[T], key: str, updater: Any) -> T:
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
return self._update(document, key, updater)
|
|
|
|
|
|
|
|
|
|
|
|
def _update(self, document: DocumentDefinition[T], key: str, updater: Any) -> T:
|
2026-06-13 20:35:58 +01:00
|
|
|
|
current = self.get_required(document, key)
|
|
|
|
|
|
updated = updater(current)
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
self._put(document, key, updated)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
return updated
|
|
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def update_global(self, document: DocumentDefinition[T], updater: Any) -> T:
|
|
|
|
|
|
self._assert_global(document)
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
return self._update(document, GLOBAL_KEY, updater)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def delete(self, document: DocumentDefinition[Any], key: str) -> None:
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
self._delete(document, key)
|
|
|
|
|
|
|
|
|
|
|
|
def _delete(self, document: DocumentDefinition[Any], key: str) -> None:
|
2026-06-13 20:35:58 +01:00
|
|
|
|
self._assert_registered(document)
|
2026-11-12 04:24:07 +00:00
|
|
|
|
# A key held as another type's record this document owns is removed, as a write of the key would replace it (C# Remove is by key).
|
|
|
|
|
|
owned = self._refuse_at(document, key)
|
2026-09-14 00:37:31 +02:00
|
|
|
|
store = self._store_for_type(document.type)
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
legacy_key = self._state.legacy_global_keys.get(document.type) if key == GLOBAL_KEY else None
|
2026-09-14 00:37:31 +02:00
|
|
|
|
if store is not None:
|
2026-11-12 04:24:07 +00:00
|
|
|
|
# One record per key: the owned record when this document does not hold the key, else its own, in one store call.
|
|
|
|
|
|
holder = owned[0][0] if owned else document.type
|
|
|
|
|
|
store.delete(holder, key if legacy_key is None else legacy_key)
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
if legacy_key is not None:
|
|
|
|
|
|
del self._state.legacy_global_keys[document.type]
|
2026-11-12 04:24:07 +00:00
|
|
|
|
for other, _ in owned:
|
|
|
|
|
|
self._drop(other, key)
|
2026-11-12 00:45:11 +00:00
|
|
|
|
self._drop(document.type, key)
|
|
|
|
|
|
|
|
|
|
|
|
def _drop(self, type: str, key: str) -> None:
|
|
|
|
|
|
"""Removes the held record and its lookups from the cache's maps; the store is the caller's."""
|
|
|
|
|
|
self._remove_lookups(type, key)
|
2026-09-14 11:48:59 +02:00
|
|
|
|
for by_type in (self._state.values, self._state.envelopes, self._state.lookup_keys):
|
2026-11-12 00:45:11 +00:00
|
|
|
|
held = by_type.get(type)
|
2026-09-14 11:48:59 +02:00
|
|
|
|
if held is not None:
|
|
|
|
|
|
held.pop(key, None)
|
|
|
|
|
|
if not held:
|
2026-11-12 00:45:11 +00:00
|
|
|
|
by_type.pop(type, None)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
@_mutating
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def delete_global(self, document: DocumentDefinition[Any]) -> None:
|
|
|
|
|
|
self._assert_global(document)
|
Refuse re-entrant Python cache mutations and adopt legacy-key globals on load
Attach, pull, registration, writes and deletes raise when started on a
thread already inside a mutation of the same cache (a store call,
decoder, encoder, extractor or updater), instead of running inside it
and corrupting the state being built. Reads stay reentrant. Internal
delegation (put_global, update, delete_global, register_registry,
add_backing_store) goes through private helpers so it is not re-entry.
A pull adopts a global persisted under a key other than __global__ as
that type's global without writing. The first write or delete of it
removes the legacy record in the same call; a failed removal takes the
new record back out. Two globals of one type on disk are still refused.
The lock and unlocked-read comments now state the per-call guarantee.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:27:55 +02:00
|
|
|
|
self._delete(document, GLOBAL_KEY)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
2026-09-14 12:03:45 +02:00
|
|
|
|
# Snapshots iterate dicts a concurrent write would resize mid-iteration, so they hold the lock.
|
|
|
|
|
|
@_locked
|
2026-06-13 20:35:58 +01:00
|
|
|
|
def snapshot(self) -> dict[str, dict[str, Any]]:
|
|
|
|
|
|
out: dict[str, dict[str, Any]] = {}
|
2026-06-14 15:12:40 +01:00
|
|
|
|
for type, values in self._state.values.items():
|
|
|
|
|
|
out[type] = dict(values)
|
2026-06-13 20:35:58 +01:00
|
|
|
|
return out
|
|
|
|
|
|
|
2026-09-14 12:03:45 +02:00
|
|
|
|
@_locked
|
2026-06-13 21:21:51 +01:00
|
|
|
|
def snapshot_envelopes(self) -> list[CultCacheEnvelope]:
|
2026-06-14 15:12:40 +01:00
|
|
|
|
return [
|
|
|
|
|
|
envelope
|
|
|
|
|
|
for envelopes in self._state.envelopes.values()
|
|
|
|
|
|
for envelope in envelopes.values()
|
|
|
|
|
|
]
|
2026-06-13 21:21:51 +01:00
|
|
|
|
|
2026-09-14 00:37:31 +02:00
|
|
|
|
def _store_for_type(self, type: str) -> BackingStore | None:
|
|
|
|
|
|
"""The store that claims the type, else the generic store.
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
2026-09-14 00:37:31 +02:00
|
|
|
|
Returns None only for a cache with no stores, which is an in-memory cache.
|
|
|
|
|
|
"""
|
|
|
|
|
|
store = self._state.stores_by_type.get(type, self._state.generic_store)
|
|
|
|
|
|
if store is None and self._state.stores_by_type:
|
|
|
|
|
|
raise CultCacheError(f"No backing store is home to document type: {type}")
|
|
|
|
|
|
return store
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
2026-09-14 11:48:59 +02:00
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _lookup_keys_for(
|
|
|
|
|
|
value: Any, name_extractor: str | Any | None, index_extractors: dict[str, str | Any]
|
|
|
|
|
|
) -> _LookupKeys:
|
|
|
|
|
|
name = None if name_extractor is None else extract_value(value, name_extractor)
|
|
|
|
|
|
indexes: dict[str, str] = {}
|
|
|
|
|
|
for index, extractor in index_extractors.items():
|
2026-11-11 06:59:08 +00:00
|
|
|
|
index_value = index_text(extract_value(value, extractor))
|
2026-09-14 11:48:59 +02:00
|
|
|
|
if index_value is not None:
|
2026-11-11 06:59:08 +00:00
|
|
|
|
indexes[index] = index_value
|
2026-09-14 11:48:59 +02:00
|
|
|
|
return _LookupKeys(None if name is None else str(name), indexes)
|
Build the whole next state before a pull swaps it in
A pull is all-or-nothing, but TS cleared the cache and then ran user name and
index accessors while re-applying entries, and Python swapped values in and
then rebuilt lookups. An accessor that threw left the cache partly loaded.
TS: the hydrated maps (entries, type entry ids, name and index lookups, global
keys) are one HydratedState. The pull builds a fresh one, running every check
and accessor, and replaces #hydrated in one assignment at the end. The
reset-then-apply sequence, #resetHydratedState, the staged global-key map and
the three per-map getOrCreate helpers are deleted; apply/remove take the
target state. The duplicate-global check now lives only in apply. Name and
index lookup rebuilds build a local map before assigning.
Python: the pull derives names and indexes into local dicts and assigns
values, envelopes, names and indexes together; _rebuild_indexes delegates to
the same pure _derive_lookups.
Rust already stages into a local map and assigns self.entries last, with no
derived lookups; unchanged.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 01:03:30 +02:00
|
|
|
|
|
|
|
|
|
|
def _derive_lookups(
|
2026-09-14 11:48:59 +02:00
|
|
|
|
self,
|
2026-11-11 08:05:39 +00:00
|
|
|
|
records: list[tuple[str, str, Any]],
|
2026-09-14 11:48:59 +02:00
|
|
|
|
name_extractors: dict[str, str | Any],
|
|
|
|
|
|
index_extractors: dict[str, dict[str, str | Any]],
|
|
|
|
|
|
) -> tuple[_Names, _Indexes, _LookupKeysByType]:
|
2026-11-11 11:48:38 +00:00
|
|
|
|
"""Builds name and index lookups for the given (type, key, value) records, judged whole and order-free, in fresh dicts, touching no cache state."""
|
2026-09-14 11:48:59 +02:00
|
|
|
|
names: _Names = {}
|
|
|
|
|
|
indexes: _Indexes = {}
|
|
|
|
|
|
lookup_keys: _LookupKeysByType = {}
|
2026-11-11 08:05:39 +00:00
|
|
|
|
landing: list[tuple[str, str, _LookupKeys]] = []
|
|
|
|
|
|
for type, key, value in records:
|
|
|
|
|
|
keys = self._lookup_keys_for(value, name_extractors.get(type), index_extractors.get(type, {}))
|
|
|
|
|
|
lookup_keys.setdefault(type, {})[key] = keys
|
|
|
|
|
|
landing.append((type, key, keys))
|
2026-11-11 11:48:38 +00:00
|
|
|
|
# Judged whole and order-free, over every type at once and on the file alone (never against what the cache held): a held value can
|
2026-11-11 06:59:08 +00:00
|
|
|
|
# have been mutated in place since it was admitted, and another process may have moved a value between records.
|
2026-11-11 08:05:39 +00:00
|
|
|
|
self._refuse_index_sharing(landing, {}, ())
|
2026-11-11 06:59:08 +00:00
|
|
|
|
for type in lookup_keys:
|
|
|
|
|
|
for key, keys in lookup_keys.get(type, {}).items():
|
2026-09-14 11:48:59 +02:00
|
|
|
|
if keys.name is not None:
|
|
|
|
|
|
names[(type, keys.name)] = key
|
|
|
|
|
|
for index, index_value in keys.indexes.items():
|
|
|
|
|
|
indexes[(type, index, index_value)] = key
|
|
|
|
|
|
return names, indexes, lookup_keys
|
|
|
|
|
|
|
2026-11-11 06:59:08 +00:00
|
|
|
|
def _refuse_index_sharing(
|
|
|
|
|
|
self,
|
|
|
|
|
|
landing: list[tuple[str, str, _LookupKeys]],
|
|
|
|
|
|
held: dict[tuple[str, str, str], str],
|
|
|
|
|
|
replaced: Iterable[tuple[str, str]],
|
|
|
|
|
|
) -> None:
|
2026-11-11 11:48:38 +00:00
|
|
|
|
"""The one index rule (variants:ruling:unique-indexes): within one type and one unique alias, no two records hold one
|
|
|
|
|
|
non-blank value, judged on the state the admission would leave and never on staging, file or pull order. The holders
|
|
|
|
|
|
of a value are the landing keys projecting it plus the held key unless this admission replaces it. Of every
|
|
|
|
|
|
(type, alias, value) with two or more distinct holders, the refusal names the least by (alias, its least key, its
|
|
|
|
|
|
second-least key, schema name), each compared by UTF-16 code unit, never the value."""
|
2026-11-11 06:59:08 +00:00
|
|
|
|
released = set(replaced)
|
|
|
|
|
|
landed: dict[tuple[str, str, str], list[str]] = {}
|
|
|
|
|
|
for type, key, keys in landing:
|
|
|
|
|
|
for index, index_value in keys.indexes.items():
|
|
|
|
|
|
landed.setdefault((type, index, index_value), []).append(key)
|
2026-11-11 11:48:38 +00:00
|
|
|
|
violations: list[tuple[bytes, bytes, bytes, bytes, str, str, str, str]] = []
|
|
|
|
|
|
for (type, index, index_value), keys in landed.items():
|
2026-11-11 06:59:08 +00:00
|
|
|
|
held_key = held.get((type, index, index_value))
|
|
|
|
|
|
if held_key is not None and (type, held_key) not in released:
|
|
|
|
|
|
keys = [*keys, held_key]
|
2026-11-11 11:48:38 +00:00
|
|
|
|
distinct = sorted(keys, key=_utf16_order)
|
2026-11-11 06:59:08 +00:00
|
|
|
|
if len(distinct) > 1:
|
|
|
|
|
|
document = self._state.documents.get(type)
|
|
|
|
|
|
schema_name = (document.schema_name if document is not None else None) or type
|
2026-11-11 11:48:38 +00:00
|
|
|
|
violations.append(
|
|
|
|
|
|
(_utf16_order(index), _utf16_order(distinct[0]), _utf16_order(distinct[1]), _utf16_order(schema_name),
|
|
|
|
|
|
index, distinct[0], distinct[1], schema_name)
|
2026-11-11 06:59:08 +00:00
|
|
|
|
)
|
2026-11-11 11:48:38 +00:00
|
|
|
|
if violations:
|
|
|
|
|
|
*_, index, first, second, schema_name = min(violations, key=lambda violation: violation[:4])
|
|
|
|
|
|
raise CultCacheError(
|
|
|
|
|
|
f"Records {first} and {second} ({schema_name}) both hold unique index '{index}'; "
|
|
|
|
|
|
"an index value names one record."
|
|
|
|
|
|
)
|
2026-11-11 06:59:08 +00:00
|
|
|
|
|
2026-09-14 11:48:59 +02:00
|
|
|
|
def _remove_lookups(self, type: str, key: str) -> None:
|
2026-11-11 06:59:08 +00:00
|
|
|
|
"""Removes the lookups the held record produced at admission, handing a name to another held
|
|
|
|
|
|
record that produced it too (an index value has one holder). Reads stored lookup keys only; runs no extractor."""
|
2026-09-14 11:48:59 +02:00
|
|
|
|
held = self._state.lookup_keys.get(type, {})
|
|
|
|
|
|
keys = held.get(key)
|
|
|
|
|
|
if keys is None:
|
2026-06-14 01:37:35 +01:00
|
|
|
|
return
|
2026-09-14 11:48:59 +02:00
|
|
|
|
if keys.name is not None and self._state.names.get((type, keys.name)) == key:
|
|
|
|
|
|
del self._state.names[(type, keys.name)]
|
|
|
|
|
|
for candidate_key, candidate in held.items():
|
|
|
|
|
|
if candidate_key != key and candidate.name == keys.name:
|
|
|
|
|
|
self._state.names[(type, keys.name)] = candidate_key
|
|
|
|
|
|
for index, index_value in keys.indexes.items():
|
|
|
|
|
|
lookup_key = (type, index, index_value)
|
|
|
|
|
|
if self._state.indexes.get(lookup_key) != key:
|
|
|
|
|
|
continue
|
|
|
|
|
|
del self._state.indexes[lookup_key]
|
2026-06-13 20:35:58 +01:00
|
|
|
|
|
|
|
|
|
|
def _assert_registered(self, document: DocumentDefinition[Any]) -> None:
|
|
|
|
|
|
if self._state.documents.get(document.type) is not document:
|
|
|
|
|
|
raise CultCacheError(f"Document type is not registered on this cache: {document.type}")
|
|
|
|
|
|
|
|
|
|
|
|
def _assert_global(self, document: DocumentDefinition[Any]) -> None:
|
|
|
|
|
|
self._assert_registered(document)
|
|
|
|
|
|
if not document.global_document:
|
|
|
|
|
|
raise CultCacheError(f"Document type is not global: {document.type}")
|
2026-06-27 14:34:53 +01:00
|
|
|
|
|
|
|
|
|
|
def _resolve_document_for_envelope(self, envelope: CultCacheEnvelope) -> DocumentDefinition[Any] | None:
|
Python: a document listing an id registers beside the one owning it; registration refuses typed
Owner beats lister, as in C#. A document owns its schema id; others may list it
as compatible beside its owner, in either registration order (batch 9 refused
any overlap, which forbade keeping v1 beside a v2 that declares v1's id; Soul
F8). A record resolves to the document owning its id, else to the one document
listing it. Several listers and no owner name no single document, and the load
is refused with SchemaConflictError naming the id, the record key and the
listers: refusing at registration would depend on whether the owner had
registered yet.
Every registration refusal is now SchemaConflictError (Soul F10): a second owner
of one schema id, a second document with one schema name, and a second
definition of one document type. Each names the new document's id and both
schema names and document types. Before, the last two raised CultCacheError.
Tests: an owner and a lister register in both orders and each reads its own
records, and a lister alone reads the owner's id; two listers register in both
orders, a record under their id is refused typed without its owner and is the
owner's with it, registered before or after them; two owners, one schema name
and one document type twice are each refused as a schema conflict.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:31:25 +02:00
|
|
|
|
"""A record resolves by its schema id: the document that owns the id, else the one document that lists it as compatible.
|
|
|
|
|
|
Several listers and no owner name no single document, and the record is refused. 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)."""
|
Python: a record resolves to its document by schema id, and the type check runs across tiers
A record now resolves to the document that owns its schema id, else one that lists it as
compatible, before the catalog name is tried; a schema renamed under a stable id opens, and an id
that names one document is not overruled by a name that names another. The name resolves a record
only when no local document has the id.
The writer refuses a write that would change which type an existing record resolves to, unless the
entries of both the existing records and the written ones own the id (a rename, the registered
descriptor wins).
Tests pin the arrived-overwrites-registered guard in both id orders, the content-hash tie-break
against the compatible-list order, sorted id processing, the cross-tier refusal and the rename, and
a cache whose document does not list the id a loaded record sits under.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-09-30 11:04:07 +02:00
|
|
|
|
if envelope.schema_id:
|
Python: a document listing an id registers beside the one owning it; registration refuses typed
Owner beats lister, as in C#. A document owns its schema id; others may list it
as compatible beside its owner, in either registration order (batch 9 refused
any overlap, which forbade keeping v1 beside a v2 that declares v1's id; Soul
F8). A record resolves to the document owning its id, else to the one document
listing it. Several listers and no owner name no single document, and the load
is refused with SchemaConflictError naming the id, the record key and the
listers: refusing at registration would depend on whether the owner had
registered yet.
Every registration refusal is now SchemaConflictError (Soul F10): a second owner
of one schema id, a second document with one schema name, and a second
definition of one document type. Each names the new document's id and both
schema names and document types. Before, the last two raised CultCacheError.
Tests: an owner and a lister register in both orders and each reads its own
records, and a lister alone reads the owner's id; two listers register in both
orders, a record under their id is refused typed without its owner and is the
owner's with it, registered before or after them; two owners, one schema name
and one document type twice are each refused as a schema conflict.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:31:25 +02:00
|
|
|
|
entries = [(document, document.catalog_entry()) for document in self._state.documents.values()]
|
|
|
|
|
|
for document, entry in entries:
|
|
|
|
|
|
if entry.schema_id == envelope.schema_id:
|
Python: a record resolves to its document by schema id, and the type check runs across tiers
A record now resolves to the document that owns its schema id, else one that lists it as
compatible, before the catalog name is tried; a schema renamed under a stable id opens, and an id
that names one document is not overruled by a name that names another. The name resolves a record
only when no local document has the id.
The writer refuses a write that would change which type an existing record resolves to, unless the
entries of both the existing records and the written ones own the id (a rename, the registered
descriptor wins).
Tests pin the arrived-overwrites-registered guard in both id orders, the content-hash tie-break
against the compatible-list order, sorted id processing, the cross-tier refusal and the rename, and
a cache whose document does not list the id a loaded record sits under.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-09-30 11:04:07 +02:00
|
|
|
|
return document
|
Python: a document listing an id registers beside the one owning it; registration refuses typed
Owner beats lister, as in C#. A document owns its schema id; others may list it
as compatible beside its owner, in either registration order (batch 9 refused
any overlap, which forbade keeping v1 beside a v2 that declares v1's id; Soul
F8). A record resolves to the document owning its id, else to the one document
listing it. Several listers and no owner name no single document, and the load
is refused with SchemaConflictError naming the id, the record key and the
listers: refusing at registration would depend on whether the owner had
registered yet.
Every registration refusal is now SchemaConflictError (Soul F10): a second owner
of one schema id, a second document with one schema name, and a second
definition of one document type. Each names the new document's id and both
schema names and document types. Before, the last two raised CultCacheError.
Tests: an owner and a lister register in both orders and each reads its own
records, and a lister alone reads the owner's id; two listers register in both
orders, a record under their id is refused typed without its owner and is the
owner's with it, registered before or after them; two owners, one schema name
and one document type twice are each refused as a schema conflict.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:31:25 +02:00
|
|
|
|
listers = [document for document, entry in entries if envelope.schema_id in entry.compatible_schema_ids]
|
|
|
|
|
|
if len(listers) > 1:
|
|
|
|
|
|
raise SchemaConflictError(
|
|
|
|
|
|
envelope.schema_id,
|
|
|
|
|
|
sorted(document.catalog_entry().schema_name for document in listers),
|
|
|
|
|
|
envelope.key,
|
|
|
|
|
|
message=f"Schema id {envelope.schema_id!r} of record {envelope.key!r} is owned by no registered document and "
|
|
|
|
|
|
f"declared compatible by several ({', '.join(sorted(document.type for document in listers))}), so it resolves "
|
|
|
|
|
|
"to none. Register the document that owns the id, or declare it on one document.",
|
|
|
|
|
|
)
|
|
|
|
|
|
if listers:
|
|
|
|
|
|
return listers[0]
|
2026-06-27 14:34:53 +01:00
|
|
|
|
document = self._state.documents.get(envelope.type)
|
|
|
|
|
|
if document is not None:
|
|
|
|
|
|
return document
|
|
|
|
|
|
return self._state.documents_by_schema_name.get(envelope.type)
|