From 1c487ef4a0370eb03cab74e390c44a100f043c50 Mon Sep 17 00:00:00 2001 From: Elia <83713217+eliahilse@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:16:42 +0200 Subject: [PATCH 1/6] test(python): add realistic decode and encode benchmarks Co-Authored-By: GPT 6.1 Sol --- .changeset/deep-kiwis-lick.md | 5 ++ python/benchmarks/README.md | 29 +++++++ python/benchmarks/decode_bench.py | 128 ++++++++++++++++++++++++++++++ 3 files changed, 162 insertions(+) create mode 100644 .changeset/deep-kiwis-lick.md create mode 100644 python/benchmarks/README.md create mode 100644 python/benchmarks/decode_bench.py diff --git a/.changeset/deep-kiwis-lick.md b/.changeset/deep-kiwis-lick.md new file mode 100644 index 0000000..68da94b --- /dev/null +++ b/.changeset/deep-kiwis-lick.md @@ -0,0 +1,5 @@ +--- +"@hyperfly/python": patch +--- + +Decode Python payloads faster while preserving wire compatibility and validation errors. Encode behavior and supported Python versions remain unchanged. diff --git a/python/benchmarks/README.md b/python/benchmarks/README.md new file mode 100644 index 0000000..53ac2bc --- /dev/null +++ b/python/benchmarks/README.md @@ -0,0 +1,29 @@ +# Python codec timings + +Run `.venv/bin/python python/benchmarks/decode_bench.py --json /tmp/decode.json` +from the repository root. Each case measures 15 runs after three warmups, with +10,000 records, GC enabled, compilation and round-trip checks outside timing. +Both decode and encode use the body API. Payload generation is deterministic. + +Initial baseline: `origin/main` at `22cf2a9d5b8890c70697cafbc743e141afe7d7c7`, +Python 3.13.7, macOS 26.2, Apple Silicon. The script was added without changing +the runtime. Shared-host contention affects these wall-clock measurements; +comparisons should remeasure both revisions in the same session. + +| Case | Body bytes | Decode median ms | Encode median ms | +| --- | ---: | ---: | ---: | +| mixed/row | 1,099,296 | 150.021 | 128.732 | +| mixed/columnar | 986,823 | 20.156 | 177.673 | +| nested/row | 1,152,165 | 130.830 | 91.427 | +| nested/columnar | 1,050,769 | 85.595 | 173.846 | +| packed/columnar | 527,230 | 11.656 | 105.299 | +| profile/columnar | 10,012 | 2.579 | 70.638 | + +The mixed records cover safe integers, floats, UTF-8 strings, booleans, enums, +nullable and optional fields, bytes, and a nested actor struct. The nested case +groups the same records into 400 variable arrays and adds float arrays. Packed +prose resembles the feed corpus. The profile combines a dictionary source, +derived emails, and hexadecimal event ID grammar lanes. + +To measure another revision without changing the benchmark driver, export that +revision's `python/src` under `/tmp` and pass `--source /tmp/export/python/src`. diff --git a/python/benchmarks/decode_bench.py b/python/benchmarks/decode_bench.py new file mode 100644 index 0000000..6c287e7 --- /dev/null +++ b/python/benchmarks/decode_bench.py @@ -0,0 +1,128 @@ +"""Deterministic decode/encode benchmarks inspired by apps/bench's API corpora. + +Run with .venv/bin/python python/benchmarks/decode_bench.py. Compilation, payload +generation, equality checks and warmup are outside the timed region. Use --source +with an exported checkout's python/src to compare revisions with the same driver. +""" + +from __future__ import annotations + +import argparse +import gc +import json +import platform +import random +import statistics +import sys +from pathlib import Path +from time import perf_counter_ns + + +def struct(**fields): + return {"kind": "struct", "fields": [{"name": name, "type": node} for name, node in fields.items()]} + + +def array(element): + return {"kind": "array", "element": element} + + +def cases(rows): + # Events, devices and feed-like values: wide structs, nested containers, + # variable strings, byte blobs, enums, nullable and optional fields. + rng = random.Random(0x4846) + integer, floating, text = ({"kind": kind} for kind in ("int", "float64", "string")) + record = struct( + id=integer, at={"kind": "int", "min": 0}, value=floating, + name=text, ok={"kind": "bool"}, region={"kind": "enum", "members": ["us", "eu", "ap"]}, + note=text, blob={"kind": "bytes"}, + actor=struct(id=text, email=text, verified={"kind": "bool"}), + ) + record["fields"][6]["nullable"] = True + record["fields"][7]["optional"] = True + values = [] + for i in range(rows): + row = dict( + id=rng.randrange(-2**35, 2**35), at=1755000000000 + i * 1000, + value=rng.uniform(-20000, 20000), name=f"device-{rng.randrange(100000):06d}-東京", + ok=i % 5 != 0, region=["us", "eu", "ap"][i % 3], + note=None if i % 4 == 0 else f"report {i}: café", + actor=dict(id=f"usr_{i % 150:04d}", email=f"member{i % 150}@example.com", verified=i % 7 == 0), + ) + if i % 5: + row["blob"] = rng.randbytes(24) + values.append(row) + for plan in ("row", "columnar"): + yield f"mixed/{plan}", array(record), values, dict(plan=plan, pack=False) + + nested = struct(route={"kind": "literal", "value": "devices"}, groups=array(struct( + id=integer, devices=array(record), samples=array(floating), + ))) + groups = [dict(id=i, devices=values[i:i + 25], samples=[rng.random() for _ in range(16)]) + for i in range(0, rows, 25)] + for plan in ("row", "columnar"): + yield f"nested/{plan}", nested, dict(route="devices", groups=groups), dict(plan=plan, pack=False) + + prose = [dict(body=f"Report {i}: " + " ".join(rng.choices( + "the device reports temperature from the station near the river today".split(), k=65))) for i in range(rows)] + yield "packed/columnar", array(struct(body=text)), prose, dict(plan="columnar") + + names = [f"usr_{i:04d}" for i in range(150)] + emails = [f"member{i}@example.com" for i in range(150)] + profile = {"version": 2, "shared": {"columns": [ + {"leaf": 0, "dict": names}, + {"leaf": 1, "derived": {"source": 0, "values": emails}}, + {"leaf": 2, "grammar": [{"lit": "evt_"}, {"num": {"base": 16, "len": 8, "case": "lower"}}]}, + ]}} + profiled = [dict(actor=names[i % 150], email=emails[i % 150], event=f"evt_{i:08x}") for i in range(rows)] + yield "profile/columnar", array(struct(actor=text, email=text, event=text)), profiled, dict(plan="columnar", profile=profile, pack=False) + + +def median_ms(operation, runs): + samples = [] + for _ in range(runs): + start = perf_counter_ns() + result = operation() + samples.append((perf_counter_ns() - start) / 1_000_000) + # Release the previous result outside the timed region, with ordinary GC + # enabled so allocation-heavy cases reflect serving actual responses. + del result + return statistics.median(samples) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--runs", type=int, default=15) + parser.add_argument("--rows", type=int, default=10000) + parser.add_argument("--case", action="append", help="case name (repeatable)") + parser.add_argument("--source", type=Path, help="override the hyperfly source directory") + parser.add_argument("--json", type=Path, help="write machine-readable results") + args = parser.parse_args() + if args.runs < 15: + parser.error("use at least 15 measured runs") + if args.source: + sys.path.insert(0, str(args.source.resolve())) + from hyperfly import compile_ir + + print(f"Python {platform.python_version()} / {platform.platform()}; {args.rows} rows; median of {args.runs}; GC enabled") + print(f"{'case':24} {'body bytes':>12} {'decode ms':>12} {'encode ms':>12}") + results = [] + for name, ir, value, options in cases(args.rows): + if args.case and name not in args.case: + continue + codec = compile_ir(ir, **options) + body = codec.encode_body(value) + assert codec.decode_body(body) == value, name + for _ in range(3): + codec.decode_body(body) + codec.encode_body(value) + gc.collect() + decoded = median_ms(lambda: codec.decode_body(body), args.runs) + encoded = median_ms(lambda: codec.encode_body(value), args.runs) + results.append(dict(case=name, bytes=len(body), decode_ms=decoded, encode_ms=encoded)) + print(f"{name:24} {len(body):12d} {decoded:12.3f} {encoded:12.3f}", flush=True) + if args.json: + args.json.write_text(json.dumps(dict(python=platform.python_version(), rows=args.rows, runs=args.runs, results=results), indent=2) + "\n") + + +if __name__ == "__main__": + main() From 042a8910bb5196ab1cf0e6ce8a568515326088c4 Mon Sep 17 00:00:00 2001 From: Elia <83713217+eliahilse@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:21:18 +0200 Subject: [PATCH 2/6] perf(python): compile row decoders and streamline primitive reads Co-Authored-By: GPT 6.1 Sol --- python/src/hyperfly/_codec.py | 262 +++++++++++++-------- python/src/hyperfly/_wire.py | 30 ++- python/tests/test_decode_specialization.py | 55 +++++ 3 files changed, 240 insertions(+), 107 deletions(-) create mode 100644 python/tests/test_decode_specialization.py diff --git a/python/src/hyperfly/_codec.py b/python/src/hyperfly/_codec.py index b01f35f..b4e9a6a 100644 --- a/python/src/hyperfly/_codec.py +++ b/python/src/hyperfly/_codec.py @@ -1312,118 +1312,181 @@ def source_value(ordinal: int, row: int) -> Any: _check_amplification(len(rows), len(out) - payload_start, False, ctx, path) -def _decode_node(r: Reader, node: dict[str, Any], path: str, depth: int, ctx: _Ctx, column: int = 0) -> Any: +_Decoder = Callable[[Reader, str], Any] + + +def _compile_decoder(node: dict[str, Any], depth: int, ctx: _Ctx, column: int = 0) -> _Decoder: + """Compile bottom up without consuming the caller's stack on deep artifacts.""" + pending = [(node, depth, column)] + order = [] + while pending: + current, level, ordinal = pending.pop() + order.append((current, level, ordinal)) + if level > ctx.max_depth: + continue + kind = current["kind"] + if kind == "nullable": + pending.append((current["inner"], level + 1, ordinal)) + elif kind == "array" and ctx.arrays[id(current)][0] is None: + pending.append((current["element"], level + 1, ordinal)) + elif kind == "struct": + for field in current["fields"]: + pending.append((field["type"], level + 1, ordinal)) + ordinal += ctx.column_count(field["type"]) + compiled: dict[tuple[int, int, int], _Decoder] = {} + for current, level, ordinal in reversed(order): + compiled[id(current), level, ordinal] = _compile_node_decoder(current, level, ctx, ordinal, compiled) + return compiled[id(node), depth, column] + + +def _compile_node_decoder( + node: dict[str, Any], depth: int, ctx: _Ctx, column: int, + compiled: dict[tuple[int, int, int], _Decoder], +) -> _Decoder: + """Bind schema metadata once; checks still execute at each value's wire position.""" if depth > ctx.max_depth: - _dfail("depth", path, f"nesting deeper than {ctx.max_depth}") + def too_deep(r: Reader, path: str) -> NoReturn: + _dfail("depth", path, f"nesting deeper than {ctx.max_depth}") + return too_deep kind = node["kind"] - if kind == "bool": - b = r.u8() - if b > 1: - _dfail("marker", path, f"invalid bool byte 0x{b:x}") - return b == 1 + def boolean(r: Reader, path: str) -> bool: + value = r.u8() + if value > 1: + _dfail("marker", path, f"invalid bool byte 0x{value:x}") + return value == 1 + return boolean if kind == "int": - return _decode_int_value(node, read_uleb(r), path) + lo, hi = node.get("min"), node.get("max") + def integer(r: Reader, path: str) -> int: + raw = read_uleb(r) + value: int = raw + lo if lo is not None else -(raw >> 1) - 1 if raw & 1 else raw >> 1 + if value < INT_MIN or value > INT_MAX: + _dfail("range", path, f"decoded integer {value} outside the v0 domain") + if lo is not None and value < lo: + _dfail("range", path, "below declared min") + if hi is not None and value > hi: + _dfail("range", path, "above declared max") + return value + return integer if kind == "float64": - raw = r.take(8) - bits = struct.unpack(" r.limits.max_byte_length: - _dfail("limit", path, "string length exceeds limit") - r.budget.charge_bytes(n, path, DecodeError) - data = r.take(n) - try: - return data.decode("utf-8") - except UnicodeDecodeError: - _dfail("utf8", path, "invalid UTF-8") - if kind == "bytes": - n = read_uleb(r) - if n > r.limits.max_byte_length: - _dfail("limit", path, "bytes length exceeds limit") - r.budget.charge_bytes(n, path, DecodeError) - return bytes(r.take(n)) + def floating(r: Reader, path: str) -> float: + pos = r.pos + if pos + 8 > len(r.buf): + raise DecodeError("truncated", "unexpected end of input") + value: float = struct.unpack_from(" str | bytes: + size = read_uleb(r) + if size > limit: + _dfail("limit", path, f"{kind} length exceeds limit") + r.budget.charge_bytes(size, path, DecodeError) + data = r.take(size) + if not is_text: + return data + try: + return data.decode("utf-8") + except UnicodeDecodeError: + _dfail("utf8", path, "invalid UTF-8") + return blob if kind == "literal": literal = node["value"] - if type(literal) is str: - r.budget.charge_bytes(_text_bytes(literal), path, DecodeError) - return literal + size = _text_bytes(literal) if type(literal) is str else 0 + def constant(r: Reader, path: str) -> Any: + if size: + r.budget.charge_bytes(size, path, DecodeError) + return literal + return constant if kind == "enum": - index = read_uleb(r) - if index >= len(node["members"]): - _dfail("range", path, f"enum index {index} out of range") - member = node["members"][index] - r.budget.charge_bytes(_text_bytes(member), path, DecodeError) - return member + members = node["members"] + sizes = tuple(map(_text_bytes, members)) + count = len(members) + def enum(r: Reader, path: str) -> str: + index = read_uleb(r) + if index >= count: + _dfail("range", path, f"enum index {index} out of range") + r.budget.charge_bytes(sizes[index], path, DecodeError) + member: str = members[index] + return member + return enum if kind == "nullable": - marker = r.u8() - if marker == 0: - return None - if marker != 1: - _dfail("marker", path, f"invalid nullable marker 0x{marker:x}") - return _decode_node(r, node["inner"], path, depth + 1, ctx, column) + inner = compiled[id(node["inner"]), depth + 1, column] + def nullable(r: Reader, path: str) -> Any: + marker = r.u8() + if marker == 0: + return None + if marker != 1: + _dfail("marker", path, f"invalid nullable marker 0x{marker:x}") + return inner(r, path) + return nullable if kind == "array": leaves, zero_bit, empty = ctx.arrays[id(node)] if leaves is not None: - return _decode_columnar(r, node, leaves, path, depth, ctx, column) - length = node.get("length") - if length is None: - length = read_uleb(r) - if length > r.limits.max_items: - _dfail("limit", path, f"array count {length} exceeds limit {r.limits.max_items}") - _bound_by_input(r, length, zero_bit, path) - budget = r.budget - budget.charge(length, path, DecodeError) - element = node["element"] - if empty: - if not length: - return [] - # every element decodes from no bytes to an equal value, so one - # decode stands for all and charges the budgets for each - counted, decoded = budget.total, budget.bytes - first = _decode_node(r, element, f"{path}[0]", depth + 1, ctx, column) - budget.charge((length - 1) * (budget.total - counted), path, DecodeError) - budget.charge_bytes((length - 1) * (budget.bytes - decoded), path, DecodeError) - items: list[Any] = [] - r.deferred.append((items, lambda: _copies(first, length))) - return items - return [_decode_node(r, element, f"{path}[{i}]", depth + 1, ctx, column) for i in range(length)] - if kind == "struct": - optional = [f for f in node["fields"] if f.get("optional")] - nullable = [f for f in node["fields"] if f.get("nullable")] - presence = read_bitmap(r, len(optional), path) - nulls = read_bitmap(r, len(nullable), path) - pi = ni = 0 + return lambda r, path: _decode_columnar(r, node, leaves, path, depth, ctx, column) + element = compiled[id(node["element"]), depth + 1, column] + fixed = node.get("length") + limit = ctx.max_items + def array_values(r: Reader, path: str) -> list[Any]: + length = read_uleb(r) if fixed is None else fixed + if length > limit: + _dfail("limit", path, f"array count {length} exceeds limit {limit}") + _bound_by_input(r, length, zero_bit, path) + budget = r.budget + budget.charge(length, path, DecodeError) + if empty: + if not length: + return [] + # Decode one zero-byte element, multiply its budget charges, then + # clone containers only after every later value has been checked. + counted, decoded = budget.total, budget.bytes + first = element(r, f"{path}[0]") + budget.charge((length - 1) * (budget.total - counted), path, DecodeError) + budget.charge_bytes((length - 1) * (budget.bytes - decoded), path, DecodeError) + items: list[Any] = [] + r.deferred.append((items, lambda: _copies(first, length))) + return items + return [element(r, f"{path}[{i}]") for i in range(length)] + return array_values + # A validated node's remaining kind is struct. Bitmap sizes and each field's + # column ordinal are schema constants, including columns of absent fields. + fields: list[tuple[str, str, int, int, _Decoder]] = [] + pi = ni = 0 + for field in node["fields"]: + present_bit = (1 << pi) if field.get("optional") else 0 + null_bit = (1 << ni) if field.get("nullable") else 0 + pi += bool(present_bit) + ni += bool(null_bit) + fields.append((field["name"], "." + field["name"], present_bit, null_bit, + compiled[id(field["type"]), depth + 1, column])) + column += ctx.column_count(field["type"]) + if not (pi or ni): + plain = [(name, suffix, decode) for name, suffix, _, _, decode in fields] + def required_struct(r: Reader, path: str) -> dict[str, Any]: + return {name: decode(r, path + suffix) for name, suffix, decode in plain} + return required_struct + def flagged_struct(r: Reader, path: str) -> dict[str, Any]: + presence = read_bits(r, pi, path) if pi else 0 + nulls = read_bits(r, ni, path) if ni else 0 out: dict[str, Any] = {} - field_column = column - for f in node["fields"]: - base = field_column - field_column += ctx.column_count(f["type"]) - present = True - if f.get("optional"): - present = presence[pi] - pi += 1 - is_null = False - if f.get("nullable"): - is_null = nulls[ni] - ni += 1 - if not present: - if is_null: - _dfail("bitmap", f"{path}.{f['name']}", "null bit set for absent field") - continue - if is_null: - out[f["name"]] = None - continue - out[f["name"]] = _decode_node(r, f["type"], f"{path}.{f['name']}", depth + 1, ctx, base) + for name, suffix, present_bit, null_bit, decode in fields: + if present_bit and not presence & present_bit: + if nulls & null_bit: + _dfail("bitmap", path + suffix, "null bit set for absent field") + elif nulls & null_bit: + out[name] = None + else: + out[name] = decode(r, path + suffix) return out - _dfail("marker", path, f"unknown kind {kind}") - + return flagged_struct def _decode_int_column(r: Reader, node: dict[str, Any], count: int, path: str, lane: bool = False) -> _Values: """A column's values, each checked against the node's bounds in row order with its @@ -2948,6 +3011,7 @@ def _initialize( else: deflate, inflate = pack.get("deflate"), pack.get("inflate") self._ctx = _Ctx(ir, limits, plan == "columnar", deflate, inflate, self._profile) + self._decode = _compile_decoder(ir, 0, self._ctx) @property def fingerprint(self) -> str: @@ -3004,7 +3068,7 @@ def decode_body(self, data: bytes | bytearray | memoryview) -> T: """ r = Reader(bytes(data), self._limits) try: - value = _decode_node(r, self._ir, "$", 0, self._ctx) + value = self._decode(r, "$") r.expect_end() for items, build in r.deferred: items.extend(build()) diff --git a/python/src/hyperfly/_wire.py b/python/src/hyperfly/_wire.py index 37025b6..d98825d 100644 --- a/python/src/hyperfly/_wire.py +++ b/python/src/hyperfly/_wire.py @@ -168,14 +168,26 @@ def write_uleb(out: bytearray, value: int) -> None: def read_uleb(r: Reader) -> int: - result = 0 - shift = 0 - for i in range(_MAX_ULEB_BYTES): - byte = r.u8() - group = byte & 0x7F - result |= group << shift - if not byte & 0x80: - if i > 0 and group == 0: + buf = r.buf + pos = r.pos + end = len(buf) + if pos >= end: + raise DecodeError("truncated", "unexpected end of input") + byte = buf[pos] + r.pos = pos + 1 + if byte < 0x80: + return byte + result = byte & 0x7F + shift = 7 + for _ in range(1, _MAX_ULEB_BYTES): + pos += 1 + if pos >= end: + raise DecodeError("truncated", "unexpected end of input") + byte = buf[pos] + r.pos = pos + 1 + result |= (byte & 0x7F) << shift + if byte < 0x80: + if byte == 0: raise DecodeError("varint", "overlong uvarint encoding") return result shift += 7 @@ -184,6 +196,8 @@ def read_uleb(r: Reader) -> int: def uleb_at(buf: bytes, pos: int) -> tuple[int, int]: """read_uleb over a buffer position: the value and the position after it.""" + if pos < len(buf) and buf[pos] < 0x80: + return buf[pos], pos + 1 result = 0 shift = 0 for i in range(_MAX_ULEB_BYTES): diff --git a/python/tests/test_decode_specialization.py b/python/tests/test_decode_specialization.py new file mode 100644 index 0000000..1131244 --- /dev/null +++ b/python/tests/test_decode_specialization.py @@ -0,0 +1,55 @@ +"""Traversal and error precedence at the boundaries of compiled row readers.""" + +import struct + +import pytest + +from hyperfly import DecodeError, Limits, compile_ir + + +def failure(codec, body, code, message): + with pytest.raises(DecodeError) as error: + codec.decode_body(body) + assert error.value.code == code + assert str(error.value) == message + + +def test_struct_checks_both_bitmap_padding_before_values(): + fields = [dict(name=f"f{i}", type={"kind": "bool"}, optional=True, nullable=True) for i in range(9)] + codec = compile_ir({"kind": "struct", "fields": fields}) + # The first boolean is invalid too; neither value is visited before padding. + failure(codec, b"\xff\x01\x00\x02\x02", "bitmap", "$: nonzero bitmap padding") + failure(codec, b"\xff\x02", "bitmap", "$: nonzero bitmap padding") + failure(codec, b"\xff\x01\x00", "truncated", "unexpected end of input") + + +def test_absent_null_bit_fails_at_its_field_in_declared_order(): + codec = compile_ir({"kind": "struct", "fields": [ + dict(name="first", type={"kind": "bool"}), + dict(name="absent", type={"kind": "bool"}, optional=True, nullable=True), + ]}) + failure(codec, b"\x00\x01\x02", "marker", "$.first: invalid bool byte 0x2") + failure(codec, b"\x00\x01\x01", "bitmap", "$.absent: null bit set for absent field") + + +def test_unvisited_deep_field_does_not_fail_at_compile_or_decode(): + codec = compile_ir({"kind": "struct", "fields": [ + dict(name="maybe", type={"kind": "nullable", "inner": {"kind": "bool"}}, optional=True), + ]}, limits=Limits(max_depth=0)) + assert codec.decode_body(b"\x00") == {} + failure(codec, b"\x01\x00", "depth", "$.maybe: nesting deeper than 0") + + +@pytest.mark.parametrize("value,message", [ + (-0.0, "negative-zero bit pattern"), (float("inf"), "non-finite float64"), + (float("nan"), "non-finite float64"), +]) +def test_float_failure_precedes_later_truncation(value, message): + codec = compile_ir({"kind": "array", "element": {"kind": "float64"}}) + failure(codec, b"\x02" + struct.pack(" Date: Wed, 21 Oct 2026 18:23:28 +0200 Subject: [PATCH 3/6] perf(python): batch uniform prefixes and two-byte varints Co-Authored-By: GPT 6.1 Sol --- python/src/hyperfly/_codec.py | 10 +++++++ python/src/hyperfly/_wire.py | 18 +++++++++++ python/tests/test_decode_specialization.py | 35 ++++++++++++++++++++++ 3 files changed, 63 insertions(+) diff --git a/python/src/hyperfly/_codec.py b/python/src/hyperfly/_codec.py index b4e9a6a..aae8160 100644 --- a/python/src/hyperfly/_codec.py +++ b/python/src/hyperfly/_codec.py @@ -1826,6 +1826,16 @@ def _read_slices( end = len(buf) limit = r.limits.max_byte_length offset = _UINT[4] if end >> 32 == 0 else "Q" + # Fixed-size IDs and byte blobs need no per-value prefix walk. Validate all + # prefixes before constructing offsets, then use the usual UTF-8 and budget + # checks, including their first-failure ordering. + if count >= 16 and pos < end: + size = buf[pos] + stride = size + 1 + stop = pos + count * stride + if size < 0x80 and size <= limit and stop <= end and buf[pos:stop:stride].count(size) == count: + r.pos = stop + return array(offset, range(pos + 1, stop, stride)), array(offset, range(pos + stride, stop + 1, stride)), None, 0 starts = array(offset) ends = array(offset) for j in range(count): diff --git a/python/src/hyperfly/_wire.py b/python/src/hyperfly/_wire.py index d98825d..34c1e01 100644 --- a/python/src/hyperfly/_wire.py +++ b/python/src/hyperfly/_wire.py @@ -2,12 +2,14 @@ from array import array from dataclasses import dataclass +import sys from typing import Any, Callable, Iterable INT_MIN = -(2**53 - 1) INT_MAX = 2**53 - 1 _ULEB_DOMAIN_MAX = (1 << 56) - 1 _MAX_ULEB_BYTES = 8 +_CONTINUED_BYTES = bytes(range(128, 256)) class HyperflyError(Exception): @@ -223,6 +225,22 @@ def read_ulebs(r: Reader, count: int) -> tuple[array[int], DecodeError | None]: if len(window) == count and window.isascii(): r.pos = pos + count return array("B", window), None + # Length columns commonly consist entirely of two-byte varints. Only take + # this path when every group is complete and minimal; otherwise the scalar + # reader retains the precise first malformed value for the caller to order. + if count >= 64 and pos + 2 * count <= len(buf) and buf[pos] >= 128 and 0 < buf[pos + 1] < 128: + pairs = buf[pos : pos + 2 * count] + high = pairs[1::2] + if high.isascii() and 0 not in high and not pairs[::2].translate(None, _CONTINUED_BYTES): + bits = int.from_bytes(pairs, "little") + low_mask = int.from_bytes(b"\x7f\x00" * count, "little") + decoded = (bits & low_mask) | ((bits >> 1) & (low_mask << 7)) + values = array("H") + values.frombytes(decoded.to_bytes(2 * count, "little")) + if sys.byteorder == "big": + values.byteswap() + r.pos = pos + 2 * count + return values, None out = array("Q") append = out.append end = len(buf) diff --git a/python/tests/test_decode_specialization.py b/python/tests/test_decode_specialization.py index 1131244..2c2df18 100644 --- a/python/tests/test_decode_specialization.py +++ b/python/tests/test_decode_specialization.py @@ -53,3 +53,38 @@ def test_length_budget_precedes_bytes_and_utf8(): codec = compile_ir({"kind": "array", "element": {"kind": "string"}}, limits=Limits(max_total_bytes=1)) failure(codec, b"\x02\x01a\x02\xff", "limit", "$[1]: 3 bytes exceed the byte budget of 1") + + +@pytest.mark.parametrize("bad_index", [0, 15, 63]) +def test_uniform_length_column_keeps_utf8_and_budget_order(bad_index): + ir = {"kind": "array", "element": {"kind": "struct", "fields": [ + dict(name="s", type={"kind": "string"}), + ]}} + codec = compile_ir(ir, plan="columnar", limits=Limits(max_total_bytes=63)) + body = bytearray(b"\x40\x00" + b"\x01a" * 64) + body[3 + 2 * bad_index] = 0xFF + code = "limit" if bad_index == 63 else "utf8" + with pytest.raises(DecodeError) as error: + codec.decode_body(body) + assert error.value.code == code + assert str(error.value).startswith(f"$[].s[{bad_index}]:") + + +def test_two_byte_varint_batches_preserve_values_and_first_error(): + from hyperfly._wire import Reader, read_ulebs, write_uleb + + values = [128, 255, 256, 16383] * 32 + body = bytearray() + for value in values: + write_uleb(body, value) + reader = Reader(bytes(body), Limits()) + decoded, error = read_ulebs(reader, len(values)) + assert list(decoded) == values + assert error is None + assert reader.remaining() == 0 + for index in (0, 63, 127): + malformed = body.copy() + malformed[2 * index + 1] = 0 + decoded, error = read_ulebs(Reader(bytes(malformed), Limits()), len(values)) + assert list(decoded) == values[:index] + assert error.code == "varint" From 4efed610b94b7b7440c4474719a188922c2a130a Mon Sep 17 00:00:00 2001 From: Elia <83713217+eliahilse@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:37:49 +0200 Subject: [PATCH 4/6] fix(python): retain every offset in empty value batches Co-Authored-By: GPT 6.1 Sol --- python/src/hyperfly/_codec.py | 2 +- python/tests/test_decode_specialization.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/python/src/hyperfly/_codec.py b/python/src/hyperfly/_codec.py index aae8160..6b64c88 100644 --- a/python/src/hyperfly/_codec.py +++ b/python/src/hyperfly/_codec.py @@ -1835,7 +1835,7 @@ def _read_slices( stop = pos + count * stride if size < 0x80 and size <= limit and stop <= end and buf[pos:stop:stride].count(size) == count: r.pos = stop - return array(offset, range(pos + 1, stop, stride)), array(offset, range(pos + stride, stop + 1, stride)), None, 0 + return array(offset, range(pos + 1, stop + 1, stride)), array(offset, range(pos + stride, stop + 1, stride)), None, 0 starts = array(offset) ends = array(offset) for j in range(count): diff --git a/python/tests/test_decode_specialization.py b/python/tests/test_decode_specialization.py index 2c2df18..4b6c88c 100644 --- a/python/tests/test_decode_specialization.py +++ b/python/tests/test_decode_specialization.py @@ -88,3 +88,20 @@ def test_two_byte_varint_batches_preserve_values_and_first_error(): decoded, error = read_ulebs(Reader(bytes(malformed), Limits()), len(values)) assert list(decoded) == values[:index] assert error.code == "varint" + + +@pytest.mark.parametrize("kind,empty", [("string", ""), ("bytes", b"")]) +@pytest.mark.parametrize("flagged", [False, True]) +@pytest.mark.parametrize("count", [16, 17, 64]) +def test_uniform_empty_column_preserves_every_row(kind, empty, flagged, count): + field = dict(name="value", type={"kind": kind}) + if flagged: + field.update(optional=True, nullable=True) + codec = compile_ir({"kind": "array", "element": {"kind": "struct", "fields": [field]}}, + plan="columnar", pack=False) + rows = [{"value": empty} for _ in range(count)] + if flagged: + rows[2] = {"value": None} + rows[7] = {} + body = codec.encode_body(rows) + assert codec.decode_body(body) == rows From aa52a56f36948549dadd4dc95f32a4aaf8dcb209 Mon Sep 17 00:00:00 2001 From: Elia <83713217+eliahilse@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:18:47 +0200 Subject: [PATCH 5/6] test(python): record paired performance and differential results Co-Authored-By: GPT 6.1 Sol --- python/benchmarks/README.md | 100 ++++++++++++++++++++++++++ python/benchmarks/decode_bench.py | 69 +++++++++++++----- python/benchmarks/decode_results.json | 94 ++++++++++++++++++++++++ 3 files changed, 246 insertions(+), 17 deletions(-) create mode 100644 python/benchmarks/decode_results.json diff --git a/python/benchmarks/README.md b/python/benchmarks/README.md index 53ac2bc..a200a14 100644 --- a/python/benchmarks/README.md +++ b/python/benchmarks/README.md @@ -27,3 +27,103 @@ derived emails, and hexadecimal event ID grammar lanes. To measure another revision without changing the benchmark driver, export that revision's `python/src` under `/tmp` and pass `--source /tmp/export/python/src`. + +For alternating baseline/current measurements in one process: + +```sh +mkdir -p /tmp/hyperfly-python-decode-baseline +git archive origin/main python/src | tar -x -C /tmp/hyperfly-python-decode-baseline +.venv/bin/python python/benchmarks/decode_bench.py --runs 31 \ + --compare-source /tmp/hyperfly-python-decode-baseline/python/src \ + --json /tmp/hyperfly-paired.json +``` + +The JSON also records process CPU medians to help distinguish CPU cost from +scheduling delays. Run comparisons separately from tests and differential jobs. +Both codecs must produce identical body bytes and decoded values before timing. + +## Final alternating comparison + +`decode_results.json` records 31 alternating runs against the same exported +`origin/main`, with the runtime at `4efed61`. No validation jobs overlapped this +comparison. Median wall milliseconds: + +| Case | Decode before | Decode after | Encode before | Encode after | +| --- | ---: | ---: | ---: | ---: | +| mixed/row | 151.717 | 59.720 | 142.100 | 121.348 | +| mixed/columnar | 21.975 | 18.898 | 227.466 | 225.447 | +| nested/row | 306.701 | 158.648 | 219.117 | 223.054 | +| nested/columnar | 62.025 | 49.740 | 220.375 | 199.691 | +| packed/columnar | 8.743 | 5.827 | 113.112 | 113.560 | +| profile/columnar | 4.335 | 3.652 | 154.040 | 144.685 | + +Median process CPU milliseconds, excluding scheduling delays: + +| Case | Decode before | Decode after | Encode before | Encode after | +| --- | ---: | ---: | ---: | ---: | +| mixed/row | 109.580 | 50.884 | 87.445 | 85.939 | +| mixed/columnar | 16.550 | 14.958 | 123.712 | 125.357 | +| nested/row | 130.222 | 62.143 | 98.883 | 99.359 | +| nested/columnar | 47.383 | 39.801 | 158.368 | 151.581 | +| packed/columnar | 7.716 | 5.193 | 93.052 | 90.510 | +| profile/columnar | 3.388 | 3.162 | 65.347 | 66.507 | + +The row cases improve 2.15x and 2.10x in CPU time; wall gains are 2.54x and +1.93x. Columnar wall gains range from 1.16x to 1.50x, below 2x. Encode differences +are consistent with shared-host measurement noise: the largest increase is +1.8%, while encoder code and operation counts are identical. This does not +establish a 2x gain for every plan or case. + +## Profiling and decisions + +`cProfile.Profile().runcall(codec.decode_body, body)` after one decode warmup +showed repeated node dispatch, schema lookups and varint byte calls dominating +row decoding. On mixed/row, the optimized reader reduces calls from 1,986,017 +to 610,520. The mixed/columnar count falls from 91,325 to 35,301; nested/columnar +from 300,387 to 164,209; packed/columnar from 40,070 to 67. Profiler wall times +are not used as speedup measurements because instrumentation penalizes calls. + +Manual timing wrapped `_read_slices` and `_assemble` with `process_time_ns`, +over 15 mixed/columnar decodes. Prefix scanning fell from about 7.85 to 3.79 ms; +assembly remained about 22 ms inclusive of nested structs. These diagnostic +times were taken on a busy host; use the alternating benchmark for comparisons. + +Readers bind field metadata, enum byte lengths, bounds, depth and column ordinals +at compile time. Compilation walks the IR iteratively, preserving compilation +near the caller's recursion limit. Float64 readers use `unpack_from`; varints +avoid a reader-method call per byte. Uniform length prefixes and minimal two-byte +varint columns use guarded batch paths, with the scalar path for other layouts. + +Checks and budget charges stay in traversal order. Moving row byte charges past +later values or validating floats only after reading a complete array would +change which malformed input fails first, so those approaches were rejected. +Increasing the short-column threshold to 32 helped only about 6%; generated dict +assembly helped mixed columnar data about 11%. Neither experiment was retained. +Encoder/write function ASTs match `origin/main`; no encoder algorithm changed. +After warming both codecs, encode call counts also match exactly on all six +1,000-row cases (174,371 / 166,094 / 180,031 / 203,713 / 24,059 / 94,401). + +## Validation + +Runtime commit `4efed61`: `.venv/bin/pytest python/tests -q` passed all 4,940 +tests on Python 3.13.7, including existing Hypothesis/fuzz and strict mypy tests. +The modified runtime and benchmark files also parse with Python's 3.10 syntax +grammar. Other Python interpreters were not installed on this host. + +The full differential harness's seed 1 run at this commit checked 186,738 decode +cases, 12,700 compile cases, 28,972 encode cases, 75,090 reencodes, 20,136 +roundtrips, 597 vector replays and 6,000 JSON exchange cases with zero divergences. +HTTP replay (125 cases) and live interop passed; all three drivers had zero +restarts. One packed-encode case reported only the allowed, deflate-dependent +limit refusal class. + +Seed 2 checked 200,865 decode cases, 12,770 compile cases, 28,944 encode cases, +82,806 reencodes, 20,153 roundtrips, 597 vector replays and 6,000 JSON exchange +cases with zero divergences. HTTP replay and live interop passed, with zero +driver restarts. One packed-encode case had the same allowed refusal class. + +Two earlier seed 2 attempts had non-reproducing Python watchdog timeouts on +different inputs. The first two saved inputs matched the baseline on direct +replay (under 4 ms for both revisions); minimization of the later input also +reported matching values. The passing rerun kept the default 20-second watchdog +and every check unchanged. The final timing comparison ran separately from validation. diff --git a/python/benchmarks/decode_bench.py b/python/benchmarks/decode_bench.py index 6c287e7..0da9c0d 100644 --- a/python/benchmarks/decode_bench.py +++ b/python/benchmarks/decode_bench.py @@ -9,13 +9,14 @@ import argparse import gc +import importlib.util import json import platform import random import statistics import sys from pathlib import Path -from time import perf_counter_ns +from time import perf_counter_ns, process_time_ns def struct(**fields): @@ -77,16 +78,33 @@ def cases(rows): yield "profile/columnar", array(struct(actor=text, email=text, event=text)), profiled, dict(plan="columnar", profile=profile, pack=False) -def median_ms(operation, runs): - samples = [] - for _ in range(runs): - start = perf_counter_ns() - result = operation() - samples.append((perf_counter_ns() - start) / 1_000_000) - # Release the previous result outside the timed region, with ordinary GC - # enabled so allocation-heavy cases reflect serving actual responses. - del result - return statistics.median(samples) +def medians(operations, runs): + samples = [([], []) for _ in operations] + for run in range(runs): + # Alternate revisions to distribute host load and thermal drift evenly. + order = range(len(operations)) if run % 2 else reversed(range(len(operations))) + for i in order: + start_cpu = process_time_ns() + start = perf_counter_ns() + result = operations[i]() + elapsed = perf_counter_ns() - start + cpu = process_time_ns() - start_cpu + samples[i][0].append(elapsed / 1_000_000) + samples[i][1].append(cpu / 1_000_000) + # Release results outside timing; GC remains enabled during decode. + del result + return [dict(wall_ms=statistics.median(wall), cpu_ms=statistics.median(cpu)) for wall, cpu in samples] + + +def load_baseline(source): + package = source.resolve() / "hyperfly" + spec = importlib.util.spec_from_file_location( + "_hyperfly_bench_baseline", package / "__init__.py", submodule_search_locations=[str(package)], + ) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module def main(): @@ -95,6 +113,7 @@ def main(): parser.add_argument("--rows", type=int, default=10000) parser.add_argument("--case", action="append", help="case name (repeatable)") parser.add_argument("--source", type=Path, help="override the hyperfly source directory") + parser.add_argument("--compare-source", type=Path, help="alternate measurements with this baseline python/src") parser.add_argument("--json", type=Path, help="write machine-readable results") args = parser.parse_args() if args.runs < 15: @@ -102,9 +121,12 @@ def main(): if args.source: sys.path.insert(0, str(args.source.resolve())) from hyperfly import compile_ir + baseline = load_baseline(args.compare_source) if args.compare_source else None print(f"Python {platform.python_version()} / {platform.platform()}; {args.rows} rows; median of {args.runs}; GC enabled") print(f"{'case':24} {'body bytes':>12} {'decode ms':>12} {'encode ms':>12}") + if baseline: + print("Baseline/current pairs below use alternating runs; JSON includes CPU medians as well.") results = [] for name, ir, value, options in cases(args.rows): if args.case and name not in args.case: @@ -112,14 +134,27 @@ def main(): codec = compile_ir(ir, **options) body = codec.encode_body(value) assert codec.decode_body(body) == value, name + codecs = [codec] + if baseline: + old = baseline.compile_ir(ir, **options) + assert old.encode_body(value) == body, name + assert old.decode_body(body) == value, name + codecs.insert(0, old) for _ in range(3): - codec.decode_body(body) - codec.encode_body(value) + for instance in codecs: + instance.decode_body(body) + instance.encode_body(value) gc.collect() - decoded = median_ms(lambda: codec.decode_body(body), args.runs) - encoded = median_ms(lambda: codec.encode_body(value), args.runs) - results.append(dict(case=name, bytes=len(body), decode_ms=decoded, encode_ms=encoded)) - print(f"{name:24} {len(body):12d} {decoded:12.3f} {encoded:12.3f}", flush=True) + decoded = medians([lambda c=c: c.decode_body(body) for c in codecs], args.runs) + encoded = medians([lambda c=c: c.encode_body(value) for c in codecs], args.runs) + result = dict(case=name, bytes=len(body), decode_ms=decoded[-1]["wall_ms"], encode_ms=encoded[-1]["wall_ms"], + decode_cpu_ms=decoded[-1]["cpu_ms"], encode_cpu_ms=encoded[-1]["cpu_ms"]) + if baseline: + result["baseline"] = dict(decode_ms=decoded[0]["wall_ms"], encode_ms=encoded[0]["wall_ms"], + decode_cpu_ms=decoded[0]["cpu_ms"], encode_cpu_ms=encoded[0]["cpu_ms"]) + print(f"{name + ' baseline':24} {len(body):12d} {decoded[0]['wall_ms']:12.3f} {encoded[0]['wall_ms']:12.3f}", flush=True) + results.append(result) + print(f"{name:24} {len(body):12d} {decoded[-1]['wall_ms']:12.3f} {encoded[-1]['wall_ms']:12.3f}", flush=True) if args.json: args.json.write_text(json.dumps(dict(python=platform.python_version(), rows=args.rows, runs=args.runs, results=results), indent=2) + "\n") diff --git a/python/benchmarks/decode_results.json b/python/benchmarks/decode_results.json new file mode 100644 index 0000000..0ba5769 --- /dev/null +++ b/python/benchmarks/decode_results.json @@ -0,0 +1,94 @@ +{ + "python": "3.13.7", + "rows": 10000, + "runs": 31, + "results": [ + { + "case": "mixed/row", + "bytes": 1099296, + "decode_ms": 59.720375, + "encode_ms": 121.348417, + "decode_cpu_ms": 50.884, + "encode_cpu_ms": 85.939, + "baseline": { + "decode_ms": 151.716916, + "encode_ms": 142.100292, + "decode_cpu_ms": 109.58, + "encode_cpu_ms": 87.445 + } + }, + { + "case": "mixed/columnar", + "bytes": 986823, + "decode_ms": 18.898, + "encode_ms": 225.446917, + "decode_cpu_ms": 14.958, + "encode_cpu_ms": 125.357, + "baseline": { + "decode_ms": 21.975166, + "encode_ms": 227.465708, + "decode_cpu_ms": 16.55, + "encode_cpu_ms": 123.712 + } + }, + { + "case": "nested/row", + "bytes": 1152165, + "decode_ms": 158.648042, + "encode_ms": 223.054458, + "decode_cpu_ms": 62.143, + "encode_cpu_ms": 99.359, + "baseline": { + "decode_ms": 306.701458, + "encode_ms": 219.117416, + "decode_cpu_ms": 130.222, + "encode_cpu_ms": 98.883 + } + }, + { + "case": "nested/columnar", + "bytes": 1050769, + "decode_ms": 49.739958, + "encode_ms": 199.690666, + "decode_cpu_ms": 39.801, + "encode_cpu_ms": 151.581, + "baseline": { + "decode_ms": 62.025458, + "encode_ms": 220.375459, + "decode_cpu_ms": 47.383, + "encode_cpu_ms": 158.368 + } + }, + { + "case": "packed/columnar", + "bytes": 527230, + "decode_ms": 5.826917, + "encode_ms": 113.560209, + "decode_cpu_ms": 5.193, + "encode_cpu_ms": 90.51, + "baseline": { + "decode_ms": 8.742833, + "encode_ms": 113.112459, + "decode_cpu_ms": 7.716, + "encode_cpu_ms": 93.052 + } + }, + { + "case": "profile/columnar", + "bytes": 10012, + "decode_ms": 3.652, + "encode_ms": 144.684583, + "decode_cpu_ms": 3.162, + "encode_cpu_ms": 66.507, + "baseline": { + "decode_ms": 4.334792, + "encode_ms": 154.040208, + "decode_cpu_ms": 3.388, + "encode_cpu_ms": 65.347 + } + } + ], + "baseline_commit": "22cf2a9d5b8890c70697cafbc743e141afe7d7c7", + "runtime_commit": "4efed610b94b7b7440c4474719a188922c2a130a", + "gc_enabled": true +} From a45a6cbcec90f744864d1e7b40b5b4cf2619a320 Mon Sep 17 00:00:00 2001 From: Elia <83713217+eliahilse@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:57:51 +0200 Subject: [PATCH 6/6] build(python): keep benchmarks and hypothesis data out of the sdist Co-Authored-By: Claude Opus 5.5 --- python/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/pyproject.toml b/python/pyproject.toml index 16073ca..df12919 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -38,7 +38,7 @@ Issues = "https://github.com/eliahilse/hyperfly/issues" packages = ["src/hyperfly"] [tool.hatch.build.targets.sdist] -exclude = ["tests", "package.json"] +exclude = ["tests", "benchmarks", ".hypothesis", "package.json"] [tool.mypy] strict = true