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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions .github/workflows/benchmark-report.yml
Original file line number Diff line number Diff line change
@@ -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
84 changes: 84 additions & 0 deletions .github/workflows/benchmarks.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
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: Audited StringX, SDS and bstrlib rerun
runs-on: ubuntu-24.04
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 audit tools
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 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:
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: 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: search-recheck-${{ github.run_id }}
path: |
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
103 changes: 103 additions & 0 deletions benchmarks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# 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.


## 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.
58 changes: 58 additions & 0 deletions benchmarks/RECHECK.md
Original file line number Diff line number Diff line change
@@ -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
54 changes: 54 additions & 0 deletions benchmarks/SEARCH_DIAGNOSIS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# 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.
- 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.
- 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.
Loading
Loading