Repository navigation
Add LinearBinarySearch{MAX}: bounded linear walk + binary fallback - #72
Draft
ChrisRackauckas-Claude wants to merge 2 commits into
Draft
ChrisRackauckas-Claude wants to merge 2 commits into
ChrisRackauckas-Claude wants to merge 2 commits into
Conversation
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
Member
|
Documenter failure is just a link check flake. This seems ready for review. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds
LinearBinarySearch{MAX} <: SearchStrategyto FFF: walk linearly from the hint for up toMAXsteps, 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 hadExpFromLeft(forward exponential doubling) andBracketGallop(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/BracketGallopis pure cost and a tight unrolled linear walk is fastest.Design choices
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-MAXmethod specialization table bounded. Arbitrary integers via the parametric formLinearBinarySearch{k}()still work but won't go through validation.MAXis a type parameter, so the walk is fully unrolled. ForMAX ≤ 16an@generatedfunction produces flat branchless-ish code; forMAX > 16the walk falls back to a bounded while-loop (unrolling at 128 would balloon the code size).Base.Order.lton the predicate, soForwardandReverseorderings share one code path.BinaryBracket.MAXcovers gaps0..MAX(initial gap-0 check plus MAX advance-and-check pairs).Bench (bench/linearbinary_sweep.jl, n = 100k Float64, ns/query)
LinearBinarySearch{4}wins by ~0.5–1 ns/q at gap = 1 and tiesLinearScanat gap = 2. At gaps beyondMAX, the binary fallback caps the worst case at O(log n) — slightly worse thanBracketGallopat large gaps but bounded.Auto integration decision: opt-in only
The gap=1 win is too marginal (~1 ns/q) for a runtime
Autoheuristic to recoup — the per-call branch to chooseLinearBinarySearchoverLinearScanwould itself cost the same. This matches FFF's existing pattern forBitInterpolationSearch: keep the strategy as opt-in for callers with workloads they've measured. Auto's per-query tree is unchanged.Test plan
MAXvalues, includingArgumentErroron bad valuesBase.searchsortedlast/firstfuzz on Float64 + Int64 acrossMAX ∈ {0, 1, 2, 4, 8, 16, 32, 64, 128}MAXvs gap =MAX + 1(binary fallback boundary)searchsortedfirstfinds the first occurrence after a backward walk)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 everyfailing check's logs have since expired (GitHub API returns HTTP 410 for run
26253914507et al.), so classification below is by failure signature againstthe current base (
main@2263792, all green — e.g. Tests35739730551,IntegrationTest
35739730245, Documentation35739730216successes on2026-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.
GROUP=QApasses locally on merged head (21 + 34)typosclean locally; upstream_typos.tomlmerged in)26253914507Local verification on the merged head (
58b3e9e):GROUP=Core208501 pass,GROUP=QA21 + 34 pass, docsmake.jlbuilds clean (with the package devved,as CI does),
Runic --checkclean,typosclean. New CI on the merged headis running (runs
36088032xxx).Risk assessment
LinearBinarySearch, opt-in only).No existing dispatch changed: singleton enum/kind switches untouched,
Autopicker 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, +1strategy_kindthrow),src/strategies.jl(LBS struct, unchanged semantics),test/core_tests.jl(new testset),
bench/linearbinary_sweep.jl(v3 call names).src/dispatch.jldeletion is upstream's v3 redesign, not this PR.
GROUP=Core: 208501 pass;GROUP=QA: 55 pass; LBS testsetalone: 36296 pass; docs build clean; Runic/typos clean.
pattern in the v3 architecture (mirrors
GuesserHintprecedent); confirmthe 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
LinearBinarySearch{MAX} <: SearchStrategy, its kernels are appended tosrc/kernels.jl, it gets struct entry points insrc/strategy_kind.jl, and it is added to the precompile workload. TheAutopicker, the enum/kind dispatch and the batched kind loops are unchanged. Batchedsearchsortedlast!/searchsortedrange/findequalhandle 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:LinearBinarySearch. Any module that doesusing FastInterpolations, FindFirstFunctionswill have the bare name made ambiguous.strategy_kindcan now throw:strategy_kind(::LinearBinarySearch)raisesArgumentError. Generic code that callsstrategy_kindon anySearchStrategywill throw for the new type.GuesserHintalready behaves this way.58b3e9e, which is 2 commits ahead of / 1 behindmainand 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.:linkcheckstep, with 404s forraw.githubusercontent.com/.../main/bench/auto_sweep.jland.../bench/analyze.jl.docs/src/auto.md,NEWS.md). Both files are byte-identical on head andmain, and both URLs return 200 now.mainpasses at the merge base2263792(https://github.com/SciML/FindFirstFunctions.jl/actions/runs/36142550343) and at the current tipd0bb23e(https://github.com/SciML/FindFirstFunctions.jl/actions/runs/37014996253).mainfails here.Base.searchsortedlast/first(v, x, lo, hi, order), which Base does not document, is already used insrc/kernels.jlonmain.!hasmethod(searchsortedlast, …)guard is extended toLinearBinarySearch{8}, and about 36k new tests are added.Project.tomlis untouched.searchsortedrangeorfindequalwithLinearBinarySearch, or for OffsetArrays;LinearBinarySearch{k}()accepts anykwithout validation, including negative values (which act likeMAX = 0);LinearBinarySearchis a design decision and a minor version bump, and it clashes with FastInterpolations.jl's export of the same name.StrategyKindtag, wherestrategy_kindthrows.🤖 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)
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
LinearBinarySearchtype 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_firstqueries 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 fullgit diff origin/HEAD...HEAD; verified HEAD is58b3e9e6eb8c8183d6663ed22b7bfa4bd9dd1079andgit status --shortremains empty.gh pr view 72 --repo SciML/FindFirstFunctions.jl --json closingIssuesReferences,statusCheckRollup,commitsreturned no linked closing issue; the body and comments contain no separate issue link.git diff --check origin/HEAD...HEADpassed. 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. Rantimeout 3600 julia --startup-file=no --project=<scratch>/env <scratch>/run_tests.jlafter 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, andfindequal. Actual output: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 inscratch/extra_tests.jl,scratch/tests.log,scratch/boundary_probe.jl, andscratch/boundary.logbeside 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.jlandmain/bench/analyze.jl.git diff origin/HEAD HEAD -- docs/src/auto.md docs/make.jl bench/auto_sweep.jl bench/analyze.jlis empty. The latest default-branch documentation run ate3c0636succeeded 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.