From 4d3ae1af87ca6e509239898eca06c53151954daa Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 14 Jun 2026 06:33:22 +0100 Subject: [PATCH] Persist Python shard replica cursors --- packages/cultcache-py/PARITY.md | 9 +- packages/cultcache-py/README.md | 2 + .../cultcache-py/src/cultcache_py/verify.py | 1 + .../cultcache-py/src/cultnet_py/__init__.py | 2 + .../src/cultnet_py/shard_replication.py | 58 +++++++++++++ packages/cultcache-py/tests/test_cultcache.py | 82 +++++++++++-------- 6 files changed, 115 insertions(+), 39 deletions(-) diff --git a/packages/cultcache-py/PARITY.md b/packages/cultcache-py/PARITY.md index ce663d85..344c5ff3 100644 --- a/packages/cultcache-py/PARITY.md +++ b/packages/cultcache-py/PARITY.md @@ -55,7 +55,8 @@ CultCache, CultNet, and CultMesh. It is evidence, not confetti. Provides schema-v0 shard-log and shard-snapshot fetchers plus a pull-once `CultNetShardReplicator` that tracks replica cursors, applies log responses through the existing database owner, and recovers from compacted-history - resync pressure by fetching a shard snapshot. + resync pressure by fetching a shard snapshot. Replica cursor storage can be + in-memory or restart-safe through a local MessagePack cursor file. - Python CultNet database subscription changes: Provides typed `CultNetDatabaseChange` parsing plus `CultNetDatabaseSubscription.read_next_change(...)` / `iter_changes(...)` for @@ -179,6 +180,6 @@ node --test packages\cultnet-ts\dist-test\test\interop\cultnet-interop.test.js - Python does not claim the full C# shard mutation-log service surface. It can create/apply raw snapshots, create/apply package-local raw shard-log responses, consume remote shard-log responses, and run pull-once replica - catch-up with snapshot recovery. It does not yet claim the full C# background - replicator, durable cursor file store, write-forwarder, or file-backed - authoritative mutation-log store. + catch-up with snapshot recovery and a file-backed replica cursor store. It + does not yet claim the full C# background replicator, write-forwarder, or + file-backed authoritative mutation-log store. diff --git a/packages/cultcache-py/README.md b/packages/cultcache-py/README.md index a082d0f2..d402a994 100644 --- a/packages/cultcache-py/README.md +++ b/packages/cultcache-py/README.md @@ -225,6 +225,7 @@ local prediction reconciliation: from cultcache_py import define_database_entry_type from cultnet_py import ( CultNetClientAuthorityScope, + CultNetFileShardReplicaCursorStore, CultNetRawClient, CultNetSchemaShardLogFetcher, CultNetSchemaShardSnapshotFetcher, @@ -277,6 +278,7 @@ replicator = CultNetShardReplicator( CultNetShardReplicatorOptions( fetcher=CultNetSchemaShardLogFetcher(), snapshot_fetcher=CultNetSchemaShardSnapshotFetcher(), + cursor_store=CultNetFileShardReplicaCursorStore("mesh.replica-cursors.msgpack"), ), ) replicator.pull_once(CultNetShardDescriptor( diff --git a/packages/cultcache-py/src/cultcache_py/verify.py b/packages/cultcache-py/src/cultcache_py/verify.py index 41e4aa1e..7ca367c9 100644 --- a/packages/cultcache-py/src/cultcache_py/verify.py +++ b/packages/cultcache-py/src/cultcache_py/verify.py @@ -42,6 +42,7 @@ EXPECTED_EXPORTS: dict[str, tuple[str, ...]] = { "CultNetShardDescriptor", "CultNetShardLogEntry", "CultNetShardLogResponse", + "CultNetFileShardReplicaCursorStore", "CultNetInMemoryShardReplicaCursorStore", "CultNetSchemaShardLogFetcher", "CultNetSchemaShardSnapshotFetcher", diff --git a/packages/cultcache-py/src/cultnet_py/__init__.py b/packages/cultcache-py/src/cultnet_py/__init__.py index 8ddf5cad..59058b2b 100644 --- a/packages/cultcache-py/src/cultnet_py/__init__.py +++ b/packages/cultcache-py/src/cultnet_py/__init__.py @@ -38,6 +38,7 @@ from .schema_catalog import ( from .shard_catalog import CultNetShardCatalog, CultNetShardDescriptor from .shard_log import CultNetShardLogEntry, CultNetShardLogResponse from .shard_replication import ( + CultNetFileShardReplicaCursorStore, CultNetInMemoryShardReplicaCursorStore, CultNetSchemaShardLogFetcher, CultNetSchemaShardSnapshotFetcher, @@ -70,6 +71,7 @@ __all__ = [ "CultNetShardDescriptor", "CultNetShardLogEntry", "CultNetShardLogResponse", + "CultNetFileShardReplicaCursorStore", "CultNetInMemoryShardReplicaCursorStore", "CultNetSchemaShardLogFetcher", "CultNetSchemaShardSnapshotFetcher", diff --git a/packages/cultcache-py/src/cultnet_py/shard_replication.py b/packages/cultcache-py/src/cultnet_py/shard_replication.py index 712a9f35..279d13ad 100644 --- a/packages/cultcache-py/src/cultnet_py/shard_replication.py +++ b/packages/cultcache-py/src/cultnet_py/shard_replication.py @@ -2,9 +2,12 @@ from __future__ import annotations from dataclasses import dataclass, field from datetime import UTC, datetime +from pathlib import Path from typing import Any, Protocol from urllib.parse import urlparse +import msgpack + from .client import CultNetRawClient from .shard_catalog import CultNetShardDescriptor from .shard_log import CultNetShardLogResponse @@ -56,6 +59,61 @@ class CultNetInMemoryShardReplicaCursorStore: self._cursors[cursor.shard_id] = cursor +@dataclass(frozen=True) +class CultNetFileShardReplicaCursorStore: + file_path: str | Path + + def read(self, shard_id: str) -> CultNetShardReplicaCursor | None: + _require_non_empty(shard_id, "shard_id") + return next((cursor for cursor in self._read_all() if cursor.shard_id == shard_id), None) + + def write(self, cursor: CultNetShardReplicaCursor) -> None: + _require_non_empty(cursor.shard_id, "cursor.shard_id") + cursors = [ + existing + for existing in self._read_all() + if existing.shard_id != cursor.shard_id + ] + cursors.append(cursor) + path = Path(self.file_path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(msgpack.packb( + [self._cursor_to_wire(value) for value in sorted(cursors, key=lambda value: value.shard_id)], + use_bin_type=True, + )) + + def _read_all(self) -> list[CultNetShardReplicaCursor]: + path = Path(self.file_path) + if not path.exists() or path.stat().st_size == 0: + return [] + value = msgpack.unpackb(path.read_bytes(), raw=False) + if not isinstance(value, list): + raise ValueError("CultNet shard replica cursor file must contain a MessagePack array") + return [ + self._cursor_from_wire(item) + for item in value + if isinstance(item, dict) + ] + + @staticmethod + def _cursor_to_wire(cursor: CultNetShardReplicaCursor) -> dict[str, Any]: + return { + "shardId": cursor.shard_id, + "shardEpoch": cursor.shard_epoch, + "lastAppliedSequence": cursor.last_applied_sequence, + "updatedAt": cursor.updated_at, + } + + @staticmethod + def _cursor_from_wire(value: dict[str, Any]) -> CultNetShardReplicaCursor: + return CultNetShardReplicaCursor( + shard_id=str(value.get("shardId") or ""), + shard_epoch=int(value.get("shardEpoch") or 0), + last_applied_sequence=int(value.get("lastAppliedSequence") or 0), + updated_at=str(value.get("updatedAt") or ""), + ) + + @dataclass(frozen=True) class CultNetSchemaShardLogFetcher: timeout_seconds: float = 4.0 diff --git a/packages/cultcache-py/tests/test_cultcache.py b/packages/cultcache-py/tests/test_cultcache.py index 7366e982..00a9250d 100644 --- a/packages/cultcache-py/tests/test_cultcache.py +++ b/packages/cultcache-py/tests/test_cultcache.py @@ -35,6 +35,7 @@ from cultnet_py import ( CultNetShardDescriptor, CultNetShardLogEntry, CultNetShardLogResponse, + CultNetFileShardReplicaCursorStore, CultNetInMemoryShardReplicaCursorStore, CultNetSchemaShardLogFetcher, CultNetSchemaShardSnapshotFetcher, @@ -1466,43 +1467,54 @@ class CultCacheTests(unittest.TestCase): source.database.register_document(document) source.database.put_raw_message(document, "note:1", {"body": "one"}, shard_id="notes", shard_epoch=3) source.database.put_raw_message(document, "note:2", {"body": "two"}, shard_id="notes", shard_epoch=3) - server = CultMesh.serve_node(source) - try: - shard = CultNetShardDescriptor( - shard_id="notes", - owner_runtime_id="primary", - epoch=3, - is_primary=False, - schema_ids=("mesh.replica_note.v1",), - primary_endpoints=(f"cultnet://127.0.0.1:{server.port}",), - ) - target = CultMesh.create_node(runtime_id="replica") - target.database.register_document(document) - cursor_store = CultNetInMemoryShardReplicaCursorStore() - replicator = CultNetShardReplicator( - target.database, - CultNetShardReplicatorOptions( - fetcher=CultNetSchemaShardLogFetcher(timeout_seconds=2.0), - snapshot_fetcher=CultNetSchemaShardSnapshotFetcher(timeout_seconds=2.0), - cursor_store=cursor_store, - batch_size=16, - ), - ) + with tempfile.TemporaryDirectory() as tmp: + cursor_path = Path(tmp) / "replica-cursors.msgpack" + server = CultMesh.serve_node(source) + try: + shard = CultNetShardDescriptor( + shard_id="notes", + owner_runtime_id="primary", + epoch=3, + is_primary=False, + schema_ids=("mesh.replica_note.v1",), + primary_endpoints=(f"cultnet://127.0.0.1:{server.port}",), + ) + target = CultMesh.create_node(runtime_id="replica") + target.database.register_document(document) + cursor_store = CultNetFileShardReplicaCursorStore(cursor_path) + replicator = CultNetShardReplicator( + target.database, + CultNetShardReplicatorOptions( + fetcher=CultNetSchemaShardLogFetcher(timeout_seconds=2.0), + snapshot_fetcher=CultNetSchemaShardSnapshotFetcher(timeout_seconds=2.0), + cursor_store=cursor_store, + batch_size=16, + ), + ) - first_sequence = replicator.pull_once(shard) - second_sequence = replicator.pull_once(shard) + first_sequence = replicator.pull_once(shard) + restarted_replicator = CultNetShardReplicator( + target.database, + CultNetShardReplicatorOptions( + fetcher=CultNetSchemaShardLogFetcher(timeout_seconds=2.0), + snapshot_fetcher=CultNetSchemaShardSnapshotFetcher(timeout_seconds=2.0), + cursor_store=CultNetFileShardReplicaCursorStore(cursor_path), + batch_size=16, + ), + ) + second_sequence = restarted_replicator.pull_once(shard) - self.assertEqual(first_sequence, 2) - self.assertEqual(second_sequence, 2) - self.assertEqual(target.get_required(document, "note:1")["body"], "one") - self.assertEqual(target.get_required(document, "note:2")["body"], "two") - cursor = cursor_store.read("notes") - self.assertIsNotNone(cursor) - assert cursor is not None - self.assertEqual(cursor.last_applied_sequence, 2) - self.assertEqual(cursor.shard_epoch, 3) - finally: - server.stop() + self.assertEqual(first_sequence, 2) + self.assertEqual(second_sequence, 2) + self.assertEqual(target.get_required(document, "note:1")["body"], "one") + self.assertEqual(target.get_required(document, "note:2")["body"], "two") + cursor = CultNetFileShardReplicaCursorStore(cursor_path).read("notes") + self.assertIsNotNone(cursor) + assert cursor is not None + self.assertEqual(cursor.last_applied_sequence, 2) + self.assertEqual(cursor.shard_epoch, 3) + finally: + server.stop() resync_target = CultMesh.create_node(runtime_id="resync-replica") resync_target.database.register_document(document)