Add Python CultMesh name and index watchers

This commit is contained in:
Meta Vens 2026-06-14 02:18:20 +01:00
commit 59ddafe473
4 changed files with 201 additions and 11 deletions

View file

@ -24,9 +24,11 @@ CultCache, CultNet, and CultMesh. It is evidence, not confetti.
- Python CultMesh database facade:
`node.database` owns the local typed document read/write/snapshot/sync surface
so Python callers do not need to reach through the node composition wrapper.
It also exposes local `watch(...)` / `watch_record(...)` callbacks for database
changes, including authoritative shard-log reconciliation applied through the
session facade.
It also exposes local `watch(...)`, `watch_record(...)`, `watch_by_name(...)`,
and `watch_by_index(...)` callbacks for database changes, including
authoritative shard-log reconciliation applied through the session facade.
Change notifications carry previous values when the database can observe the
old record before local or replicated application.
- Python CultMesh committed simulation facts:
The live interop harness sends Python a simulation observation, receives a
consensus candidate, then requests the committed `gamecult.mesh.simulation_fact`

View file

@ -221,13 +221,26 @@ from cultcache_py import define_database_entry_type
from cultnet_py import CultNetClientAuthorityScope, CultNetRawClient
from cultmesh_py import CultMesh, CultMeshGameSessionOptions, peer_exchange_request
note_doc = define_database_entry_type("mesh.note", [("body", 0)])
note_doc = define_database_entry_type(
"mesh.note",
[("body", 0), ("name", 1), ("kind", 2)],
name="name",
indexes={"kind": "kind"},
)
node = CultMesh.start_node("mesh.cc", runtime_id="python-runtime")
node.database.register_document(note_doc)
unsubscribe = node.database.watch_record(note_doc, "note:1", lambda change: print(change.change_kind))
node.database.put(note_doc, "note:1", {"body": "hello"})
unsubscribe_named = node.database.watch_by_name(note_doc, "intro", lambda change: print(change.record_key))
unsubscribe_kind = node.database.watch_by_index(note_doc, "kind", "guide", lambda change: print(change.record_key))
node.database.put(note_doc, "note:1", {"body": "hello", "name": "intro", "kind": "guide"})
live_note = node.database.get_required(note_doc, "note:1")
put_message = node.database.put_raw_message(note_doc, "note:2", {"body": "wire me"}, shard_id="interop", shard_epoch=1)
put_message = node.database.put_raw_message(
note_doc,
"note:2",
{"body": "wire me", "name": "wire", "kind": "interop"},
shard_id="interop",
shard_epoch=1,
)
delete_message = node.database.delete_raw_message(note_doc, "note:2", shard_id="interop", shard_epoch=1)
peers = CultMesh.create_peer_catalog()

View file

@ -5,7 +5,7 @@ from pathlib import Path
from typing import Any, Callable
from cultcache_py import CultCache, CultCacheEnvelope, SingleFileMessagePackBackingStore
from cultcache_py.documents import DocumentDefinition
from cultcache_py.documents import DocumentDefinition, extract_value
from cultnet_py import (
CultNetAppliedRecord,
CultNetMessage,
@ -171,7 +171,51 @@ class CultMeshDatabase:
) -> Callable[[], None]:
return self.watch(callback, document=document, key=key)
def watch_by_name(
self,
document: DocumentDefinition[Any],
name: str,
callback: Callable[[CultMeshDatabaseChange], None],
) -> Callable[[], None]:
if not name:
raise ValueError("Name watch values must be non-empty")
if document.name is None:
raise ValueError(f"Document type {document.type!r} has no name lookup")
def filtered(change: CultMeshDatabaseChange) -> None:
if self._change_matches_extractor(change, document.name, name):
callback(change)
return self.watch(filtered, document=document)
def watch_by_index(
self,
document: DocumentDefinition[Any],
index: str,
value: str,
callback: Callable[[CultMeshDatabaseChange], None],
) -> Callable[[], None]:
if not index:
raise ValueError("Index watch aliases must be non-empty")
if not value:
raise ValueError("Index watch values must be non-empty")
extractor = document.indexes.get(index)
if extractor is None:
raise ValueError(f"Document type {document.type!r} has no index {index!r}")
def filtered(change: CultMeshDatabaseChange) -> None:
if self._change_matches_extractor(change, extractor, value):
callback(change)
return self.watch(filtered, document=document)
def register_document(self, document: DocumentDefinition[Any]) -> None:
for registered in self.documents:
if registered.type != document.type:
continue
if registered == document:
return
raise ValueError(f"Document type {document.type!r} is already registered with a different definition")
self.cache.register_document_type(document)
self.documents.append(document)
@ -284,13 +328,15 @@ class CultMeshDatabase:
return self.apply_shard_log_response(response)
def apply_snapshot_response(self, response: dict[str, Any]) -> list[CultNetAppliedRecord]:
previous = self._previous_values_for_snapshot_response(response)
applied = apply_cultnet_raw_snapshot(self.cache, self.documents, response)
self._publish_applied_records(applied)
self._publish_applied_records(applied, previous)
return applied
def apply_shard_log_response(self, response: dict[str, Any]) -> list[CultNetAppliedRecord]:
previous = self._previous_values_for_shard_log_response(response)
applied = apply_cultnet_shard_log_response(self.cache, self.documents, response)
self._publish_applied_records(applied)
self._publish_applied_records(applied, previous)
return applied
def _publish_local_change(
@ -310,18 +356,27 @@ class CultMeshDatabase:
previous_value=previous,
))
def _publish_applied_records(self, applied: list[CultNetAppliedRecord]) -> None:
def _publish_applied_records(
self,
applied: list[CultNetAppliedRecord],
previous: dict[tuple[str, str], Any],
) -> None:
documents_by_schema_id = schema_document_map(self.documents)
for record in applied:
document = documents_by_schema_id.get(record.schema_id)
if document is None:
continue
previous_value = previous.get((record.schema_id, record.record_key))
change_kind = record.change_kind
if change_kind == "added" and previous_value is not None:
change_kind = "updated"
self._publish(CultMeshDatabaseChange(
document=document,
schema_id=record.schema_id,
record_key=record.record_key,
change_kind=record.change_kind,
change_kind=change_kind,
value=record.value,
previous_value=previous_value,
))
def _publish(self, change: CultMeshDatabaseChange) -> None:
@ -332,6 +387,70 @@ class CultMeshDatabase:
continue
callback(change)
def _change_matches_extractor(
self,
change: CultMeshDatabaseChange,
extractor: str | Callable[[Any], str | int | float | bool | None],
expected: str,
) -> bool:
return (
self._value_matches_extractor(change.value, extractor, expected)
or self._value_matches_extractor(change.previous_value, extractor, expected)
)
def _value_matches_extractor(
self,
value: Any | None,
extractor: str | Callable[[Any], str | int | float | bool | None],
expected: str,
) -> bool:
if value is None:
return False
actual = extract_value(value, extractor)
return actual is not None and str(actual) == expected
def _previous_values_for_snapshot_response(self, response: dict[str, Any]) -> dict[tuple[str, str], Any]:
if response.get("schemaVersion") != "cultnet.snapshot_response_raw.v0":
return {}
return self._previous_values_for_raw_records(response.get("documents", []))
def _previous_values_for_shard_log_response(self, response: dict[str, Any]) -> dict[tuple[str, str], Any]:
if response.get("schemaVersion") != "cultnet.shard_log_response.v0":
return {}
records: list[dict[str, Any]] = []
deletes: list[dict[str, Any]] = []
for entry in response.get("entries", []):
if not isinstance(entry, dict):
continue
if isinstance(entry.get("put"), dict) and isinstance(entry["put"].get("document"), dict):
records.append(entry["put"]["document"])
elif isinstance(entry.get("delete"), dict):
deletes.append(entry["delete"])
previous = self._previous_values_for_raw_records(records)
documents_by_schema_id = schema_document_map(self.documents)
for delete in deletes:
schema_id = str(delete.get("schemaId"))
document = documents_by_schema_id.get(schema_id)
if document is None:
continue
record_key = str(delete.get("recordKey"))
previous[(schema_id, record_key)] = self.cache.get(document, record_key)
return previous
def _previous_values_for_raw_records(self, records: Any) -> dict[tuple[str, str], Any]:
previous: dict[tuple[str, str], Any] = {}
documents_by_schema_id = schema_document_map(self.documents)
for record in records:
if not isinstance(record, dict):
continue
schema_id = str(record.get("schemaId"))
document = documents_by_schema_id.get(schema_id)
if document is None:
continue
record_key = str(record.get("recordKey"))
previous[(schema_id, record_key)] = self.cache.get(document, record_key)
return previous
def create_node(cache_path: str | Path | None = None, *, runtime_id: str = "python-runtime") -> CultMeshNode:
cache = CultCache()

View file

@ -903,6 +903,61 @@ class CultCacheTests(unittest.TestCase):
self.assertIsNone(changes[2].value)
self.assertEqual([change.record_key for change in all_changes], ["note:1", "note:2", "note:1", "note:1", "note:1"])
def test_cultmesh_database_register_document_is_idempotent(self) -> None:
document = define_database_entry_type("mesh.idempotent", [("body", 0)])
conflicting = define_database_entry_type("mesh.idempotent", [("title", 0)])
node = CultMesh.create_node(runtime_id="mesh-idempotent")
node.database.register_document(document)
node.database.register_document(document)
node.database.put(document, "note:1", {"body": "still registered once"})
self.assertEqual(node.database.get_required(document, "note:1")["body"], "still registered once")
self.assertEqual([registered.type for registered in node.documents], ["mesh.idempotent"])
with self.assertRaises(ValueError):
node.database.register_document(conflicting)
def test_cultmesh_database_watchers_observe_name_and_index_changes(self) -> None:
document = define_database_entry_type(
"mesh.named_watch",
[("name", 0), ("kind", 1)],
name="name",
indexes={"kind": "kind"},
)
node = CultMesh.create_node(runtime_id="mesh-named-watch")
node.database.register_document(document)
name_changes: list[CultMeshDatabaseChange] = []
index_changes: list[CultMeshDatabaseChange] = []
node.database.watch_by_name(document, "Potion", name_changes.append)
node.database.watch_by_index(document, "kind", "consumable", index_changes.append)
node.database.put(document, "item:1", {"name": "Potion", "kind": "consumable"})
node.database.put(document, "item:2", {"name": "Sword", "kind": "weapon"})
node.database.put(document, "item:1", {"name": "Elixir", "kind": "rare"})
node.database.delete(document, "item:1")
self.assertEqual([change.change_kind for change in name_changes], ["added", "updated"])
self.assertEqual([change.record_key for change in name_changes], ["item:1", "item:1"])
self.assertEqual(name_changes[1].previous_value, {"name": "Potion", "kind": "consumable"})
self.assertEqual([change.change_kind for change in index_changes], ["added", "updated"])
self.assertEqual([change.record_key for change in index_changes], ["item:1", "item:1"])
self.assertEqual(index_changes[1].value, {"name": "Elixir", "kind": "rare"})
def test_cultmesh_database_watch_by_name_and_index_validate_lookup_shape(self) -> None:
document = define_database_entry_type("mesh.unnamed_watch", [("body", 0)])
node = CultMesh.create_node(runtime_id="mesh-watch-validation")
node.database.register_document(document)
with self.assertRaises(ValueError):
node.database.watch_by_name(document, "missing", lambda _: None)
with self.assertRaises(ValueError):
node.database.watch_by_index(document, "missing", "value", lambda _: None)
with self.assertRaises(ValueError):
node.database.watch_by_index(document, "", "value", lambda _: None)
with self.assertRaises(ValueError):
node.database.watch_by_index(document, "missing", "", lambda _: None)
def test_cultmesh_facade_matches_peer_runtime_entrypoints(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
store_path = Path(tmp) / "mesh.cc"
@ -1196,6 +1251,7 @@ class CultCacheTests(unittest.TestCase):
self.assertEqual([change.change_kind for change in seen], ["added", "updated"])
self.assertEqual(seen[1].value, {"body": "authoritative"})
self.assertEqual(seen[1].previous_value, {"body": "predicted"})
self.assertEqual(session_changes[0].change_kind, "reconciled")
def test_cultmesh_verse_catalog_response_matches_schema_v0_wire_shape(self) -> None: