Add Python shard replication pull helper
This commit is contained in:
parent
0251816eb1
commit
cf0849c73b
6 changed files with 328 additions and 3 deletions
|
|
@ -51,6 +51,11 @@ CultCache, CultNet, and CultMesh. It is evidence, not confetti.
|
|||
from the package-local mutation log and reports resync-required responses for
|
||||
unknown shards or stale epoch cursors; `create_shard_log_response(...)`
|
||||
remains the raw wire-dict compatibility projection.
|
||||
- Python CultNet shard replication:
|
||||
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.
|
||||
- Python CultNet database subscription changes:
|
||||
Provides typed `CultNetDatabaseChange` parsing plus
|
||||
`CultNetDatabaseSubscription.read_next_change(...)` / `iter_changes(...)` for
|
||||
|
|
@ -173,5 +178,7 @@ node --test packages\cultnet-ts\dist-test\test\interop\cultnet-interop.test.js
|
|||
state participant.
|
||||
- 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, and consume remote shard-log responses, while the live interop peer
|
||||
owns its harness mutation 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.
|
||||
|
|
|
|||
|
|
@ -223,7 +223,15 @@ local prediction reconciliation:
|
|||
|
||||
```python
|
||||
from cultcache_py import define_database_entry_type
|
||||
from cultnet_py import CultNetClientAuthorityScope, CultNetRawClient
|
||||
from cultnet_py import (
|
||||
CultNetClientAuthorityScope,
|
||||
CultNetRawClient,
|
||||
CultNetSchemaShardLogFetcher,
|
||||
CultNetSchemaShardSnapshotFetcher,
|
||||
CultNetShardDescriptor,
|
||||
CultNetShardReplicator,
|
||||
CultNetShardReplicatorOptions,
|
||||
)
|
||||
from cultmesh_py import CultMesh, CultMeshGameSessionOptions, peer_exchange_request
|
||||
|
||||
note_doc = define_database_entry_type(
|
||||
|
|
@ -264,6 +272,20 @@ client.sync_peer_catalog(peers, verse_id="python-interop", roles=["read-replica"
|
|||
raw_client = CultNetRawClient("127.0.0.1", 3075)
|
||||
node.database.sync_snapshot(raw_client, schema_ids=[note_doc.catalog_entry().schema_id])
|
||||
node.database.sync_shard_log(raw_client, shard_id="interop", shard_epoch=1)
|
||||
replicator = CultNetShardReplicator(
|
||||
node.database,
|
||||
CultNetShardReplicatorOptions(
|
||||
fetcher=CultNetSchemaShardLogFetcher(),
|
||||
snapshot_fetcher=CultNetSchemaShardSnapshotFetcher(),
|
||||
),
|
||||
)
|
||||
replicator.pull_once(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",),
|
||||
))
|
||||
server.stop()
|
||||
|
||||
streams = CultMesh.create_stream_catalog()
|
||||
|
|
|
|||
|
|
@ -42,6 +42,15 @@ EXPECTED_EXPORTS: dict[str, tuple[str, ...]] = {
|
|||
"CultNetShardDescriptor",
|
||||
"CultNetShardLogEntry",
|
||||
"CultNetShardLogResponse",
|
||||
"CultNetInMemoryShardReplicaCursorStore",
|
||||
"CultNetSchemaShardLogFetcher",
|
||||
"CultNetSchemaShardSnapshotFetcher",
|
||||
"CultNetShardLogFetcher",
|
||||
"CultNetShardReplicaCursor",
|
||||
"CultNetShardReplicaCursorStore",
|
||||
"CultNetShardReplicator",
|
||||
"CultNetShardReplicatorOptions",
|
||||
"CultNetShardSnapshotFetcher",
|
||||
"CultNetSimulationConsensus",
|
||||
"CultNetSimulationConsensusCandidate",
|
||||
"CultNetSimulationConsensusOptions",
|
||||
|
|
|
|||
|
|
@ -37,6 +37,17 @@ from .schema_catalog import (
|
|||
)
|
||||
from .shard_catalog import CultNetShardCatalog, CultNetShardDescriptor
|
||||
from .shard_log import CultNetShardLogEntry, CultNetShardLogResponse
|
||||
from .shard_replication import (
|
||||
CultNetInMemoryShardReplicaCursorStore,
|
||||
CultNetSchemaShardLogFetcher,
|
||||
CultNetSchemaShardSnapshotFetcher,
|
||||
CultNetShardLogFetcher,
|
||||
CultNetShardReplicaCursor,
|
||||
CultNetShardReplicaCursorStore,
|
||||
CultNetShardReplicator,
|
||||
CultNetShardReplicatorOptions,
|
||||
CultNetShardSnapshotFetcher,
|
||||
)
|
||||
from .snapshot import CultNetRawDocumentRecord, CultNetRawSnapshotResponse
|
||||
from .subscription import CultNetDatabaseChange
|
||||
from .simulation import (
|
||||
|
|
@ -59,6 +70,15 @@ __all__ = [
|
|||
"CultNetShardDescriptor",
|
||||
"CultNetShardLogEntry",
|
||||
"CultNetShardLogResponse",
|
||||
"CultNetInMemoryShardReplicaCursorStore",
|
||||
"CultNetSchemaShardLogFetcher",
|
||||
"CultNetSchemaShardSnapshotFetcher",
|
||||
"CultNetShardLogFetcher",
|
||||
"CultNetShardReplicaCursor",
|
||||
"CultNetShardReplicaCursorStore",
|
||||
"CultNetShardReplicator",
|
||||
"CultNetShardReplicatorOptions",
|
||||
"CultNetShardSnapshotFetcher",
|
||||
"CultNetRawDocumentRecord",
|
||||
"CultNetRawSnapshotResponse",
|
||||
"CultNetAppliedRecord",
|
||||
|
|
|
|||
174
packages/cultcache-py/src/cultnet_py/shard_replication.py
Normal file
174
packages/cultcache-py/src/cultnet_py/shard_replication.py
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any, Protocol
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from .client import CultNetRawClient
|
||||
from .shard_catalog import CultNetShardDescriptor
|
||||
from .shard_log import CultNetShardLogResponse
|
||||
from .snapshot import CultNetRawSnapshotResponse
|
||||
|
||||
|
||||
class CultNetShardLogFetcher(Protocol):
|
||||
def fetch(
|
||||
self,
|
||||
shard: CultNetShardDescriptor,
|
||||
*,
|
||||
after_sequence: int,
|
||||
limit: int | None = None,
|
||||
) -> CultNetShardLogResponse:
|
||||
...
|
||||
|
||||
|
||||
class CultNetShardSnapshotFetcher(Protocol):
|
||||
def fetch(self, shard: CultNetShardDescriptor) -> CultNetRawSnapshotResponse:
|
||||
...
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultNetShardReplicaCursor:
|
||||
shard_id: str
|
||||
shard_epoch: int
|
||||
last_applied_sequence: int
|
||||
updated_at: str
|
||||
|
||||
|
||||
class CultNetShardReplicaCursorStore(Protocol):
|
||||
def read(self, shard_id: str) -> CultNetShardReplicaCursor | None:
|
||||
...
|
||||
|
||||
def write(self, cursor: CultNetShardReplicaCursor) -> None:
|
||||
...
|
||||
|
||||
|
||||
@dataclass
|
||||
class CultNetInMemoryShardReplicaCursorStore:
|
||||
_cursors: dict[str, CultNetShardReplicaCursor] = field(default_factory=dict)
|
||||
|
||||
def read(self, shard_id: str) -> CultNetShardReplicaCursor | None:
|
||||
_require_non_empty(shard_id, "shard_id")
|
||||
return self._cursors.get(shard_id)
|
||||
|
||||
def write(self, cursor: CultNetShardReplicaCursor) -> None:
|
||||
_require_non_empty(cursor.shard_id, "cursor.shard_id")
|
||||
self._cursors[cursor.shard_id] = cursor
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultNetSchemaShardLogFetcher:
|
||||
timeout_seconds: float = 4.0
|
||||
|
||||
def fetch(
|
||||
self,
|
||||
shard: CultNetShardDescriptor,
|
||||
*,
|
||||
after_sequence: int,
|
||||
limit: int | None = None,
|
||||
) -> CultNetShardLogResponse:
|
||||
if after_sequence < 0:
|
||||
raise ValueError("after_sequence must be non-negative")
|
||||
endpoint = _resolve_primary_endpoint(shard)
|
||||
host, port = _parse_endpoint(endpoint)
|
||||
return CultNetRawClient(host, port, self.timeout_seconds).fetch_shard_log_response(
|
||||
shard_id=shard.shard_id,
|
||||
shard_epoch=shard.epoch,
|
||||
after_sequence=after_sequence,
|
||||
limit=limit,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultNetSchemaShardSnapshotFetcher:
|
||||
timeout_seconds: float = 4.0
|
||||
|
||||
def fetch(self, shard: CultNetShardDescriptor) -> CultNetRawSnapshotResponse:
|
||||
endpoint = _resolve_primary_endpoint(shard)
|
||||
host, port = _parse_endpoint(endpoint)
|
||||
return CultNetRawClient(host, port, self.timeout_seconds).fetch_snapshot_response(
|
||||
schema_ids=list(shard.schema_ids) or None,
|
||||
shard_id=shard.shard_id,
|
||||
shard_epoch=shard.epoch,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CultNetShardReplicatorOptions:
|
||||
fetcher: CultNetShardLogFetcher | None = None
|
||||
snapshot_fetcher: CultNetShardSnapshotFetcher | None = None
|
||||
cursor_store: CultNetShardReplicaCursorStore | None = None
|
||||
batch_size: int | None = 256
|
||||
|
||||
|
||||
@dataclass
|
||||
class CultNetShardReplicator:
|
||||
database: Any
|
||||
options: CultNetShardReplicatorOptions = field(default_factory=CultNetShardReplicatorOptions)
|
||||
_applied_sequences: dict[str, int] = field(default_factory=dict)
|
||||
|
||||
def pull_once(self, shard: CultNetShardDescriptor) -> int:
|
||||
if self.options.fetcher is None:
|
||||
raise ValueError("A shard log fetcher is required before pulling replication")
|
||||
if shard.is_primary:
|
||||
raise ValueError(f"Shard {shard.shard_id!r} is primary on this node and does not need replica pulling")
|
||||
after_sequence = self._after_sequence(shard)
|
||||
response = self.options.fetcher.fetch(
|
||||
shard,
|
||||
after_sequence=after_sequence,
|
||||
limit=self.options.batch_size,
|
||||
)
|
||||
if response.resync_required and response.reason == "compacted_history":
|
||||
if self.options.snapshot_fetcher is None:
|
||||
raise ValueError(
|
||||
f"Shard {shard.shard_id!r} requires snapshot resync, but no shard snapshot fetcher is configured"
|
||||
)
|
||||
snapshot = self.options.snapshot_fetcher.fetch(shard)
|
||||
self.database.apply_snapshot_response(snapshot)
|
||||
sequence = snapshot.shard_log_sequence or 0
|
||||
self._write_cursor(shard, sequence)
|
||||
return sequence
|
||||
self.database.apply_shard_log_response(response)
|
||||
sequence = max(after_sequence, response.last_sequence)
|
||||
self._write_cursor(shard, sequence)
|
||||
return sequence
|
||||
|
||||
def _after_sequence(self, shard: CultNetShardDescriptor) -> int:
|
||||
current = self._applied_sequences.get(shard.shard_id, 0)
|
||||
if current > 0 or self.options.cursor_store is None:
|
||||
return current
|
||||
cursor = self.options.cursor_store.read(shard.shard_id)
|
||||
if cursor is None or cursor.shard_epoch != shard.epoch:
|
||||
return current
|
||||
self._applied_sequences[shard.shard_id] = cursor.last_applied_sequence
|
||||
return cursor.last_applied_sequence
|
||||
|
||||
def _write_cursor(self, shard: CultNetShardDescriptor, sequence: int) -> None:
|
||||
self._applied_sequences[shard.shard_id] = sequence
|
||||
if self.options.cursor_store is None:
|
||||
return
|
||||
self.options.cursor_store.write(CultNetShardReplicaCursor(
|
||||
shard_id=shard.shard_id,
|
||||
shard_epoch=shard.epoch,
|
||||
last_applied_sequence=sequence,
|
||||
updated_at=datetime.now(UTC).isoformat(),
|
||||
))
|
||||
|
||||
|
||||
def _resolve_primary_endpoint(shard: CultNetShardDescriptor) -> str:
|
||||
if not shard.primary_endpoints:
|
||||
raise ValueError(f"Shard {shard.shard_id!r} does not advertise a primary endpoint")
|
||||
return shard.primary_endpoints[0]
|
||||
|
||||
|
||||
def _parse_endpoint(endpoint: str) -> tuple[str, int]:
|
||||
_require_non_empty(endpoint, "endpoint")
|
||||
parsed = urlparse(endpoint if "://" in endpoint else f"cultnet://{endpoint}")
|
||||
if not parsed.hostname or parsed.port is None:
|
||||
raise ValueError(f"CultNet endpoint must include host and port: {endpoint!r}")
|
||||
return parsed.hostname, parsed.port
|
||||
|
||||
|
||||
def _require_non_empty(value: str, name: str) -> None:
|
||||
if not value or not value.strip():
|
||||
raise ValueError(f"{name} must be non-empty")
|
||||
|
|
@ -35,6 +35,11 @@ from cultnet_py import (
|
|||
CultNetShardDescriptor,
|
||||
CultNetShardLogEntry,
|
||||
CultNetShardLogResponse,
|
||||
CultNetInMemoryShardReplicaCursorStore,
|
||||
CultNetSchemaShardLogFetcher,
|
||||
CultNetSchemaShardSnapshotFetcher,
|
||||
CultNetShardReplicator,
|
||||
CultNetShardReplicatorOptions,
|
||||
CultNetSimulationConsensusOptions,
|
||||
CultNetSimulationConsensusCandidate,
|
||||
CultNetSimulationObservation,
|
||||
|
|
@ -1451,6 +1456,94 @@ class CultCacheTests(unittest.TestCase):
|
|||
self.assertEqual([record.change_kind for record in typed_applied], ["updated", "removed"])
|
||||
self.assertIsNone(typed_target.database.get(document, "note:1"))
|
||||
|
||||
def test_cultnet_shard_replicator_pulls_logs_and_resyncs_from_snapshot(self) -> None:
|
||||
document = define_database_entry_type(
|
||||
"mesh.replica_note",
|
||||
[("body", 0)],
|
||||
schema_id="mesh.replica_note.v1",
|
||||
)
|
||||
source = CultMesh.create_node(runtime_id="primary")
|
||||
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,
|
||||
),
|
||||
)
|
||||
|
||||
first_sequence = replicator.pull_once(shard)
|
||||
second_sequence = 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()
|
||||
|
||||
resync_target = CultMesh.create_node(runtime_id="resync-replica")
|
||||
resync_target.database.register_document(document)
|
||||
snapshot = source.database.build_snapshot_response(shard_id="notes", shard_epoch=3, shard_log_sequence=2)
|
||||
|
||||
class CompactingFetcher:
|
||||
def fetch(self, shard: CultNetShardDescriptor, *, after_sequence: int, limit: int | None = None) -> CultNetShardLogResponse:
|
||||
return CultNetShardLogResponse(
|
||||
message_id="compact",
|
||||
shard_id=shard.shard_id,
|
||||
shard_epoch=shard.epoch,
|
||||
entries=(),
|
||||
resync_required=True,
|
||||
reason="compacted_history",
|
||||
compacted_through=after_sequence,
|
||||
)
|
||||
|
||||
class SnapshotFetcher:
|
||||
def fetch(self, shard: CultNetShardDescriptor) -> CultNetRawSnapshotResponse:
|
||||
return snapshot
|
||||
|
||||
resync_replicator = CultNetShardReplicator(
|
||||
resync_target.database,
|
||||
CultNetShardReplicatorOptions(
|
||||
fetcher=CompactingFetcher(),
|
||||
snapshot_fetcher=SnapshotFetcher(),
|
||||
cursor_store=CultNetInMemoryShardReplicaCursorStore(),
|
||||
),
|
||||
)
|
||||
resync_sequence = resync_replicator.pull_once(CultNetShardDescriptor(
|
||||
shard_id="notes",
|
||||
owner_runtime_id="primary",
|
||||
epoch=3,
|
||||
is_primary=False,
|
||||
schema_ids=("mesh.replica_note.v1",),
|
||||
primary_endpoints=("cultnet://primary:3075",),
|
||||
))
|
||||
|
||||
self.assertEqual(resync_sequence, 2)
|
||||
self.assertEqual(resync_target.get_required(document, "note:1")["body"], "one")
|
||||
|
||||
def test_cultmesh_database_watchers_observe_name_and_index_changes(self) -> None:
|
||||
document = define_database_entry_type(
|
||||
"mesh.named_watch",
|
||||
|
|
|
|||
Loading…
Reference in a new issue