Skip to content

Accelerate forward substring search with bounded fast paths - #7

Merged
minelogy-dev merged 10 commits into
mainfrom
perf/forward-search-fast-paths
Nov 12, 2026
Merged

minelogy-dev merged 10 commits into
mainfrom
perf/forward-search-fast-paths

Conversation

@minelogy-dev

@minelogy-dev minelogy-dev commented Nov 1, 2026 •

Copy link
Copy Markdown
Owner

Forward substring searches currently allocate a KMP prefix table for every multi-byte needle and scan even when a required endpoint byte is absent. The glibc forward path now checks the front window, probes the bounded first/last-byte ranges, and uses native memmem for needles up to 32 bytes. These paths avoid the prefix-table allocation.

The original KMP kernel is unchanged. A private non-inlined native decision function preserves its compiler optimization context; unresolved long needles enter KMP with their original boundary. Other platforms and the forced-portable configuration use the original implementation directly. The single-byte API retains its direct memchr specialization. Public signatures, binary matching, reverse search, overlapping all-match results, ownership and growth policy retain their semantics.

Validation at 40987da6ddaa2f31ca04d5d7f4545fa0704b7eb4:

  • GCC 14 and Clang 19: all 22 tests passed with ASan, UBSan and leak checking. Each native/forced-portable differential test runs 6,689 deterministic input fixtures plus boundary variations against an independent naive oracle, covering NUL/high bytes, nonzero view offsets, empty/end/past-end boundaries, repetitive inputs and cutoff lengths.
  • Compiler warnings, GCC static analysis, workflow/secret checks and CodeQL passed: CI, CodeQL.
  • Same-host performance comparison passed, including sanitizer validation of all 15 search fixtures. Seven representative cases were timed across three fresh processes per compiler/variant, 11 hot-input samples per process, pinned to CPU 0 on AMD EPYC 7763, glibc 2.39, -O3 -march=x86-64, no LTO. Baseline: 452314a7ca51f90a7a8fa66930947164af8fc4f6; immutable harness: ecf31d3d65a45466222dfb0f358e176a22d1bc1c from Add audited cross-library benchmarks and search diagnostics #6. Allocation counting uses a separate untimed executable.
Case, 64KiB haystack GCC baseline / native / portable µs Clang baseline / native / portable µs
8B miss; first byte absent 40.866 / 0.659 / 40.843 61.292 / 0.661 / 61.258
128B repeated-prefix miss; last byte absent 122.783 / 0.671 / 122.861 245.345 / 0.672 / 245.261
8B miss; common endpoint bytes 56.782 / 9.083 / 56.812 77.429 / 9.067 / 77.252
8B periodic miss 40.991 / 26.159 / 40.935 63.260 / 26.167 / 62.123
33B miss; common endpoint bytes 56.800 / 48.395 / 56.793 77.427 / 77.280 / 77.240
128B periodic miss; both endpoints present 168.545 / 168.312 / 168.614 249.533 / 254.658 / 254.424
1B tail hit 0.654 / 0.653 / 0.652 0.653 / 0.654 / 0.652

The endpoint-absent cases improve about 62–93x and 183–365x; the common-byte 8B miss improves about 6–9x. Native fast-path cases perform zero prefix-table malloc calls versus one before. Dense long needles still pay KMP's existing fallback-chain cost; the Clang dense 128B case is about 2% slower in this run, with a similar difference in the unchanged portable control. These are hot-input microbenchmarks on a shared runner; small differences require further evidence before attribution. Raw per-process CSV, p10/p90 summaries, generated fixture source and environment metadata are retained as workflow artifacts for 14 days.

This addresses the search diagnosis in #6.

Patched StringX versus SDS and bstrlib: same-run library comparison

These rows use patched StringX at 40987da from #7, with peers measured in the same executable/processes and the same original benchmark run. Saved-results report reads the existing artifact without new timing measurements. Host: EPYC 7763, glibc 2.39, CPU 0, -O3 -march=x86-64 -fno-lto; three processes and eleven samples per process. SDS search here is glibc memmem/memchr.

gcc-14

Case, 64KiB text StringX µs SDS + glibc µs bstrlib µs
1B tail hit 0.653 0.647 0.650
8B miss; first byte absent 0.659 6.158 30.654
128B repeated-prefix miss; last byte absent 0.671 292.362 30.787
8B miss; common endpoint bytes 9.083 9.013 48.246
8B periodic miss 26.159 25.876 119.391
33B miss; common endpoint bytes 48.395 2.391 47.773
128B periodic miss; both endpoints present 168.312 0.621 120.363

clang-19

Case, 64KiB text StringX µs SDS + glibc µs bstrlib µs
1B tail hit 0.654 0.646 0.650
8B miss; first byte absent 0.661 6.161 20.506
128B repeated-prefix miss; last byte absent 0.672 292.554 20.836
8B miss; common endpoint bytes 9.067 9.113 40.116
8B periodic miss 26.167 25.983 86.559
33B miss; common endpoint bytes 77.280 2.395 39.730
128B periodic miss; both endpoints present 254.658 0.612 94.361

The common-byte 8B case is approximately tied with SDS/glibc and 4.4–5.3x faster than bstrlib. Endpoint-absent cases strongly favor the new filters. The 33B fixture is 20–32x slower than SDS/glibc and exposes the private 32B cutoff. The synthetic 128B periodic fixture is 271–416x slower than SDS/glibc and 1.4–2.7x slower than bstrlib, but its period is coupled to glibc's maximum skip and strongly favors that algorithm; this ratio is specific to this corpus, rather than an average long-pattern result. See the source-model analysis below.

Why 0.671 / 2.391 / 0.621 microseconds occur: exact fixture and search-path analysis

The 0.671 us StringX case is text containing only a bytes and a needle consisting of 127 a bytes followed by b. The front window fails, the first-byte probe returns immediately, and a bounded memchr scans 65,408 bytes for the absent b. It returns before KMP preprocessing or prefix-table allocation. The same run's single-byte full-buffer scan takes about 0.653 us. This is a hot-cache SIMD-scan measurement.

The glibc 2.39 memmem path for lengths 3..256 uses pair-hash modified Horspool. Replaying the exact deterministic fixtures against that source gives the following logical counts (source model, not measured hardware events):

Fixture Pair-hash probes 8-byte filter calls Full-prefix memcmp calls
Common-byte 8B miss 9,489 0 52
Common-byte 33B miss 2,221 9 0
128B, all-a text, final b absent 65,409 0 0
128B, text (a^126 b) repeated 516 0 0

For the 33B fixture, the maximum skip is 32; the observed source-model advance averages about 29.5 bytes per probe. The 8B counterpart averages 6.9 bytes. A longer needle can therefore search this text faster.

The 0.621 us fixture is unusually favorable to glibc: its text period is 127, exactly the 128B needle's maximum skip (m-1). Probes at offsets 127, 254, ... always inspect ba. The needle contains only aa and ab pairs, so ba hashes to a zero shift-table entry and each probe skips 127 bytes. It makes no candidate memcmp calls. The existing END_PRESENT generator couples the text period to m-1, creating this favorable alignment by construction.

Changing the text period independently from 127 to 126 (while keeping the same 128B needle and a miss) raises the source-model probe count from 516 to 21,813; period 125 gives 32,487. Those are logical controls, not new timing results. Rotating the period-127 text also changes filtering work. The model agrees with an independent naive oracle on the exact fixtures and 2,000 randomized cases.

The 271–416x dense-128 ratio is thus specific to this synthetic corpus. It is useful as an algorithm-sensitive counterexample, but cannot establish an average long-pattern ranking. A broader corpus should vary period, phase, terminal-byte frequency, and hit position independently of needle length. The separate common-33 fixture still exposes the fixed 32B routing cutoff.

Source: glibc 2.39 memmem.c. The harness reuses hot fixtures, compiles library and worker sources separately, disables LTO, and includes a memory-clobber barrier in each iteration. These checks support the source-path explanation; the logical model is not a replacement for auditing the exact timed binary.

Audited rerun of the disputed search timings

Fresh benchmark run passed at benchmark commit 7f8a624af4809c9dc606c41533991acd1b51917d, measuring the unchanged patched StringX implementation 40987da6ddaa2f31ca04d5d7f4545fa0704b7eb4. This rerun is the current validation of the unusually large gaps discussed below.

  • 79 fixtures, 4 adapters, 2 data-cache conditions, GCC 14 and Clang 19, three fresh processes and seven samples per process: 26,544 raw batch samples.
  • An independent byte-window oracle validates every result. Exact lengths, byte content, binary NUL cases, fixture hashes and hit positions are checked. Fixture signature 91aaca138a68b3db agrees across compilers/processes.
  • Separate ASan/UBSan/leak-check builds verify nine adapter calls per fixture/library, totaling 2,844 checked calls per compiler.
  • Release adapters are separate translation units with no LTO and memmem/memchr builtins disabled. Disassembly checks confirm an indirect call inside the timed loop and calls to the underlying search functions; release adapters contain no counters.
  • A raw glibc adapter uses the same SDS buffers with an explicit length. Its timings closely track SDS + glibc.
  • Empty-adapter controls are about 1.87 ns/op; timestamp-pair controls about 33.6 ns. These costs are reported without subtraction.
  • Hot measurements use warmups and calibrated batches. Flushed measurements use CLFLUSH on text and pattern, MFENCE/LFENCE, then time the call; each sample averages eight individually flushed calls. Flushing cost is excluded, metadata is not explicitly flushed.
  • Host: AMD EPYC 7763, CPU 0, glibc 2.39. Flags: -O3 -DNDEBUG -march=x86-64 -fno-lto -fno-builtin-memmem -fno-builtin-memchr. Each group has 21 samples; p10/p90 and all fixture descriptions remain in the artifact.

Findings: the disputed hot-cache values reproduce: StringX's absent-terminal 128B case is about 0.683 us, the SDS common-33 case about 2.403 us, and SDS period-127 about 0.625 us (GCC). After flushing they are about 3.285, 4.799 and 3.304 us. With the same 128B needle and another miss, changing the text period to 126 raises SDS to about 97.704 us; period 125 gives 147.720 us. Rotating period-127 by one byte raises it to 3.251 us. No removed or hoisted search calls were found in the audited timing paths. The gaps are strongly corpus/cache dependent and are not a universal ranking.

The independent-random cutoff check also remains significant: StringX changes from 2.458 us at 32B to 41.056 us at 33B on the GCC seed-0 fixtures, while SDS stays near 2.5 us. Conversely, the rare-terminal tail near-miss favors bstrlib and penalizes glibc. Broad routing decisions should use these controls, rather than only the period-127 or terminal-absent fixtures.

Fresh cross-library tables: hot and flushed data

gcc-14, hot

Case, 64KiB text; all misses StringX µs SDS + glibc µs bstrlib µs raw glibc, same SDS buffer µs
8B miss; first byte absent 0.661 6.156 30.667 6.155
128B repeated prefix; terminal byte absent 0.683 292.094 30.847 292.198
8B common-byte miss 9.135 9.055 48.320 9.029
33B original common-byte miss 48.437 2.403 47.814 2.401
32B independent-random miss 2.458 2.480 48.640 2.483
33B independent-random miss 41.056 2.454 48.174 2.447
128B independent-random miss 41.226 1.783 47.886 1.781
128B needle; text period 125, phase 0 168.492 147.720 121.382 147.706
128B needle; text period 126, phase 0 168.390 97.704 121.982 97.810
128B needle; text period 127, phase 0 168.740 0.625 120.251 0.618
128B needle; text period 127, phase 1 168.364 3.251 121.583 3.253
128B near miss; rare terminal byte at tail 124.175 292.542 31.097 292.228

gcc-14, flushed

Case, 64KiB text; all misses StringX µs SDS + glibc µs bstrlib µs raw glibc, same SDS buffer µs
8B miss; first byte absent 3.238 6.855 30.628 6.700
128B repeated prefix; terminal byte absent 3.285 292.902 31.752 292.280
8B common-byte miss 9.453 9.377 49.675 9.285
33B original common-byte miss 49.257 4.799 48.937 4.862
32B independent-random miss 4.731 4.839 49.725 4.869
33B independent-random miss 42.314 4.808 49.244 4.878
128B independent-random miss 44.815 5.203 48.763 5.242
128B needle; text period 125, phase 0 168.900 148.066 120.519 148.057
128B needle; text period 126, phase 0 168.615 98.352 121.521 98.283
128B needle; text period 127, phase 0 168.554 3.304 119.883 3.291
128B needle; text period 127, phase 1 168.518 6.490 121.151 6.327
128B near miss; rare terminal byte at tail 126.571 292.269 32.095 292.441

clang-19, hot

Case, 64KiB text; all misses StringX µs SDS + glibc µs bstrlib µs raw glibc, same SDS buffer µs
8B miss; first byte absent 0.660 6.155 30.714 6.158
128B repeated prefix; terminal byte absent 0.682 292.291 30.915 292.246
8B common-byte miss 9.068 9.005 48.303 9.024
33B original common-byte miss 79.123 2.403 47.678 2.401
32B independent-random miss 2.464 2.484 47.806 2.482
33B independent-random miss 80.127 2.451 47.338 2.447
128B independent-random miss 80.167 1.781 47.085 1.778
128B needle; text period 125, phase 0 250.808 147.649 104.657 147.704
128B needle; text period 126, phase 0 250.710 97.806 103.046 97.738
128B needle; text period 127, phase 0 250.833 0.614 103.870 0.611
128B needle; text period 127, phase 1 250.742 3.250 102.758 3.253
128B near miss; rare terminal byte at tail 246.513 292.323 31.347 292.141

clang-19, flushed

Case, 64KiB text; all misses StringX µs SDS + glibc µs bstrlib µs raw glibc, same SDS buffer µs
8B miss; first byte absent 3.085 6.730 30.642 6.744
128B repeated prefix; terminal byte absent 3.136 292.481 30.712 292.244
8B common-byte miss 9.343 9.367 49.153 9.342
33B original common-byte miss 79.755 4.595 48.132 4.596
32B independent-random miss 4.502 4.820 48.923 4.889
33B independent-random miss 81.332 4.705 48.023 4.904
128B independent-random miss 80.877 5.108 47.865 5.165
128B needle; text period 125, phase 0 250.887 147.936 108.454 147.940
128B needle; text period 126, phase 0 250.938 98.398 101.657 98.237
128B needle; text period 127, phase 0 250.889 3.196 100.634 3.221
128B needle; text period 127, phase 1 250.734 6.478 100.658 6.306
128B near miss; rare terminal byte at tail 248.879 292.762 35.693 292.611

Raw CSV, full fixture manifests, compiler versions, source/binary hashes, exact release binaries and disassembly are retained as search-recheck-41466782569 for 14 days. Reproduction and measurement contracts. Shared-runner frequency/scheduling and address-layout variation remain limits; observed spreads are not confidence intervals.

minelogy-dev and others added 2 commits November 1, 2026 07:56
Use bounded endpoint probes and native short-pattern search while retaining
portable KMP for longer needles. Exercise native and fallback paths with
binary differential tests and compare against the baseline on one runner.

Co-authored-by: Codex <codex@openai.com>
Use memchr only when the prefix state has fallen back to zero, preserving
linear scanning and the existing all-match behavior.

Co-authored-by: Codex <codex@openai.com>
Comment thread src/sx_core.c Fixed
Compare the portable search build alongside native before/after results.

Co-authored-by: Codex <codex@openai.com>
Comment thread src/sx_core.c Fixed
Comment thread src/sx_core.c Fixed
Stop batch skipping after eight nearby candidates and resume scalar KMP
at the first unconsumed candidate. This bounds setup work on periodic
inputs and keeps sparse-candidate acceleration portable.

Co-authored-by: Codex <codex@openai.com>
Comment thread src/sx_core.c Fixed
Comment thread src/sx_core.c Fixed
minelogy-dev and others added 6 commits November 1, 2026 08:25
Keep the original KMP kernel unchanged. Apply front-window and endpoint
filters in a glibc-only forward-search adapter, using native memmem for
short patterns. Focus final measurements on the sixteen search cases,
including the forced-portable build.

Co-authored-by: Codex <codex@openai.com>
Co-authored-by: Codex <codex@openai.com>
Endpoint checks can reject a missing long needle without allocation.
If both endpoints exist, enter KMP with the original boundary so the
fallback retains its existing compiler specialization.

Co-authored-by: Codex <codex@openai.com>
Keep the optional native decision in a non-inlined private function and
retain the original KMP call context. Measure six representative search
cases across three fresh processes per compiler and variant; sanitizer
validation continues to cover all fifteen search cases.

Co-authored-by: Codex <codex@openai.com>
Keep sx_find_char on its original memchr specialization and include it
in the repeated-process performance comparison.

Co-authored-by: Codex <codex@openai.com>
@minelogy-dev
minelogy-dev marked this pull request as ready for review November 1, 2026 16:47
@minelogy-dev
minelogy-dev merged commit 5f30a10 into main Nov 12, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants