Skip to content

Add LinearBinarySearch{MAX}: bounded linear walk + binary fallback - #72

Draft
ChrisRackauckas-Claude wants to merge 2 commits into
SciML:mainfrom
ChrisRackauckas-Claude:linearbinary-search
Draft

ChrisRackauckas-Claude wants to merge 2 commits into
SciML:mainfrom
ChrisRackauckas-Claude:linearbinary-search

Conversation

@ChrisRackauckas-Claude

@ChrisRackauckas-Claude ChrisRackauckas-Claude commented May 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds LinearBinarySearch{MAX} <: SearchStrategy to FFF: walk linearly from the hint for up to MAX steps, fall back to a binary search if the answer isn't bracketed within the window. Mirrors the strategy of the same name in FastInterpolations.jl; FFF previously had ExpFromLeft (forward exponential doubling) and BracketGallop (bidirectional doubling) but no bounded-linear-with-binary-fallback option.

The intended workload is small-gap ODE-style monotone-forward sweeps where the exponential-doubling overhead of ExpFromLeft/BracketGallop is pure cost and a tight unrolled linear walk is fastest.

Design choices

  • Default MAX = 8, matching FastInterpolations.jl. Allowed values are {0, 1, 2, 4, 8, 16, 32, 64, 128} via a factory constructor — curated to keep the per-MAX method specialization table bounded. Arbitrary integers via the parametric form LinearBinarySearch{k}() still work but won't go through validation.
  • MAX is a type parameter, so the walk is fully unrolled. For MAX ≤ 16 an @generated function produces flat branchless-ish code; for MAX > 16 the walk falls back to a bounded while-loop (unrolling at 128 would balloon the code size).
  • Order-aware — uses Base.Order.lt on the predicate, so Forward and Reverse orderings share one code path.
  • No-hint and out-of-range hint fall through to BinaryBracket.
  • MAX covers gaps 0..MAX (initial gap-0 check plus MAX advance-and-check pairs).

Bench (bench/linearbinary_sweep.jl, n = 100k Float64, ns/query)

gap LBS{4} LinearScan ExpFromLeft BracketGallop
1 9.6 10.0 11.7 17.0
2 11.0 11.0 12.8 20.5
4 14.0 14.0 22.0 23.5
8 43.0 19.0 22.7 25.0 ← MAX exceeded → fallback
16 42.0 30.0 26.0 29.5
64 42.0 101.0 33.0 39.5

LinearBinarySearch{4} wins by ~0.5–1 ns/q at gap = 1 and ties LinearScan at gap = 2. At gaps beyond MAX, the binary fallback caps the worst case at O(log n) — slightly worse than BracketGallop at large gaps but bounded.

Auto integration decision: opt-in only

The gap=1 win is too marginal (~1 ns/q) for a runtime Auto heuristic to recoup — the per-call branch to choose LinearBinarySearch over LinearScan would itself cost the same. This matches FFF's existing pattern for BitInterpolationSearch: keep the strategy as opt-in for callers with workloads they've measured. Auto's per-query tree is unchanged.

Test plan

  • Construction & dispatch on all allowed MAX values, including ArgumentError on bad values
  • Parity vs Base.searchsortedlast/first fuzz on Float64 + Int64 across MAX ∈ {0, 1, 2, 4, 8, 16, 32, 64, 128}
  • Reverse-order parity fuzz
  • Hint past / below / at the answer (walks correct direction)
  • Gap = MAX vs gap = MAX + 1 (binary fallback boundary)
  • Edge cases: empty vector, n=1, n=1M, hint at firstindex/lastindex, hint == answer, out-of-range hint, no-hint dispatch
  • Duplicates (verifies searchsortedfirst finds the first occurrence after a backward walk)
  • All ~36k new tests pass; full suite passes (136766 passes total)
  • Runic-clean

Please ignore until reviewed by @ChrisRackauckas.

🤖 Generated with Claude Code


CI triage (2026-09-25)

The head commit (9b82f92, May 2026) sat on a 4-month-stale base and every
failing check's logs have since expired (GitHub API returns HTTP 410 for run
26253914507 et al.), so classification below is by failure signature against
the current base (main @ 2263792, all green — e.g. Tests 35739730551,
IntegrationTest 35739730245, Documentation 35739730216 successes on
2026-09-22). The branch has now been merged up to current main
(58b3e9e, merge commit, no rebase) with the feature ported to the v3 API
(see commit message), which supersedes the stale results.

check (May head) classification evidence
Core - Julia pre - ubuntu-latest (fail, 4s; pre macos/windows passed) infra flake (setup failure, siblings green) https://github.com/SciML/FindFirstFunctions.jl/actions/runs/26253914507/job/77271812755 (logs expired, HTTP 410)
DataInterpolations.jl/Core/1 (fail, 9s), ModelingToolkit.jl/InterfaceI/1 (fail, 9s) stale-base (dep-resolve failure on May base; downstream green on current base) https://github.com/SciML/FindFirstFunctions.jl/actions/runs/26253914460/job/77271812382 ; base IntegrationTest green https://github.com/SciML/FindFirstFunctions.jl/actions/runs/35739730245
Documentation (fail, 5m32s) stale-base (docs rewritten for v3 since; verified clean locally on merged head) https://github.com/SciML/FindFirstFunctions.jl/actions/runs/26253914628/job/77271813377 ; base docs green https://github.com/SciML/FindFirstFunctions.jl/actions/runs/35739730216
QA - Julia 1 - ubuntu-latest (fail, 3m33s) stale-base, exact cause unrecoverable (logs expired); GROUP=QA passes locally on merged head (21 + 34) https://github.com/SciML/FindFirstFunctions.jl/actions/runs/26253914507/job/77271812736
Spell Check with Typos (fail, 10s) stale-base / resolved (typos clean locally; upstream _typos.toml merged in) https://github.com/SciML/FindFirstFunctions.jl/actions/runs/26253914505/job/77271812432
benchmark (fail, 2m56s) stale-base/infra (old benchpkg workflow; upstream replaced it with the AirspeedVelocity action, adopted via merge) https://github.com/SciML/FindFirstFunctions.jl/actions/runs/26253914506/job/77271812520
Core 1/lts (all OSes), pre mac/win, runic (passed in May) unaffected same run 26253914507

Local verification on the merged head (58b3e9e): GROUP=Core 208501 pass,
GROUP=QA 21 + 34 pass, docs make.jl builds clean (with the package devved,
as CI does), Runic --check clean, typos clean. New CI on the merged head
is running (runs 36088032xxx).

Risk assessment

  • Risk: medium
  • Blast radius: additive feature (LinearBinarySearch, opt-in only).
    No existing dispatch changed: singleton enum/kind switches untouched, Auto
    picker untouched, batched paths route LBS through the generic struct loop.
    Files touched by the port: src/kernels.jl (append-only LBS section),
    src/strategy_kind.jl (+4 entry points, +1 strategy_kind throw),
    src/strategies.jl (LBS struct, unchanged semantics), test/core_tests.jl
    (new testset), bench/linearbinary_sweep.jl (v3 call names). src/dispatch.jl
    deletion is upstream's v3 redesign, not this PR.
  • Evidence: GROUP=Core: 208501 pass; GROUP=QA: 55 pass; LBS testset
    alone: 36296 pass; docs build clean; Runic/typos clean.
  • Independent review: none yet
  • Merge: needs review — parametric-strategy-without-enum-tag is a new
    pattern in the v3 architecture (mirrors GuesserHint precedent); confirm
    the maintainers want it vs. a different integration.

🤖 Posted by an AI agent — harness: opencode 1.18.31 · model: opencode/muse-spark-1.3-contributor-free
Conversation: /log.txt

Risk assessment

  • Risk: low
  • Blast radius: The change only adds things. Nothing changes for existing callers: there is a new exported LinearBinarySearch{MAX} <: SearchStrategy, its kernels are appended to src/kernels.jl, it gets struct entry points in src/strategy_kind.jl, and it is added to the precompile workload. The Auto picker, the enum/kind dispatch and the batched kind loops are unchanged. Batched searchsortedlast!/searchsortedrange/findequal handle it through the existing generic struct loop. That works on reading the code, but no test covers it. The things that could break are outside this repo:
    • Name clash: FastInterpolations.jl (v0.4.19, does not depend on FindFirstFunctions) also exports LinearBinarySearch. Any module that does using FastInterpolations, FindFirstFunctions will have the bare name made ambiguous.
    • strategy_kind can now throw: strategy_kind(::LinearBinarySearch) raises ArgumentError. Generic code that calls strategy_kind on any SearchStrategy will throw for the new type. GuesserHint already behaves this way.
  • Evidence: I checked head 58b3e9e, which is 2 commits ahead of / 1 behind main and reports as mergeable. 25 of 26 checks pass. That includes Core on Julia 1/lts/pre for every OS plus x86, QA, Enzyme, Mooncake, Downgrade, Runic, typos, benchmark, and downstream DataInterpolations Core and ModelingToolkit InterfaceI on 3 OSes.
  • Independent review: Devin CLI / fusion-claude-opus-5-5-high-sidekick-swe-2-medium rated it low, medium confidence: CI shows no regressions and I traced the four walk kernels' boundary logic and found it correct, but the PR adds new public API and a new dispatch pattern that the author explicitly leaves for the maintainer to decide.
  • Merge: needs human review. Reasons:
    • The new export LinearBinarySearch is a design decision and a minor version bump, and it clashes with FastInterpolations.jl's export of the same name.
    • It sets a new v3 pattern: a parametric strategy with no StrategyKind tag, where strategy_kind throws.
    • The PR body says "Please ignore until reviewed by @ChrisRackauckas".
    • The red Documentation check is a pre-existing linkcheck flake; re-running it should turn it green.

🤖 Risk assessment posted by an AI agent (fleet master) — harness: Devin CLI / fusion-claude-opus-5-5-high-sidekick-swe-2-medium; dispatched by Devin CLI 3000.11.3 fleet-master caretaker, model Fusion (claude-opus-5-5 medium + swe-2 medium)
Conversation: local transcript (no session URL)

🤖 Automated review section from an AI agent running as Chris Rackauckas's account — not written or reviewed by Chris.

Risk assessment (independent review, Codex gpt-6.1-sol, head 58b3e9e)

  • Verdict: CHANGES

  • Rating: Codex gpt-6.1-sol rated it medium-low (ML7) at head 58b3e9e

  • Risk: medium-low (ML7: new exported LinearBinarySearch type and methods on package-owned functions, with a docstring, rendered docs entry, and tests; existing calls and defaults are unchanged).

  • Blast radius: Callers explicitly selecting the new strategy, including scalar, batched, range, and equality searches. The confirmed issue increases work for backward searchsorted_first queries at the window boundary; it does not change returned indices in the cases tested. No dependencies, AD rules, existing numerical defaults, or mutable shared state are changed. This additive API requires a minor release: the reviewed head retains version 3.4.0, while origin/HEAD is 3.4.1; publish this feature in 3.5.0 or later, rather than a patch release.

  • Evidence: Read pr.txt, the complete risk policy, and the full git diff origin/HEAD...HEAD; verified HEAD is 58b3e9e6eb8c8183d6663ed22b7bfa4bd9dd1079 and git status --short remains empty. gh pr view 72 --repo SciML/FindFirstFunctions.jl --json closingIssuesReferences,statusCheckRollup,commits returned no linked closing issue; the body and comments contain no separate issue link. git diff --check origin/HEAD...HEAD passed. No tests were skipped, deleted, or loosened, and no copyleft dependency was added.

    Local Julia 1.12.4 runs used the requested depot, JULIA_NUM_THREADS=4, scratch TMPDIR, and one Julia process at a time. Ran timeout 3600 julia --startup-file=no --project=<scratch>/env <scratch>/run_tests.jl after creating a scratch-only environment pointing to the unchanged checkout. This executes the PR's extracted LinearBinarySearch testset and supplemental tests of offsets, Forward/Reverse order, infinities, NaNs, signed zero, duplicates, ranges, views, integer hint types, batched searches, searchsortedrange, and findequal. Actual output:

    LinearBinarySearch | 36296  36296  4.8s
    Reviewer: offsets, ordering, special values, integration | 102870  102870  17.8s
    

    Ran timeout 3600 julia --startup-file=no --project=<scratch>/env <scratch>/boundary_probe.jl; the public-call access trace and direct walk result confirm finding 1. Scripts and output are in scratch/extra_tests.jl, scratch/tests.log, scratch/boundary_probe.jl, and scratch/boundary.log beside this report.

    Inspected the latest failed documentation job's actual logs, rather than relying on the PR's older triage. It fails exclusively on HTTP 404 for main/bench/auto_sweep.jl and main/bench/analyze.jl. git diff origin/HEAD HEAD -- docs/src/auto.md docs/make.jl bench/auto_sweep.jl bench/analyze.jl is empty. The latest default-branch documentation run at e3c0636 succeeded and its logs show document checks followed by HTML rendering; direct HTTP GETs to both raw URLs returned 200. This supports an external linkcheck failure, not a feature-induced documentation regression; it does not make the PR's red check green.

    G1: pass — exact search results are checked against the independent Base implementation, including the reviewer-run edge cases. G2: not applicable — no GPU kernels, AD rules, Reactant, or MPI paths are changed; existing Enzyme and Mooncake CI jobs at this head succeeded. G3: not applicable — the added strategy is an immutable zero-field value with no cache or shared mutable state.

  • Merge: needs changes (finding 1); the documentation check also needs a successful rerun before merging. ML7 additionally requires two qualifying independent reviews under the supplied policy.


🤖 Posted by an AI agent — harness: Codex CLI 0.162.1 · model: gpt-6.1-sol
Conversation: local headless review run (no public session URL); transcript kept by the fleet master.

ChrisRackauckas and others added 2 commits May 21, 2026 17:22
LinearBinarySearch{MAX} walks linearly from the hint for up to MAX steps,
then falls back to BinaryBracket if the answer isn't bracketed within the
window. The win regime is small-gap ODE-style monotone-forward workloads
where the exponential-doubling overhead of ExpFromLeft / BracketGallop is
pure cost and a tight unrolled linear walk is fastest.

Default MAX = 8; allowed values are {0, 1, 2, 4, 8, 16, 32, 64, 128} via a
factory constructor. The set is curated to keep the per-MAX method
specialization table bounded; arbitrary integers would explode it. MAX is
a type parameter so the walk is fully unrolled (for MAX ≤ 16) via
@generated, producing flat branchless-ish code that LLVM can fold.

Bench (bench/linearbinary_sweep.jl, n = 100k Float64, ns/query):

  gap   LBS{4}   LinearScan   ExpFromLeft   BracketGallop
  1      9.6     10.0         11.7          17.0
  2     11.0    11.0          12.8          20.5
  4     14.0    14.0          22.0          23.5
  8     43.0    19.0          22.7          25.0  ← MAX exceeded → fallback
  16    42.0    30.0          26.0          29.5
  64    42.0   101.0          33.0          39.5

LBS{4} wins by ~0.5–1 ns/q at gap = 1; ties LinearScan at gap = 2. At
gaps beyond MAX, the binary fallback caps the worst case at O(log n).
The strategy is opt-in — Auto does not pick it, because the gap=1 win is
too marginal for a runtime heuristic to recoup.

Includes tests covering: factory constructor validation, parity-vs-Base
across MAX ∈ {0, 1, 2, 4, 8, 16, 32, 64, 128}, Forward and Reverse
orderings, hint past / below / at the answer, gap = MAX vs gap = MAX+1
boundary, empty / n=1 / n=1M, duplicates, and no-hint fallback.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-Authored-By: Chris Rackauckas <accounts@chrisrackauckas.com>
… to v3 API

Upstream replaced the v2 Base.searchsortedlast(::S, ...) extensions with
the v3 StrategyKind enum + kernels architecture (src/dispatch.jl deleted,
split into src/kernels.jl + src/kinds.jl + src/strategy_kind.jl; tests
moved to test/core_tests.jl via SciMLTesting).

Port preserving intent:
- LinearBinarySearch{MAX} walks/kernels move verbatim to src/kernels.jl
  as _kernel_last/first_linear_binary_search with trailing Val{MAX}.
- Struct entry points in src/strategy_kind.jl (multimethod, like
  GuesserHint); strategy_kind(::LinearBinarySearch) throws ArgumentError
  since no single enum tag can represent every MAX. Opt-in only: Auto
  unchanged, no new StrategyKind value.
- LBS tests move to test/core_tests.jl with searchsorted_last/first
  names; guard test covers LinearBinarySearch{8} for no-Base-extension.
- bench/linearbinary_sweep.jl updated to searchsorted_last.

Verified: Core 208501 pass, QA 21+34 pass, docs build clean,
Runic --check clean, typos clean.

Co-Authored-By: Chris Rackauckas <accounts@chrisrackauckas.com>
Agent-Harness: opencode 1.18.31
Agent-Model: opencode/muse-spark-1.3-contributor-free
Agent-Session: /home/crackauc/sandbox/fleet-master-jobs/nw-findfirstfunctions-72/log.txt
@ArnoStrouwen

Copy link
Copy Markdown
Member

Documenter failure is just a link check flake. This seems ready for review.

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.

3 participants