diff --git a/.github/scripts/compare-search.py b/.github/scripts/compare-search.py new file mode 100644 index 0000000..2249818 --- /dev/null +++ b/.github/scripts/compare-search.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Same-host before/after check; timing is evidence, not a noisy merge gate.""" +import csv +import importlib.util +import json +import os +from pathlib import Path +import shutil +import statistics + +ROOT = Path(__file__).resolve().parents[2] +WORK = ROOT / "build/search-performance" +BASELINE = "452314a7ca51f90a7a8fa66930947164af8fc4f6" +HARNESS = "ecf31d3d65a45466222dfb0f358e176a22d1bc1c" + +def main(): + harness = WORK / "harness" + spec = importlib.util.spec_from_file_location("baseline_bench", harness / "benchmarks/run.py") + bench = importlib.util.module_from_spec(spec) + spec.loader.exec_module(bench) + assert bench.output(["git", "rev-parse", "HEAD"], WORK / "before") == BASELINE + assert bench.output(["git", "rev-parse", "HEAD"], harness) == HARNESS + deps = WORK / "deps" + for lib, sha in bench.PINS.items(): + assert bench.output(["git", "rev-parse", "HEAD"], deps / lib) == sha + after = WORK / "after" + for folder in ("src", "include"): + shutil.copytree(ROOT / folder, after / folder, dirs_exist_ok=True) + + # Extend the existing 28 cases with common endpoint bytes, misses + # across the private cutoff, and repetitive text with both bytes present. + source = (harness / "benchmarks/strings.c").read_text() + source = source.replace("RESERVED = 16", "RESERVED = 16, COMMON = 32, PERIODIC = 64, END_PRESENT = 128") + anchor = ' {"copy_cstr_16"' + extra = [ + ("common8_miss_65536", 8, "COMMON"), + ("common8_end_65536", 8, "COMMON | HIT_END"), + ("periodic8_miss_65536", 8, "PERIODIC"), + ("common31_miss_65536", 31, "COMMON"), + ("common32_miss_65536", 32, "COMMON"), + ("common33_miss_65536", 33, "COMMON"), + ("repeated128_end_present_miss_65536", 128, "REPEATED | END_PRESENT"), + ("common257_miss_65536", 257, "COMMON"), + ] + assert anchor in source + source = source.replace(anchor, "".join( + f' {{"{name}", FIND, 65536, {m}, {flags}}},\n' + for name, m, flags in extra) + anchor, 1) + anchor = " f->sep = " + assert anchor in source + setup = """ + if (c->op == FIND) { + if (c->flags & COMMON) + for (size_t i = 0; i < m; ++i) f->needle[i] = (char)('a' + i % 25); + if (c->flags & PERIODIC) { + for (size_t i = 0; i < c->n; ++i) f->data[i] = i % 2 ? 'b' : 'a'; + memset(f->needle, 'a', m); + f->needle[m - 1] = 'b'; + } + if (c->flags & END_PRESENT) + for (size_t i = m - 2; i < c->n; i += m - 1) f->data[i] = 'b'; + 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); + } +""" + source = source.replace(anchor, setup + anchor, 1) + anchor = " Fixture f; prepare(&f, &cases[ci]);" + assert anchor in source + source = source.replace(anchor, + " if (cases[ci].op != FIND && cases[ci].op != FIND_CHAR) continue;" + + chr(10) + anchor, 1) + search_cases = sum(1 for line in source.splitlines() + if line.lstrip().startswith('{"') + and (", FIND," in line or ", FIND_CHAR," in line)) + timing_names = [ + "find8_miss_65536", "find128_repeated_miss_65536", + "find_char_end_65536", + "common8_miss_65536", "common33_miss_65536", + "periodic8_miss_65536", "repeated128_end_present_miss_65536", + ] + selected = " || ".join(f'strcmp(cases[ci].name, "{name}") == 0' + for name in timing_names) + source = source.replace(anchor, + f" if (!check_only && !({selected})) continue;" + + chr(10) + anchor, 1) + repeats = 3 + for variant in ("before", "after"): + folder = WORK / variant / "benchmarks" + folder.mkdir(parents=True, exist_ok=True) + (folder / "strings.c").write_text(source) + + cpu = min(os.sched_getaffinity(0)) + out = WORK / "results" + out.mkdir(parents=True, exist_ok=True) + metadata = { + "before": BASELINE, "after": bench.output(["git", "rev-parse", "HEAD"], ROOT), + "harness": HARNESS, "dependencies": bench.PINS, + "pinned_cpu": cpu, "lscpu": json.loads(bench.output(["lscpu", "-J"])), + "libc": bench.output(["ldd", "--version"]).splitlines()[0], + "timing_flags": bench.COMMON + ["-O3", "-DNDEBUG"], + "portable_flags": ["-DSX_FORCE_NO_MEMMEM"], + "correctness_cases": search_cases, "timing_cases": len(timing_names), + "processes": repeats, "samples_per_process": 11, "samples": 11 * repeats, "target_sample_ns": 20000000, + "note": "Variants run sequentially on the same pinned CPU. Hosted-runner scheduling and frequency remain uncontrolled.", + } + (out / "environment.json").write_text(json.dumps(metadata, indent=2) + "\n") + (out / "strings.c").write_text(source) + print("SEARCH_COMPARE_ENV=" + json.dumps(metadata), flush=True) + report = ["# Search before/after", "", + "Same job, pinned CPU, -O3, no LTO; 3 fresh processes, 11 hot-input samples each.", + "Sequential runs are subject to host scheduling/frequency changes; small differences are inconclusive.", ""] + env = os.environ.copy() + env.update(ASAN_OPTIONS="detect_leaks=1:halt_on_error=1", + UBSAN_OPTIONS="halt_on_error=1:print_stacktrace=1") + common_flags = list(bench.COMMON) + for ci, cc in enumerate(("gcc-14", "clang-19")): + results = {} + for variant in (("before", "after", "portable") if ci == 0 else ("portable", "after", "before")): + bench.ROOT = WORK / ("before" if variant == "before" else "after") + bench.COMMON = common_flags + (["-DSX_FORCE_NO_MEMMEM"] if variant == "portable" else []) + folder = out / cc / variant + folder.mkdir(parents=True, exist_ok=True) + log = folder / "commands.log" + check = bench.compile_binary(cc, folder / "check", "check", deps, log) + bench.invoke([str(check), "--check"], log, env=env, cpu=cpu) + binary = bench.compile_binary(cc, folder / "timing", "timing", deps, log) + rows = [] + for process in range(repeats): + samples = folder / f"samples-{process}.csv" + bench.invoke([str(binary)], log, stdout=samples, cpu=cpu) + rows.extend(csv.DictReader(samples.open())) + alloc = bench.compile_binary(cc, folder / "alloc", "alloc", deps, log) + bench.invoke([str(alloc)], log, stdout=folder / "allocations.csv", cpu=cpu) + memory = {(r["case"], r["library"]): r + for r in csv.DictReader((folder / "allocations.csv").open())} + groups = {} + for r in rows: + groups.setdefault((r["case"], r["library"]), []).append(float(r["ns_per_op"])) + assert len(groups) == len(timing_names) * 3, len(groups) + stats = {} + for (case, library), values in groups.items(): + assert len(values) == 11 * repeats + stats[case, library] = { + "case": case, "library": library, + "median_ns": statistics.median(values), + "p10_ns": bench.quantile(values, .1), "p90_ns": bench.quantile(values, .9), + "malloc_calls": int(memory[case, library]["malloc_calls"]), + } + (folder / "summary.json").write_text(json.dumps(list(stats.values()), indent=2) + "\n") + results[variant] = stats + bench.COMMON = common_flags + report += [f"## {bench.output([cc, '--version']).splitlines()[0]}", "", + "| Case | Before ns | Native ns | Portable ns | Native speedup | Portable speedup |", + "| --- | ---: | ---: | ---: | ---: | ---: |"] + compared = [] + for key, before in sorted(results["before"].items()): + case, library = key + if not library.startswith("StringX"): + continue + after_row = results["after"][key] + ratio = before["median_ns"] / after_row["median_ns"] + portable = results["portable"][key] + portable_ratio = before["median_ns"] / portable["median_ns"] + row = {"case": case, "before": before, "after": after_row, "speedup": ratio, + "portable": portable, "portable_speedup": portable_ratio} + compared.append(row) + report.append(f"| {case} | {before['median_ns']:.2f} | {after_row['median_ns']:.2f} | {portable['median_ns']:.2f} | {ratio:.2f}x | {portable_ratio:.2f}x |") + print("SEARCH_COMPARE_JSON=" + json.dumps({"compiler": cc, "results": compared}), flush=True) + report.append("") + text = "\n".join(report) + "\n" + (out / "summary.md").write_text(text) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as dest: + dest.write(text) + +if __name__ == "__main__": + main() diff --git a/.github/workflows/search-performance.yml b/.github/workflows/search-performance.yml new file mode 100644 index 0000000..998feab --- /dev/null +++ b/.github/workflows/search-performance.yml @@ -0,0 +1,78 @@ +name: Search performance + +on: + pull_request: + paths: + - 'src/sx_core.c' + - '.github/scripts/compare-search.py' + - '.github/workflows/search-performance.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: search-performance-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +defaults: + run: + shell: bash + +jobs: + benchmark: + name: Search before and after (GCC and Clang) + 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 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 the library baseline + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: 452314a7ca51f90a7a8fa66930947164af8fc4f6 + path: build/search-performance/before + persist-credentials: false + - name: Check out the immutable benchmark harness + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ecf31d3d65a45466222dfb0f358e176a22d1bc1c + path: build/search-performance/harness + persist-credentials: false + - name: Check out pinned SDS + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: antirez/sds + ref: 5347739b1581fcba74fd5cab1fc21d2aef317d71 + path: build/search-performance/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/search-performance/deps/bstrlib + persist-credentials: false + - name: Validate, measure and report on one pinned CPU + run: python3 .github/scripts/compare-search.py + - name: Preserve raw samples and environment + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: search-performance-${{ github.run_id }} + path: build/search-performance/results + if-no-files-found: ignore + retention-days: 14 diff --git a/src/sx_core.c b/src/sx_core.c index a09638d..43adca9 100644 --- a/src/sx_core.c +++ b/src/sx_core.c @@ -296,7 +296,7 @@ extern void *memrchr(const void *s, int c, size_t n); * * opt bit1 (2): "first" -- single result: leftmost (or, with right, * rightmost) match position, or (find_ret_t)-1 if none. - * No allocation. + * KMP fallback may allocate a temporary prefix table. * opt bit1 clear: ALL mode -- malloc'd size_t array, caller frees: * arr[0] = count, arr[1..count] = positions in ascending order * (overlapping matches included). count == 0 -> a valid {0} array. @@ -477,6 +477,74 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, r[0] = cnt; return (find_ret_t)r; } +/* Keep optional native checks out of the portable KMP callers' + optimizer context. The forced build uses the original path directly. */ +#if !defined(SX_FORCE_NO_MEMMEM) && defined(__GLIBC__) +extern void *memmem(const void *haystack, size_t haystacklen, + const void *needle, size_t needlelen); + +/* GCC and Clang support this private hint on glibc targets. It keeps + native-path conditions from changing the fallback's specialization. */ +static __attribute__((noinline)) int +try_native_find_first(const sx_t *h, const char *needle, int len, + size_t boundary, find_ret_t *result) { + const size_t H = h->ref->len; + const size_t m = (size_t)len; + const char *t = h->ref->ptr; + size_t l = boundary; + *result = (find_ret_t)-1; + if (len <= 0 || l >= H || m > H - l) + return 1; + if (m == 1) { + const char *p = memchr(t + l, needle[0], H - l); + if (p) + *result = (find_ret_t)(p - t); + return 1; + } + + /* Front hits need no preprocessing or prefix-table allocation. */ + if (memcmp(t + l, needle, m) == 0) { + *result = (find_ret_t)l; + return 1; + } + if (H - l == m) + return 1; + + /* Only [l+1, H-m] can start another legal window. */ + const char *p = memchr(t + l + 1, needle[0], H - m - l); + if (!p) + return 1; + l = (size_t)(p - t); + + /* A valid window must also end with the needle's final byte. + No earlier start can match before this first possible endpoint. */ + p = memchr(t + l + m - 1, needle[m - 1], H - l - m + 1); + if (!p) + return 1; + l = (size_t)(p - t) - (m - 1); + + /* Limit native search to short patterns. Long repeated prefixes can + be a bad case for libc's short-pattern implementation. */ + if (m <= 32) { + p = memmem(t + l, H - l, needle, m); + if (p) + *result = (find_ret_t)(p - t); + return 1; + } + return 0; /* original KMP handles the unresolved long needle */ +} +#endif + +static inline find_ret_t find_first(const sx_t *h, const char *needle, int len, + size_t boundary) { +#if !defined(SX_FORCE_NO_MEMMEM) && defined(__GLIBC__) + find_ret_t result; + if (try_native_find_first(h, needle, len, boundary, &result)) + return result; +#endif + return find(h, needle, len, boundary, 2); +} + /* Wrappers translate the public API onto find(). Per the buffer model, a needle's searchable length is its CONTENT length (the trailing '\0' at ptr[len] is not content): sx_find* pass the needle's own length, @@ -485,7 +553,7 @@ static inline find_ret_t find(const sx_t *h, const char *needle, int len, SYMBOL_PUBLIC size_t sx_find(const sx_t *h, const sx_t *needle) { if (!h || !needle) return (size_t)-1; - return (size_t)find(h, needle->ref->ptr, needle->ref->len, 0, 2); + return (size_t)find_first(h, needle->ref->ptr, needle->ref->len, 0); } SYMBOL_PUBLIC size_t sx_find_view(const sx_t *h, sx_view_t needle) { return sx_find_view_b(h, needle, 0); @@ -495,13 +563,13 @@ SYMBOL_PUBLIC size_t sx_find_view_b(const sx_t *h, sx_view_t needle, size_t boundary) { if (!h) return (size_t)-1; - return (size_t)find(h, needle.ref->ptr + needle.offset, needle.len, boundary, - 2); + return (size_t)find_first(h, needle.ref->ptr + needle.offset, needle.len, + boundary); } SYMBOL_PUBLIC size_t sx_find_cstr(const sx_t *h, const char *needle) { if (!h || !needle) return (size_t)-1; - return (size_t)find(h, needle, (int)strlen(needle), 0, 2); + return (size_t)find_first(h, needle, (int)strlen(needle), 0); } SYMBOL_PUBLIC size_t sx_find_char(const sx_t *h, char c) { if (!h) diff --git a/tests/find_differential.c b/tests/find_differential.c new file mode 100644 index 0000000..56ea735 --- /dev/null +++ b/tests/find_differential.c @@ -0,0 +1,13 @@ +// Include include +// Include src +// Include /usr/lib/forge/include +// Source src/sx_raw.c +// Source src/sx_core.c +// Source src/sx_adv.c +// Option -std=c23 +// Option -O1 +// Option -g +// Option -fsanitize=address,undefined +// Option -fno-omit-frame-pointer +// Library /usr/local/lib +#include "find_differential.h" diff --git a/tests/find_differential.h b/tests/find_differential.h new file mode 100644 index 0000000..dcb2e98 --- /dev/null +++ b/tests/find_differential.h @@ -0,0 +1,124 @@ +#ifndef SX_FIND_DIFFERENTIAL_TEST +#define SX_FIND_DIFFERENTIAL_TEST +#include "sx_core.h" +#include +#include +#include + +/* Independent window-by-window oracle. Test binary content, nonzero + view offsets and boundaries at either side of legal match windows. + Both native and forced-portable builds execute the same cases. */ +static size_t reference(const unsigned char *h, size_t n, + const unsigned char *p, size_t m, size_t start) { + if (!m || start >= n || m > n - start) + return SIZE_MAX; + for (size_t i = start; i <= n - m; ++i) { + size_t j = 0; + while (j < m && h[i + j] == p[j]) + ++j; + if (j == m) + return i; + } + return SIZE_MAX; +} + +static uint32_t state = 0x72d9a351; +static uint32_t next(void) { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + return state; +} + +static void check(const unsigned char *h, size_t n, + const unsigned char *p, size_t m) { + /* Minimal capacities put the content terminator immediately before + the ASan redzone. The view's content also ends at its terminator. */ + sx_t *text = sx_new_with_cap(n + 1); + sx_t *pattern = sx_new_with_cap(m + 4); + TEST(text && pattern); + TEST(sx_truncate(text, n) == text); + TEST(sx_truncate(pattern, m + 3) == pattern); + memcpy(sx_buf_mut(text), h, n); + memset(sx_buf_mut(pattern), 0xa5, 3); + memcpy(sx_buf_mut(pattern) + 3, p, m); + sx_view_t v = sx_view(pattern); + v.offset = 3; + v.len = m; + + size_t expected = reference(h, n, p, m, 0); + TEST(sx_find_view(text, v) == expected); + sx_t *owned_pattern = sx_new_from_view(v); + TEST(owned_pattern); + TEST(sx_find(text, owned_pattern) == expected); + if (!memchr(p, 0, m)) + TEST(sx_find_cstr(text, sx_buf_mut(owned_pattern)) == expected); + + size_t bounds[] = {0, 1, n / 2, n, n + 1, SIZE_MAX, + n >= m ? n - m : 0, next() % (n + 1)}; + for (size_t i = 0; i < sizeof(bounds) / sizeof(bounds[0]); ++i) + TEST(sx_find_view_b(text, v, bounds[i]) == + reference(h, n, p, m, bounds[i])); + if (expected != SIZE_MAX) { + TEST(sx_find_view_b(text, v, expected) == expected); + TEST(sx_find_view_b(text, v, expected + 1) == + reference(h, n, p, m, expected + 1)); + } + sx_free(owned_pattern); + sx_free(pattern); + sx_free(text); +} + +int main(void) { + unsigned char h[2048], p[320]; + const size_t lengths[] = {0, 1, 2, 3, 7, 8, 16, 31, 32, 33, + 63, 64, 127, 128, 129, 255, 256, 257, 320}; + for (size_t k = 0; k < sizeof(lengths) / sizeof(lengths[0]); ++k) { + size_t m = lengths[k]; + for (size_t n = 0; n <= m + 2; ++n) { + memset(h, 'a', n); + memset(p, 'a', m); + check(h, n, p, m); + if (m) { + p[m - 1] = 'b'; + check(h, n, p, m); + } + } + for (unsigned mode = 0; mode < 6; ++mode) { + memset(h, 'a', sizeof(h)); + memset(p, 'a', m); + if (m) + p[m - 1] = 'b'; + if (mode == 1 && m) /* tail hit */ + memcpy(h + sizeof(h) - m, p, m); + if (mode == 2 && m) /* middle hit */ + memcpy(h + sizeof(h) / 2, p, m); + if (mode == 3) /* both endpoint bytes present; near matches */ + for (size_t i = 0; i < sizeof(h); ++i) + h[i] = (i % (m + 1) == 0) ? 'b' : 'a'; + if (mode == 4) /* binary content, high bytes and NULs */ + for (size_t i = 0; i < m; ++i) + p[i] = (unsigned char)(i * 113); + if (mode == 5 && m) { + memset(p, 'a', m); + p[m / 2] = 'c'; /* equal endpoints do not imply a match */ + h[sizeof(h) / 2] = 'c'; + } + check(h, sizeof(h), p, m); + } + } + for (unsigned it = 0; it < 3000; ++it) { + size_t n = next() % (sizeof(h) + 1); + size_t m = next() % (sizeof(p) + 1); + unsigned alphabet = it % 3 == 0 ? 256 : it % 3 == 1 ? 3 : 1; + for (size_t i = 0; i < n; ++i) + h[i] = (unsigned char)(next() % alphabet); + for (size_t i = 0; i < m; ++i) + p[i] = (unsigned char)(next() % alphabet); + if (m && m <= n && it % 2 == 0) + memcpy(h + next() % (n - m + 1), p, m); + check(h, n, p, m); + } + PASS(); +} +#endif diff --git a/tests/find_differential_fallback.c b/tests/find_differential_fallback.c new file mode 100644 index 0000000..c3cc83a --- /dev/null +++ b/tests/find_differential_fallback.c @@ -0,0 +1,14 @@ +// Include include +// Include src +// Include /usr/lib/forge/include +// Source src/sx_raw.c +// Source src/sx_core.c +// Source src/sx_adv.c +// Option -std=c23 +// Option -O1 +// Option -g +// Option -fsanitize=address,undefined +// Option -fno-omit-frame-pointer +// Option -DSX_FORCE_NO_MEMMEM +// Library /usr/local/lib +#include "find_differential.h"