Skip to content

Make fuzz draws independent of imported integer literals - #640

Merged
suraj-ranganath merged 4 commits into
developfrom
cursor/deterministic-fuzz-draws-730b
Nov 18, 2026
Merged

suraj-ranganath merged 4 commits into
developfrom
cursor/deterministic-fuzz-draws-730b

Conversation

@suraj-ranganath

@suraj-ranganath suraj-ranganath commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Nightly fuzz cases now come from a SHA-256 counter owned by this repo. A draw depends on the seed, the target name, and the example index, and not on which modules were imported, the platform, or the Python version. Importing the sigprocfunc package, gauss.py, or a new module full of integer literals leaves the case list unchanged, so #602 and #603 can rebase without moving the golden file.

The golden file for seed 20261012 is re-recorded. The old four examples shared a few partial crops. Every filter set an explicit order on 1 to 18 channels. Every rereference was an average. Resample asked only for 64, 90, or 100 Hz. clean_asr and pop_clean_rawdata shared cutoff 5, and pop_clean_rawdata turned every other criterion off. One shared crop was 55 samples at half rate with a short NaN run. The new four examples are independent. Filters use all 32 channels: two epoched lowpasses of order 40 (30 Hz and 45 Hz) and two automatic 49-51 Hz notches. Rereference is an average, an average that excludes one channel, and a kept two-channel reference on a flat channel. Resample asks for 100, 256, and 64 Hz, including epoched data. clean_asr uses cutoffs 5 and 3 with reference limits 0.075, off, and 0.2. pop_clean_rawdata runs the bids highpass preset, the GUI burst-20 rejection preset, and one burst-only call at cutoff 20. A 40 example test locks the wider set, including odd filter orders, an added reference location, and resample transition widths. Saved reproduce commands are paths from the repository root.

A pop_reref refloc sent through the batch session now carries every field of that recording's chanlocs and nodatchans, including sph_theta, because EEGLAB copies those fields off the struct. reproduce exits 0 when both sides raise the same error.

MATLAB was not run here. The comparison commands are in the first comment.

Open in Web Open in Cursor 

Generate each case from a SHA-256 counter seeded by the target and the
example index, and re-record the golden draws for the new strategies.

Co-authored-by: Suraj Ranganath <[email protected]>

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Code review skipped — your organization has no extra usage available to pay for this review.

If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.

Once extra usage is available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.

@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 1m 39s —— View job


Code review

  • Overall assessment: Looks good. The SHA-256 counter draw (tests/fuzz/draw.py) depends only on the seed, the target name, and the example index. The forced-trace shrinker (shrink_case) replays and shrinks traces correctly. The changed MATLAB dispatch arguments go through matlab_batch_engine._encode: numeric lists for exclude and channels arrive as double rows, and the refloc dict arrives as a struct. The Hypothesis-to-Draw port in targets.py keeps the same branch structure as before.
  • Highest-risk area: the wider strategy space, which now includes odd filter orders, refloc, resample fc/df, and clean_rawdata presets. Its MATLAB comparison has not been run (the PR description says so).
  • Merge recommendation: Safe to merge after the nits below. They are optional.

Blocking

None.

Important

None.

Nits

  • tests/fuzz/harness.py:990-991, _generate_cases. Nothing defines a builder with a generate method, so the hasattr(builder, "generate") branch never runs. AGENTS.md also asks us to avoid hasattr checks like this. Delete both lines. ⚠️ The suggestion block on the inline comment removes only line 990. Do not commit it alone: the return list(builder.generate(...)) on line 991 would be left at the top of the function and every case would fail.
  • tests/fuzz/harness.py:1331, build_strategies.eegfiltnew. The epoched branch passes srate where _filter_edges expects a Nyquist frequency, so its lowpass check is 2× too loose. The golden file is unaffected today because the epoch file is 128 Hz and every candidate is ≤45 Hz. Fix: pass srate / 2.0. A committable suggestion is on the inline comment.
  • tests/fuzz/harness.py:2905, _resample_frequencies. The srate parameter is never used inside the function. Drop it from the signature and from both call sites.
  • tests/test_fuzz_events.py:148-153. The comment explains how Hypothesis 6.169 copies literals into its draws. The fuzzer no longer uses Hypothesis, so as written it reads as a description of the current code. Reword it to one line, e.g. "imports that moved the golden file under the old Hypothesis generator". The probe also writes /tmp/eegprep_fuzz_integer_literals_<pid>.py and never deletes it. Remove the file at the end of the probe, or build it under a tempfile.TemporaryDirectory().

Test gaps

None. The golden snapshot, the 40-example coverage test, and the 8 import-order cases cover the changed draw behavior. test_draw_integers_are_fixed_for_a_seed pins the generator output itself.

EEGLAB parity notes

None about the draws themselves, since this PR changes only the fuzz harness. The new cases (refloc, exclude with keepref, pop_resample(EEG, freq, fc, df), odd filtorder) are worth checking in the first MATLAB nightly against the commands in the PR comment.

@cursor

cursor Bot commented Nov 18, 2026

Copy link
Copy Markdown

🤖 Problem. Hypothesis 6.169 folds integer literals from already imported local modules into its integer draws. There is no setting to turn that off. The golden file then moves whenever a new module is imported first, which is what #602 (fdlibm constants in gauss.py) and #603 (sigprocfunc package init) hit on macOS and Windows. The old strategies were also a poor sample of real calls: explicit short filter orders, partial montages, average reference only, resample rates of 64, 90, and 100 Hz, and pop_clean_rawdata identical to clean_asr with every other criterion off.

Approach. tests/fuzz/draw.py generates each example from SHA-256 in counter mode with rejection sampling. mix_seed hashes the seed, the target name, and the example index, so one target cannot shift another. The builder records the inclusive range of every integer it asks for. Shrinking replays that trace and binary-searches the widest entries toward the low end, keeping a candidate only when it still diverges with the same signature. Production generation and shrinking no longer call Hypothesis. The original five builders now spend about 70 percent of draws on tutorial and GUI values (automatic filter order, 0.5 to 2 Hz highpass, 30 to 45 Hz lowpass, bandpass and 49-51 or 59-61 notches, average and channel references, exclude, keepref, refloc, resample to the same rate or half or double or 100, 250, or 256 Hz, ASR cutoffs 5, 20, and 3, and the GUI and bids pop_clean_rawdata presets). The other draws cover short data, a flat channel, a NaN run, an odd order, a cutoff at Nyquist, an order below the notch transition, epoched lowpass and resample, and resample fc and df. pop_epoch, pop_select, pop_rmbase, eeg_eegrej, and the clean_* targets were already in the nightly list. pop_runica was not added.

Key code. The seed and the integer draw:

def mix_seed(seed_value: int, function: str, index: int) -> int:
    payload = f"eegprep-fuzz-v1\0{int(seed_value)}\0{function}\0{int(index)}".encode()
    return int.from_bytes(hashlib.sha256(payload).digest()[:16], "little")

integers(low, high) draws uniformly on that inclusive range, or clamps a forced replay value into the live range. Values past the end of a forced trace use low, which is the shrink target.

Tests. A fresh interpreter checks the golden file. Another test imports, before drawing, eegfilt, pop_eegfiltnew, runica, the fuzz targets, the sigprocfunc package, gauss.py, and a new local module whose literals sit at and above 128 (the band Hypothesis actually copies). The case list matches the fresh interpreter. Locally, the same probe, the sigprocfunc package, and gauss.py each change a Hypothesis integer sequence, so that test would have failed under the old generator. 147 fuzz unit tests passed and 3 MATLAB replay tests were deselected. ruff check passed. tolerances.toml was not edited.

MATLAB was not available here. On jamming, point EEGPREP_MATLAB_BATCH_DIR at a directory where tests/matlab/eegprep_batch_engine_serve.m is serving, and EEGPREP_EEGLAB_ROOT at the EEGLAB checkout. Do not pass --file-issues.

export EEGPREP_MATLAB_BATCH_DIR=/tmp/eegprep-matlab-batch
export EEGPREP_EEGLAB_ROOT=src/eegprep/eeglab
uv run python -m tests.fuzz run --output fuzz-out --examples 4 --shrink-budget 12 --max-shrinks 4
uv run python -m tests.fuzz run --output fuzz-out-wide --examples 20 --shrink-budget 12 --max-shrinks 4 --functions pop_eegfiltnew,pop_reref,pop_resample,clean_asr,pop_clean_rawdata --seed 20261012

Replay any saved case with the command stored in its JSON, which is a path from the repository root: uv run python -m tests.fuzz reproduce

Please check that these agree with EEGLAB: a cutoff at Nyquist, odd order 101, and a 59-61 Hz notch of order 40 raise the same text; refloc arrives as a struct; pop_resample receives fc and df in that positional order when they are set, and otherwise uses its own defaults; the GUI preset (burst 20, rejection on, highpass off, flatline 5, correlation 0.8, line noise 4, window 0.25 with tolerances -Inf and 7) and the bids preset (burst 5, rejection off, highpass 0.25 0.75) run; an epoched lowpass of order 40 and an epoched resample match; a flat channel is handled. option_single stays off, and the compared data are float64. A clean_channels threshold flip or a RANSAC difference between this machine and CI's R2024b should be triaged, not folded into a tolerance.

Left for a maintainer. pop_resample still compares data only, so resampled event latencies are not checked. Float32 is not drawn, because option_single and the BLAS kernel move the reref product. A 0.1 Hz highpass is not drawn, because the automatic order does not fit the 1536 sample crop. A reference channel that is also excluded is not drawn, because the MATLAB error text is not confirmed. Python raises "Reference channels cannot also be excluded". If an invalid filter or refloc message differs, the nightly job should file that mismatch.

Comment thread tests/fuzz/harness.py Outdated


def _generate_cases(builder, seed_value: int, examples: int, function: str) -> list[FuzzCase]:
if hasattr(builder, "generate"):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: nothing in the repo defines a builder with a generate method, so this branch never runs. It is also the kind of hasattr check that AGENTS.md asks us to avoid. If it ever ran, the cases it returned would have an empty trace, and shrink_case would skip them without saying so. Suggest deleting it:

Suggested change
if hasattr(builder, "generate"):

(and also delete the return list(builder.generate(seed_value, examples)) line after it)

Comment thread tests/fuzz/harness.py Outdated
if not user and draw.choice((False, False, False, True)):
spec = _draw_epoched_spec(draw)
srate = _event_targets().recording(spec.source).srate
params = _filter_edges(draw, "lowpass", srate)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: _filter_edges takes a Nyquist frequency, but this line passes the full sampling rate. For epoched data the lowpass check therefore becomes hz < 0.9 * srate, when it should be hz < 0.9 * srate / 2. With the 128 Hz epoch file every candidate (≤45 Hz) is still valid, so the golden file stays the same. A faster or slower epoch source would allow lowpass cutoffs above Nyquist. The _draw_filter path already divides by 2.

Suggested change
params = _filter_edges(draw, "lowpass", srate)
params = _filter_edges(draw, "lowpass", srate / 2.0)

Drop the unused generate branch so every case records a shrink trace.

Co-authored-by: Suraj Ranganath <[email protected]>
cursoragent and others added 2 commits November 18, 2026 12:24
MATLAB reref reads every chanlocs field from refloc. A matched error on
reproduce is a successful replay, so that command exits 0.

Co-authored-by: Suraj Ranganath <[email protected]>
The import-order test created that module under /tmp, which Windows does
not have, so the probe failed before the draw ran.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath merged commit eec2f0f into develop Nov 18, 2026
19 of 20 checks passed
cursor Bot pushed a commit that referenced this pull request Nov 18, 2026
…trum-summaries-ab6b

Drop the sigprocfunc pre-import. The draw generator from #640 no longer
reads Hypothesis local constants, and the golden draws still match.

Co-authored-by: Suraj Ranganath <[email protected]>
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