From 7494b31f8c1c234e6f79d72bead4ad0d4e60b11f Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:52:59 +0800 Subject: [PATCH 1/6] bench: compare native string operations with SDS and bstrlib Add reproducible correctness-checked benchmarks, separate allocation counting, raw samples and runner metadata without modifying library implementations. Co-authored-by: Codex --- .github/workflows/benchmarks.yml | 70 +++++ benchmarks/README.md | 92 +++++++ benchmarks/run.py | 171 +++++++++++++ benchmarks/strings.c | 427 +++++++++++++++++++++++++++++++ 4 files changed, 760 insertions(+) create mode 100644 .github/workflows/benchmarks.yml create mode 100644 benchmarks/README.md create mode 100644 benchmarks/run.py create mode 100644 benchmarks/strings.c diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml new file mode 100644 index 0000000..3d1a948 --- /dev/null +++ b/.github/workflows/benchmarks.yml @@ -0,0 +1,70 @@ +name: String benchmarks + +on: + pull_request: + paths: + - 'benchmarks/**' + - '.github/workflows/benchmarks.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: string-benchmarks-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +defaults: + run: + shell: bash + +jobs: + benchmark: + name: GCC and Clang string benchmarks + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Install benchmark compilers and PCRE2 headers + timeout-minutes: 5 + run: | + if test -f /etc/apt/apt-mirrors.txt; then + printf '%s\n' 'https://archive.ubuntu.com/ubuntu' | sudo tee /etc/apt/apt-mirrors.txt > /dev/null + fi + sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update + sudo env DEBIAN_FRONTEND=noninteractive apt-get \ + -o DPkg::Lock::Timeout=120 -o Acquire::Retries=3 \ + -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ + install --no-install-recommends -y gcc-14 clang-19 libclang-rt-19-dev libpcre2-dev pkg-config + - name: Check out pinned SDS + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: antirez/sds + ref: 5347739b1581fcba74fd5cab1fc21d2aef317d71 + path: build/benchmarks/deps/sds + persist-credentials: false + - name: Check out pinned bstrlib + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: websnarf/bstrlib + ref: f0ff1e808102a42cdc7204a4bb6fe231a24c4546 + path: build/benchmarks/deps/bstrlib + persist-credentials: false + - name: Validate, measure and report on one pinned CPU + run: python3 benchmarks/run.py --cc gcc-14 --cc clang-19 + - name: Preserve raw samples and environment + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: string-benchmarks-${{ github.run_id }} + path: | + build/benchmarks/results/**/*.csv + build/benchmarks/results/**/*.json + build/benchmarks/results/**/*.md + build/benchmarks/results/**/*.txt + build/benchmarks/results/**/*.log + if-no-files-found: ignore + retention-days: 14 diff --git a/benchmarks/README.md b/benchmarks/README.md new file mode 100644 index 0000000..bd0b368 --- /dev/null +++ b/benchmarks/README.md @@ -0,0 +1,92 @@ +# Native string-library benchmarks + +This suite benchmarks the current StringX implementation against pinned +[SDS](https://github.com/antirez/sds) and +[bstrlib](https://github.com/websnarf/bstrlib), using their normal public APIs. +It starts from StringX main at +452314a7ca51f90a7a8fa66930947164af8fc4f6; no library implementation is changed. + +## Workloads and contracts + +28 workloads produce 82 case/library combinations: + +- Allocate/copy/free C strings at 16, 64, 1024 and 65536 bytes, with strlen + discovery included for every library. +- Copy known-length binary strings at 64 and 65536 bytes, including embedded + NULs. StringX uses an existing view, SDS uses sdsnewlen, bstrlib uses blk2bstr. +- Build and free a complete string by repeated known-length appends, with and + without reserve: 4096 x 1 byte, 256 x 16 bytes, and 1024 x 1024 bytes. +- Lexicographic comparisons, equal strings and a mismatch in the final byte. +- Single-byte and multi-byte searches, front/end hits, misses and a repetitive + prefix adversary. SDS has no native substring-search API: its search rows are + explicitly labeled SDS+glibc and use binary-safe memmem/memchr. +- Owned substring copies and borrowed views, reported as separate workloads. + The SDS view baseline is a borrowed pointer/length pair; bstrlib uses its + borrowed tagbstring macro. These rows do not represent memory-copy throughput. +- Owned splitting with leading/trailing empty fields, using one- and two-byte + separators. StringX returns views natively; its owned-output row explicitly + adds materialization of each token and is labeled StringX+materialize. + Native StringX view-only splitting is an additional StringX-only workload; + it is not ranked against APIs that copy token bytes. + +An append "operation" is the entire create/reserve/append/free batch. +Read-only fixtures and input generation are outside the timed region. +Ownership and cleanup are included in allocating operations. +Regex, Unicode processing, formatting and multithreaded use are outside this suite. + +## Measurement + +- GCC 14 and Clang 19 run sequentially on the same Linux host and pinned CPU. +- All libraries compile into separate translation units with the same + -std=c23 -O3 -DNDEBUG -march=x86-64 -fno-lto flags. There is no header-only or + LTO visibility advantage for StringX. Native public-header inline operations + in other libraries remain available, as they are to their normal callers. +- A separate ASan/UBSan/leak-checked binary first validates all 82 combinations, + including byte contents for copies/appends and semantic checksums for queries + and tokens. The timed binary is not instrumented. +- Each case/library pair calibrates iterations to at least 20 ms in two pilot + batches (up to an iteration cap), followed by 11 recorded samples. + Library order is shuffled deterministically within each sample round. +- A compiler memory barrier and consumed/checked checksums prevent dead-code + elimination and hoisting across iterations. Loop, branch and checksum overhead + remain in the measurements; no guessed overhead is subtracted. +- Allocation counts come from a third, untimed binary using GNU ld --wrap. + malloc/calloc/realloc calls and cumulative requested sizes are recorded for + one complete operation, excluding fixture setup. Requested bytes are allocator + traffic, not resident memory or peak live allocation. Allocator caches still + affect the normal timed build. +- summary.json and summary.md report median and p10/p90 observed timings. + These quantiles describe sample spread, not statistical confidence bounds. + The effective MiB/s raw column uses logical workload bytes; early search hits + and borrowed views do not physically process/copy that many bytes. + +These are hot-input, single-threaded microbenchmarks on a shared hosted runner. +CPU frequency, VM scheduling and allocator behavior limit absolute timing claims. +Compare libraries within a case and compiler; avoid general-purpose rankings. +No noisy timing threshold is used as a merge gate. + +## Reproduce + +Install Python 3, GCC 14, Clang 19, the matching Clang sanitizer runtime, +pkg-config and PCRE2 development headers. Forge is not needed for this harness. + +Clone the public dependencies and select the reviewed revisions: + +```sh +mkdir -p build/benchmarks/deps +git clone https://github.com/antirez/sds build/benchmarks/deps/sds +git -C build/benchmarks/deps/sds checkout --detach 5347739b1581fcba74fd5cab1fc21d2aef317d71 +git clone https://github.com/websnarf/bstrlib build/benchmarks/deps/bstrlib +git -C build/benchmarks/deps/bstrlib checkout --detach f0ff1e808102a42cdc7204a4bb6fe231a24c4546 +python3 benchmarks/run.py --cc gcc-14 --cc clang-19 +``` + +The runner verifies dependency revisions and records compiler versions, CPU +affinity, lscpu, flags, commit IDs and SHA-256 hashes of the measured StringX +sources. Outputs live under the ignored build/benchmarks/results directory. +GitHub Actions publishes a job summary and retains raw CSV/JSON/log artifacts +for 14 days. Performance runs are limited to PRs changing the benchmark or its +workflow, and manual dispatch; ordinary library PRs do not run this suite. + +Dependencies are fetched separately and retain their original licenses. +Their source code is not vendored or relicensed by this harness. diff --git a/benchmarks/run.py b/benchmarks/run.py new file mode 100644 index 0000000..3fdf52d --- /dev/null +++ b/benchmarks/run.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +"""Reproducible native-library microbenchmarks; no third-party Python packages.""" +import argparse +import csv +import hashlib +import json +import os +from pathlib import Path +import platform +import statistics +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +BASELINE = "452314a7ca51f90a7a8fa66930947164af8fc4f6" +PINS = { + "sds": "5347739b1581fcba74fd5cab1fc21d2aef317d71", + "bstrlib": "f0ff1e808102a42cdc7204a4bb6fe231a24c4546", +} +COMMON = ["-std=c23", "-march=x86-64", "-fno-lto"] + +def output(args, cwd=ROOT): + return subprocess.check_output(args, cwd=cwd, text=True).strip() + +def invoke(args, log, *, env=None, stdout=None, cpu=None): + print("+", " ".join(map(str, args)), flush=True) + hook = (lambda: os.sched_setaffinity(0, {cpu})) if cpu is not None else None + with log.open("a") as err: + if stdout is None: + result = subprocess.run(args, cwd=ROOT, env=env, stdout=err, stderr=err, preexec_fn=hook) + else: + with stdout.open("w") as out: + result = subprocess.run(args, cwd=ROOT, env=env, stdout=out, stderr=err, preexec_fn=hook) + if result.returncode: + print(log.read_text()[-20000:], file=sys.stderr) + raise RuntimeError(f"command failed ({result.returncode}): {args}") + +def compile_binary(cc, dest, mode, deps, log): + flags = COMMON + (["-O1", "-g", "-fsanitize=address,undefined", + "-fno-sanitize-recover=all", "-fno-omit-frame-pointer"] + if mode == "check" else ["-O3", "-DNDEBUG"]) + includes = ["-I" + str(ROOT / "include"), "-I" + str(deps / "sds"), + "-I" + str(deps / "bstrlib")] + pkg_cflags = output(["pkg-config", "--cflags", "libpcre2-8"]).split() + pkg_libs = output(["pkg-config", "--libs", "libpcre2-8"]).split() + sources = [ROOT / "src/sx_core.c", ROOT / "src/sx_raw.c", ROOT / "src/sx_adv.c", + deps / "sds/sds.c", deps / "bstrlib/bstrlib.c", ROOT / "benchmarks/strings.c"] + objects = [] + dest.mkdir(parents=True, exist_ok=True) + for i, source in enumerate(sources): + obj = dest / f"{i}.o" + options = flags + includes + pkg_cflags + if source == ROOT / "benchmarks/strings.c": + options += ["-Wall", "-Wextra", "-Werror"] + if mode == "alloc": + options += ["-DBENCH_ALLOC"] + invoke([cc, *options, "-c", str(source), "-o", str(obj)], log) + objects.append(str(obj)) + binary = dest / "strings" + wrap = ["-Wl,--wrap=malloc,--wrap=calloc,--wrap=realloc,--wrap=free"] if mode == "alloc" else [] + invoke([cc, *flags, *objects, *wrap, *pkg_libs, "-o", str(binary)], log) + return binary + +def quantile(values, fraction): + ordered = sorted(values) + point = (len(ordered) - 1) * fraction + lo = int(point) + hi = min(lo + 1, len(ordered) - 1) + return ordered[lo] + (ordered[hi] - ordered[lo]) * (point - lo) + +def summarize(samples, allocations, compiler): + rows = list(csv.DictReader(samples.open())) + alloc = {(r["case"], r["library"]): r for r in csv.DictReader(allocations.open())} + groups = {} + for r in rows: + groups.setdefault((r["case"], r["library"]), []).append(r) + stats = [] + for (case, library), data in groups.items(): + values = [float(r["ns_per_op"]) for r in data] + assert len(values) == 11, (case, library, len(values)) + memory = alloc[(case, library)] + stats.append({ + "case": case, "library": library, "bytes": int(data[0]["bytes"]), + "part": int(data[0]["part"]), "samples": len(values), + "median_ns": statistics.median(values), + "p10_ns": quantile(values, 0.1), "p90_ns": quantile(values, 0.9), + "malloc_calls": int(memory["malloc_calls"]), + "calloc_calls": int(memory["calloc_calls"]), + "realloc_calls": int(memory["realloc_calls"]), + "free_calls": int(memory["free_calls"]), + "requested_bytes": int(memory["requested_bytes"]), + }) + assert len(stats) == 82, len(stats) + return {"compiler": compiler, "results": stats} + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--cc", action="append", required=True) + parser.add_argument("--deps", type=Path, default=ROOT / "build/benchmarks/deps") + parser.add_argument("--out", type=Path, default=ROOT / "build/benchmarks/results") + args = parser.parse_args() + args.deps = args.deps.resolve() + args.out = args.out.resolve() + args.out.mkdir(parents=True, exist_ok=True) + for lib, sha in PINS.items(): + assert output(["git", "rev-parse", "HEAD"], args.deps / lib) == sha, lib + affinity = sorted(os.sched_getaffinity(0)) + assert affinity + cpu = affinity[0] + hardware = { + "platform": platform.platform(), "machine": platform.machine(), + "date_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "benchmark_commit": output(["git", "rev-parse", "HEAD"]), + "initial_library_baseline": BASELINE, + "dependency_commits": PINS, "allowed_cpus": affinity, "pinned_cpu": cpu, + "lscpu": json.loads(output(["lscpu", "-J"])), + "timing_flags": COMMON + ["-O3", "-DNDEBUG"], + "samples": 11, "target_sample_ns": 20000000, + "source_sha256": {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest() + for p in [ROOT / "src/sx_core.c", ROOT / "src/sx_raw.c", ROOT / "src/sx_adv.c"]}, + } + (args.out / "environment.json").write_text(json.dumps(hardware, indent=2) + "\n") + print("BENCH_ENVIRONMENT_JSON=" + json.dumps(hardware, separators=(",", ":")), flush=True) + all_results = [] + for cc in args.cc: + folder = args.out / Path(cc).name + folder.mkdir(parents=True, exist_ok=True) + log = folder / "commands.log" + version = output([cc, "--version"]) + (folder / "compiler.txt").write_text(version + "\n") + sanitizer = compile_binary(cc, folder / "check", "check", args.deps, log) + env = os.environ.copy() + env.update(ASAN_OPTIONS="detect_leaks=1:halt_on_error=1", + UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1") + invoke([str(sanitizer), "--check"], log, env=env, cpu=cpu) + binary = compile_binary(cc, folder / "timing", "timing", args.deps, log) + invoke([str(binary)], log, stdout=folder / "samples.csv", cpu=cpu) + counter = compile_binary(cc, folder / "alloc", "alloc", args.deps, log) + invoke([str(counter)], log, stdout=folder / "allocations.csv", cpu=cpu) + result = summarize(folder / "samples.csv", folder / "allocations.csv", cc) + result["compiler_version"] = version.splitlines()[0] + (folder / "summary.json").write_text(json.dumps(result, indent=2) + "\n") + all_results.append(result) + print("BENCH_RESULT_JSON=" + json.dumps(result, separators=(",", ":")), flush=True) + lines = [ + "# StringX baseline benchmark", "", + f"Measured commit: {hardware['benchmark_commit']}; initial library baseline: {BASELINE}. See environment.json for CPU and flags.", "", + "Each value is median ns/op from 11 samples; p10–p90 describes observed spread, not a confidence interval.", + "An append operation builds and frees the entire output string. Allocation totals are from a separate untimed binary.", + "SDS search uses glibc memmem/memchr. StringX owned split materializes its returned views; view-only split is reported separately.", + "Borrowed substring views do not copy bytes. All fixtures are reused in-process; these are hot-input microbenchmarks.", + "Shared hosted-runner scheduling and frequency changes limit absolute timing claims.", "", + ] + for result in all_results: + lines += [f"## {result['compiler_version']}", "", + "| Case | Library | Median ns/op | p10–p90 ns | malloc + calloc | realloc | Requested bytes/op |", + "| --- | --- | ---: | ---: | ---: | ---: | ---: |"] + for row in result["results"]: + lines.append(f"| {row['case']} | {row['library']} | {row['median_ns']:.2f} | " + f"{row['p10_ns']:.2f}–{row['p90_ns']:.2f} | " + f"{row['malloc_calls'] + row['calloc_calls']} | {row['realloc_calls']} | {row['requested_bytes']} |") + lines.append("") + report = "\n".join(lines) + "\n" + (args.out / "summary.md").write_text(report) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as out: + out.write(report) + +if __name__ == "__main__": + main() diff --git a/benchmarks/strings.c b/benchmarks/strings.c new file mode 100644 index 0000000..011a23d --- /dev/null +++ b/benchmarks/strings.c @@ -0,0 +1,427 @@ +// SPDX-License-Identifier: MIT +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(x) do { if (!(x)) { fprintf(stderr, "benchmark check failed: %s:%d: %s\n", __FILE__, __LINE__, #x); exit(1); } } while (0) +#define SAMPLES 11 +enum { COPY_CSTR, COPY_BYTES, APPEND, COMPARE, FIND, FIND_CHAR, SUBSTR, VIEW, SPLIT_OWNED, SPLIT_VIEW }; +enum { HIT_FRONT = 1, HIT_END = 2, REPEATED = 4, DIFFERENT = 8, RESERVED = 16 }; +typedef struct { const char *name; int op; size_t n, part; unsigned flags; } Case; +static const Case cases[] = { + {"copy_cstr_16", COPY_CSTR, 16, 0, 0}, + {"copy_cstr_64", COPY_CSTR, 64, 0, 0}, + {"copy_cstr_1024", COPY_CSTR, 1024, 0, 0}, + {"copy_cstr_65536", COPY_CSTR, 65536, 0, 0}, + {"copy_bytes_64", COPY_BYTES, 64, 0, 0}, + {"copy_bytes_65536", COPY_BYTES, 65536, 0, 0}, + {"append_1x4096_auto", APPEND, 4096, 1, 0}, + {"append_1x4096_reserved", APPEND, 4096, 1, RESERVED}, + {"append_16x256_auto", APPEND, 4096, 16, 0}, + {"append_16x256_reserved", APPEND, 4096, 16, RESERVED}, + {"append_1024x1024_auto", APPEND, 1048576, 1024, 0}, + {"append_1024x1024_reserved", APPEND, 1048576, 1024, RESERVED}, + {"compare_equal_64", COMPARE, 64, 0, 0}, + {"compare_equal_65536", COMPARE, 65536, 0, 0}, + {"compare_last_diff_65536", COMPARE, 65536, 0, DIFFERENT}, + {"find_char_end_65536", FIND_CHAR, 65536, 1, HIT_END}, + {"find_char_miss_65536", FIND_CHAR, 65536, 1, 0}, + {"find8_front_64", FIND, 64, 8, HIT_FRONT}, + {"find8_end_1024", FIND, 1024, 8, HIT_END}, + {"find8_end_65536", FIND, 65536, 8, HIT_END}, + {"find8_miss_65536", FIND, 65536, 8, 0}, + {"find128_repeated_miss_65536", FIND, 65536, 128, REPEATED}, + {"substr_copy_64", SUBSTR, 65536, 64, 0}, + {"substr_copy_4096", SUBSTR, 65536, 4096, 0}, + {"substr_view_64", VIEW, 65536, 64, 0}, + {"split_owned_comma_4096", SPLIT_OWNED, 4096, 1, 0}, + {"split_owned_pair_4096", SPLIT_OWNED, 4096, 2, 0}, + {"split_views_comma_4096", SPLIT_VIEW, 4096, 1, 0} +}; + +typedef struct { + const Case *c; + char *data, *other, *needle; + const char *sep; + sx_t *sx, *sx_other, *sx_needle; + sds sd, sd_other; + bstring bs, bs_other, bs_needle, bs_sep; + uint64_t expected; +} Fixture; +static int validating; +static volatile uint64_t sink; + +static inline void escape(const void *p) { + __asm__ __volatile__("" : : "g"(p) : "memory"); +} +static uint64_t digest(const void *ptr, size_t n) { + const unsigned char *p = ptr; + escape(ptr); + return (uint64_t)n + (n ? (uint64_t)p[0] + p[n - 1] : 0); +} +static uint64_t checked_content(Fixture *f, const void *p, size_t n, int append) { + if (validating) { + size_t wanted = f->c->op == SUBSTR || f->c->op == VIEW ? f->c->part : f->c->n; + CHECK(n == wanted); + if (append) { + for (size_t at = 0; at < n; at += f->c->part) + CHECK(memcmp((const char *)p + at, f->data, f->c->part) == 0); + } else { + size_t off = f->c->op == SUBSTR || f->c->op == VIEW ? f->c->n / 3 : 0; + CHECK(memcmp(p, f->data + off, n) == 0); + } + } + return digest(p, n); +} +static uint64_t order(int result) { return result < 0 ? 0 : result > 0 ? 2 : 1; } +static uint64_t reference_split(Fixture *f) { + size_t start = 0, at = 0; + uint64_t sum = 0; + while (at + f->c->part <= f->c->n) { + if (memcmp(f->data + at, f->sep, f->c->part) != 0) { ++at; continue; } + sum += 1 + digest(f->data + start, at - start); + at += f->c->part; + start = at; + } + return sum + 1 + digest(f->data + start, f->c->n - start); +} +static void prepare(Fixture *f, const Case *c) { + memset(f, 0, sizeof(*f)); + f->c = c; + f->data = malloc(c->n + 1); + f->other = malloc(c->n + 1); + f->needle = malloc((c->part ? c->part : 1) + 1); + CHECK(f->data && f->other && f->needle); + uint32_t state = 0x12ab34cd; + for (size_t i = 0; i < c->n; ++i) { + state = state * 1664525u + 1013904223u; + f->data[i] = (char)('a' + (state % 25)); + } + f->data[c->n] = 0; + if (c->op == COPY_BYTES) { + for (size_t i = 3; i < c->n; i += 17) f->data[i] = 0; + } + size_t m = c->part ? c->part : 1; + memset(f->needle, 'Z', m); + f->needle[m] = 0; + if (c->op == FIND && (c->flags & REPEATED)) { + memset(f->data, 'a', c->n); + memset(f->needle, 'a', m); + f->needle[m - 1] = 'b'; + } else if (c->op == FIND || c->op == FIND_CHAR) { + if (c->flags & HIT_FRONT) memcpy(f->data, f->needle, m); + if (c->flags & HIT_END) memcpy(f->data + c->n - m, f->needle, m); + } + f->sep = c->part == 2 ? "::" : ","; + if (c->op == SPLIT_OWNED || c->op == SPLIT_VIEW) { + memcpy(f->data, f->sep, c->part); + for (size_t at = 64 - c->part; at + c->part <= c->n; at += 64) + memcpy(f->data + at, f->sep, c->part); + } + memcpy(f->other, f->data, c->n + 1); + if (c->flags & DIFFERENT) + f->other[c->n - 1] = f->data[c->n - 1] == 'a' ? 'b' : 'a'; + + f->sx = sx_new_with_cap(c->n + 1); + CHECK(f->sx && sx_truncate(f->sx, c->n)); + memcpy(sx_buf_mut(f->sx), f->data, c->n); + f->sx_other = sx_new_with_cap(c->n + 1); + CHECK(f->sx_other && sx_truncate(f->sx_other, c->n)); + memcpy(sx_buf_mut(f->sx_other), f->other, c->n); + f->sx_needle = sx_new_from_cstr(f->needle); + f->sd = sdsnewlen(f->data, c->n); + f->sd_other = sdsnewlen(f->other, c->n); + f->bs = blk2bstr(f->data, (int)c->n); + f->bs_other = blk2bstr(f->other, (int)c->n); + f->bs_needle = bfromcstr(f->needle); + f->bs_sep = bfromcstr(f->sep); + CHECK(f->sx_needle && f->sd && f->sd_other && f->bs && f->bs_other && f->bs_needle && f->bs_sep); + + switch (c->op) { + case APPEND: + f->expected = c->n + (unsigned char)f->data[0] + (unsigned char)f->data[c->part - 1]; + break; + case COMPARE: f->expected = order(memcmp(f->data, f->other, c->n)); break; + case FIND: { + const char *p = memmem(f->data, c->n, f->needle, c->part); + f->expected = p ? (uint64_t)(p - f->data) + 1 : 0; + break; + } + case FIND_CHAR: { + const char *p = memchr(f->data, 'Z', c->n); + f->expected = p ? (uint64_t)(p - f->data) + 1 : 0; + break; + } + case SUBSTR: case VIEW: + f->expected = digest(f->data + c->n / 3, c->part); + break; + case SPLIT_OWNED: case SPLIT_VIEW: f->expected = reference_split(f); break; + default: f->expected = digest(f->data, c->n); break; + } +} +static void cleanup(Fixture *f) { + sx_free(f->sx); sx_free(f->sx_other); sx_free(f->sx_needle); + sdsfree(f->sd); sdsfree(f->sd_other); + CHECK(bdestroy(f->bs) == BSTR_OK); + CHECK(bdestroy(f->bs_other) == BSTR_OK); + CHECK(bdestroy(f->bs_needle) == BSTR_OK); + CHECK(bdestroy(f->bs_sep) == BSTR_OK); + free(f->data); free(f->other); free(f->needle); +} + +static uint64_t work_sx(Fixture *f, size_t iterations) { + const Case *c = f->c; + uint64_t sum = 0; + for (size_t it = 0; it < iterations; ++it) { + escape(f->sx); + sx_t *s; + switch (c->op) { + case COPY_CSTR: case COPY_BYTES: + s = c->op == COPY_CSTR ? sx_new_from_cstr(f->data) : sx_new_from_view(sx_view(f->sx)); + CHECK(s); + sum += checked_content(f, sx_buf_mut(s), (size_t)sx_len(s), 0); + sx_free(s); break; + case APPEND: { + s = sx_new(); CHECK(s); + if (c->flags & RESERVED) CHECK(sx_reserve(s, c->n)); + sx_view_t chunk = sx_view_range(sx_view(f->sx), 0, c->part); + for (size_t at = 0; at < c->n; at += c->part) CHECK(sx_append_view(s, chunk)); + sum += checked_content(f, sx_buf_mut(s), (size_t)sx_len(s), 1); + sx_free(s); break; + } + case COMPARE: sum += order(sx_cmp(f->sx, f->sx_other)); break; + case FIND: sum += sx_find(f->sx, f->sx_needle) + (size_t)1; break; + case FIND_CHAR: sum += sx_find_char(f->sx, 'Z') + (size_t)1; break; + case SUBSTR: + s = sx_substr(f->sx, c->n / 3, c->part); CHECK(s); + sum += checked_content(f, sx_buf_mut(s), (size_t)sx_len(s), 0); + sx_free(s); break; + case VIEW: { + sx_view_t v = sx_view_range(sx_view(f->sx), c->n / 3, c->part); + sum += checked_content(f, sx_buf_view_mut(v), v.len, 0); break; + } + case SPLIT_OWNED: case SPLIT_VIEW: { + sx_view_t *tokens = sx_split(f->sx, f->sep); CHECK(tokens); + for (size_t j = 0; tokens[j].ref; ++j) { + if (c->op == SPLIT_OWNED) { + s = sx_new_from_view(tokens[j]); CHECK(s); + sum += 1 + digest(sx_buf_mut(s), (size_t)sx_len(s)); + sx_free(s); + } else sum += 1 + digest(sx_buf_view_mut(tokens[j]), tokens[j].len); + } + free(tokens); break; + } + default: CHECK(0); + } + } + return sum; +} +static uint64_t work_sds(Fixture *f, size_t iterations) { + const Case *c = f->c; + uint64_t sum = 0; + for (size_t it = 0; it < iterations; ++it) { + escape(f->sd); + sds s; + switch (c->op) { + case COPY_CSTR: case COPY_BYTES: + s = c->op == COPY_CSTR ? sdsnew(f->data) : sdsnewlen(f->data, c->n); + CHECK(s); sum += checked_content(f, s, sdslen(s), 0); sdsfree(s); break; + case APPEND: + s = sdsempty(); CHECK(s); + if (c->flags & RESERVED) { s = sdsMakeRoomFor(s, c->n); CHECK(s); } + for (size_t at = 0; at < c->n; at += c->part) { s = sdscatlen(s, f->data, c->part); CHECK(s); } + sum += checked_content(f, s, sdslen(s), 1); sdsfree(s); break; + case COMPARE: sum += order(sdscmp(f->sd, f->sd_other)); break; + case FIND: { + const char *p = memmem(f->sd, sdslen(f->sd), f->needle, c->part); + sum += p ? (uint64_t)(p - f->sd) + 1 : 0; break; + } + case FIND_CHAR: { + const char *p = memchr(f->sd, 'Z', sdslen(f->sd)); + sum += p ? (uint64_t)(p - f->sd) + 1 : 0; break; + } + case SUBSTR: + s = sdsnewlen(f->sd + c->n / 3, c->part); CHECK(s); + sum += checked_content(f, s, sdslen(s), 0); sdsfree(s); break; + case VIEW: + sum += checked_content(f, f->sd + c->n / 3, c->part, 0); break; + case SPLIT_OWNED: { + int count = 0; + sds *tokens = sdssplitlen(f->sd, (ssize_t)sdslen(f->sd), f->sep, (int)c->part, &count); + CHECK(tokens); + for (int j = 0; j < count; ++j) sum += 1 + digest(tokens[j], sdslen(tokens[j])); + sdsfreesplitres(tokens, count); break; + } + default: CHECK(0); + } + } + return sum; +} +static uint64_t work_bstr(Fixture *f, size_t iterations) { + const Case *c = f->c; + uint64_t sum = 0; + for (size_t it = 0; it < iterations; ++it) { + escape(f->bs); + bstring s; + switch (c->op) { + case COPY_CSTR: case COPY_BYTES: + s = c->op == COPY_CSTR ? bfromcstr(f->data) : blk2bstr(f->data, (int)c->n); + CHECK(s); sum += checked_content(f, s->data, (size_t)s->slen, 0); + CHECK(bdestroy(s) == BSTR_OK); break; + case APPEND: + s = bfromcstr(""); CHECK(s); + if (c->flags & RESERVED) CHECK(balloc(s, (int)c->n + 1) == BSTR_OK); + for (size_t at = 0; at < c->n; at += c->part) CHECK(bcatblk(s, f->data, (int)c->part) == BSTR_OK); + sum += checked_content(f, s->data, (size_t)s->slen, 1); + CHECK(bdestroy(s) == BSTR_OK); break; + case COMPARE: sum += order(bstrcmp(f->bs, f->bs_other)); break; + case FIND: { int p = binstr(f->bs, 0, f->bs_needle); sum += p >= 0 ? (uint64_t)p + 1 : 0; break; } + case FIND_CHAR: { int p = bstrchr(f->bs, 'Z'); sum += p >= 0 ? (uint64_t)p + 1 : 0; break; } + case SUBSTR: + s = bmidstr(f->bs, (int)(c->n / 3), (int)c->part); CHECK(s); + sum += checked_content(f, s->data, (size_t)s->slen, 0); + CHECK(bdestroy(s) == BSTR_OK); break; + case VIEW: { + struct tagbstring view; + bmid2tbstr(view, f->bs, (int)(c->n / 3), (int)c->part); + sum += checked_content(f, view.data, (size_t)view.slen, 0); break; + } + case SPLIT_OWNED: { + struct bstrList *tokens = bsplitstr(f->bs, f->bs_sep); CHECK(tokens); + for (int j = 0; j < tokens->qty; ++j) + sum += 1 + digest(tokens->entry[j]->data, (size_t)tokens->entry[j]->slen); + CHECK(bstrListDestroy(tokens) == BSTR_OK); break; + } + default: CHECK(0); + } + } + return sum; +} + +typedef uint64_t (*Worker)(Fixture *, size_t); +static Worker workers[] = {work_sx, work_sds, work_bstr}; +static const char *library_name(const Case *c, int lib) { + if (lib == 0) return c->op == SPLIT_OWNED ? "StringX+materialize" : "StringX"; + if (lib == 1) return c->op == FIND || c->op == FIND_CHAR ? "SDS+glibc" : + c->op == VIEW ? "SDS+raw-view" : "SDS"; + return c->op == VIEW ? "bstrlib+borrowed-view" : "bstrlib"; +} +#ifndef BENCH_ALLOC +static uint64_t now_ns(void) { + struct timespec t; CHECK(clock_gettime(CLOCK_MONOTONIC, &t) == 0); + return (uint64_t)t.tv_sec * 1000000000ULL + (uint64_t)t.tv_nsec; +} +#endif +static uint64_t checked_run(Worker fn, Fixture *f, size_t it) { + uint64_t value = fn(f, it); + CHECK(value == f->expected * (uint64_t)it); + sink ^= value; + return value; +} +#ifndef BENCH_ALLOC +static uint64_t measure(Worker fn, Fixture *f, size_t it) { + uint64_t begin = now_ns(); + checked_run(fn, f, it); + return now_ns() - begin; +} +static size_t calibrate(Worker fn, Fixture *f) { + size_t it = 1; + for (;;) { + uint64_t a = measure(fn, f, it), b = measure(fn, f, it); + if ((a < b ? a : b) >= 20000000ULL || it >= (1u << 24)) return it; + it *= 2; + } +} + +#endif +#ifdef BENCH_ALLOC +static int counting; +static uint64_t mallocs, callocs, reallocs, frees, requested; +void *__real_malloc(size_t); +void *__real_calloc(size_t, size_t); +void *__real_realloc(void *, size_t); +void __real_free(void *); +void *__wrap_malloc(size_t n) { + if (counting) { ++mallocs; requested += n; } + return __real_malloc(n); +} +void *__wrap_calloc(size_t n, size_t s) { + if (counting) { ++callocs; requested += n * s; } + return __real_calloc(n, s); +} +void *__wrap_realloc(void *p, size_t n) { + if (counting) { ++reallocs; requested += n; } + return __real_realloc(p, n); +} +void __wrap_free(void *p) { + if (counting && p) ++frees; + __real_free(p); +} +#endif + +int main(int argc, char **argv) { + int check_only = argc == 2 && strcmp(argv[1], "--check") == 0; + #ifndef BENCH_ALLOC + uint32_t rng = 0x7132a8ef; + #endif +#ifdef BENCH_ALLOC + if (!check_only) puts("case,library,bytes,part,malloc_calls,calloc_calls,realloc_calls,free_calls,requested_bytes"); +#else + if (!check_only) puts("case,library,bytes,part,iterations,sample,elapsed_ns,ns_per_op,mib_per_s"); +#endif + size_t combinations = 0; + for (size_t ci = 0; ci < sizeof(cases) / sizeof(cases[0]); ++ci) { + Fixture f; prepare(&f, &cases[ci]); + int libs = f.c->op == SPLIT_VIEW ? 1 : 3; + validating = 1; + for (int lib = 0; lib < libs; ++lib) { + checked_run(workers[lib], &f, 1); + ++combinations; + } + validating = 0; + if (!check_only) { +#ifdef BENCH_ALLOC + for (int lib = 0; lib < libs; ++lib) { + mallocs = callocs = reallocs = frees = requested = 0; + counting = 1; + checked_run(workers[lib], &f, 1); + counting = 0; + printf("%s,%s,%zu,%zu,%" PRIu64 ",%" PRIu64 ",%" PRIu64 ",%" PRIu64 ",%" PRIu64 "\n", + f.c->name, library_name(f.c, lib), f.c->n, f.c->part, + mallocs, callocs, reallocs, frees, requested); + } +#else + size_t iterations[3]; + for (int lib = 0; lib < libs; ++lib) iterations[lib] = calibrate(workers[lib], &f); + for (int sample = 0; sample < SAMPLES; ++sample) { + int sequence[] = {0, 1, 2}; + for (int i = libs - 1; i > 0; --i) { + rng = rng * 1664525u + 1013904223u; + int j = (int)(rng % (uint32_t)(i + 1)); + int tmp = sequence[i]; sequence[i] = sequence[j]; sequence[j] = tmp; + } + for (int j = 0; j < libs; ++j) { + int lib = sequence[j]; + uint64_t elapsed = measure(workers[lib], &f, iterations[lib]); + double ns = (double)elapsed / (double)iterations[lib]; + size_t bytes = f.c->op == SUBSTR || f.c->op == VIEW ? f.c->part : f.c->n; + double rate = (double)bytes * 1000000000.0 / ns / 1048576.0; + printf("%s,%s,%zu,%zu,%zu,%d,%" PRIu64 ",%.6f,%.6f\n", + f.c->name, library_name(f.c, lib), f.c->n, f.c->part, + iterations[lib], sample, elapsed, ns, rate); + } + } +#endif + } + cleanup(&f); + } + fprintf(stderr, "Validated %zu case/library combinations; sink=%" PRIu64 "\n", combinations, sink); + return 0; +} From c07b13661f5681c9dc317d2c8c8bd5e08c7d4b2e Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:23:21 +0800 Subject: [PATCH 2/6] bench: diagnose search scanning, allocation and code generation Add diagnostic-only kernels, same-object allocator ablation, logical comparison traces and native disassembly. Keep production search code unchanged and expand input distributions before choosing optimizations. Co-authored-by: Codex --- .github/workflows/benchmarks.yml | 2 + benchmarks/SEARCH_DIAGNOSIS.md | 48 +++++ benchmarks/search_diag.c | 299 +++++++++++++++++++++++++++++++ benchmarks/search_diag.py | 222 +++++++++++++++++++++++ 4 files changed, 571 insertions(+) create mode 100644 benchmarks/SEARCH_DIAGNOSIS.md create mode 100644 benchmarks/search_diag.c create mode 100644 benchmarks/search_diag.py diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml index 3d1a948..bc74151 100644 --- a/.github/workflows/benchmarks.yml +++ b/.github/workflows/benchmarks.yml @@ -55,6 +55,8 @@ jobs: persist-credentials: false - name: Validate, measure and report on one pinned CPU run: python3 benchmarks/run.py --cc gcc-14 --cc clang-19 + - name: Analyze search cost and generated code + run: python3 benchmarks/search_diag.py --cc gcc-14 --cc clang-19 - name: Preserve raw samples and environment if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/benchmarks/SEARCH_DIAGNOSIS.md b/benchmarks/SEARCH_DIAGNOSIS.md new file mode 100644 index 0000000..d8a186e --- /dev/null +++ b/benchmarks/SEARCH_DIAGNOSIS.md @@ -0,0 +1,48 @@ +# Search-cost diagnosis + +The library implementation is unchanged. This experiment separates measured +components and logical algorithm work before choosing an optimization. + +Run the same pinned dependency setup as the parent benchmark, then: + +```sh +python3 benchmarks/search_diag.py --cc gcc-14 --cc clang-19 +``` + +The diagnostic covers the original 8-byte absent-first-byte case at three input +sizes, the original 128-byte repeated-prefix case, common first bytes with a +missing/full end match, a periodic-text counterexample, and a front hit. + +- sx_unwrapped: original sx_find with the normal allocator. +- sx_heap / sx_arena: the same compiled library object, linked with allocation + wrappers. The arena changes only prefix-table malloc/free; the table is still + rebuilt and the original generic search still executes. Comparing these + shuffled variants isolates allocation more directly than timing malloc alone. +- kmp_first_only_heap: a diagnostic-only forward-FIRST specialization of KMP. + It omits reverse/ALL configuration and has its own malloc/prefix construction. +- kmp_scan_precomputed: only the forward scan, with a prefix table prepared + outside the timed region. +- prefix_build_only / malloc_free_only: component controls. These timings + cannot be added to reconstruct an exact whole-call breakdown. +- bstrlib / glibc_memmem: native comparison paths. +- scalar/glibc byte probes: necessary-condition controls, not full substring + search implementations. Their returned positions are checked separately. + +All full-search results are checked against the reference result. A separate +sanitizer build checks the diagnostic kernels. Nine shuffled timing samples +use the same pinned CPU and optimized flags as the parent suite. + +Logical counters trace the forward KMP algorithm and an instrumented copy of +the pinned bstrlib function. The latter is generated in the ignored build tree +with its original notice; bstrlib source is not vendored into this directory. +Logical comparison counts are not machine instructions or branch misses. + +The runner preserves source-interleaved disassembly, compiler vectorization +remarks, component CSV/JSON, and disassembly at resolved libc memchr/memmem +addresses. A perf_event_open probe records whether hardware counters are +available; this harness does not collect those counters. Do not infer +branch-misprediction rates or memory-stall fractions from wall time alone. + +All output goes under build/benchmarks/results/search and is included in the +workflow artifact. No public API, allocator layout, or production search path +is modified by this experiment. diff --git a/benchmarks/search_diag.c b/benchmarks/search_diag.c new file mode 100644 index 0000000..676b714 --- /dev/null +++ b/benchmarks/search_diag.c @@ -0,0 +1,299 @@ +// SPDX-License-Identifier: MIT +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(x) do { if (!(x)) { fprintf(stderr, "search diagnostic failed: %s:%d: %s\n", __FILE__, __LINE__, #x); exit(1); } } while (0) +#define NOINLINE __attribute__((noinline)) +typedef struct { + const char *name; + size_t n, m; + int kind; +} Case; +static const Case cases[] = { + {"absent_first_8_64", 64, 8, 0}, + {"absent_first_8_1024", 1024, 8, 0}, + {"absent_first_8_65536", 65536, 8, 0}, + {"repeated_128_65536", 65536, 128, 1}, + {"common_first_8_miss_65536", 65536, 8, 2}, + {"common_first_8_end_65536", 65536, 8, 3}, + {"periodic_8_miss_65536", 65536, 8, 4}, + {"front_hit_8_64", 64, 8, 5} +}; +typedef struct { + const Case *c; + unsigned char *t, *p; + size_t pi[256]; + sx_t *text, *needle; + bstring bt, bp; + size_t expected; +} Input; +static volatile uint64_t sink; +static inline void escape(const void *p) { + __asm__ __volatile__("" : : "g"(p) : "memory"); +} +static void make_pi(const unsigned char *p, size_t m, size_t *pi) { + pi[0] = 0; + for (size_t k = 0, i = 1; i < m; ++i) { + while (k && p[i] != p[k]) k = pi[k - 1]; + if (p[i] == p[k]) ++k; + pi[i] = k; + } +} +static void prepare(Input *f, const Case *c) { + memset(f, 0, sizeof(*f)); + f->c = c; + f->t = malloc(c->n + 1); + f->p = malloc(c->m + 1); + CHECK(f->t && f->p); + uint32_t state = 0x12ab34cd; + for (size_t i = 0; i < c->n; ++i) { + state = state * 1664525u + 1013904223u; + f->t[i] = (unsigned char)('a' + state % 25); + } + memset(f->p, 'Z', c->m); + if (c->kind == 1) { + memset(f->t, 'a', c->n); + memset(f->p, 'a', c->m); + f->p[c->m - 1] = 'b'; + } else if (c->kind == 2 || c->kind == 3) { + memcpy(f->p, "abcdefgh", 8); + if (c->kind == 3) memcpy(f->t + c->n - c->m, f->p, c->m); + } else if (c->kind == 4) { + for (size_t i = 0; i < c->n; ++i) f->t[i] = i & 1 ? 'b' : 'a'; + memset(f->p, 'a', c->m); + f->p[c->m - 1] = 'b'; + } else if (c->kind == 5) memcpy(f->t, f->p, c->m); + f->t[c->n] = f->p[c->m] = 0; + f->text = sx_new_from_cstr((const char *)f->t); + f->needle = sx_new_from_cstr((const char *)f->p); + f->bt = blk2bstr(f->t, (int)c->n); + f->bp = blk2bstr(f->p, (int)c->m); + CHECK(f->text && f->needle && f->bt && f->bp); + make_pi(f->p, c->m, f->pi); + const unsigned char *found = memmem(f->t, c->n, f->p, c->m); + f->expected = found ? (size_t)(found - f->t) : SIZE_MAX; + CHECK(f->expected == (c->kind == 3 ? c->n - c->m : c->kind == 5 ? 0 : SIZE_MAX)); +} +static void cleanup(Input *f) { + sx_free(f->text); sx_free(f->needle); + CHECK(bdestroy(f->bt) == BSTR_OK); CHECK(bdestroy(f->bp) == BSTR_OK); + free(f->t); free(f->p); +} + +#ifdef DIAG_WRAP_ALLOC +static int use_arena, arena_busy; +static alignas(max_align_t) unsigned char arena[4096]; +void *__real_malloc(size_t); +void __real_free(void *); +void *__wrap_malloc(size_t n) { + if (!use_arena) return __real_malloc(n); + CHECK(!arena_busy && n <= sizeof(arena)); + arena_busy = 1; + return arena; +} +void __wrap_free(void *p) { + if (p == arena) { CHECK(arena_busy); arena_busy = 0; return; } + __real_free(p); +} +static void arena_mode(int enabled) { CHECK(!arena_busy); use_arena = enabled; } +#else +static void arena_mode(int enabled) { CHECK(!enabled); } +#endif + +static NOINLINE size_t kernel_sx(Input *f) { return sx_find(f->text, f->needle); } +static NOINLINE size_t kernel_bstr(Input *f) { + int result = binstr(f->bt, 0, f->bp); + return result < 0 ? SIZE_MAX : (size_t)result; +} +static NOINLINE size_t kernel_memmem(Input *f) { + const unsigned char *p = memmem(f->t, f->c->n, f->p, f->c->m); + return p ? (size_t)(p - f->t) : SIZE_MAX; +} +/* Diagnostic-only specialization of the existing forward-FIRST algorithm. + Bounds are valid by construction; it has no reverse/ALL-mode handling. */ +static NOINLINE size_t kernel_kmp_first(Input *f) { + size_t n = f->c->n, m = f->c->m; + size_t *pi = malloc(m * sizeof(*pi)); + CHECK(pi); + make_pi(f->p, m, pi); + size_t q = 0; + for (size_t i = 0; i < n; ++i) { + while (q && f->t[i] != f->p[q]) q = pi[q - 1]; + if (f->t[i] == f->p[q]) ++q; + if (q == m) { free(pi); return i + 1 - m; } + } + free(pi); + return SIZE_MAX; +} +static NOINLINE size_t kernel_kmp_scan(Input *f) { + size_t q = 0, n = f->c->n, m = f->c->m; + for (size_t i = 0; i < n; ++i) { + while (q && f->t[i] != f->p[q]) q = f->pi[q - 1]; + if (f->t[i] == f->p[q]) ++q; + if (q == m) return i + 1 - m; + } + return SIZE_MAX; +} +static size_t prefix_scratch[256]; +static NOINLINE size_t kernel_prefix(Input *f) { + make_pi(f->p, f->c->m, prefix_scratch); + escape(prefix_scratch); + return prefix_scratch[f->c->m - 1]; +} +static NOINLINE size_t kernel_alloc(Input *f) { + size_t bytes = f->c->m * sizeof(size_t); + void *p = malloc(bytes); CHECK(p); + escape(p); + free(p); + return bytes; +} +/* Byte probes are controls, not complete substring-search replacements. */ +static NOINLINE size_t kernel_scalar_probe(Input *f) { + unsigned char c = f->p[0]; + for (size_t i = 0; i < f->c->n; ++i) if (f->t[i] == c) return i; + return SIZE_MAX; +} +static NOINLINE size_t kernel_first_probe(Input *f) { + const unsigned char *p = memchr(f->t, f->p[0], f->c->n); + return p ? (size_t)(p - f->t) : SIZE_MAX; +} +static NOINLINE size_t kernel_last_probe(Input *f) { + const unsigned char *p = memchr(f->t, f->p[f->c->m - 1], f->c->n); + return p ? (size_t)(p - f->t) : SIZE_MAX; +} +typedef size_t (*Kernel)(Input *); +typedef struct { const char *name; Kernel fn; int expected_kind, arena; } Variant; +static const Variant variants[] = { + {"sx_heap", kernel_sx, 0, 0}, +#ifdef DIAG_WRAP_ALLOC + {"sx_arena", kernel_sx, 0, 1}, +#endif + {"kmp_first_only_heap", kernel_kmp_first, 0, 0}, + {"kmp_scan_precomputed", kernel_kmp_scan, 0, 0}, + {"prefix_build_only", kernel_prefix, 1, 0}, + {"malloc_free_only", kernel_alloc, 2, 0}, + {"bstrlib", kernel_bstr, 0, 0}, + {"glibc_memmem", kernel_memmem, 0, 0}, + {"scalar_first_byte_probe", kernel_scalar_probe, 3, 0}, + {"glibc_first_byte_probe", kernel_first_probe, 3, 0}, + {"glibc_last_byte_probe", kernel_last_probe, 4, 0} +}; +static uint64_t now_ns(void) { + struct timespec t; CHECK(clock_gettime(CLOCK_MONOTONIC, &t) == 0); + return (uint64_t)t.tv_sec * 1000000000ULL + (uint64_t)t.tv_nsec; +} +static uint64_t batch(const Variant *v, Input *f, size_t iterations) { + uint64_t value = 0; + for (size_t i = 0; i < iterations; ++i) { + escape(f); + value += (uint64_t)v->fn(f); + } + return value; +} +static uint64_t timed(const Variant *v, Input *f, size_t iterations, size_t expected) { + uint64_t start = now_ns(), value = batch(v, f, iterations); + uint64_t elapsed = now_ns() - start; + CHECK(value == (uint64_t)expected * (uint64_t)iterations); + sink ^= value; + return elapsed; +} + +extern uint64_t diag_bstr_comparisons, diag_bstr_resets; +int diag_binstr_counted(const_bstring, int, const_bstring); +static void count_logical(Input *f) { + size_t pi[256] = {0}, q = 0; + uint64_t prep = 0, prep_fallback = 0, text_checks = 0, fallback = 0, visited = 0; + for (size_t i = 1, k = 0; i < f->c->m; ++i) { + while (k) { + ++prep; + if (f->p[i] == f->p[k]) break; + ++prep_fallback; k = pi[k - 1]; + } + ++prep; + if (f->p[i] == f->p[k]) ++k; + pi[i] = k; + } + size_t result = SIZE_MAX; + for (size_t i = 0; i < f->c->n; ++i) { + ++visited; + while (q) { + ++text_checks; + if (f->t[i] == f->p[q]) break; + ++fallback; q = pi[q - 1]; + } + ++text_checks; + if (f->t[i] == f->p[q]) ++q; + if (q == f->c->m) { result = i + 1 - q; break; } + } + CHECK(result == f->expected); + diag_bstr_comparisons = diag_bstr_resets = 0; + int br = diag_binstr_counted(f->bt, 0, f->bp); + CHECK((br < 0 ? SIZE_MAX : (size_t)br) == result); + printf("COUNTS_JSON={\"case\":\"%s\",\"text_bytes_visited\":%" PRIu64 + ",\"kmp_text_comparisons\":%" PRIu64 ",\"kmp_text_fallbacks\":%" PRIu64 + ",\"prefix_comparisons\":%" PRIu64 ",\"prefix_fallbacks\":%" PRIu64 + ",\"bstr_text_comparisons\":%" PRIu64 ",\"bstr_start_resets\":%" PRIu64 "}\n", + f->c->name, visited, text_checks, fallback, prep, prep_fallback, + diag_bstr_comparisons, diag_bstr_resets); +} +int main(int argc, char **argv) { + int check_only = argc > 1 && strcmp(argv[1], "--check") == 0; + int unwrapped_only = argc > 1 && strcmp(argv[1], "--unwrapped-only") == 0; + uint32_t rng = 0x731a9; + CHECK(check_only || argc == 3); + FILE *csv = check_only ? NULL : fopen(argv[2], "w"); + CHECK(check_only || csv); + if (csv) fputs("case,variant,iterations,sample,elapsed_ns,ns_per_op\n", csv); + for (size_t ci = 0; ci < sizeof(cases) / sizeof(cases[0]); ++ci) { + Input f; prepare(&f, &cases[ci]); count_logical(&f); + size_t expected[16], iterations[16], count = sizeof(variants) / sizeof(variants[0]); + CHECK(count <= 16); + if (unwrapped_only) count = 1; + for (size_t j = 0; j < count; ++j) { + const Variant *v = &variants[j]; + expected[j] = v->expected_kind == 1 ? f.pi[f.c->m - 1] : + v->expected_kind == 2 ? f.c->m * sizeof(size_t) : + v->expected_kind == 3 ? kernel_first_probe(&f) : + v->expected_kind == 4 ? kernel_last_probe(&f) : f.expected; + arena_mode(v->arena); + CHECK(v->fn(&f) == expected[j]); + iterations[j] = 1; + if (!check_only) for (;;) { + uint64_t a = timed(v, &f, iterations[j], expected[j]); + uint64_t b = timed(v, &f, iterations[j], expected[j]); + if ((a < b ? a : b) >= 20000000ULL || iterations[j] >= (1u << 24)) break; + iterations[j] *= 2; + } + arena_mode(0); + } + if (!check_only) for (int sample = 0; sample < 9; ++sample) { + size_t sequence[16]; for (size_t j = 0; j < count; ++j) sequence[j] = j; + for (size_t j = count - 1; j > 0; --j) { + rng = rng * 1664525u + 1013904223u; + size_t k = rng % (j + 1), temp = sequence[j]; sequence[j] = sequence[k]; sequence[k] = temp; + } + for (size_t k = 0; k < count; ++k) { + size_t j = sequence[k]; const Variant *v = &variants[j]; + arena_mode(v->arena); + uint64_t elapsed = timed(v, &f, iterations[j], expected[j]); + arena_mode(0); + fprintf(csv, "%s,%s,%zu,%d,%" PRIu64 ",%.6f\n", f.c->name, + unwrapped_only ? "sx_unwrapped" : v->name, iterations[j], + sample, elapsed, (double)elapsed / (double)iterations[j]); + } + } + cleanup(&f); + } + if (csv) CHECK(fclose(csv) == 0); + fprintf(stderr, "search diagnostics validated; sink=%" PRIu64 "\n", sink); + return 0; +} diff --git a/benchmarks/search_diag.py b/benchmarks/search_diag.py new file mode 100644 index 0000000..ac47baf --- /dev/null +++ b/benchmarks/search_diag.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +"""Search diagnosis: unchanged library, allocation ablation, logical traces and assembly.""" +import argparse +import csv +import ctypes +import errno +import json +import os +from pathlib import Path +import re +import statistics +import struct +import shutil +import subprocess +import sys + +from run import ROOT, COMMON, PINS, invoke, output, quantile + +def perf_probe(): + if os.uname().machine != "x86_64": + return {"allowed": None, "reason": "probe only implemented for x86_64"} + libc = ctypes.CDLL(None, use_errno=True) + libc.syscall.restype = ctypes.c_long + attr = ctypes.create_string_buffer(128) + struct.pack_into("IIQ", attr, 0, 0, 128, 0) + struct.pack_into("Q", attr, 40, (1 << 0) | (1 << 5) | (1 << 6)) + fd = libc.syscall(ctypes.c_long(298), ctypes.byref(attr), ctypes.c_int(0), + ctypes.c_int(-1), ctypes.c_int(-1), ctypes.c_ulong(0)) + if fd < 0: + code = ctypes.get_errno() + return {"allowed": False, "errno": code, "reason": os.strerror(code)} + os.close(fd) + return {"allowed": True, "note": "availability probe only; this suite does not collect hardware counters"} + +def disassemble_libc(out, log): + class DlInfo(ctypes.Structure): + _fields_ = [("filename", ctypes.c_char_p), ("base", ctypes.c_void_p), + ("symbol", ctypes.c_char_p), ("symbol_address", ctypes.c_void_p)] + libc = ctypes.CDLL("libc.so.6") + libc.dladdr.argtypes = [ctypes.c_void_p, ctypes.POINTER(DlInfo)] + libc.dladdr.restype = ctypes.c_int + resolved = {} + for name in ("memchr", "memmem"): + address = ctypes.cast(getattr(libc, name), ctypes.c_void_p).value + info = DlInfo() + assert libc.dladdr(ctypes.c_void_p(address), ctypes.byref(info)) + offset = address - info.base + path = info.filename.decode() + target = out / f"libc-{name}.asm.txt" + invoke(["objdump", "-d", "-Mintel", f"--start-address={offset}", + f"--stop-address={offset + 768}", path], log, stdout=target) + resolved[name] = {"library": path, "offset": offset, + "resolved_symbol": info.symbol.decode() if info.symbol else None} + print("LIBC_ASM_JSON=" + json.dumps({"name": name, "assembly": target.read_text()})) + return resolved + + +def make_counted_bstrlib(deps, out): + """Instrument the pinned source at build time, preserving its notice.""" + assert output(["git", "rev-parse", "HEAD"], deps / "bstrlib") == PINS["bstrlib"] + source = (deps / "bstrlib/bstrlib.c").read_text() + start = source.index("\nint binstr (") + end = source.index("\n}\n", start) + 3 + function = source[start:end].replace("int binstr (", "int diag_binstr_counted (", 1) + edits = [ + ("c1 != d1[i]", "(++diag_bstr_comparisons, c1 != d1[i])"), + ("c1 != d1[1+i]", "(++diag_bstr_comparisons, c1 != d1[1+i])"), + ("c1 == d1[i]", "(++diag_bstr_comparisons, c1 == d1[i])"), + ("i -= j;", "diag_bstr_resets++; i -= j;"), + ] + for old, new in edits: + assert function.count(old) == 1, old + function = function.replace(old, new, 1) + notice = source[:source.index("#include")] + target = out / "counted-bstrlib.c" + target.write_text(notice + "\n#include \n#include \n" + "uint64_t diag_bstr_comparisons, diag_bstr_resets;\n" + function + "\n") + shutil.copyfile(deps / "bstrlib/LICENSE", out / "bstrlib-license.txt") + return target + +def build(cc, folder, deps, log, counted, sanitize=False): + folder.mkdir(parents=True, exist_ok=True) + flags = COMMON + (["-O1", "-g", "-fsanitize=address,undefined", + "-fno-sanitize-recover=all", "-fno-omit-frame-pointer"] + if sanitize else ["-O3", "-DNDEBUG", "-g"]) + includes = ["-I" + str(ROOT / "include"), "-I" + str(deps / "bstrlib")] + sources = [ROOT / "src/sx_core.c", ROOT / "src/sx_raw.c", + deps / "bstrlib/bstrlib.c", counted] + objects = [] + for i, source in enumerate(sources): + obj = folder / f"{i}.o" + remarks = [] + if not sanitize and i == 0: + remarks = ([f"-fopt-info-vec-all={folder / 'vectorization.txt'}"] + if "gcc" in Path(cc).name else + ["-Rpass=loop-vectorize", "-Rpass-missed=loop-vectorize", + "-Rpass-analysis=loop-vectorize"]) + invoke([cc, *flags, *includes, *remarks, "-c", str(source), "-o", str(obj)], log) + objects.append(str(obj)) + for wrapped in ([False] if sanitize else [False, True]): + driver = folder / ("driver-wrapped.o" if wrapped else "driver.o") + macros = ["-DDIAG_WRAP_ALLOC"] if wrapped else [] + invoke([cc, *flags, *includes, "-Wall", "-Wextra", "-Werror", *macros, + "-c", str(ROOT / "benchmarks/search_diag.c"), "-o", str(driver)], log) + binary = folder / ("wrapped" if wrapped else "plain") + wrap = ["-Wl,--wrap=malloc,--wrap=free"] if wrapped else [] + invoke([cc, *flags, *objects, str(driver), *wrap, "-o", str(binary)], log) + if not sanitize: + for obj, label in [(Path(objects[0]), "sx-core"), (folder / "driver.o", "kernels")]: + target = folder / f"{label}.asm.txt" + invoke(["objdump", "-drwCS", "-Mintel", str(obj)], log, stdout=target) + text = target.read_text() + symbols = re.findall(r"^[0-9a-f]+ <([^>]+)>:", text, re.M) + print("ASM_SYMBOLS_JSON=" + json.dumps({"compiler": cc, "unit": label, "symbols": symbols})) + if label == "sx-core": + selected = [] + lines = text.splitlines() + needles = ["while (q && t[i] != needle[q])", "if (t[i] == needle[q])"] + for i, line in enumerate(lines): + if any(needle in line for needle in needles): + selected.append("\n".join(lines[max(0, i - 4):i + 40])) + if len(selected) == 2: + break + print("KMP_ASM_JSON=" + json.dumps({"compiler": cc, "snippets": selected})) + + else: + clean = output(["objdump", "-d", "-Mintel", str(obj)]) + selected = {} + for name in ("kernel_scalar_probe", "kernel_kmp_scan", "kernel_kmp_first"): + match = re.search(r"^[0-9a-f]+ <" + name + r">:\n(.*?)(?=\n\n|\Z)", clean, re.M | re.S) + if match: + selected[name] = match.group(0)[:6500] + print("KERNEL_ASM_JSON=" + json.dumps({"compiler": cc, "functions": selected})) + + loop_line = next(i for i, line in enumerate((ROOT / "src/sx_core.c").read_text().splitlines(), 1) + if "for (size_t i = l; i < er; i++)" in line) + remark_file = folder / "vectorization.txt" + remarks = remark_file.read_text() if remark_file.exists() else log.read_text() + selected_remarks = [] + for line in remarks.splitlines(): + position = re.search(r"sx_core.c:(\d+):", line) + if position and abs(int(position.group(1)) - loop_line) <= 8: + selected_remarks.append(line) + print("VECTORIZATION_JSON=" + json.dumps({"compiler": cc, "forward_loop_line": loop_line, + "remarks": selected_remarks[-24:]})) + return folder / "plain", folder / "wrapped" + +def report(csvs): + groups = {} + for path in csvs: + for row in csv.DictReader(path.open()): + groups.setdefault((row["case"], row["variant"]), []).append(float(row["ns_per_op"])) + results = [] + for (case, variant), values in groups.items(): + assert len(values) == 9, (case, variant, len(values)) + results.append({"case": case, "variant": variant, "samples": 9, + "median_ns": statistics.median(values), + "p10_ns": quantile(values, .1), "p90_ns": quantile(values, .9)}) + return results + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--cc", action="append", required=True) + ap.add_argument("--out", type=Path, default=ROOT / "build/benchmarks/results/search") + ap.add_argument("--deps", type=Path, default=ROOT / "build/benchmarks/deps") + args = ap.parse_args() + args.out = args.out.resolve() + args.deps = args.deps.resolve() + args.out.mkdir(parents=True, exist_ok=True) + cpu = min(os.sched_getaffinity(0)) + log = args.out / "diagnostics.log" + counted = make_counted_bstrlib(args.deps, args.out) + metadata = { + "commit": output(["git", "rev-parse", "HEAD"]), "pinned_cpu": cpu, + "flags": COMMON + ["-O3", "-DNDEBUG", "-g"], "samples": 9, + "hardware_perf": perf_probe(), + "counter_interpretation": "logical C-level comparisons, not retired machine instructions", + "control_interpretation": "byte probes and component timings do not implement a full substring search; timings are not additive", + "libc": disassemble_libc(args.out, log), + } + (args.out / "metadata.json").write_text(json.dumps(metadata, indent=2) + "\n") + print("SEARCH_META_JSON=" + json.dumps(metadata), flush=True) + all_results = [] + for cc in args.cc: + folder = args.out / Path(cc).name + folder.mkdir(parents=True, exist_ok=True) + check, _ = build(cc, folder / "check", args.deps, log, counted, True) + env = os.environ.copy() + env.update(ASAN_OPTIONS="detect_leaks=1:halt_on_error=1", + UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1") + invoke([str(check), "--check"], log, env=env, stdout=folder / "counts.log", cpu=cpu) + counts = [json.loads(line.split("=", 1)[1]) for line in + (folder / "counts.log").read_text().splitlines() if line.startswith("COUNTS_JSON=")] + assert len(counts) == 8 + (folder / "counts.json").write_text(json.dumps(counts, indent=2) + "\n") + plain, wrapped = build(cc, folder / "timing", args.deps, log, counted) + invoke([str(plain), "--unwrapped-only", str(folder / "unwrapped.csv")], + log, stdout=folder / "unwrapped.log", cpu=cpu) + invoke([str(wrapped), "--measure", str(folder / "components.csv")], + log, stdout=folder / "components.log", cpu=cpu) + result = {"compiler": cc, "results": report([folder / "unwrapped.csv", folder / "components.csv"]), + "counts": counts} + (folder / "summary.json").write_text(json.dumps(result, indent=2) + "\n") + print("SEARCH_DIAG_JSON=" + json.dumps(result, separators=(",", ":")), flush=True) + all_results.append(result) + lines = ["# Search diagnosis", "", + "The production implementation is unchanged. sx_heap and sx_arena use the same compiled library object.", + "Arena mode substitutes only the prefix-table allocation/free; prefix construction and scanning remain.", + "Standalone first-only and precomputed-table kernels are controlled algorithm references, not production patches.", + "Component timings cannot be added to obtain an exact original-runtime breakdown.", + "Counters count logical source comparisons; they are not retired-instruction or branch-miss measurements.", ""] + for item in all_results: + lines += [f"## {item['compiler']}", "", + "| Case | Variant | Median ns | p10–p90 ns |", + "| --- | --- | ---: | ---: |"] + for r in item["results"]: + lines.append(f"| {r['case']} | {r['variant']} | {r['median_ns']:.2f} | {r['p10_ns']:.2f}–{r['p90_ns']:.2f} |") + lines.append("") + (args.out / "summary.md").write_text("\n".join(lines) + "\n") + +if __name__ == "__main__": + main() From ecf31d3d65a45466222dfb0f358e176a22d1bc1c Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:32:26 +0800 Subject: [PATCH 3/6] bench: isolate KMP if-conversion and equality retest costs Add diagnostic-only equivalent scan loops and preserve all generated forward-loop snippets. Production code remains unchanged. Co-authored-by: Codex --- benchmarks/SEARCH_DIAGNOSIS.md | 6 ++++++ benchmarks/search_diag.c | 32 ++++++++++++++++++++++++++++++++ benchmarks/search_diag.py | 8 ++++---- 3 files changed, 42 insertions(+), 4 deletions(-) diff --git a/benchmarks/SEARCH_DIAGNOSIS.md b/benchmarks/SEARCH_DIAGNOSIS.md index d8a186e..fb81232 100644 --- a/benchmarks/SEARCH_DIAGNOSIS.md +++ b/benchmarks/SEARCH_DIAGNOSIS.md @@ -22,6 +22,12 @@ missing/full end match, a periodic-text counterexample, and a front hit. It omits reverse/ALL configuration and has its own malloc/prefix construction. - kmp_scan_precomputed: only the forward scan, with a prefix table prepared outside the timed region. +- kmp_scan_branch_control: diagnostic-only empty register asm forces the + matched branch to remain conditional; it emits no CPU instruction. This + tests if-conversion/data-dependency effects without recommending asm for + production use. +- kmp_scan_match_loop: equivalent KMP state transitions expressed with an + explicit match-first loop, avoiding the source-level equality retest. - prefix_build_only / malloc_free_only: component controls. These timings cannot be added to reconstruct an exact whole-call breakdown. - bstrlib / glibc_memmem: native comparison paths. diff --git a/benchmarks/search_diag.c b/benchmarks/search_diag.c index 676b714..00828ac 100644 --- a/benchmarks/search_diag.c +++ b/benchmarks/search_diag.c @@ -143,6 +143,36 @@ static NOINLINE size_t kernel_kmp_scan(Input *f) { } return SIZE_MAX; } + +/* Diagnostic control: an empty read/write register asm forces an explicit + matched branch. It emits no CPU instruction and leaves q unchanged at run + time, but prevents if-conversion. This is not a production implementation. */ +static NOINLINE size_t kernel_kmp_branch_control(Input *f) { + size_t q = 0, n = f->c->n, m = f->c->m; + for (size_t i = 0; i < n; ++i) { + while (q && f->t[i] != f->p[q]) q = f->pi[q - 1]; + if (f->t[i] == f->p[q]) { + __asm__ __volatile__("" : "+r"(q)); + ++q; + } + if (q == m) return i + 1 - m; + } + return SIZE_MAX; +} +/* Same KMP state transitions with one explicit match test per state, instead + of retesting equality after the while condition exits. */ +static NOINLINE size_t kernel_kmp_match_loop(Input *f) { + size_t q = 0, n = f->c->n, m = f->c->m; + for (size_t i = 0; i < n; ++i) { + for (;;) { + if (f->t[i] == f->p[q]) { ++q; break; } + if (!q) break; + q = f->pi[q - 1]; + } + if (q == m) return i + 1 - m; + } + return SIZE_MAX; +} static size_t prefix_scratch[256]; static NOINLINE size_t kernel_prefix(Input *f) { make_pi(f->p, f->c->m, prefix_scratch); @@ -179,6 +209,8 @@ static const Variant variants[] = { #endif {"kmp_first_only_heap", kernel_kmp_first, 0, 0}, {"kmp_scan_precomputed", kernel_kmp_scan, 0, 0}, + {"kmp_scan_branch_control", kernel_kmp_branch_control, 0, 0}, + {"kmp_scan_match_loop", kernel_kmp_match_loop, 0, 0}, {"prefix_build_only", kernel_prefix, 1, 0}, {"malloc_free_only", kernel_alloc, 2, 0}, {"bstrlib", kernel_bstr, 0, 0}, diff --git a/benchmarks/search_diag.py b/benchmarks/search_diag.py index ac47baf..e446a04 100644 --- a/benchmarks/search_diag.py +++ b/benchmarks/search_diag.py @@ -115,18 +115,18 @@ def build(cc, folder, deps, log, counted, sanitize=False): if label == "sx-core": selected = [] lines = text.splitlines() - needles = ["while (q && t[i] != needle[q])", "if (t[i] == needle[q])"] + needles = ["if (t[i] == needle[q])"] for i, line in enumerate(lines): if any(needle in line for needle in needles): - selected.append("\n".join(lines[max(0, i - 4):i + 40])) - if len(selected) == 2: + selected.append("\n".join(lines[max(0, i - 12):i + 44])) + if len(selected) == 8: break print("KMP_ASM_JSON=" + json.dumps({"compiler": cc, "snippets": selected})) else: clean = output(["objdump", "-d", "-Mintel", str(obj)]) selected = {} - for name in ("kernel_scalar_probe", "kernel_kmp_scan", "kernel_kmp_first"): + for name in ("kernel_scalar_probe", "kernel_kmp_scan", "kernel_kmp_first", "kernel_kmp_branch_control", "kernel_kmp_match_loop"): match = re.search(r"^[0-9a-f]+ <" + name + r">:\n(.*?)(?=\n\n|\Z)", clean, re.M | re.S) if match: selected[name] = match.group(0)[:6500] From 63c397e60531bf516eac7f39b79b146c6051a855 Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:02:54 -0800 Subject: [PATCH 4/6] ci: report all libraries from saved benchmark artifacts Read existing result files without rerunning benchmarks, and publish StringX, SDS and bstrlib statistics in logs and the job summary. Co-authored-by: Codex --- .github/workflows/benchmark-report.yml | 82 ++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 .github/workflows/benchmark-report.yml diff --git a/.github/workflows/benchmark-report.yml b/.github/workflows/benchmark-report.yml new file mode 100644 index 0000000..fcb07ce --- /dev/null +++ b/.github/workflows/benchmark-report.yml @@ -0,0 +1,82 @@ +name: Benchmark results report + +on: + pull_request: + paths: + - '.github/workflows/benchmark-report.yml' + workflow_dispatch: + inputs: + run_id: + description: Completed benchmark run to report + required: true + default: '41327686998' + type: string + artifact_name: + description: Optional artifact name (defaults to search-performance-RUN_ID) + required: false + type: string + +permissions: + actions: read + contents: read + +defaults: + run: + shell: bash + +jobs: + report: + name: StringX, SDS and bstrlib comparison + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Download existing benchmark results + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: ${{ inputs.artifact_name || format('search-performance-{0}', inputs.run_id || '41327686998') }} + path: build/benchmark-report + github-token: ${{ github.token }} + run-id: ${{ inputs.run_id || '41327686998' }} + - name: Report all libraries from the saved run + run: | + python3 - <<'PY' + import json + import os + from pathlib import Path + + roots = list(Path("build/benchmark-report").rglob("environment.json")) + assert len(roots) == 1, roots + root = roots[0].parent + environment = json.loads(roots[0].read_text()) + print("SAVED_BENCH_ENV_JSON=" + json.dumps(environment), flush=True) + report = ["# Saved benchmark: library comparison", "", + "Values are median microseconds per operation from the saved run.", + "Search rows use SDS with glibc memmem/memchr.", ""] + for compiler in ("gcc-14", "clang-19"): + path = root / compiler / "after" / "summary.json" + if not path.exists(): + path = root / compiler / "summary.json" + data = json.loads(path.read_text()) + rows = data["results"] if isinstance(data, dict) else data + print("LIBRARY_RESULTS_JSON=" + json.dumps( + {"compiler": compiler, "results": rows}), flush=True) + groups = {} + for row in rows: + groups.setdefault(row["case"], {})[row["library"]] = row + report += [f"## {compiler}", "", + "| Case | StringX us | SDS us | bstrlib us |", + "| --- | ---: | ---: | ---: |"] + for case, libraries in sorted(groups.items()): + values = [] + for aliases in (("StringX", "StringX+materialize"), + ("SDS+glibc", "SDS", "SDS+raw-view"), + ("bstrlib", "bstrlib+borrowed-view")): + row = next((libraries[name] for name in aliases if name in libraries), None) + values.append(f'{row["median_ns"] / 1000:.3f}' if row else "-") + report.append(f"| {case} | " + " | ".join(values) + " |") + report.append("") + text = "\n".join(report) + "\n" + print(text, flush=True) + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as dest: + dest.write(text) + PY From bcf50cc1a33711b0865b08de9664a2b6d995a7e1 Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 06:51:15 -0800 Subject: [PATCH 5/6] bench: independently audit and rerun cross-library search timings Validate exact bytes and lengths with a naive oracle; use opaque separately compiled adapters, call-count checks, and release disassembly. Reproduce old fixtures alongside independent period, phase, length, seed and hit controls, with hot and CLFLUSH-based conditions across three fresh processes. Co-authored-by: Codex --- .github/workflows/benchmarks.yml | 40 +++-- benchmarks/README.md | 11 ++ benchmarks/RECHECK.md | 58 +++++++ benchmarks/recheck.c | 284 +++++++++++++++++++++++++++++++ benchmarks/recheck.h | 25 +++ benchmarks/recheck.py | 240 ++++++++++++++++++++++++++ benchmarks/recheck_adapter.c | 44 +++++ 7 files changed, 688 insertions(+), 14 deletions(-) create mode 100644 benchmarks/RECHECK.md create mode 100644 benchmarks/recheck.c create mode 100644 benchmarks/recheck.h create mode 100644 benchmarks/recheck.py create mode 100644 benchmarks/recheck_adapter.c diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml index bc74151..28c7aa0 100644 --- a/.github/workflows/benchmarks.yml +++ b/.github/workflows/benchmarks.yml @@ -20,15 +20,15 @@ defaults: jobs: benchmark: - name: GCC and Clang string benchmarks + name: Audited StringX, SDS and bstrlib rerun runs-on: ubuntu-24.04 - timeout-minutes: 20 + timeout-minutes: 25 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.event.pull_request.head.sha || github.sha }} persist-credentials: false - - name: Install benchmark compilers and PCRE2 headers + - name: Install benchmark compilers and audit tools timeout-minutes: 5 run: | if test -f /etc/apt/apt-mirrors.txt; then @@ -38,7 +38,13 @@ jobs: sudo env DEBIAN_FRONTEND=noninteractive apt-get \ -o DPkg::Lock::Timeout=120 -o Acquire::Retries=3 \ -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ - install --no-install-recommends -y gcc-14 clang-19 libclang-rt-19-dev libpcre2-dev pkg-config + install --no-install-recommends -y gcc-14 clang-19 libclang-rt-19-dev libpcre2-dev pkg-config binutils + - name: Check out the exact patched StringX implementation + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: 40987da6ddaa2f31ca04d5d7f4545fa0704b7eb4 + path: build/recheck/stringx + persist-credentials: false - name: Check out pinned SDS uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -53,20 +59,26 @@ jobs: ref: f0ff1e808102a42cdc7204a4bb6fe231a24c4546 path: build/benchmarks/deps/bstrlib persist-credentials: false - - name: Validate, measure and report on one pinned CPU - run: python3 benchmarks/run.py --cc gcc-14 --cc clang-19 - - name: Analyze search cost and generated code - run: python3 benchmarks/search_diag.py --cc gcc-14 --cc clang-19 + - name: Verify calls, audit machine code and rerun both cache conditions + run: | + python3 benchmarks/recheck.py \ + --source build/recheck/stringx \ + --deps build/benchmarks/deps \ + --out build/recheck/results - name: Preserve raw samples and environment if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: string-benchmarks-${{ github.run_id }} + name: search-recheck-${{ github.run_id }} path: | - build/benchmarks/results/**/*.csv - build/benchmarks/results/**/*.json - build/benchmarks/results/**/*.md - build/benchmarks/results/**/*.txt - build/benchmarks/results/**/*.log + build/recheck/results/**/*.csv + build/recheck/results/**/*.json + build/recheck/results/**/*.md + build/recheck/results/**/*.txt + build/recheck/results/**/*.log + build/recheck/results/**/*.asm + build/recheck/results/**/*.jsonl + build/recheck/results/*.h + build/recheck/results/*/release/benchmark if-no-files-found: ignore retention-days: 14 diff --git a/benchmarks/README.md b/benchmarks/README.md index bd0b368..e947b0d 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -90,3 +90,14 @@ workflow, and manual dispatch; ordinary library PRs do not run this suite. Dependencies are fetched separately and retain their original licenses. Their source code is not vendored or relicensed by this harness. + + +## Audited rerun of the search gaps + +The primary Actions workflow now runs [the audited search recheck](RECHECK.md). +It retains the suspicious old fixtures as controls and adds independent +period/phase/length/seed/hit variations, exact call-count verification, +release disassembly, and hot versus cache-flushed conditions. It reports +StringX, SDS + glibc, bstrlib, and raw glibc from the same measurements. +The original run.py and search_diag.py remain available for reproducing their +documented baseline and diagnostic experiments. diff --git a/benchmarks/RECHECK.md b/benchmarks/RECHECK.md new file mode 100644 index 0000000..50f2c90 --- /dev/null +++ b/benchmarks/RECHECK.md @@ -0,0 +1,58 @@ +# Audited search rerun + +This rerun checks the unusually large gaps in the earlier search results. +The implementation is pinned to patched StringX commit +40987da6ddaa2f31ca04d5d7f4545fa0704b7eb4. SDS and bstrlib retain the +immutable revisions in recheck.py. Production code is unchanged. + +The original endpoint-absent fixtures and the period-127 fixture are retained +as reproduction controls. Text period and phase are then varied independently +of the 128-byte needle: periods 63/64/65/125/126/127/128/129 and phases 0/1/31. +Other cases cover independent random needles with two seeds, lengths around +32 and 256, binary NULs, real front/middle/tail hits, rare terminal bytes, +independent terminal-byte frequencies, and 4KiB/64KiB/1MiB text sizes. +Expected positions are recorded: periodic cases that actually match are +reported as hits, rather than being called misses. + +Each fixture is checked by a byte-window naive oracle outside timing. +The actual lengths and contents of all library buffers are checked, and +fixture hashes must agree across compilers and fresh processes. + +Four adapters are compiled as separate translation units with no LTO and +-fno-builtin-memmem / -fno-builtin-memchr. The timed loop calls a volatile +function pointer once per operation. A separate ASan/UBSan/leak-check build +counts nine adapter calls per fixture/library and checks the returned position. +Release disassembly is checked for the indirect loop call and the underlying +library calls. The release adapters contain no counting instrumentation. + +SDS search is explicitly SDS + glibc memmem/memchr. A fourth raw-glibc adapter +uses the exact same SDS data and pattern buffers, with an explicit length. +This separates header/adapter overhead from the search implementation. + +GCC 14 and Clang 19 use the same flags, job, and pinned CPU. Each uses three +fresh processes, seven samples per case/library/cache condition. Case order, +library order, and cache-condition order are shuffled. + +- Hot: three warmup calls, then a calibrated batch of at least about 10ms. +- Flushed: CLFLUSH all text and pattern cache lines, MFENCE/LFENCE, then time + one call. Each sample averages eight independently flushed calls. Flush + cost is outside the measured interval. Handle/length metadata is not + explicitly flushed, and this is a defined cache-flush experiment rather + than a guarantee about every hardware cache or DRAM access. +- Empty-adapter and timestamp-pair controls are reported. Their cost is not + subtracted from measurements. + +All results are validated, including timed checksums. The workflow logs the +complete per-library statistics; artifacts retain raw CSV, manifests, compiler +versions, source/binary hashes, call-site audits and full disassembly. +p10/p90 are observed sample spread, not confidence intervals. Shared-runner +scheduling/frequency and process address layout remain limitations. + +The rerun does not assume the earlier tiny times are wrong or representative. +In particular, a period of m-1 can favor glibc's pair-hash skip loop. Results +must be interpreted by corpus, hit position, and cache condition. + +Reproduction on x86-64 Linux with CLFLUSH: + + python3 benchmarks/recheck.py --source PATH_TO_PINNED_STRINGX \ + --deps PATH_CONTAINING_PINNED_SDS_AND_BSTRLIB --out build/recheck/results diff --git a/benchmarks/recheck.c b/benchmarks/recheck.c new file mode 100644 index 0000000..2387b3c --- /dev/null +++ b/benchmarks/recheck.c @@ -0,0 +1,284 @@ +// SPDX-License-Identifier: MIT +#define _GNU_SOURCE +#include "recheck.h" +#include +#include +#include +#include +#include +#include +#include + +#define CHECK(x) do { if (!(x)) { \ + fprintf(stderr, "CHECK failed %s:%d: %s\n", __FILE__, __LINE__, #x); exit(1); \ +} } while (0) +typedef struct { + const char *name; + int kind; + size_t n, m, period, phase; + uint32_t seed; + int hit; +} Case; +#include "recheck_cases.h" + +uint64_t recheck_call_counts[4]; +static volatile uint64_t sink; +static recheck_fn const workers[] = { + recheck_sx, recheck_sds, recheck_bstr, recheck_raw +}; +static const char *const names[] = { + "StringX", "SDS+glibc", "bstrlib", "raw_glibc_same_buffer" +}; + +static uint32_t next(uint32_t *s) { + *s ^= *s << 13; *s ^= *s >> 17; *s ^= *s << 5; + return *s; +} +static uint64_t now_ns(void) { + struct timespec t; + CHECK(clock_gettime(CLOCK_MONOTONIC_RAW, &t) == 0); + return (uint64_t)t.tv_sec * 1000000000ULL + (uint64_t)t.tv_nsec; +} +static uint64_t digest(const unsigned char *p, size_t n) { + uint64_t h = UINT64_C(14695981039346656037); + for (size_t i = 0; i < n; ++i) { h ^= p[i]; h *= UINT64_C(1099511628211); } + return h; +} +/* Independent byte-window oracle, outside every measured interval. */ +static uint64_t reference(const unsigned char *h, size_t n, + const unsigned char *p, size_t m) { + CHECK(m && m <= n); + for (size_t at = 0; at <= n - m; ++at) { + size_t j = 0; + while (j < m && h[at + j] == p[j]) ++j; + if (j == m) return (uint64_t)at + 1; + } + return 0; +} +static uint64_t prepare(recheck_input *f, const Case *c) { + memset(f, 0, sizeof(*f)); + unsigned char *h = malloc(c->n); + f->pattern = malloc(c->m + 1); + CHECK(h && f->pattern && c->m && c->m <= c->n); + f->n = c->n; f->m = c->m; + uint32_t state = 0x12ab34cd; + for (size_t i = 0; i < c->n; ++i) { + state = state * UINT32_C(1664525) + UINT32_C(1013904223); + h[i] = (unsigned char)('a' + state % 25); + } + memset(f->pattern, 'Z', c->m); + if (c->kind == 1) { + for (size_t i = 0; i < c->m; ++i) f->pattern[i] = (unsigned char)('a' + i % 25); + } else if (c->kind == 2 || c->kind == 3 || c->kind == 6 || c->kind == 7) { + memset(h, 'a', c->n); + memset(f->pattern, 'a', c->m); + f->pattern[c->m - 1] = 'b'; + if (c->kind == 3) { + CHECK(c->period); + for (size_t i = 0; i < c->n; ++i) + h[i] = (i + c->phase) % c->period == c->period - 1 ? 'b' : 'a'; + } + if (c->kind == 6) { + if (c->phase == 0) h[c->n - 1] = 'b'; /* real tail hit */ + if (c->phase == 1) { h[c->n - 1] = 'b'; h[c->n - 2] = 'c'; } + if (c->phase == 2) { h[c->m - 1] = 'b'; h[c->m - 2] = 'c'; } + } + if (c->kind == 7) { + CHECK(c->period && c->m >= 3); + state = c->seed; + f->pattern[c->m / 2] = 'c'; /* absent interior byte, independent of b frequency */ + for (size_t i = 0; i < c->n; ++i) h[i] = next(&state) % c->period == 0 ? 'b' : 'a'; + } + } else if (c->kind == 4 || c->kind == 5) { + unsigned alphabet = c->kind == 5 ? 256 : 25; + unsigned base = c->kind == 5 ? 0 : 'a'; + state = c->seed; + for (size_t i = 0; i < c->n; ++i) h[i] = (unsigned char)(base + next(&state) % alphabet); + state = c->seed ^ UINT32_C(0x9e3779b9); + for (size_t i = 0; i < c->m; ++i) f->pattern[i] = (unsigned char)(base + next(&state) % alphabet); + } + f->pattern[c->m] = 0; + size_t hit_at = 0; + if (c->hit) { + hit_at = c->hit == 1 ? 0 : c->hit == 2 ? (c->n - c->m) / 2 : c->n - c->m; + memcpy(h + hit_at, f->pattern, c->m); + } + uint64_t expected = reference(h, c->n, f->pattern, c->m); + if (c->hit) CHECK(expected == hit_at + 1); + f->sx = sx_new_with_cap(c->n + 1); + f->sx_pattern = sx_new_with_cap(c->m + 1); + CHECK(f->sx && f->sx_pattern); + CHECK(sx_truncate(f->sx, c->n) && sx_truncate(f->sx_pattern, c->m)); + memcpy(sx_buf_mut(f->sx), h, c->n); + memcpy(sx_buf_mut(f->sx_pattern), f->pattern, c->m); + f->sd = sdsnewlen(h, c->n); + f->bs = blk2bstr(h, (int)c->n); + f->bs_pattern = blk2bstr(f->pattern, (int)c->m); + CHECK(f->sd && f->bs && f->bs_pattern); + CHECK(sx_len(f->sx) == (int)c->n && sx_len(f->sx_pattern) == (int)c->m); + CHECK(sdslen(f->sd) == c->n && f->bs->slen == (int)c->n && f->bs_pattern->slen == (int)c->m); + f->text_bytes[0] = (const unsigned char *)sx_buf_mut(f->sx); + f->text_bytes[1] = (const unsigned char *)f->sd; + f->text_bytes[2] = f->bs->data; + f->text_bytes[3] = (const unsigned char *)f->sd; + f->pattern_bytes[0] = (const unsigned char *)sx_buf_mut(f->sx_pattern); + f->pattern_bytes[1] = f->pattern; + f->pattern_bytes[2] = f->bs_pattern->data; + f->pattern_bytes[3] = f->pattern; + for (int lib = 0; lib < 4; ++lib) { + CHECK(memcmp(f->text_bytes[lib], h, c->n) == 0); + CHECK(memcmp(f->pattern_bytes[lib], f->pattern, c->m) == 0); + } + free(h); + return expected; +} +static void cleanup(recheck_input *f) { + sx_free(f->sx); sx_free(f->sx_pattern); sdsfree(f->sd); + CHECK(bdestroy(f->bs) == BSTR_OK && bdestroy(f->bs_pattern) == BSTR_OK); + free(f->pattern); +} +static void flush_range(const unsigned char *p, size_t n) { + if (!n) return; + _mm_clflush(p); + uintptr_t at = ((uintptr_t)p + 64) & ~(uintptr_t)63; + for (; at < (uintptr_t)p + n; at += 64) _mm_clflush((const void *)at); +} +static void flush_input(recheck_input *f, int lib) { + flush_range(f->text_bytes[lib], f->n); + flush_range(f->pattern_bytes[lib], f->m); + _mm_mfence(); _mm_lfence(); +} +/* Separate adapters, no LTO, and a volatile function pointer force a + real call for each iteration. The release disassembly is retained. */ +__attribute__((noinline)) uint64_t +recheck_hot(recheck_fn fn, recheck_input *f, size_t iterations) { + recheck_fn volatile call = fn; + uint64_t sum = 0; + for (size_t i = 0; i < iterations; ++i) sum += call(f); + return sum; +} +__attribute__((noinline)) static uint64_t noop(recheck_input *f) { + __asm__ __volatile__("" : : "g"(f) : "memory"); + return 0; +} +static uint64_t hot_time(recheck_fn fn, recheck_input *f, size_t it, uint64_t expected) { + uint64_t begin = now_ns(); + uint64_t sum = recheck_hot(fn, f, it); + _mm_lfence(); + uint64_t elapsed = now_ns() - begin; + CHECK(sum == expected * it); + sink ^= sum; + return elapsed; +} +static size_t calibrate(recheck_fn fn, recheck_input *f, uint64_t expected) { + size_t it = 1; + for (;;) { + uint64_t t = hot_time(fn, f, it, expected); + if (t >= UINT64_C(10000000) || it >= (1u << 22)) return it; + it *= 2; + } +} +static uint64_t cold_once(recheck_fn fn, recheck_input *f, int lib, uint64_t expected) { + flush_input(f, lib); + recheck_fn volatile call = fn; + uint64_t begin = now_ns(); + uint64_t result = call(f); + _mm_lfence(); + uint64_t elapsed = now_ns() - begin; + CHECK(result == expected); + sink ^= result; + return elapsed; +} +static void shuffle(int *a, int n, uint32_t *rng) { + for (int i = n - 1; i > 0; --i) { + int j = (int)(next(rng) % (unsigned)(i + 1)), t = a[i]; + a[i] = a[j]; a[j] = t; + } +} +int main(int argc, char **argv) { + unsigned eax, ebx, ecx, edx; + CHECK(__get_cpuid(1, &eax, &ebx, &ecx, &edx)); + CHECK((edx & (1u << 19)) && (((ebx >> 8) & 255) * 8 == 64)); + CHECK(argc >= 2); + int verify = strcmp(argv[1], "--verify") == 0; + int describe = strcmp(argv[1], "--describe") == 0; + CHECK(verify || describe || strcmp(argv[1], "--measure") == 0); + uint32_t rng = UINT32_C(0x7132a8ef) + (argc > 2 ? (uint32_t)strtoul(argv[2], NULL, 10) * 17 : 0); + enum { N = sizeof(cases) / sizeof(cases[0]), SAMPLES = 7, COLD_OPS = 8 }; + int order[N]; + for (int i = 0; i < N; ++i) order[i] = i; + if (!verify && !describe) { + shuffle(order, N, &rng); + puts("case,library,mode,n,m,expected_pos,sample,iterations,elapsed_ns,ns_per_op"); + size_t it = calibrate(noop, NULL, 0); + double noop_ns = (double)hot_time(noop, NULL, it, 0) / (double)it; + uint64_t clock_sum = 0; + for (int i = 0; i < 1000; ++i) { + uint64_t begin = now_ns(); _mm_lfence(); clock_sum += now_ns() - begin; + } + fprintf(stderr, "RECHECK_CONTROL_JSON={\"noop_hot_ns\":%.3f,\"clock_pair_mean_ns\":%.3f}\n", + noop_ns, (double)clock_sum / 1000); + } + uint64_t signature = 0; + for (int ci = 0; ci < N; ++ci) { + const Case *c = &cases[order[ci]]; + recheck_input f; + uint64_t expected = prepare(&f, c); + signature ^= digest(f.text_bytes[0], f.n) ^ digest(f.pattern, f.m) + ^ digest((const unsigned char *)c->name, strlen(c->name)); + if (describe) { + size_t first = 0, last = 0; + for (size_t i = 0; i < f.n; ++i) { + first += f.text_bytes[0][i] == f.pattern[0]; + last += f.text_bytes[0][i] == f.pattern[f.m - 1]; + } + printf("{\"case\":\"%s\",\"kind\":%d,\"n\":%zu,\"m\":%zu,\"period\":%zu,\"phase\":%zu," + "\"seed\":%" PRIu32 ",\"expected_pos\":%lld,\"first_byte_count\":%zu,\"last_byte_count\":%zu," + "\"text_hash\":\"%016" PRIx64 "\",\"needle_hash\":\"%016" PRIx64 "\"}\n", + c->name,c->kind,c->n,c->m,c->period,c->phase,c->seed,(long long)expected-1, + first,last,digest(f.text_bytes[0],f.n),digest(f.pattern,f.m)); + } else if (verify) { + memset(recheck_call_counts, 0, sizeof(recheck_call_counts)); + for (int lib = 0; lib < 4; ++lib) { + CHECK(workers[lib](&f) == expected); + CHECK(recheck_hot(workers[lib], &f, 7) == expected * 7); + (void)cold_once(workers[lib], &f, lib, expected); +#ifdef RECHECK_VERIFY_CALLS + CHECK(recheck_call_counts[lib] == 9); +#endif + } + } else { + size_t iterations[4]; + for (int lib = 0; lib < 4; ++lib) { + CHECK(workers[lib](&f) == expected); + iterations[lib] = calibrate(workers[lib], &f, expected); + } + for (int sample = 0; sample < SAMPLES; ++sample) { + int libs[] = {0,1,2,3}; shuffle(libs, 4, &rng); + for (int li = 0; li < 4; ++li) { + int lib = libs[li], first_mode = (int)(next(&rng) & 1); + for (int which = 0; which < 2; ++which) { + int cold = first_mode ^ which; + uint64_t elapsed = 0; + size_t it = cold ? COLD_OPS : iterations[lib]; + if (cold) { + for (int op = 0; op < COLD_OPS; ++op) + elapsed += cold_once(workers[lib], &f, lib, expected); + } else { + for (int warm = 0; warm < 3; ++warm) CHECK(workers[lib](&f) == expected); + elapsed = hot_time(workers[lib], &f, it, expected); + } + printf("%s,%s,%s,%zu,%zu,%lld,%d,%zu,%" PRIu64 ",%.6f\n", + c->name,names[lib],cold?"flushed":"hot",f.n,f.m,(long long)expected-1, + sample,it,elapsed,(double)elapsed/(double)it); + } + } + } + } + cleanup(&f); + } + fprintf(stderr, "RECHECK_MANIFEST_SIGNATURE=%016" PRIx64 "\n", signature); + fprintf(stderr, "RECHECK_VALIDATED cases=%d adapters=4 mode=%s sink=%" PRIu64 "\n", + N, verify?"verify":describe?"describe":"measure", sink); + return 0; +} diff --git a/benchmarks/recheck.h b/benchmarks/recheck.h new file mode 100644 index 0000000..21bf499 --- /dev/null +++ b/benchmarks/recheck.h @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: MIT +#ifndef RECHECK_H +#define RECHECK_H +#include +#include +#include +#include +#include + +typedef struct { + sx_t *sx, *sx_pattern; + sds sd; + bstring bs, bs_pattern; + unsigned char *pattern; + size_t n, m; + const unsigned char *text_bytes[4], *pattern_bytes[4]; +} recheck_input; + +typedef uint64_t (*recheck_fn)(recheck_input *); +uint64_t recheck_sx(recheck_input *); +uint64_t recheck_sds(recheck_input *); +uint64_t recheck_bstr(recheck_input *); +uint64_t recheck_raw(recheck_input *); +extern uint64_t recheck_call_counts[4]; +#endif diff --git a/benchmarks/recheck.py b/benchmarks/recheck.py new file mode 100644 index 0000000..c119f13 --- /dev/null +++ b/benchmarks/recheck.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Independent-oracle, opaque-call, hot/flushed search benchmark recheck.""" +import argparse +import csv +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import statistics +import subprocess + +ROOT = Path(__file__).resolve().parents[1] +SOURCE = "40987da6ddaa2f31ca04d5d7f4545fa0704b7eb4" +PINS = {"sds": "5347739b1581fcba74fd5cab1fc21d2aef317d71", + "bstrlib": "f0ff1e808102a42cdc7204a4bb6fe231a24c4546"} +COMMON = ["-std=c23", "-march=x86-64", "-fno-lto", + "-fno-builtin-memmem", "-fno-builtin-memchr"] +PROCESSES, SAMPLES = 3, 7 + +def capture(args, cwd=ROOT): + return subprocess.check_output(list(map(str, args)), cwd=cwd, text=True).strip() + +def run(args, log, *, stdout=None, cpu=None, env=None): + args = list(map(str, args)) + print("+", " ".join(args), flush=True) + hook = (lambda: os.sched_setaffinity(0, {cpu})) if cpu is not None else None + with log.open("a") as err: + if stdout is None: + code = subprocess.run(args, cwd=ROOT, stdout=err, stderr=err, + preexec_fn=hook, env=env).returncode + else: + with stdout.open("w") as out: + code = subprocess.run(args, cwd=ROOT, stdout=out, stderr=err, + preexec_fn=hook, env=env).returncode + if code: + print(log.read_text()[-18000:], flush=True) + raise RuntimeError(f"exit {code}: {args}") + +def cases(): + result = [] + def add(name, kind, n=65536, m=128, period=0, phase=0, seed=0x12ab34cd, hit=0): + result.append(dict(name=name, kind=kind, n=n, m=m, period=period, + phase=phase, seed=seed, hit=hit)) + add("legacy_absent8", 0, m=8) + add("legacy_absent128", 2) + add("legacy_common8", 1, m=8) + add("legacy_common33", 1, m=33) + add("byte_absent", 0, m=1) + for period in (63, 64, 65, 125, 126, 127, 128, 129): + for phase in (0, 1, 31): + add(f"period{period}_phase{phase}", 3, period=period, phase=phase) + for m in (8, 16, 31, 32, 33, 64, 127, 128, 129, 256, 257): + for i, seed in enumerate((0x18273645, 0x4f295a17)): + add(f"random{m}_seed{i}", 4, m=m, seed=seed) + for m in (8, 33, 128): + for hit, label in ((1, "front"), (2, "middle"), (3, "tail")): + add(f"random{m}_hit_{label}", 4, m=m, hit=hit) + add(f"binary{m}_miss", 5, m=m) + add(f"binary{m}_hit_tail", 5, m=m, hit=3) + for phase, label in enumerate(("tail_hit", "tail_nearmiss", "early_nearmiss")): + add(f"rare_b_{label}", 6, phase=phase) + for denominator in (2, 16, 256, 4096): + add(f"terminal_frequency_1in{denominator}", 7, period=denominator) + for n in (4096, 1048576): + add(f"size{n}_random33", 4, n=n, m=33) + for period in (126, 127): + add(f"size{n}_period{period}", 3, n=n, period=period) + assert len({c["name"] for c in result}) == len(result) + return result + +def build(cc, folder, mode, source, deps, generated, log): + folder.mkdir(parents=True, exist_ok=True) + flags = COMMON + (["-O1", "-g", "-fsanitize=address,undefined", + "-fno-sanitize-recover=all", "-fno-omit-frame-pointer", + "-DRECHECK_VERIFY_CALLS"] if mode == "verify" + else ["-O3", "-DNDEBUG"]) + includes = ["-I" + str(source / "include"), "-I" + str(deps / "sds"), + "-I" + str(deps / "bstrlib"), "-I" + str(ROOT / "benchmarks"), + "-I" + str(generated)] + sources = [source / "src/sx_core.c", source / "src/sx_raw.c", + deps / "sds/sds.c", deps / "bstrlib/bstrlib.c"] + objects = [] + for i, src in enumerate(sources): + obj = folder / f"lib-{i}.o" + run([cc, *flags, *includes, "-c", src, "-o", obj], log) + objects.append(obj) + for i in range(4): + obj = folder / f"adapter-{i}.o" + run([cc, *flags, *includes, "-Wall", "-Wextra", "-Wpedantic", "-Werror", + f"-DLIB_INDEX={i}", "-c", ROOT / "benchmarks/recheck_adapter.c", + "-o", obj], log) + objects.append(obj) + main = folder / "main.o" + run([cc, *flags, *includes, "-Wall", "-Wextra", "-Wpedantic", "-Werror", + "-c", ROOT / "benchmarks/recheck.c", "-o", main], log) + binary = folder / "benchmark" + run([cc, *flags, *objects, main, "-o", binary], log) + return binary + +def quantile(values, p): + v = sorted(values) + point = (len(v) - 1) * p + lo = int(point) + hi = min(lo + 1, len(v) - 1) + return v[lo] + (v[hi] - v[lo]) * (point - lo) + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--deps", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + source, deps, out = args.source.resolve(), args.deps.resolve(), args.out.resolve() + out.mkdir(parents=True, exist_ok=True) + assert capture(["git", "rev-parse", "HEAD"], source) == SOURCE + for lib, sha in PINS.items(): + assert capture(["git", "rev-parse", "HEAD"], deps / lib) == sha + configs = cases() + (out / "cases.json").write_text(json.dumps(configs, indent=2) + "\n") + header = ["static const Case cases[] = {"] + for c in configs: + header.append(" {%s, %d, %d, %d, %d, %d, UINT32_C(%d), %d}," % + (json.dumps(c["name"]), c["kind"], c["n"], c["m"], + c["period"], c["phase"], c["seed"], c["hit"])) + header.append("};") + (out / "recheck_cases.h").write_text("\n".join(header) + "\n") + cpu = min(os.sched_getaffinity(0)) + tracked = [ROOT / "benchmarks" / p for p in + ("recheck.c", "recheck.h", "recheck_adapter.c", "recheck.py")] + metadata = dict( + benchmark_commit=capture(["git", "rev-parse", "HEAD"]), + stringx_commit=SOURCE, dependencies=PINS, cases=len(configs), + compilers=["gcc-14", "clang-19"], processes=PROCESSES, + samples_per_process=SAMPLES, samples_per_group=PROCESSES * SAMPLES, + hot_target_ns=10000000, flushed_calls_per_sample=8, cpu=cpu, + platform=platform.platform(), libc=capture(["ldd", "--version"]).splitlines()[0], + lscpu=json.loads(capture(["lscpu", "-J"])), + timing_flags=COMMON + ["-O3", "-DNDEBUG"], + cold_method="CLFLUSH each text/needle cache line; MFENCE+LFENCE before timing; flush cost excluded; metadata not explicitly flushed", + source_sha256={p.name: hashlib.sha256(p.read_bytes()).hexdigest() + for p in tracked + [source / "src/sx_core.c", source / "src/sx_raw.c"]}, + limitations="Shared runner; reused hot data and flush-based data-cache conditions; no subtraction of timer/adapter overhead.") + (out / "environment.json").write_text(json.dumps(metadata, indent=2) + "\n") + print("RECHECK_ENV_JSON=" + json.dumps(metadata), flush=True) + common_manifest = None + selected = ["legacy_absent8", "legacy_absent128", "legacy_common8", "legacy_common33", + "byte_absent", "period125_phase0", "period126_phase0", "period127_phase0", + "period127_phase1", "period128_phase0", "period129_phase0", + "rare_b_tail_nearmiss", "random32_seed0", "random33_seed0"] + report = ["# Audited search rerun", "", + "Four adapters, identical bytes, independent naive oracle, separate translation units, no LTO.", + "Hot samples use repeated calls. Flushed samples average eight individually timed calls after CLFLUSH.", + "Values are medians of 21 batch samples across three fresh processes; p10/p90 are observed spread.", + "SDS and raw glibc use the same SDS buffer; raw glibc receives an explicit length.", ""] + for cc in ("gcc-14", "clang-19"): + folder = out / cc + folder.mkdir(parents=True, exist_ok=True) + log = folder / "commands.log" + version = capture([cc, "--version"]) + (folder / "compiler.txt").write_text(version + "\n") + sanitizer = build(cc, folder / "verify", "verify", source, deps, out, log) + env = os.environ.copy() + env.update(ASAN_OPTIONS="detect_leaks=1:halt_on_error=1", + UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1") + run([sanitizer, "--verify"], log, cpu=cpu, env=env) + binary = build(cc, folder / "release", "release", source, deps, out, log) + assembly = capture(["objdump", "-drwC", binary]) + (folder / "release.asm").write_text(assembly + "\n") + hot = capture(["objdump", "-d", "--disassemble=recheck_hot", binary]) + assert re.search(r"\bcallq?\s+\*", hot), hot + snippets = {"recheck_hot": hot} + for symbol, expected in (("recheck_sx", "sx_find"), + ("recheck_sds", "memmem"), + ("recheck_bstr", "binstr"), + ("recheck_raw", "memmem")): + text = capture(["objdump", "-d", f"--disassemble={symbol}", binary]) + assert expected in text, text + assert "recheck_call_counts" not in text, text + snippets[symbol] = text + (folder / "call-audit.asm").write_text("\n".join(snippets.values())) + audit = dict(compiler=cc, indirect_call_in_hot_loop=True, + separate_adapter_calls_verified=True, + release_has_no_call_counter=True, + binary_sha256=hashlib.sha256(binary.read_bytes()).hexdigest()) + print("RECHECK_AUDIT_JSON=" + json.dumps(audit), flush=True) + print("RECHECK_HOT_ASM=" + json.dumps(hot), flush=True) + run([binary, "--describe"], log, cpu=cpu, stdout=folder / "fixtures.jsonl") + manifest = [json.loads(s) for s in (folder / "fixtures.jsonl").read_text().splitlines()] + assert len(manifest) == len(configs) + if common_manifest is not None: + assert manifest == common_manifest + common_manifest = manifest + rows = [] + for process in range(PROCESSES): + raw = folder / f"samples-{process}.csv" + run([binary, "--measure", str(process)], log, cpu=cpu, stdout=raw) + with raw.open() as f: + rows.extend(csv.DictReader(f)) + groups = {} + for row in rows: + groups.setdefault((row["case"], row["library"], row["mode"]), []).append(row) + assert len(groups) == len(configs) * 4 * 2 + stats = [] + for (case, library, mode), group in sorted(groups.items()): + assert len(group) == PROCESSES * SAMPLES + values = [float(r["ns_per_op"]) for r in group] + stats.append(dict(case=case, library=library, mode=mode, + n=int(group[0]["n"]), m=int(group[0]["m"]), + expected_pos=int(group[0]["expected_pos"]), + samples=len(values), median_ns=statistics.median(values), + p10_ns=quantile(values, .1), p90_ns=quantile(values, .9))) + text = log.read_text() + signatures = re.findall(r"RECHECK_MANIFEST_SIGNATURE=([0-9a-f]+)", text) + assert len(signatures) == PROCESSES + 2 and len(set(signatures)) == 1, signatures + controls = [json.loads(s) for s in + re.findall(r"RECHECK_CONTROL_JSON=(\{[^\n]*\})", text)] + assert len(controls) == PROCESSES + result = dict(compiler=cc, version=version.splitlines()[0], + fixture_signature=signatures[0], controls=controls, results=stats) + (folder / "summary.json").write_text(json.dumps(result, indent=2) + "\n") + print("RECHECK_RESULT_JSON=" + json.dumps(result, separators=(",", ":")), flush=True) + for mode in ("hot", "flushed"): + report += [f"## {cc}: {mode}", "", + "| Case | Expected offset | StringX us | SDS + glibc us | bstrlib us | raw glibc us |", + "| --- | ---: | ---: | ---: | ---: | ---: |"] + for case in selected: + data = {r["library"]: r for r in stats if r["case"] == case and r["mode"] == mode} + vals = [data[lib] for lib in ("StringX", "SDS+glibc", "bstrlib", "raw_glibc_same_buffer")] + report.append(f'| {case} | {vals[0]["expected_pos"]} | ' + + " | ".join(f'{r["median_ns"]/1000:.3f}' for r in vals) + " |") + report.append("") + (out / "summary.md").write_text("\n".join(report) + "\n") + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as f: + f.write("\n".join(report) + "\n") + +if __name__ == "__main__": + main() diff --git a/benchmarks/recheck_adapter.c b/benchmarks/recheck_adapter.c new file mode 100644 index 0000000..a0ea07b --- /dev/null +++ b/benchmarks/recheck_adapter.c @@ -0,0 +1,44 @@ +// SPDX-License-Identifier: MIT +#define _GNU_SOURCE +#include "recheck.h" +#include + +#ifdef RECHECK_VERIFY_CALLS +#define RECORD() (++recheck_call_counts[LIB_INDEX]) +#else +#define RECORD() ((void)0) +#endif + +#if LIB_INDEX == 0 +__attribute__((noinline)) uint64_t recheck_sx(recheck_input *f) { + RECORD(); + size_t p = f->m == 1 ? sx_find_char(f->sx, (char)f->pattern[0]) + : sx_find(f->sx, f->sx_pattern); + return p == (size_t)-1 ? 0 : (uint64_t)p + 1; +} +#elif LIB_INDEX == 1 +__attribute__((noinline)) uint64_t recheck_sds(recheck_input *f) { + RECORD(); + const char *p = f->m == 1 ? memchr(f->sd, f->pattern[0], sdslen(f->sd)) + : memmem(f->sd, sdslen(f->sd), f->pattern, f->m); + return p ? (uint64_t)(p - f->sd) + 1 : 0; +} +#elif LIB_INDEX == 2 +__attribute__((noinline)) uint64_t recheck_bstr(recheck_input *f) { + RECORD(); + int p = f->m == 1 ? bstrchr(f->bs, f->pattern[0]) + : binstr(f->bs, 0, f->bs_pattern); + return p < 0 ? 0 : (uint64_t)p + 1; +} +#elif LIB_INDEX == 3 +__attribute__((noinline)) uint64_t recheck_raw(recheck_input *f) { + RECORD(); + /* Same SDS buffer and needle as the SDS adapter; explicit length + isolates header/adapter overhead from the glibc implementation. */ + const char *p = f->m == 1 ? memchr(f->sd, f->pattern[0], f->n) + : memmem(f->sd, f->n, f->pattern, f->m); + return p ? (uint64_t)(p - f->sd) + 1 : 0; +} +#else +#error LIB_INDEX must be 0..3 +#endif From 7f8a624af4809c9dc606c41533991acd1b51917d Mon Sep 17 00:00:00 2001 From: minelogy <72928567+minelogy-dev@users.noreply.github.com> Date: Mon, 2 Nov 2026 06:56:43 -0800 Subject: [PATCH 6/6] bench: treat pinned library headers as external during strict adapter checks Keep warnings fatal for benchmark sources while avoiding formatting-only warnings in immutable dependency headers. Verify Clang first. Co-authored-by: Codex --- benchmarks/recheck.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/benchmarks/recheck.py b/benchmarks/recheck.py index c119f13..6aa5133 100644 --- a/benchmarks/recheck.py +++ b/benchmarks/recheck.py @@ -76,8 +76,8 @@ def build(cc, folder, mode, source, deps, generated, log): "-fno-sanitize-recover=all", "-fno-omit-frame-pointer", "-DRECHECK_VERIFY_CALLS"] if mode == "verify" else ["-O3", "-DNDEBUG"]) - includes = ["-I" + str(source / "include"), "-I" + str(deps / "sds"), - "-I" + str(deps / "bstrlib"), "-I" + str(ROOT / "benchmarks"), + includes = ["-isystem", str(source / "include"), "-isystem", str(deps / "sds"), + "-isystem", str(deps / "bstrlib"), "-I" + str(ROOT / "benchmarks"), "-I" + str(generated)] sources = [source / "src/sx_core.c", source / "src/sx_raw.c", deps / "sds/sds.c", deps / "bstrlib/bstrlib.c"] @@ -154,7 +154,7 @@ def main(): "Hot samples use repeated calls. Flushed samples average eight individually timed calls after CLFLUSH.", "Values are medians of 21 batch samples across three fresh processes; p10/p90 are observed spread.", "SDS and raw glibc use the same SDS buffer; raw glibc receives an explicit length.", ""] - for cc in ("gcc-14", "clang-19"): + for cc in ("clang-19", "gcc-14"): folder = out / cc folder.mkdir(parents=True, exist_ok=True) log = folder / "commands.log"