Add Python CultNet shard log facade
This commit is contained in:
parent
c1afc6b77f
commit
699df36cce
6 changed files with 186 additions and 1 deletions
|
|
@ -26,6 +26,10 @@ CultCache, CultNet, and CultMesh. It is evidence, not confetti.
|
|||
ingesting, filtering, and emitting shard topology responses, plus
|
||||
`CultNetRawClient.sync_shard_catalog(...)` for peer topology discovery over
|
||||
the same framed CultNet pipe.
|
||||
- Python CultNet shard log:
|
||||
Provides typed `CultNetShardLogResponse` and `CultNetShardLogEntry` helpers
|
||||
for inspecting mutation-log entries, resync pressure, and sequence cursors,
|
||||
while cache mutation remains owned by the existing replication helpers.
|
||||
- Python CultMesh discovery client:
|
||||
Fetches Verse catalogs and peer exchange responses from the live Python
|
||||
endpoint over CultNet frames.
|
||||
|
|
|
|||
|
|
@ -36,6 +36,8 @@ EXPECTED_EXPORTS: dict[str, tuple[str, ...]] = {
|
|||
"CultNetSchemaDescriptor",
|
||||
"CultNetShardCatalog",
|
||||
"CultNetShardDescriptor",
|
||||
"CultNetShardLogEntry",
|
||||
"CultNetShardLogResponse",
|
||||
"CultNetSimulationConsensus",
|
||||
"CultNetSimulationConsensusOptions",
|
||||
"CultNetSimulationObservationHub",
|
||||
|
|
|
|||
|
|
@ -35,6 +35,7 @@ from .schema_catalog import (
|
|||
wire_message_schema_json,
|
||||
)
|
||||
from .shard_catalog import CultNetShardCatalog, CultNetShardDescriptor
|
||||
from .shard_log import CultNetShardLogEntry, CultNetShardLogResponse
|
||||
from .simulation import (
|
||||
CultNetSimulationConsensus,
|
||||
CultNetSimulationConsensusOptions,
|
||||
|
|
@ -49,6 +50,8 @@ __all__ = [
|
|||
"CultNetSchemaDescriptor",
|
||||
"CultNetShardCatalog",
|
||||
"CultNetShardDescriptor",
|
||||
"CultNetShardLogEntry",
|
||||
"CultNetShardLogResponse",
|
||||
"CultNetAppliedRecord",
|
||||
"CultNetClientAuthorityScope",
|
||||
"CultNetSimulationConsensus",
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ from .messages import (
|
|||
)
|
||||
from .schema_catalog import CultNetSchemaCatalog, CultNetSchemaDescriptor
|
||||
from .shard_catalog import CultNetShardCatalog, CultNetShardDescriptor
|
||||
from .shard_log import CultNetShardLogResponse
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
|
@ -173,6 +174,23 @@ class CultNetRawClient:
|
|||
expected_schema_version="cultnet.shard_log_response.v0",
|
||||
)
|
||||
|
||||
def fetch_shard_log_response(
|
||||
self,
|
||||
*,
|
||||
shard_id: str,
|
||||
message_id: str = "cultnet-python-shard-log",
|
||||
shard_epoch: int | None = None,
|
||||
after_sequence: int = 0,
|
||||
limit: int | None = None,
|
||||
) -> CultNetShardLogResponse:
|
||||
return CultNetShardLogResponse.from_wire(self.fetch_shard_log(
|
||||
shard_id=shard_id,
|
||||
message_id=message_id,
|
||||
shard_epoch=shard_epoch,
|
||||
after_sequence=after_sequence,
|
||||
limit=limit,
|
||||
))
|
||||
|
||||
def subscribe_database(
|
||||
self,
|
||||
*,
|
||||
|
|
|
|||
113
packages/cultcache-py/src/cultnet_py/shard_log.py
Normal file
113
packages/cultcache-py/src/cultnet_py/shard_log.py
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultNetShardLogEntry:
|
||||
sequence: int
|
||||
change_kind: str
|
||||
put: dict[str, Any] | None = None
|
||||
delete: dict[str, Any] | None = None
|
||||
committed_at: str | None = None
|
||||
|
||||
@classmethod
|
||||
def from_wire(cls, value: dict[str, Any]) -> "CultNetShardLogEntry":
|
||||
sequence = int(value.get("sequence") or 0)
|
||||
change_kind = str(value.get("changeKind") or "")
|
||||
if sequence <= 0:
|
||||
raise ValueError("shard log entry sequence must be positive")
|
||||
if change_kind not in {"added", "updated", "removed"}:
|
||||
raise ValueError(f"unsupported shard log changeKind {change_kind!r}")
|
||||
put = value.get("put")
|
||||
delete = value.get("delete")
|
||||
return cls(
|
||||
sequence=sequence,
|
||||
change_kind=change_kind,
|
||||
put=dict(put) if isinstance(put, dict) else None,
|
||||
delete=dict(delete) if isinstance(delete, dict) else None,
|
||||
committed_at=_optional_string(value.get("committedAt")),
|
||||
)
|
||||
|
||||
def to_wire(self) -> dict[str, Any]:
|
||||
wire: dict[str, Any] = {
|
||||
"sequence": self.sequence,
|
||||
"changeKind": self.change_kind,
|
||||
}
|
||||
if self.put is not None:
|
||||
wire["put"] = self.put
|
||||
if self.delete is not None:
|
||||
wire["delete"] = self.delete
|
||||
if self.committed_at is not None:
|
||||
wire["committedAt"] = self.committed_at
|
||||
return wire
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CultNetShardLogResponse:
|
||||
message_id: str
|
||||
shard_id: str
|
||||
shard_epoch: int
|
||||
entries: tuple[CultNetShardLogEntry, ...]
|
||||
resync_required: bool = False
|
||||
reason: str | None = None
|
||||
compacted_through: int | None = None
|
||||
|
||||
@classmethod
|
||||
def from_wire(cls, response: dict[str, Any]) -> "CultNetShardLogResponse":
|
||||
if response.get("schemaVersion") != "cultnet.shard_log_response.v0":
|
||||
raise ValueError(f"Expected cultnet.shard_log_response.v0, received {response.get('schemaVersion')!r}")
|
||||
entries = tuple(
|
||||
CultNetShardLogEntry.from_wire(entry)
|
||||
for entry in response.get("entries") or []
|
||||
if isinstance(entry, dict)
|
||||
)
|
||||
return cls(
|
||||
message_id=str(response.get("messageId") or ""),
|
||||
shard_id=str(response.get("shardId") or ""),
|
||||
shard_epoch=int(response.get("shardEpoch") or 0),
|
||||
entries=entries,
|
||||
resync_required=response.get("resyncRequired") is True,
|
||||
reason=_optional_string(response.get("reason")),
|
||||
compacted_through=_optional_int(response.get("compactedThrough")),
|
||||
)
|
||||
|
||||
@property
|
||||
def last_sequence(self) -> int:
|
||||
if not self.entries:
|
||||
return self.compacted_through or 0
|
||||
return max(entry.sequence for entry in self.entries)
|
||||
|
||||
def require_usable(self) -> "CultNetShardLogResponse":
|
||||
if self.resync_required:
|
||||
raise ValueError(f"Shard log response requires resync: {self.reason or 'unspecified'}")
|
||||
return self
|
||||
|
||||
def to_wire(self) -> dict[str, Any]:
|
||||
wire: dict[str, Any] = {
|
||||
"schemaVersion": "cultnet.shard_log_response.v0",
|
||||
"messageId": self.message_id,
|
||||
"shardId": self.shard_id,
|
||||
"shardEpoch": self.shard_epoch,
|
||||
"entries": [entry.to_wire() for entry in self.entries],
|
||||
"resyncRequired": self.resync_required,
|
||||
}
|
||||
if self.reason is not None:
|
||||
wire["reason"] = self.reason
|
||||
if self.compacted_through is not None:
|
||||
wire["compactedThrough"] = self.compacted_through
|
||||
return wire
|
||||
|
||||
|
||||
def _optional_string(value: Any) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value)
|
||||
return text if text else None
|
||||
|
||||
|
||||
def _optional_int(value: Any) -> int | None:
|
||||
if value is None:
|
||||
return None
|
||||
return int(value)
|
||||
|
|
@ -28,6 +28,8 @@ from cultnet_py import (
|
|||
CultNetSchemaDescriptor,
|
||||
CultNetShardCatalog,
|
||||
CultNetShardDescriptor,
|
||||
CultNetShardLogEntry,
|
||||
CultNetShardLogResponse,
|
||||
CultNetSimulationConsensusOptions,
|
||||
apply_raw_snapshot,
|
||||
apply_shard_log_response,
|
||||
|
|
@ -470,7 +472,10 @@ class CultCacheTests(unittest.TestCase):
|
|||
synced_shards = client.sync_shard_catalog(shard_catalog, schema_ids=["schema-a"])
|
||||
self.assertEqual(synced_shards[0].shard_id, "interop")
|
||||
self.assertEqual(shard_catalog.get("interop"), synced_shards[0])
|
||||
self.assertEqual(client.fetch_shard_log(shard_id="interop", shard_epoch=1, after_sequence=7)["schemaVersion"], "cultnet.shard_log_response.v0")
|
||||
shard_log = client.fetch_shard_log_response(shard_id="interop", shard_epoch=1, after_sequence=7)
|
||||
self.assertEqual(shard_log.shard_id, "interop")
|
||||
self.assertFalse(shard_log.resync_required)
|
||||
self.assertEqual(shard_log.last_sequence, 0)
|
||||
|
||||
thread.join(2.0)
|
||||
self.assertFalse(server_error)
|
||||
|
|
@ -959,6 +964,43 @@ class CultCacheTests(unittest.TestCase):
|
|||
self.assertEqual(applied[0].shard_id, "notes")
|
||||
self.assertEqual(remote.get("notes"), applied[0])
|
||||
|
||||
def test_cultnet_shard_log_response_tracks_cursor_and_resync_state(self) -> None:
|
||||
response = CultNetShardLogResponse.from_wire({
|
||||
"schemaVersion": "cultnet.shard_log_response.v0",
|
||||
"messageId": "log",
|
||||
"shardId": "notes",
|
||||
"shardEpoch": 2,
|
||||
"entries": [
|
||||
CultNetShardLogEntry(
|
||||
sequence=2,
|
||||
change_kind="updated",
|
||||
put={"schemaVersion": "cultnet.document_put_raw.v0", "messageId": "put", "document": {"schemaId": "schema-note", "recordKey": "note:1", "payload": b"p"}},
|
||||
committed_at="2026-06-14T00:00:00Z",
|
||||
).to_wire(),
|
||||
{"sequence": 3, "changeKind": "removed", "delete": {"schemaId": "schema-note", "recordKey": "note:1"}},
|
||||
],
|
||||
"resyncRequired": False,
|
||||
})
|
||||
self.assertEqual(response.last_sequence, 3)
|
||||
self.assertFalse(response.resync_required)
|
||||
self.assertEqual(response.entries[0].put["document"]["recordKey"], "note:1")
|
||||
self.assertEqual(response.to_wire()["entries"][1]["delete"]["recordKey"], "note:1")
|
||||
self.assertIs(response.require_usable(), response)
|
||||
|
||||
resync = CultNetShardLogResponse.from_wire({
|
||||
"schemaVersion": "cultnet.shard_log_response.v0",
|
||||
"messageId": "log-resync",
|
||||
"shardId": "notes",
|
||||
"shardEpoch": 2,
|
||||
"entries": [],
|
||||
"resyncRequired": True,
|
||||
"reason": "compacted",
|
||||
"compactedThrough": 12,
|
||||
})
|
||||
self.assertEqual(resync.last_sequence, 12)
|
||||
with self.assertRaisesRegex(ValueError, "compacted"):
|
||||
resync.require_usable()
|
||||
|
||||
def test_cultnet_simulation_observation_helper_matches_schema_v0_shape(self) -> None:
|
||||
claim_hash = compute_simulation_claim_hash("frame:42", "subject:player-1", "hit")
|
||||
self.assertEqual(len(claim_hash), 64)
|
||||
|
|
@ -1768,6 +1810,7 @@ class CultCacheTests(unittest.TestCase):
|
|||
synced_shard_catalog = CultNetShardCatalog()
|
||||
synced_shards = raw_client.sync_shard_catalog(synced_shard_catalog, schema_ids=["mesh.server_note.v1"])
|
||||
shard_log = raw_client.fetch_shard_log(shard_id="primary", shard_epoch=1)
|
||||
typed_shard_log = raw_client.fetch_shard_log_response(shard_id="primary", shard_epoch=1)
|
||||
discovery_client = CultMesh.create_verse_discovery_client("127.0.0.1", server.port, timeout_seconds=2.0)
|
||||
fetched_verses = discovery_client.fetch_verses(transport_version="cultmesh.v0")
|
||||
fetched_peers = discovery_client.fetch_peers(verse_id="server-verse", roles=["read-replica"])
|
||||
|
|
@ -1811,6 +1854,8 @@ class CultCacheTests(unittest.TestCase):
|
|||
self.assertEqual(synced_shards[0].shard_id, "primary")
|
||||
self.assertEqual(synced_shard_catalog.get("primary"), synced_shards[0])
|
||||
self.assertEqual(shard_log["entries"][0]["changeKind"], "added")
|
||||
self.assertEqual(typed_shard_log.last_sequence, 1)
|
||||
self.assertEqual(typed_shard_log.entries[0].put["document"]["recordKey"], "note:1")
|
||||
self.assertEqual(fetched_verses[0].verse_id, "server-verse")
|
||||
self.assertEqual(fetched_peers[0].peer_id, "mesh-server")
|
||||
self.assertEqual(subscription_snapshot["schemaVersion"], "cultnet.snapshot_response_raw.v0")
|
||||
|
|
|
|||
Loading…
Reference in a new issue