Add Python CultNet delete interop

This commit is contained in:
Meta Vens 2026-06-13 22:42:30 +01:00
commit dec000882d
5 changed files with 192 additions and 15 deletions

View file

@ -227,11 +227,11 @@ Current receipts:
CultCache v1 parity matrix with TypeScript, Rust, and C#.
- `packages/cultnet-ts/test/interop/cultnet-interop.test.ts` includes Python in
the live TS/Rust/C#/Python schema-v0 peer ring: discovery, hello, schema
catalog, raw snapshot, raw document put, mutation receipt, fire-command
receipt, database subscription changes, shard catalog, shard log catch-up,
simulation consensus candidates, and witness artifact bundle round-trips. The
same test asks the Python peer for CultMesh Verse catalog and peer exchange
responses over the CultNet pipe.
catalog, raw snapshot, raw document put/delete, mutation receipt,
fire-command receipt, database subscription changes, shard catalog, shard log
catch-up, simulation consensus candidates, and witness artifact bundle
round-trips. The same test asks the Python peer for CultMesh Verse catalog and
peer exchange responses over the CultNet pipe.
- `packages/cultcache-py/tests/test_cultcache.py` covers Python CultMesh
Verse catalog, peer exchange, authority lease, stream negotiation, CultNet
helper shapes, simulation claim hashing, and witness artifact bundle payload

View file

@ -244,6 +244,8 @@ def handle_server_message(state: PeerState, message: dict[str, Any], subscriptio
return []
if schema_version == "cultnet.document_put_raw.v0":
return handle_raw_put(state, message, subscriptions)
if schema_version == "cultnet.document_delete.v0":
return handle_document_delete(state, message, subscriptions)
if schema_version == VERSE_CATALOG_REQUEST:
return [state.verse_catalog.create_response(message)]
if schema_version == PEER_EXCHANGE_REQUEST:
@ -311,6 +313,19 @@ def handle_raw_put(state: PeerState, message: dict[str, Any], subscriptions: dic
return responses
def handle_document_delete(state: PeerState, message: dict[str, Any], subscriptions: dict[str, DatabaseSubscription]) -> list[dict[str, Any]]:
schema_id = str(message.get("schemaId") or "")
record_key = str(message.get("recordKey") or "")
binding = state.bindings_by_schema_id.get(schema_id)
if binding is None or not record_key:
return []
if state.cache.get(binding.document, record_key) is None:
return []
state.cache.delete(binding.document, record_key)
append_shard_log_delete(state, message)
return database_delete_notifications(message, subscriptions)
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 []}
@ -394,11 +409,30 @@ def append_shard_log_put(state: PeerState, message: dict[str, Any], document: di
state.shard_log.append({
"sequence": sequence,
"committedAt": now_iso(),
"changeKind": "put",
"changeKind": "added",
"put": put_message,
})
def append_shard_log_delete(state: PeerState, message: dict[str, Any]) -> None:
with state.shard_log_lock:
sequence = len(state.shard_log) + 1
delete_message = {
"schemaVersion": "cultnet.document_delete.v0",
"messageId": message.get("messageId", ""),
"schemaId": message.get("schemaId", ""),
"recordKey": message.get("recordKey", ""),
"shardId": state.shard_id,
"shardEpoch": state.shard_epoch,
}
state.shard_log.append({
"sequence": sequence,
"committedAt": now_iso(),
"changeKind": "removed",
"delete": delete_message,
})
def simulation_candidate_responses(state: PeerState, message: dict[str, Any]) -> list[dict[str, Any]]:
observation = message.get("observation")
if not isinstance(observation, dict):
@ -469,12 +503,32 @@ def database_change_notifications(message: dict[str, Any], document: dict[str, A
"schemaVersion": "cultnet.database_change_raw.v0",
"messageId": f"{message_id}:{subscription.subscription_id}",
"subscriptionId": subscription.subscription_id,
"changeKind": "put",
"changeKind": "added",
"document": document,
})
return notifications
def database_delete_notifications(message: dict[str, Any], subscriptions: dict[str, DatabaseSubscription]) -> list[dict[str, Any]]:
schema_id = str(message.get("schemaId") or "")
record_key = str(message.get("recordKey") or "")
notifications = []
document = {"schemaId": schema_id, "recordKey": record_key}
for subscription in subscriptions.values():
if not subscription.matches(document):
continue
message_id = message.get("messageId") or record_key or "change"
notifications.append({
"schemaVersion": "cultnet.database_change_raw.v0",
"messageId": f"{message_id}:{subscription.subscription_id}",
"subscriptionId": subscription.subscription_id,
"changeKind": "removed",
"schemaId": schema_id,
"recordKey": record_key,
})
return notifications
def discovery_loop(sock: socket.socket, advertise_host: str, tcp_port: int, state: PeerState, stop: threading.Event) -> None:
while not stop.is_set():
try:

View file

@ -70,11 +70,20 @@ def document_put_raw(
return CultNetMessage("cultnet.document_put_raw.v0", {"messageId": message_id, "document": record})
def document_delete(*, schema_id: str, record_key: str, deleted_at: str) -> CultNetMessage:
return CultNetMessage(
"cultnet.document_delete.v0",
{"schemaId": schema_id, "recordKey": record_key, "deletedAt": deleted_at},
)
def document_delete(
*,
message_id: str = "",
schema_id: str,
record_key: str,
shard_id: str | None = None,
shard_epoch: int | None = None,
) -> CultNetMessage:
body: dict[str, Any] = {"messageId": message_id, "schemaId": schema_id, "recordKey": record_key}
if shard_id is not None:
body["shardId"] = shard_id
if shard_epoch is not None:
body["shardEpoch"] = shard_epoch
return CultNetMessage("cultnet.document_delete.v0", body)
def snapshot_request(*, message_id: str = "", schema_ids: list[str] | None = None, record_keys: list[str] | None = None) -> CultNetMessage:

View file

@ -14,7 +14,7 @@ from cultcache_py import (
define_document_type,
)
from cultcache_py.interop import read_note, write_note
from cultnet_py import compute_simulation_claim_hash, database_subscribe, database_unsubscribe, decode_frame, decode_witness_artifact_bundle_payload, document_put_raw, encode_frame, encode_witness_artifact_bundle_payload, hello, parse_message, shard_catalog_request, shard_log_request, simulation_observation, witness_artifact_bundle
from cultnet_py import compute_simulation_claim_hash, database_subscribe, database_unsubscribe, decode_frame, decode_witness_artifact_bundle_payload, document_delete, document_put_raw, encode_frame, encode_witness_artifact_bundle_payload, hello, parse_message, shard_catalog_request, shard_log_request, simulation_observation, witness_artifact_bundle
from cultmesh_py import create_node
from cultmesh_py import (
CultMeshPeerCard,
@ -207,6 +207,21 @@ class CultCacheTests(unittest.TestCase):
self.assertEqual(put["document"]["recordKey"], "record-a")
self.assertEqual(put["document"]["sourceRuntimeId"], "python-test")
def test_cultnet_document_delete_helper_matches_schema_v0_shape(self) -> None:
message = document_delete(
message_id="delete-1",
schema_id="schema-a",
record_key="record-a",
shard_id="interop",
shard_epoch=1,
).to_wire()
self.assertEqual(message["schemaVersion"], "cultnet.document_delete.v0")
self.assertEqual(message["messageId"], "delete-1")
self.assertEqual(message["schemaId"], "schema-a")
self.assertEqual(message["recordKey"], "record-a")
self.assertEqual(message["shardId"], "interop")
self.assertEqual(message["shardEpoch"], 1)
def test_cultnet_shard_helpers_match_schema_v0_shape(self) -> None:
catalog = shard_catalog_request(
message_id="catalog-1",

View file

@ -293,7 +293,7 @@ test("CultNet TS/Rust/C#/Python peers discover each other and exchange raw state
});
assert.equal(pythonChange.schemaVersion, "cultnet.database_change_raw.v0");
assert.equal(pythonChange.subscriptionId, "python-sub");
assert.equal(pythonChange.changeKind, "put");
assert.equal(pythonChange.changeKind, "added");
assert.equal(pythonChange.document.schemaId, interopNoteSchemaId);
assert.equal(pythonChange.document.recordKey, "note:ts-python-sub");
@ -338,11 +338,63 @@ test("CultNet TS/Rust/C#/Python peers discover each other and exchange raw state
assert.equal(pythonShard.log.shardEpoch, 1);
assert.equal(pythonShard.log.resyncRequired, false);
assert.ok(pythonShard.log.entries.some((entry: any) =>
entry.changeKind === "put"
entry.changeKind === "added"
&& entry.put?.messageId === "python-shard-put"
&& entry.put?.document?.recordKey === "note:ts-python-log"
));
const pythonDelete = await requestPythonDatabaseDelete(pythonPort, {
schemaVersion: "cultnet.database_subscribe.v0",
messageId: "python-delete-subscribe",
subscriptionId: "python-delete-sub",
schemaIds: [interopNoteSchemaId],
recordKeys: ["note:ts-python-delete"],
includeSnapshot: false,
}, {
schemaVersion: "cultnet.document_put_raw.v0",
messageId: "python-delete-put",
document: {
schemaId: interopNoteSchemaId,
recordKey: "note:ts-python-delete",
storedAt: "2026-06-13T00:00:01Z",
payloadEncoding: "messagepack",
payload: encode([
INTEROP_SCHEMA_VERSION,
"note:ts-python-delete",
"ts-python-delete",
"Delete note",
"Python should remove this through the CultNet delete lane.",
["interop", "delete"],
]),
sourceRuntimeId: "ts-python-delete",
},
}, {
schemaVersion: "cultnet.document_delete.v0",
messageId: "python-delete",
schemaId: interopNoteSchemaId,
recordKey: "note:ts-python-delete",
shardId: "interop",
shardEpoch: 1,
}, {
schemaVersion: "cultnet.shard_log_request.v0",
messageId: "python-delete-log",
shardId: "interop",
shardEpoch: 1,
afterSequence: 0,
});
assert.equal(pythonDelete.change.schemaVersion, "cultnet.database_change_raw.v0");
assert.equal(pythonDelete.change.subscriptionId, "python-delete-sub");
assert.equal(pythonDelete.change.changeKind, "removed");
assert.equal(pythonDelete.change.schemaId, interopNoteSchemaId);
assert.equal(pythonDelete.change.recordKey, "note:ts-python-delete");
assert.ok(pythonDelete.log.entries.some((entry: any) =>
entry.changeKind === "removed"
&& entry.delete?.messageId === "python-delete"
&& entry.delete?.schemaId === interopNoteSchemaId
&& entry.delete?.recordKey === "note:ts-python-delete"
&& entry.delete?.shardEpoch === 1
));
const claimHash = computeSimulationClaimHash("frame:42", "subject:python-target", "hit");
const pythonCandidate = await requestPythonSimulationCandidate(pythonPort, {
schemaVersion: "cultnet.simulation_observation.v0",
@ -654,6 +706,53 @@ async function requestPythonDatabaseChange(port: number, subscribe: Record<strin
});
}
async function requestPythonDatabaseDelete(
port: number,
subscribe: Record<string, unknown>,
put: Record<string, unknown>,
remove: Record<string, unknown>,
logRequest: Record<string, unknown>,
): Promise<{ change: 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: { change?: any; log?: any } = {};
let sawAdded = false;
const timeout = setTimeout(() => {
socket.destroy();
reject(new Error("Timed out waiting for Python delete change/log responses."));
}, 5000);
socket.on("data", (chunk) => {
for (const frame of framer.push(chunk)) {
const decoded = decode(frame) as any;
if (decoded?.schemaVersion === "cultnet.database_change_raw.v0" && decoded.changeKind === "added") {
sawAdded = true;
socket.write(encodeFrame(encode(remove)));
socket.write(encodeFrame(encode(logRequest)));
} else if (decoded?.schemaVersion === "cultnet.database_change_raw.v0" && decoded.changeKind === "removed") {
result.change = decoded;
} else if (decoded?.schemaVersion === "cultnet.shard_log_response.v0") {
result.log = decoded;
}
if (sawAdded && result.change && result.log) {
clearTimeout(timeout);
socket.end();
resolve({ change: result.change, log: result.log });
}
}
});
socket.once("error", (error) => {
clearTimeout(timeout);
reject(error);
});
socket.write(encodeFrame(encode(subscribe)));
socket.write(encodeFrame(encode(put)));
});
}
async function requestPythonShardCatalogAndLog(
port: number,
catalogRequest: Record<string, unknown>,