|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Repeatable Avro Value protocol size and latency benchmark. |
| 3 | +
|
| 4 | +The benchmark compares compact JSON, the prerelease JSON-in-Avro wrapper, and |
| 5 | +the fixed typed Value schema. The production-path regression budget covers the |
| 6 | +fixed codec only; the old wrapper remains here solely as migration evidence. |
| 7 | +""" |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import argparse |
| 11 | +import base64 |
| 12 | +import hashlib |
| 13 | +import io |
| 14 | +import json |
| 15 | +import os |
| 16 | +import statistics |
| 17 | +import time |
| 18 | +from collections.abc import Callable |
| 19 | +from pathlib import Path |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +from fastavro import parse_schema, schemaless_reader, schemaless_writer |
| 23 | + |
| 24 | +from durable_workflow._avro import ( |
| 25 | + decode, |
| 26 | + encode, |
| 27 | +) |
| 28 | + |
| 29 | +OLD_WRAPPER_SCHEMA = parse_schema( |
| 30 | + { |
| 31 | + "type": "record", |
| 32 | + "name": "Payload", |
| 33 | + "namespace": "durable_workflow.protocol.prerelease", |
| 34 | + "fields": [{"name": "json", "type": "string"}, {"name": "version", "type": "int"}], |
| 35 | + } |
| 36 | +) |
| 37 | +CORPUS_PATH = Path(__file__).parents[1] / "schema" / "avro-value-benchmark-v1.json" |
| 38 | +CORPUS_BYTES = CORPUS_PATH.read_bytes() |
| 39 | +CORPUS = json.loads(CORPUS_BYTES) |
| 40 | +JSON_SAMPLE: dict[str, Any] = CORPUS["value"] |
| 41 | + |
| 42 | + |
| 43 | +def _adapt_bytes(value: Any) -> Any: |
| 44 | + if isinstance(value, dict) and list(value) == ["$avro_bytes"]: |
| 45 | + return base64.b64decode(value["$avro_bytes"], validate=True) |
| 46 | + if isinstance(value, dict): |
| 47 | + return {key: _adapt_bytes(item) for key, item in value.items()} |
| 48 | + if isinstance(value, list): |
| 49 | + return [_adapt_bytes(item) for item in value] |
| 50 | + return value |
| 51 | + |
| 52 | + |
| 53 | +SAMPLE: dict[str, Any] = _adapt_bytes(JSON_SAMPLE) |
| 54 | + |
| 55 | + |
| 56 | +def _json_value(value: Any) -> Any: |
| 57 | + if isinstance(value, bytes): |
| 58 | + return {"$type": "bytes", "base64": base64.b64encode(value).decode("ascii")} |
| 59 | + if isinstance(value, list): |
| 60 | + return [_json_value(item) for item in value] |
| 61 | + if isinstance(value, dict): |
| 62 | + return {key: _json_value(item) for key, item in value.items()} |
| 63 | + return value |
| 64 | + |
| 65 | + |
| 66 | +def _compact_json(value: Any) -> bytes: |
| 67 | + return json.dumps(_json_value(value), ensure_ascii=False, separators=(",", ":")).encode() |
| 68 | + |
| 69 | + |
| 70 | +def _old_encode(value: Any) -> bytes: |
| 71 | + datum = {"json": _compact_json(value).decode(), "version": 1} |
| 72 | + stream = io.BytesIO() |
| 73 | + stream.write(b"\x00") |
| 74 | + schemaless_writer(stream, OLD_WRAPPER_SCHEMA, datum) |
| 75 | + return stream.getvalue() |
| 76 | + |
| 77 | + |
| 78 | +def _old_decode(payload: bytes) -> Any: |
| 79 | + datum = schemaless_reader(io.BytesIO(payload[1:]), OLD_WRAPPER_SCHEMA) |
| 80 | + return json.loads(datum["json"]) |
| 81 | + |
| 82 | + |
| 83 | +def _measure(action: Callable[[], Any], iterations: int) -> float: |
| 84 | + samples: list[float] = [] |
| 85 | + for _ in range(5): |
| 86 | + started = time.perf_counter_ns() |
| 87 | + for _ in range(iterations): |
| 88 | + action() |
| 89 | + samples.append((time.perf_counter_ns() - started) / iterations / 1_000) |
| 90 | + return statistics.median(samples) |
| 91 | + |
| 92 | + |
| 93 | +def _http_envelope_size(blob: str) -> int: |
| 94 | + return len( |
| 95 | + json.dumps({"codec": "avro", "blob": blob}, separators=(",", ":")).encode() |
| 96 | + ) |
| 97 | + |
| 98 | + |
| 99 | +def main() -> int: |
| 100 | + parser = argparse.ArgumentParser() |
| 101 | + parser.add_argument("--iterations", type=int, default=1_000) |
| 102 | + parser.add_argument("--enforce", action="store_true") |
| 103 | + args = parser.parse_args() |
| 104 | + |
| 105 | + json_bytes = _compact_json(JSON_SAMPLE) |
| 106 | + old_payload = _old_encode(JSON_SAMPLE) |
| 107 | + typed_blob = encode(SAMPLE) |
| 108 | + typed_payload = base64.b64decode(typed_blob) |
| 109 | + |
| 110 | + results = { |
| 111 | + "implementation": "fastavro", |
| 112 | + "corpus": { |
| 113 | + "schema": CORPUS["schema"], |
| 114 | + "case": CORPUS["case"], |
| 115 | + "sha256": hashlib.sha256(CORPUS_BYTES).hexdigest(), |
| 116 | + }, |
| 117 | + "iterations": args.iterations, |
| 118 | + "sizes_bytes": { |
| 119 | + "plain_json": { |
| 120 | + "raw": len(json_bytes), |
| 121 | + "http_envelope": len( |
| 122 | + json.dumps( |
| 123 | + {"codec": "json", "blob": json_bytes.decode()}, |
| 124 | + separators=(",", ":"), |
| 125 | + ).encode() |
| 126 | + ), |
| 127 | + }, |
| 128 | + "old_json_wrapper": { |
| 129 | + "raw_datum": len(old_payload) - 1, |
| 130 | + "framed": len(old_payload), |
| 131 | + "http_envelope": _http_envelope_size(base64.b64encode(old_payload).decode()), |
| 132 | + }, |
| 133 | + "fixed_typed_value": { |
| 134 | + "raw_datum": len(typed_payload) - 10, |
| 135 | + "single_object": len(typed_payload), |
| 136 | + "http_envelope": _http_envelope_size(typed_blob), |
| 137 | + }, |
| 138 | + }, |
| 139 | + "latency_us": { |
| 140 | + "plain_json_encode": _measure( |
| 141 | + lambda: _compact_json(JSON_SAMPLE), args.iterations |
| 142 | + ), |
| 143 | + "plain_json_decode": _measure(lambda: json.loads(json_bytes), args.iterations), |
| 144 | + "old_json_wrapper_encode": _measure( |
| 145 | + lambda: _old_encode(JSON_SAMPLE), args.iterations |
| 146 | + ), |
| 147 | + "old_json_wrapper_decode": _measure( |
| 148 | + lambda: _old_decode(old_payload), args.iterations |
| 149 | + ), |
| 150 | + "fixed_typed_value_encode": _measure(lambda: encode(SAMPLE), args.iterations), |
| 151 | + "fixed_typed_value_decode": _measure(lambda: decode(typed_blob), args.iterations), |
| 152 | + }, |
| 153 | + } |
| 154 | + print(json.dumps(results, indent=2, sort_keys=True)) |
| 155 | + |
| 156 | + if not args.enforce: |
| 157 | + return 0 |
| 158 | + |
| 159 | + encode_budget = float(os.getenv("AVRO_VALUE_ENCODE_BUDGET_US", "125")) |
| 160 | + decode_budget = float(os.getenv("AVRO_VALUE_DECODE_BUDGET_US", "100")) |
| 161 | + failed = ( |
| 162 | + results["latency_us"]["fixed_typed_value_encode"] > encode_budget |
| 163 | + or results["latency_us"]["fixed_typed_value_decode"] > decode_budget |
| 164 | + ) |
| 165 | + if failed: |
| 166 | + print( |
| 167 | + "Avro Value production-path regression budget exceeded: " |
| 168 | + f"encode <= {encode_budget:g} us, decode <= {decode_budget:g} us." |
| 169 | + ) |
| 170 | + return 1 |
| 171 | + return 0 |
| 172 | + |
| 173 | + |
| 174 | +if __name__ == "__main__": |
| 175 | + raise SystemExit(main()) |
0 commit comments