Add Python shard catalog interop
This commit is contained in:
parent
3d67576444
commit
a0907366ab
5 changed files with 277 additions and 4 deletions
|
|
@ -8,6 +8,8 @@ from .messages import (
|
|||
hello,
|
||||
parse_message,
|
||||
schema_catalog_request,
|
||||
shard_catalog_request,
|
||||
shard_log_request,
|
||||
snapshot_request,
|
||||
)
|
||||
|
||||
|
|
@ -23,6 +25,8 @@ __all__ = [
|
|||
"parse_message",
|
||||
"read_frame",
|
||||
"schema_catalog_request",
|
||||
"shard_catalog_request",
|
||||
"shard_log_request",
|
||||
"snapshot_request",
|
||||
"write_frame",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -76,6 +76,11 @@ class PeerState:
|
|||
interop_schema_json: str
|
||||
verse_catalog: CultMeshVerseCatalog
|
||||
peer_catalog: CultMeshPeerCatalog
|
||||
shard_id: str
|
||||
shard_epoch: int
|
||||
shard_endpoint: str
|
||||
shard_log: list[dict[str, Any]]
|
||||
shard_log_lock: threading.Lock
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
@ -139,7 +144,14 @@ def add_common_runtime_args(parser: argparse.ArgumentParser) -> None:
|
|||
|
||||
|
||||
def serve(args: argparse.Namespace) -> None:
|
||||
state = build_state(args.runtime_id, args.runtime_kind, args.display_name, args.agent_id, args.schema_path)
|
||||
state = build_state(
|
||||
args.runtime_id,
|
||||
args.runtime_kind,
|
||||
args.display_name,
|
||||
args.agent_id,
|
||||
args.schema_path,
|
||||
shard_endpoint=f"cultnet://{args.advertise_host}:{args.tcp_port}",
|
||||
)
|
||||
state.cache.put(state.bindings["note"].document, f"note:{args.runtime_id}", build_interop_note(args.runtime_id, args.display_name))
|
||||
|
||||
stop = threading.Event()
|
||||
|
|
@ -213,6 +225,10 @@ def handle_server_message(state: PeerState, message: dict[str, Any], subscriptio
|
|||
return [catalog_response(state, message)]
|
||||
if schema_version == "cultnet.snapshot_request.v0":
|
||||
return [raw_snapshot_response(state, message)]
|
||||
if schema_version == "cultnet.shard_catalog_request.v0":
|
||||
return [shard_catalog_response(state, message)]
|
||||
if schema_version == "cultnet.shard_log_request.v0":
|
||||
return [shard_log_response(state, message)]
|
||||
if schema_version == "cultnet.database_subscribe.v0":
|
||||
return handle_database_subscribe(state, message, subscriptions)
|
||||
if schema_version == "cultnet.database_unsubscribe.v0":
|
||||
|
|
@ -246,6 +262,7 @@ def handle_raw_put(state: PeerState, message: dict[str, Any], subscriptions: dic
|
|||
if not isinstance(document, dict):
|
||||
return []
|
||||
applied = apply_raw_document_put(state, document)
|
||||
append_shard_log_put(state, message, document)
|
||||
responses = database_change_notifications(message, document, subscriptions)
|
||||
schema_id = document.get("schemaId")
|
||||
if schema_id == INTEROP_MUTATION_INTENT_SCHEMA_ID:
|
||||
|
|
@ -286,6 +303,94 @@ def handle_raw_put(state: PeerState, message: dict[str, Any], subscriptions: dic
|
|||
return responses
|
||||
|
||||
|
||||
def shard_catalog_response(state: PeerState, request: dict[str, Any]) -> dict[str, Any]:
|
||||
schema_ids = {str(value) for value in request.get("schemaIds") or []}
|
||||
record_keys = {str(value) for value in request.get("recordKeys") or []}
|
||||
include_shard = not schema_ids or state.note_schema_id in schema_ids
|
||||
if record_keys and not any(key.startswith("note:") for key in record_keys):
|
||||
include_shard = False
|
||||
return {
|
||||
"schemaVersion": "cultnet.shard_catalog_response.v0",
|
||||
"messageId": request.get("messageId", ""),
|
||||
"shards": [shard_descriptor(state)] if include_shard else [],
|
||||
}
|
||||
|
||||
|
||||
def shard_descriptor(state: PeerState) -> dict[str, Any]:
|
||||
return {
|
||||
"shardId": state.shard_id,
|
||||
"ownerRuntimeId": state.runtime_id,
|
||||
"epoch": state.shard_epoch,
|
||||
"isPrimary": True,
|
||||
"schemaIds": [state.note_schema_id],
|
||||
"keyPrefix": "note:",
|
||||
"primaryEndpoints": [state.shard_endpoint],
|
||||
"replicaEndpoints": [],
|
||||
"readReplicaEndpoints": [state.shard_endpoint],
|
||||
"region": "local",
|
||||
}
|
||||
|
||||
|
||||
def shard_log_response(state: PeerState, request: dict[str, Any]) -> dict[str, Any]:
|
||||
requested_shard = str(request.get("shardId") or "")
|
||||
message_id = request.get("messageId", "")
|
||||
if requested_shard != state.shard_id:
|
||||
return {
|
||||
"schemaVersion": "cultnet.shard_log_response.v0",
|
||||
"messageId": message_id,
|
||||
"shardId": requested_shard,
|
||||
"shardEpoch": 0,
|
||||
"entries": [],
|
||||
"resyncRequired": True,
|
||||
"reason": "unknown_shard",
|
||||
}
|
||||
requested_epoch = request.get("shardEpoch")
|
||||
if isinstance(requested_epoch, int) and requested_epoch != state.shard_epoch:
|
||||
return {
|
||||
"schemaVersion": "cultnet.shard_log_response.v0",
|
||||
"messageId": message_id,
|
||||
"shardId": state.shard_id,
|
||||
"shardEpoch": state.shard_epoch,
|
||||
"entries": [],
|
||||
"resyncRequired": True,
|
||||
"reason": "stale_epoch",
|
||||
}
|
||||
after_sequence = request.get("afterSequence")
|
||||
if not isinstance(after_sequence, int):
|
||||
after_sequence = 0
|
||||
limit = request.get("limit")
|
||||
with state.shard_log_lock:
|
||||
entries = [entry for entry in state.shard_log if entry["sequence"] > after_sequence]
|
||||
if isinstance(limit, int) and limit >= 0:
|
||||
entries = entries[:limit]
|
||||
return {
|
||||
"schemaVersion": "cultnet.shard_log_response.v0",
|
||||
"messageId": message_id,
|
||||
"shardId": state.shard_id,
|
||||
"shardEpoch": state.shard_epoch,
|
||||
"entries": entries,
|
||||
"resyncRequired": False,
|
||||
}
|
||||
|
||||
|
||||
def append_shard_log_put(state: PeerState, message: dict[str, Any], document: dict[str, Any]) -> None:
|
||||
with state.shard_log_lock:
|
||||
sequence = len(state.shard_log) + 1
|
||||
put_message = {
|
||||
"schemaVersion": "cultnet.document_put_raw.v0",
|
||||
"messageId": message.get("messageId", ""),
|
||||
"document": document,
|
||||
"shardId": state.shard_id,
|
||||
"shardEpoch": state.shard_epoch,
|
||||
}
|
||||
state.shard_log.append({
|
||||
"sequence": sequence,
|
||||
"committedAt": now_iso(),
|
||||
"changeKind": "put",
|
||||
"put": put_message,
|
||||
})
|
||||
|
||||
|
||||
def database_change_notifications(message: dict[str, Any], document: dict[str, Any], subscriptions: dict[str, DatabaseSubscription]) -> list[dict[str, Any]]:
|
||||
notifications = []
|
||||
for subscription in subscriptions.values():
|
||||
|
|
@ -421,7 +526,15 @@ def dial(args: argparse.Namespace) -> None:
|
|||
})
|
||||
|
||||
|
||||
def build_state(runtime_id: str, runtime_kind: str, display_name: str, agent_id: str, schema_path: str, store_suffix: str = "") -> PeerState:
|
||||
def build_state(
|
||||
runtime_id: str,
|
||||
runtime_kind: str,
|
||||
display_name: str,
|
||||
agent_id: str,
|
||||
schema_path: str,
|
||||
store_suffix: str = "",
|
||||
shard_endpoint: str | None = None,
|
||||
) -> PeerState:
|
||||
schema_json = Path(schema_path).read_text(encoding="utf-8")
|
||||
schema = json.loads(schema_json)
|
||||
note_schema_id = schema["$id"]
|
||||
|
|
@ -444,6 +557,11 @@ def build_state(runtime_id: str, runtime_kind: str, display_name: str, agent_id:
|
|||
interop_schema_json=schema_json,
|
||||
verse_catalog=default_verse_catalog(runtime_id),
|
||||
peer_catalog=default_peer_catalog(runtime_id),
|
||||
shard_id="interop",
|
||||
shard_epoch=1,
|
||||
shard_endpoint=shard_endpoint or f"cultnet://{runtime_id}",
|
||||
shard_log=[],
|
||||
shard_log_lock=threading.Lock(),
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -571,7 +689,13 @@ def raw_snapshot_response(state: PeerState, request: dict[str, Any]) -> dict[str
|
|||
if record_keys and envelope.key not in record_keys:
|
||||
continue
|
||||
documents.append(raw_record_from_envelope(envelope, schema_id))
|
||||
return {"schemaVersion": "cultnet.snapshot_response_raw.v0", "messageId": request.get("messageId", ""), "documents": documents}
|
||||
response: dict[str, Any] = {"schemaVersion": "cultnet.snapshot_response_raw.v0", "messageId": request.get("messageId", ""), "documents": documents}
|
||||
if request.get("shardId") == state.shard_id:
|
||||
with state.shard_log_lock:
|
||||
response["shardId"] = state.shard_id
|
||||
response["shardEpoch"] = state.shard_epoch
|
||||
response["shardLogSequence"] = len(state.shard_log)
|
||||
return response
|
||||
|
||||
|
||||
def raw_document_put(binding: Binding, message_id: str, key: str, value: dict[str, Any], state: PeerState) -> dict[str, Any]:
|
||||
|
|
|
|||
|
|
@ -115,3 +115,35 @@ def database_unsubscribe(*, subscription_id: str, message_id: str = "") -> CultN
|
|||
"cultnet.database_unsubscribe.v0",
|
||||
{"messageId": message_id, "subscriptionId": subscription_id},
|
||||
)
|
||||
|
||||
|
||||
def shard_catalog_request(
|
||||
*,
|
||||
message_id: str = "",
|
||||
schema_ids: list[str] | None = None,
|
||||
record_keys: list[str] | None = None,
|
||||
) -> CultNetMessage:
|
||||
return CultNetMessage(
|
||||
"cultnet.shard_catalog_request.v0",
|
||||
{"messageId": message_id, "schemaIds": schema_ids or [], "recordKeys": record_keys or []},
|
||||
)
|
||||
|
||||
|
||||
def shard_log_request(
|
||||
*,
|
||||
shard_id: str,
|
||||
message_id: str = "",
|
||||
shard_epoch: int | None = None,
|
||||
after_sequence: int = 0,
|
||||
limit: int | None = None,
|
||||
) -> CultNetMessage:
|
||||
body: dict[str, Any] = {
|
||||
"messageId": message_id,
|
||||
"shardId": shard_id,
|
||||
"afterSequence": after_sequence,
|
||||
}
|
||||
if shard_epoch is not None:
|
||||
body["shardEpoch"] = shard_epoch
|
||||
if limit is not None:
|
||||
body["limit"] = limit
|
||||
return CultNetMessage("cultnet.shard_log_request.v0", body)
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ from cultcache_py import (
|
|||
define_document_type,
|
||||
)
|
||||
from cultcache_py.interop import read_note, write_note
|
||||
from cultnet_py import database_subscribe, database_unsubscribe, decode_frame, document_put_raw, encode_frame, hello, parse_message
|
||||
from cultnet_py import database_subscribe, database_unsubscribe, decode_frame, document_put_raw, encode_frame, hello, parse_message, shard_catalog_request, shard_log_request
|
||||
from cultmesh_py import create_node
|
||||
from cultmesh_py import (
|
||||
CultMeshPeerCard,
|
||||
|
|
@ -207,6 +207,31 @@ class CultCacheTests(unittest.TestCase):
|
|||
self.assertEqual(put["document"]["recordKey"], "record-a")
|
||||
self.assertEqual(put["document"]["sourceRuntimeId"], "python-test")
|
||||
|
||||
def test_cultnet_shard_helpers_match_schema_v0_shape(self) -> None:
|
||||
catalog = shard_catalog_request(
|
||||
message_id="catalog-1",
|
||||
schema_ids=["schema-a"],
|
||||
record_keys=["record-a"],
|
||||
).to_wire()
|
||||
self.assertEqual(catalog["schemaVersion"], "cultnet.shard_catalog_request.v0")
|
||||
self.assertEqual(catalog["messageId"], "catalog-1")
|
||||
self.assertEqual(catalog["schemaIds"], ["schema-a"])
|
||||
self.assertEqual(catalog["recordKeys"], ["record-a"])
|
||||
|
||||
log = shard_log_request(
|
||||
message_id="log-1",
|
||||
shard_id="interop",
|
||||
shard_epoch=7,
|
||||
after_sequence=3,
|
||||
limit=2,
|
||||
).to_wire()
|
||||
self.assertEqual(log["schemaVersion"], "cultnet.shard_log_request.v0")
|
||||
self.assertEqual(log["messageId"], "log-1")
|
||||
self.assertEqual(log["shardId"], "interop")
|
||||
self.assertEqual(log["shardEpoch"], 7)
|
||||
self.assertEqual(log["afterSequence"], 3)
|
||||
self.assertEqual(log["limit"], 2)
|
||||
|
||||
def test_cultmesh_node_uses_cultcache_store(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
document = define_database_entry_type("mesh.note", [("body", 0)])
|
||||
|
|
|
|||
|
|
@ -295,6 +295,52 @@ test("CultNet TS/Rust/C#/Python peers discover each other and exchange raw state
|
|||
assert.equal(pythonChange.document.schemaId, interopNoteSchemaId);
|
||||
assert.equal(pythonChange.document.recordKey, "note:ts-python-sub");
|
||||
|
||||
const pythonShard = await requestPythonShardCatalogAndLog(pythonPort, {
|
||||
schemaVersion: "cultnet.shard_catalog_request.v0",
|
||||
messageId: "python-shards",
|
||||
schemaIds: [interopNoteSchemaId],
|
||||
recordKeys: ["note:ts-python-log"],
|
||||
}, {
|
||||
schemaVersion: "cultnet.document_put_raw.v0",
|
||||
messageId: "python-shard-put",
|
||||
document: {
|
||||
schemaId: interopNoteSchemaId,
|
||||
recordKey: "note:ts-python-log",
|
||||
storedAt: "2026-06-13T00:00:01Z",
|
||||
payloadEncoding: "messagepack",
|
||||
payload: encode([
|
||||
INTEROP_SCHEMA_VERSION,
|
||||
"note:ts-python-log",
|
||||
"ts-python-log",
|
||||
"Shard log note",
|
||||
"Python exposes accepted raw puts through the CultNet shard log lane.",
|
||||
["interop", "shard-log"],
|
||||
]),
|
||||
sourceRuntimeId: "ts-python-log",
|
||||
},
|
||||
}, {
|
||||
schemaVersion: "cultnet.shard_log_request.v0",
|
||||
messageId: "python-log",
|
||||
shardId: "interop",
|
||||
shardEpoch: 1,
|
||||
afterSequence: 0,
|
||||
});
|
||||
assert.equal(pythonShard.catalog.schemaVersion, "cultnet.shard_catalog_response.v0");
|
||||
assert.equal(pythonShard.catalog.messageId, "python-shards");
|
||||
assert.equal(pythonShard.catalog.shards[0].shardId, "interop");
|
||||
assert.equal(pythonShard.catalog.shards[0].ownerRuntimeId, "python-peer");
|
||||
assert.equal(pythonShard.catalog.shards[0].epoch, 1);
|
||||
assert.equal(pythonShard.log.schemaVersion, "cultnet.shard_log_response.v0");
|
||||
assert.equal(pythonShard.log.messageId, "python-log");
|
||||
assert.equal(pythonShard.log.shardId, "interop");
|
||||
assert.equal(pythonShard.log.shardEpoch, 1);
|
||||
assert.equal(pythonShard.log.resyncRequired, false);
|
||||
assert.ok(pythonShard.log.entries.some((entry: any) =>
|
||||
entry.changeKind === "put"
|
||||
&& entry.put?.messageId === "python-shard-put"
|
||||
&& entry.put?.document?.recordKey === "note:ts-python-log"
|
||||
));
|
||||
|
||||
const expectedPeers = ["csharp-peer", "python-peer", "rust-peer", "ts-peer"];
|
||||
|
||||
await expectProbePeers("ts-probe", process.execPath, [
|
||||
|
|
@ -536,6 +582,48 @@ async function requestPythonDatabaseChange(port: number, subscribe: Record<strin
|
|||
});
|
||||
}
|
||||
|
||||
async function requestPythonShardCatalogAndLog(
|
||||
port: number,
|
||||
catalogRequest: Record<string, unknown>,
|
||||
put: Record<string, unknown>,
|
||||
logRequest: Record<string, unknown>,
|
||||
): Promise<{ catalog: any; log: any }> {
|
||||
const socket = connectTcp(port, "127.0.0.1");
|
||||
const framer = new LengthPrefixedMessageFramer();
|
||||
await once(socket, "connect");
|
||||
|
||||
return await new Promise((resolve, reject) => {
|
||||
const result: { catalog?: any; log?: any } = {};
|
||||
const timeout = setTimeout(() => {
|
||||
socket.destroy();
|
||||
reject(new Error("Timed out waiting for Python shard catalog/log responses."));
|
||||
}, 5000);
|
||||
|
||||
socket.on("data", (chunk) => {
|
||||
for (const frame of framer.push(chunk)) {
|
||||
const decoded = decode(frame) as any;
|
||||
if (decoded?.schemaVersion === "cultnet.shard_catalog_response.v0") {
|
||||
result.catalog = decoded;
|
||||
socket.write(encodeFrame(encode(put)));
|
||||
socket.write(encodeFrame(encode(logRequest)));
|
||||
} else if (decoded?.schemaVersion === "cultnet.shard_log_response.v0") {
|
||||
result.log = decoded;
|
||||
}
|
||||
if (result.catalog && result.log) {
|
||||
clearTimeout(timeout);
|
||||
socket.end();
|
||||
resolve({ catalog: result.catalog, log: result.log });
|
||||
}
|
||||
}
|
||||
});
|
||||
socket.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
socket.write(encodeFrame(encode(catalogRequest)));
|
||||
});
|
||||
}
|
||||
|
||||
async function stopProcess(processState: RunningServeProcess): Promise<void> {
|
||||
if (processState.child.killed || processState.child.exitCode !== null) {
|
||||
return;
|
||||
|
|
|
|||
Loading…
Reference in a new issue