Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/deep-kiwis-lick.md
Original file line number Diff line number Diff line change
@@ -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.
129 changes: 129 additions & 0 deletions python/benchmarks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
# 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`.

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.
163 changes: 163 additions & 0 deletions python/benchmarks/decode_bench.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
"""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 importlib.util
import json
import platform
import random
import statistics
import sys
from pathlib import Path
from time import perf_counter_ns, process_time_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 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():
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("--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:
parser.error("use at least 15 measured runs")
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:
continue
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):
for instance in codecs:
instance.decode_body(body)
instance.encode_body(value)
gc.collect()
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")


if __name__ == "__main__":
main()
94 changes: 94 additions & 0 deletions python/benchmarks/decode_results.json
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading