diff --git a/packages/cultcache-py/PARITY.md b/packages/cultcache-py/PARITY.md index 3968eef1..886449b2 100644 --- a/packages/cultcache-py/PARITY.md +++ b/packages/cultcache-py/PARITY.md @@ -53,11 +53,13 @@ CultCache, CultNet, and CultMesh. It is evidence, not confetti. remains the raw wire-dict compatibility projection. - Python CultNet shard replication: Provides schema-v0 shard-log and shard-snapshot fetchers, a schema-v0 - write-forwarder for raw put/delete messages, plus a pull-once + write-forwarder for raw put/delete messages, plus a `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. Replica cursor storage can be - in-memory or restart-safe through a local MessagePack cursor file. + through the existing database owner, runs explicit background pull loops for + non-primary shards with advertised primaries, reports loop errors through a + caller-owned callback, and recovers from compacted-history 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 @@ -182,7 +184,7 @@ node --test packages\cultnet-ts\dist-test\test\interop\cultnet-interop.test.js 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, a file-backed replica cursor store, and - schema-v0 write forwarding. It does not yet claim the full C# background - replicator. Its authoritative shard-log store is file-backed and supports - compaction watermarks, but it is still package-local rather than the full C# - daemon/server stack. + schema-v0 write forwarding. It also has an explicit package-level background + pull loop for caller-provided shard descriptors. Its authoritative shard-log + store is file-backed and supports compaction watermarks, but it is still + package-local rather than the full C# daemon/server stack. diff --git a/packages/cultcache-py/README.md b/packages/cultcache-py/README.md index c8e32c00..fde545a4 100644 --- a/packages/cultcache-py/README.md +++ b/packages/cultcache-py/README.md @@ -281,15 +281,20 @@ replicator = CultNetShardReplicator( fetcher=CultNetSchemaShardLogFetcher(), snapshot_fetcher=CultNetSchemaShardSnapshotFetcher(), cursor_store=CultNetFileShardReplicaCursorStore("mesh.replica-cursors.msgpack"), + poll_interval_seconds=1.0, + on_error=lambda error: print(error), ), ) -replicator.pull_once(CultNetShardDescriptor( +replica_shard = CultNetShardDescriptor( shard_id="interop", owner_runtime_id="primary-runtime", epoch=1, schema_ids=(note_doc.catalog_entry().schema_id,), primary_endpoints=("cultnet://127.0.0.1:3075",), -)) +) +replicator.pull_once(replica_shard) +replicator.start([replica_shard]) +replicator.stop() server.stop() streams = CultMesh.create_stream_catalog() diff --git a/packages/cultcache-py/src/cultnet_py/shard_replication.py b/packages/cultcache-py/src/cultnet_py/shard_replication.py index 84279a17..29d21249 100644 --- a/packages/cultcache-py/src/cultnet_py/shard_replication.py +++ b/packages/cultcache-py/src/cultnet_py/shard_replication.py @@ -4,7 +4,8 @@ from dataclasses import dataclass, field from datetime import UTC, datetime import hashlib from pathlib import Path -from typing import Any, Protocol +import threading +from typing import Any, Callable, Iterable, Protocol from urllib.parse import urlparse import msgpack @@ -306,6 +307,8 @@ class CultNetShardReplicatorOptions: snapshot_fetcher: CultNetShardSnapshotFetcher | None = None cursor_store: CultNetShardReplicaCursorStore | None = None batch_size: int | None = 256 + poll_interval_seconds: float = 1.0 + on_error: Callable[[Exception], None] | None = None @dataclass @@ -313,8 +316,57 @@ class CultNetShardReplicator: database: Any options: CultNetShardReplicatorOptions = field(default_factory=CultNetShardReplicatorOptions) _applied_sequences: dict[str, int] = field(default_factory=dict) + _stop_event: threading.Event = field(default_factory=threading.Event) + _threads: list[threading.Thread] = field(default_factory=list) + _pulls_in_flight: set[str] = field(default_factory=set) + _gate: threading.Lock = field(default_factory=threading.Lock) + _disposed: bool = False + + def start(self, shards: Iterable[CultNetShardDescriptor]) -> None: + self._throw_if_disposed() + if self.options.fetcher is None: + raise ValueError("A shard log fetcher is required before starting replication") + if self.options.poll_interval_seconds <= 0: + raise ValueError("poll_interval_seconds must be positive") + if self._threads: + return + self._stop_event = threading.Event() + for shard in shards: + if shard.is_primary or not shard.primary_endpoints: + continue + thread = threading.Thread( + target=self._pull_loop, + args=(shard,), + name=f"cultnet-shard-replicator-{shard.shard_id}", + daemon=True, + ) + self._threads.append(thread) + thread.start() + + def stop(self, *, timeout_seconds: float | None = 2.0) -> None: + self._stop_event.set() + for thread in list(self._threads): + thread.join(timeout=timeout_seconds) + self._threads = [thread for thread in self._threads if thread.is_alive()] + with self._gate: + if not self._threads: + self._pulls_in_flight.clear() + + def close(self) -> None: + if self._disposed: + return + self.stop() + self._disposed = True + + def __enter__(self) -> "CultNetShardReplicator": + self._throw_if_disposed() + return self + + def __exit__(self, exc_type: object, exc: object, traceback: object) -> None: + self.close() def pull_once(self, shard: CultNetShardDescriptor) -> int: + self._throw_if_disposed() if self.options.fetcher is None: raise ValueError("A shard log fetcher is required before pulling replication") if shard.is_primary: @@ -361,6 +413,29 @@ class CultNetShardReplicator: updated_at=datetime.now(UTC).isoformat(), )) + def _pull_loop(self, shard: CultNetShardDescriptor) -> None: + while not self._stop_event.is_set(): + self._pull_if_idle(shard) + self._stop_event.wait(self.options.poll_interval_seconds) + + def _pull_if_idle(self, shard: CultNetShardDescriptor) -> None: + with self._gate: + if shard.shard_id in self._pulls_in_flight: + return + self._pulls_in_flight.add(shard.shard_id) + try: + self.pull_once(shard) + except Exception as error: + if self.options.on_error is not None: + self.options.on_error(error) + finally: + with self._gate: + self._pulls_in_flight.discard(shard.shard_id) + + def _throw_if_disposed(self) -> None: + if self._disposed: + raise RuntimeError("CultNetShardReplicator is closed") + def _resolve_primary_endpoint(shard: CultNetShardDescriptor) -> str: if not shard.primary_endpoints: diff --git a/packages/cultcache-py/tests/test_cultcache.py b/packages/cultcache-py/tests/test_cultcache.py index d60356c0..cb638184 100644 --- a/packages/cultcache-py/tests/test_cultcache.py +++ b/packages/cultcache-py/tests/test_cultcache.py @@ -119,6 +119,14 @@ def item_doc(): class CultCacheTests(unittest.TestCase): + def _wait_until(self, predicate: Callable[[], bool], *, timeout_seconds: float = 2.0) -> None: + deadline = time.monotonic() + timeout_seconds + while time.monotonic() < deadline: + if predicate(): + return + time.sleep(0.01) + self.fail("Timed out waiting for condition") + def test_round_trips_registered_documents(self) -> None: with tempfile.TemporaryDirectory() as tmp: document = item_doc() @@ -1593,6 +1601,72 @@ class CultCacheTests(unittest.TestCase): self.assertEqual(resync_sequence, 2) self.assertEqual(resync_target.get_required(document, "note:1")["body"], "one") + def test_cultnet_shard_replicator_background_loop_polls_non_primary_shards(self) -> None: + document = define_database_entry_type( + "mesh.background_replica_note", + [("body", 0)], + schema_id="mesh.background_replica_note.v1", + ) + source = CultMesh.create_node(runtime_id="background-primary") + source.database.register_document(document) + target = CultMesh.create_node(runtime_id="background-replica") + target.database.register_document(document) + cursor_store = CultNetInMemoryShardReplicaCursorStore() + errors: list[Exception] = [] + + class FlakySourceFetcher: + def __init__(self) -> None: + self.calls = 0 + + def fetch(self, shard: CultNetShardDescriptor, *, after_sequence: int, limit: int | None = None) -> CultNetShardLogResponse: + self.calls += 1 + if self.calls == 1: + raise RuntimeError("transient fetch failure") + return source.database.build_shard_log_response( + shard_id=shard.shard_id, + shard_epoch=shard.epoch, + after_sequence=after_sequence, + limit=limit, + ) + + fetcher = FlakySourceFetcher() + shard = CultNetShardDescriptor( + shard_id="background", + owner_runtime_id="background-primary", + epoch=7, + is_primary=False, + schema_ids=("mesh.background_replica_note.v1",), + primary_endpoints=("cultnet://127.0.0.1:3075",), + ) + replicator = CultNetShardReplicator( + target.database, + CultNetShardReplicatorOptions( + fetcher=fetcher, + cursor_store=cursor_store, + batch_size=1, + poll_interval_seconds=0.01, + on_error=errors.append, + ), + ) + try: + source.database.put_raw_message(document, "note:1", {"body": "one"}, shard_id="background", shard_epoch=7) + replicator.start([shard]) + self._wait_until(lambda: target.database.get(document, "note:1") is not None) + source.database.put_raw_message(document, "note:2", {"body": "two"}, shard_id="background", shard_epoch=7) + self._wait_until(lambda: target.database.get(document, "note:2") is not None) + finally: + replicator.stop() + + cursor = cursor_store.read("background") + self.assertEqual(target.get_required(document, "note:1")["body"], "one") + self.assertEqual(target.get_required(document, "note:2")["body"], "two") + self.assertIsNotNone(cursor) + assert cursor is not None + self.assertEqual(cursor.last_applied_sequence, 2) + self.assertEqual(cursor.shard_epoch, 7) + self.assertEqual(len(errors), 1) + self.assertEqual(str(errors[0]), "transient fetch failure") + def test_cultnet_schema_write_forwarder_sends_raw_writes_to_primary(self) -> None: document = define_database_entry_type( "mesh.forward_note",