Benchmark Python runtime hot paths
This commit is contained in:
parent
25afb9915c
commit
5ac5f2fb81
6 changed files with 227 additions and 12 deletions
|
|
@ -79,6 +79,7 @@ settings = cache.get_required_global(settings_doc)
|
|||
- `get_global(...)`
|
||||
- `get_required_global(...)`
|
||||
- `put(...)`
|
||||
- `put_envelopes(...)`
|
||||
- `put_global(...)`
|
||||
- `update(...)`
|
||||
- `update_global(...)`
|
||||
|
|
@ -260,3 +261,16 @@ Current receipts:
|
|||
- `cultcache_py`, `cultnet_py`, and `cultmesh_py` ship `py.typed` markers so
|
||||
downstream type checkers can inspect the package surface instead of treating
|
||||
the runtime as an untyped xenos swamp.
|
||||
|
||||
## Performance Baseline
|
||||
|
||||
The package ships a lightweight benchmark for Python-owned hot paths:
|
||||
|
||||
```powershell
|
||||
python -m cultcache_py.benchmark --records 1000 --json
|
||||
```
|
||||
|
||||
It reports slot-indexed `DatabaseEntry` encode/decode throughput, framed
|
||||
CultNet MessagePack parse throughput, and raw snapshot application into a
|
||||
registered cache. Treat it as a local baseline, not a claim that Python matches
|
||||
the C# reference in every workload.
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ msgpack = ["msgpack>=1.0"]
|
|||
[project.scripts]
|
||||
cultcache-py-interop = "cultcache_py.interop:main"
|
||||
cultnet-py-interop = "cultnet_py.interop_peer:main"
|
||||
cultcache-py-benchmark = "cultcache_py.benchmark:main"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
|
|
|
|||
135
packages/cultcache-py/src/cultcache_py/benchmark.py
Normal file
135
packages/cultcache-py/src/cultcache_py/benchmark.py
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from cultcache_py import CultCache, CultCacheEnvelope, define_database_entry_type
|
||||
from cultnet_py import apply_raw_snapshot, decode_frame, encode_frame, parse_message
|
||||
from cultnet_py.messages import document_put_raw
|
||||
|
||||
|
||||
@dataclass
|
||||
class BenchItem:
|
||||
name: str
|
||||
category: str
|
||||
value: int
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="cultcache-py-benchmark")
|
||||
parser.add_argument("--records", type=int, default=5000)
|
||||
parser.add_argument("--json", action="store_true", dest="as_json")
|
||||
args = parser.parse_args(argv)
|
||||
if args.records <= 0:
|
||||
raise ValueError("--records must be greater than zero")
|
||||
result = run_benchmark(args.records)
|
||||
if args.as_json:
|
||||
print(json.dumps(result, sort_keys=True))
|
||||
else:
|
||||
print(f"records: {result['records']}")
|
||||
for metric in result["metrics"]:
|
||||
print(f"{metric['name']}: {metric['opsPerSecond']:.0f} ops/s ({metric['elapsedMs']:.2f} ms)")
|
||||
return 0
|
||||
|
||||
|
||||
def run_benchmark(records: int) -> dict[str, Any]:
|
||||
document = define_database_entry_type(
|
||||
"bench.item",
|
||||
[
|
||||
("name", 0),
|
||||
("category", 1),
|
||||
("value", 2, 0),
|
||||
],
|
||||
cls=BenchItem,
|
||||
)
|
||||
values = [BenchItem(f"item-{index}", f"cat-{index % 8}", index) for index in range(records)]
|
||||
|
||||
encoded_payloads, encode_metric = measure("database_entry_encode", records, lambda: [
|
||||
document.encode_payload(value)
|
||||
for value in values
|
||||
])
|
||||
_, decode_metric = measure("database_entry_decode", records, lambda: [
|
||||
document.decode_payload(payload)
|
||||
for payload in encoded_payloads
|
||||
])
|
||||
wire_messages, frame_metric = measure("cultnet_frame_parse", records, lambda: [
|
||||
parse_message(decode_frame(encode_frame(document_put_raw(
|
||||
message_id=f"put-{index}",
|
||||
key=f"item:{index}",
|
||||
schema_id=document.catalog_entry().schema_id,
|
||||
stored_at="2026-06-13T00:00:00Z",
|
||||
payload=encoded_payloads[index],
|
||||
source_runtime_id="python-benchmark",
|
||||
shard_id="bench",
|
||||
shard_epoch=1,
|
||||
).to_bytes())))
|
||||
for index in range(records)
|
||||
])
|
||||
|
||||
snapshot = {
|
||||
"schemaVersion": "cultnet.snapshot_response_raw.v0",
|
||||
"messageId": "bench-snapshot",
|
||||
"documents": [
|
||||
{
|
||||
"schemaId": document.catalog_entry().schema_id,
|
||||
"recordKey": f"item:{index}",
|
||||
"storedAt": "2026-06-13T00:00:00Z",
|
||||
"payloadEncoding": "messagepack",
|
||||
"payload": encoded_payloads[index],
|
||||
}
|
||||
for index in range(records)
|
||||
],
|
||||
}
|
||||
|
||||
cache = CultCache()
|
||||
cache.register_document_type(document)
|
||||
cache.add_generic_store(InMemoryBackingStore())
|
||||
_, apply_metric = measure("raw_snapshot_apply", records, lambda: apply_raw_snapshot(cache, [document], snapshot))
|
||||
|
||||
return {
|
||||
"records": records,
|
||||
"metrics": [
|
||||
encode_metric,
|
||||
decode_metric,
|
||||
frame_metric,
|
||||
apply_metric,
|
||||
],
|
||||
"wireMessageCount": len(wire_messages),
|
||||
}
|
||||
|
||||
|
||||
def measure(name: str, operations: int, action: Any) -> tuple[Any, dict[str, Any]]:
|
||||
started = time.perf_counter()
|
||||
result = action()
|
||||
elapsed = time.perf_counter() - started
|
||||
return result, {
|
||||
"name": name,
|
||||
"operations": operations,
|
||||
"elapsedMs": elapsed * 1000,
|
||||
"opsPerSecond": operations / elapsed if elapsed > 0 else float("inf"),
|
||||
}
|
||||
|
||||
|
||||
class InMemoryBackingStore:
|
||||
def __init__(self) -> None:
|
||||
self._records: dict[tuple[str, str], CultCacheEnvelope] = {}
|
||||
|
||||
def pull_all(self) -> list[CultCacheEnvelope]:
|
||||
return list(self._records.values())
|
||||
|
||||
def push(self, envelope: CultCacheEnvelope) -> None:
|
||||
self._records[(envelope.type, envelope.key)] = envelope
|
||||
|
||||
def push_all(self, envelopes: list[CultCacheEnvelope]) -> None:
|
||||
for envelope in envelopes:
|
||||
self.push(envelope)
|
||||
|
||||
def delete(self, type: str, key: str) -> None:
|
||||
self._records.pop((type, key), None)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
|
@ -200,6 +200,27 @@ class CultCache:
|
|||
self._rebuild_indexes()
|
||||
return value
|
||||
|
||||
def put_envelopes(self, document: DocumentDefinition[T], envelopes: list[CultCacheEnvelope]) -> list[T]:
|
||||
self._assert_registered(document)
|
||||
values: list[T] = []
|
||||
for envelope in envelopes:
|
||||
if envelope.type != document.type:
|
||||
raise CultCacheError(
|
||||
f"Envelope type {envelope.type} does not match document type {document.type}"
|
||||
)
|
||||
if document.global_document and envelope.key != GLOBAL_KEY:
|
||||
raise CultCacheError(f"Global document {document.type} must use key {GLOBAL_KEY}")
|
||||
values.append(document.decode_payload(envelope.payload))
|
||||
|
||||
stores = self._stores_for_type(document.type)
|
||||
for store in stores:
|
||||
store.push_all(envelopes)
|
||||
for envelope, value in zip(envelopes, values):
|
||||
self._state.values[(document.type, envelope.key)] = value
|
||||
self._state.envelopes[(document.type, envelope.key)] = envelope
|
||||
self._rebuild_indexes()
|
||||
return values
|
||||
|
||||
def put_global(self, document: DocumentDefinition[T], value: T) -> None:
|
||||
self._assert_global(document)
|
||||
self.put(document, GLOBAL_KEY, value)
|
||||
|
|
|
|||
|
|
@ -32,14 +32,7 @@ def apply_raw_document_record(
|
|||
) -> CultNetAppliedRecord:
|
||||
schema_id = str(record["schemaId"])
|
||||
document = documents_by_schema_id[schema_id]
|
||||
envelope = CultCacheEnvelope(
|
||||
key=str(record["recordKey"]),
|
||||
type=document.type,
|
||||
schema_id=schema_id,
|
||||
payload=bytes(record["payload"]),
|
||||
stored_at=str(record.get("storedAt") or ""),
|
||||
catalog_entry=document.catalog_entry(),
|
||||
)
|
||||
envelope = raw_record_to_envelope(document, schema_id, record)
|
||||
value = cache.put_envelope(document, envelope)
|
||||
return CultNetAppliedRecord(
|
||||
schema_id=schema_id,
|
||||
|
|
@ -49,6 +42,21 @@ def apply_raw_document_record(
|
|||
)
|
||||
|
||||
|
||||
def raw_record_to_envelope(
|
||||
document: DocumentDefinition[Any],
|
||||
schema_id: str,
|
||||
record: dict[str, Any],
|
||||
) -> CultCacheEnvelope:
|
||||
return CultCacheEnvelope(
|
||||
key=str(record["recordKey"]),
|
||||
type=document.type,
|
||||
schema_id=schema_id,
|
||||
payload=bytes(record["payload"]),
|
||||
stored_at=str(record.get("storedAt") or ""),
|
||||
catalog_entry=document.catalog_entry(),
|
||||
)
|
||||
|
||||
|
||||
def apply_raw_snapshot(
|
||||
cache: CultCache,
|
||||
documents: Iterable[DocumentDefinition[Any]],
|
||||
|
|
@ -57,10 +65,33 @@ def apply_raw_snapshot(
|
|||
if response.get("schemaVersion") != "cultnet.snapshot_response_raw.v0":
|
||||
raise ValueError(f"Expected cultnet.snapshot_response_raw.v0, received {response.get('schemaVersion')!r}")
|
||||
documents_by_schema_id = schema_document_map(documents)
|
||||
batches: dict[str, tuple[DocumentDefinition[Any], list[tuple[str, CultCacheEnvelope]]]] = {}
|
||||
order: list[tuple[DocumentDefinition[Any], str, CultCacheEnvelope]] = []
|
||||
for record in response.get("documents", []):
|
||||
if not isinstance(record, dict):
|
||||
continue
|
||||
schema_id = str(record["schemaId"])
|
||||
document = documents_by_schema_id[schema_id]
|
||||
envelope = raw_record_to_envelope(document, schema_id, record)
|
||||
batch = batches.setdefault(document.type, (document, []))
|
||||
batch[1].append((schema_id, envelope))
|
||||
order.append((document, schema_id, envelope))
|
||||
|
||||
values_by_key: dict[tuple[str, str], Any] = {}
|
||||
for document, entries in batches.values():
|
||||
envelopes = [envelope for _, envelope in entries]
|
||||
values = cache.put_envelopes(document, envelopes)
|
||||
for (_, envelope), value in zip(entries, values):
|
||||
values_by_key[(document.type, envelope.key)] = value
|
||||
|
||||
return [
|
||||
apply_raw_document_record(cache, documents_by_schema_id, record)
|
||||
for record in response.get("documents", [])
|
||||
if isinstance(record, dict)
|
||||
CultNetAppliedRecord(
|
||||
schema_id=schema_id,
|
||||
record_key=envelope.key,
|
||||
change_kind="added",
|
||||
value=values_by_key[(document.type, envelope.key)],
|
||||
)
|
||||
for document, schema_id, envelope in order
|
||||
]
|
||||
|
||||
|
||||
|
|
@ -92,4 +123,3 @@ def apply_shard_log_response(
|
|||
cache.delete(document, record_key)
|
||||
applied.append(CultNetAppliedRecord(schema_id, record_key, "removed", None))
|
||||
return applied
|
||||
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ from cultcache_py import (
|
|||
define_database_entry_type,
|
||||
define_document_type,
|
||||
)
|
||||
from cultcache_py.benchmark import run_benchmark
|
||||
from cultcache_py.interop import read_note, write_note
|
||||
from cultnet_py import (
|
||||
compute_simulation_claim_hash,
|
||||
|
|
@ -193,6 +194,19 @@ class CultCacheTests(unittest.TestCase):
|
|||
self.assertEqual(loaded["authorRuntimeId"], "python-test")
|
||||
self.assertIn("interop", loaded["tags"])
|
||||
|
||||
def test_benchmark_reports_core_hot_path_metrics(self) -> None:
|
||||
result = run_benchmark(8)
|
||||
metric_names = {metric["name"] for metric in result["metrics"]}
|
||||
self.assertEqual(result["records"], 8)
|
||||
self.assertEqual(result["wireMessageCount"], 8)
|
||||
self.assertEqual(metric_names, {
|
||||
"database_entry_encode",
|
||||
"database_entry_decode",
|
||||
"cultnet_frame_parse",
|
||||
"raw_snapshot_apply",
|
||||
})
|
||||
self.assertTrue(all(metric["opsPerSecond"] > 0 for metric in result["metrics"]))
|
||||
|
||||
def test_cultnet_schema_message_frame_round_trip(self) -> None:
|
||||
message = hello(runtime_id="python-test", supported_schema_versions=["cultnet.hello.v0"])
|
||||
parsed = parse_message(decode_frame(encode_frame(message.to_bytes())))
|
||||
|
|
|
|||
Loading…
Reference in a new issue