Files
cproof/tests/bench/compare_baseline.py
jabber.developer2 b1d820462a feat(bench): synthetic load harness for flat-file backend (P1-P5)
End-to-end performance and correctness harness for the flat-file +
SQLite database backends. Lives in tests/bench/, built only on
demand (`make bench`); not part of `make check`.

Components

  gen_history (P1)
    Deterministic corpus generator. Knobs: lines, contacts, years,
    seed, stanza-id mode (uuid/libpurple/conversations/mixed), LMC
    rate, MAM-OOO rate, resources/contact, length profile
    (short/mixed/long/extreme). Emits the canonical
    flatlog/<account>/<contact>/history.log layout used by
    ff_verify_integrity. ~340 LOC.

  bench_runner (P1, P2.5)
    S1 cold tail-access via sparse index
    S2 warm tail-access (page cache hot)
    S3 deep pagination (1000 binary-search lookups)
    S4 first-time index build (cold file -> ff_state_ensure_fresh)
    S5 incremental extend (asserts no full rebuild path)
    S6 real ff_verify_integrity over the contact tree
    Reports total/err/warn/info issue counts in the CSV note.

  bench_long_messages (P2)
    L1-L14 long-message stress: 1KB up to 9.9MB bodies, plus
    oversized line rejection (10MB+1 -> ff_readline returns ""),
    embedded-newline / pipe / emoji body patterns, full parse on
    100x1MB, 1000x100KB sustained append.

  bench_failure_modes (P3)
    F1-F15 failure-injection: truncated last line, mid-file CRLF,
    mid-file BOM, LMC cycle, LMC depth>FF_MAX_LMC_DEPTH, manual
    ': ' in resource, RTL/ZWSP, Latin-1 byte, empty body,
    mtime/inode flip, empty file. Each test asserts expected issue
    levels and reports PASS/FAIL.

  bench_export_import (P5)
    Links real database_export.c + database_sqlite.c + database.c
    and drives log_database_export_to_flatfile /
    log_database_import_from_flatfile under load.
    Subcommands: seed, export, import, roundtrip, verify.
    S7a/b export, S8a/b import, S8e roundtrip with full byte-by-byte
    content diff of every row in (from_jid, to_jid, message,
    timestamp, type, stanza_id, archive_id, encryption, replace_id).

Make targets

  bench-quick / bench / bench-full
  bench-longmsg, bench-failure
  bench-multicontact, bench-lmc, bench-ooo
  bench-export, bench-import, bench-roundtrip
  bench-pipeline, bench-pipeline-max (1M rows)
  bench-compare, bench-update-baseline

Volume controls: BENCH_VOLUME (small/medium/max), BENCH_PIPE_ROWS,
BENCH_PIPE_ROWS_MAX, BENCH_DATA_DIR, BENCH_CSV.

Baseline + regression checking (P4)

  tests/bench/baseline.csv       51 rows: S1-S6 x {small,lmc,ooo}
                                 + L1-L14 + F1-F15 (11 of 15) +
                                 S7/S8 x {pipe100k, pipe1M}.
  compare_baseline.py            median over duplicate rows;
                                 exits 1 on any (scenario, volume)
                                 slowdown >= threshold (default 25%).

Verified at scale

  bench-pipeline-max: 1,000,000 rows, full content diff
    seed   17 s, export 304 s, import 31 s, idempotent re-import 10 s,
    diff 2.7 s -- mismatches=0.

Findings surfaced by the harness

  Export scales super-linearly: 4 s @ 100k -> 304 s @ 1M (76x for
    10x rows). Cause: g_slist_sort on the merged list + per-row
    ProfMessage/ff_parsed_line_t allocations. RSS peaks at 1.4 GB
    on 1M. Worth a follow-up.
  Export progress reporting only fires during the write phase --
    the merge+sort phase (~95% of wall time at 1M) is silent.
  /history export and /history import are blocking on the main
    UI thread; profanity is frozen for the duration (~5 min @ 1M).
  ff_readline sets *truncated=TRUE on partial-write tail but
    ff_verify_integrity does not surface this -- partial writes
    go unflagged (failure-injection F1).
  Parser silently truncates body at first unescaped ': ' if a
    resource was manually edited to contain it (F9).
  In gen_history (caught by the bench's own real-verify pass):
    g_strndup mid-codepoint truncation on UTF-8 bank strings -- fixed.

Linkage strategy

  database_flatfile.c + parser + verify + common.c are linked
  unconditionally. The export/import bench additionally links
  database.c + database_sqlite.c + database_export.c. bench_stubs.c
  provides minimal stubs for log_*, prefs_*, connection_get_jid,
  jid_create, files_*, message_*, ui hooks. integrity_issue_free
  is a weak symbol so it falls back to the real database.c
  implementation when that file is linked.
2026-04-30 15:39:30 +03:00

137 lines
4.5 KiB
Python
Executable File

#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
#
# This file is part of CProof.
# See LICENSE for the full GPLv3 text and the special OpenSSL linking exception.
"""
compare_baseline.py — diff a fresh `current.csv` against a committed
`baseline.csv` and exit non-zero on regressions.
Aggregation rule: same (scenario, volume) → median wall_ms across rows.
A regression is a > THRESHOLD percent slowdown vs. the baseline; speedups
of any size are reported but never fail the run.
Usage:
compare_baseline.py [--baseline=PATH] [--current=PATH]
[--threshold=PCT] [--quiet]
Exit codes:
0 — no regressions
1 — at least one regression
2 — input parse error
"""
import argparse
import csv
import statistics
import sys
from pathlib import Path
DEFAULT_THRESHOLD = 25.0 # percent slower vs baseline = regression
def load(path: Path) -> dict[tuple[str, str], list[float]]:
if not path.is_file():
return {}
rows: dict[tuple[str, str], list[float]] = {}
with path.open("r", newline="") as f:
rdr = csv.DictReader(f)
if not rdr.fieldnames or "scenario" not in rdr.fieldnames:
sys.exit(f"ERROR: {path} has no 'scenario' column")
for row in rdr:
try:
wall = float(row["wall_ms"])
except (KeyError, ValueError):
continue
key = (row.get("scenario", ""), row.get("volume", ""))
rows.setdefault(key, []).append(wall)
return rows
def median(values: list[float]) -> float:
return statistics.median(values) if values else 0.0
def fmt_ms(ms: float) -> str:
if ms < 1.0:
return f"{ms*1000:.0f} us"
if ms < 1000.0:
return f"{ms:.2f} ms"
if ms < 60000.0:
return f"{ms/1000:.2f} s"
return f"{ms/60000:.2f} min"
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--baseline", default="tests/bench/baseline.csv")
ap.add_argument("--current", default="tests/bench/current.csv")
ap.add_argument("--threshold", type=float, default=DEFAULT_THRESHOLD,
help="regression threshold in percent (default 25)")
ap.add_argument("--quiet", action="store_true",
help="only print regressions, hide unchanged/improved rows")
args = ap.parse_args()
base_p, cur_p = Path(args.baseline), Path(args.current)
if not cur_p.is_file():
sys.exit(f"ERROR: --current {cur_p} not found (run `make bench` first)")
base = load(base_p)
cur = load(cur_p)
if not cur:
sys.exit(f"ERROR: {cur_p} has no rows")
keys = sorted(set(base) | set(cur))
regressions: list[tuple[str, str, float, float, float]] = []
improvements: list[tuple[str, str, float, float, float]] = []
new_rows: list[tuple[str, str, float]] = []
missing: list[tuple[str, str, float]] = []
print(f"{'scenario':<30s} {'volume':<14s} {'baseline':>12s} {'current':>12s} {'delta':>10s}")
print("-" * 84)
for k in keys:
sc, vol = k
b = median(base.get(k, []))
c = median(cur.get(k, []))
if k not in base:
new_rows.append((sc, vol, c))
if not args.quiet:
print(f"{sc:<30s} {vol:<14s} {'(new)':>12s} {fmt_ms(c):>12s} {'':>10s}")
continue
if k not in cur:
missing.append((sc, vol, b))
if not args.quiet:
print(f"{sc:<30s} {vol:<14s} {fmt_ms(b):>12s} {'(gone)':>12s} {'':>10s}")
continue
if b == 0:
continue
pct = (c - b) / b * 100.0
marker = ""
if pct >= args.threshold:
regressions.append((sc, vol, b, c, pct))
marker = " REGRESSION"
elif pct <= -args.threshold:
improvements.append((sc, vol, b, c, pct))
marker = " improved"
if marker or not args.quiet:
sign = "+" if pct >= 0 else ""
print(f"{sc:<30s} {vol:<14s} {fmt_ms(b):>12s} {fmt_ms(c):>12s} {sign}{pct:>8.1f}%{marker}")
print()
print(f"summary: {len(regressions)} regressions, {len(improvements)} improvements, "
f"{len(new_rows)} new rows, {len(missing)} removed rows "
f"(threshold = ±{args.threshold:.0f} %)")
if regressions:
print("REGRESSED scenarios:")
for sc, vol, b, c, pct in regressions:
print(f" - {sc} ({vol}): {fmt_ms(b)}{fmt_ms(c)} (+{pct:.1f}%)")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())