Skip to content

[fuzz] Preserve float64 oracle input and reject a short ASR reference - #594

Merged
suraj-ranganath merged 14 commits into
developfrom
cursor/fix-fuzz-oracle-transport-0795
Nov 11, 2026
Merged

suraj-ranganath merged 14 commits into
developfrom
cursor/fix-fuzz-oracle-transport-0795

Conversation

@suraj-ranganath

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

Copy link
Copy Markdown
Member

The fuzz oracle receives the exact float64 EEG, including an integer-valued double packed by save -v7. NaN, +Inf, and -Inf are compared separately, and a MATLAB exception or a wrapper that returns its input is an oracle failure. The zero-width ASR fit and the one-channel clean_windows sort stay known EEGLAB defects, including when the channel-axis reference is shorter than one RMS window. clean_asr raises when the selected reference is shorter than one 0.5 s RMS window instead of calibrating on the unselected recording. A finding signature is the function, mechanism, and locus, with the input hash only in the body and repro. Open fuzz issues filed with the old magnitude signatures will not be matched automatically: #576 clean_channels|numeric|1e-5, #577 clean_flatlines|numeric|4e-14, #578 clean_flatlines|shape|na, #581 clean_flatlines|numeric|9e-15, #582 pop_clean_rawdata|numeric|8e1, #583 clean_asr|oracle-only:MatlabExecutionError|na, and #584 clean_channels|numeric|2e-5. An epoched array is compared in the shape pop_loadset holds: a 2-D channel-by-frame array whose column count is a multiple of pnts is the 3-D epoch array, and a two-file one-trial array drops the trailing singleton. A pop_epoch result with no trials is compared on trials, pnts, and events, and the pipeline stops there. Suspending option_single restores the options file and reloads it into the live session.

EEGLAB MATLAB reference (jamming)

Local equivalent of .github/workflows/eeglab-reference.yml, run once under flock ~/matlab.lock. Times are America/Los_Angeles.

cd /home/suraj3/eegprep-bench/pr594-ref
PYTHONPATH=$PWD/src:$PWD \
EEGPREP_EEGLAB_ROOT=/home/suraj3/eegprep-bench/eeglab \
EEGPREP_MATLAB_BATCH_DIR=/home/suraj3/eegprep-bench/pr594-reference/batch \
EEGPREP_SKIP_MATLAB=0 \
QT_QPA_PLATFORM=offscreen MPLBACKEND=Agg \
/home/suraj3/eegprep-bench/eegprep/.venv/bin/python -m pytest tests \
  -vv --eeglab-backend=matlab \
  --eeglab-root=/home/suraj3/eegprep-bench/eeglab \
  --eeglab-suite-root=/home/suraj3/eegprep-bench/eeglab_tests \
  --timeout=1200 --timeout-method=signal --durations=0 \
  --junitxml=/home/suraj3/eegprep-bench/pr594-reference/reference-results/junit.xml

Full suite at 88f574484138334de05ddb595bcb66b05a76c99f

  • EEGLAB: d0963be9d81acc5b66e84f8d3d7c89e3ce127cc4
  • eeglab_tests: fec88f9ffe7c225eb1de8924db8b6a3e0d53a4d9
  • MATLAB: 25.2.0.3360999 (R2025b) Update 7
  • Result: 6 failed, 3647 passed, 55 skipped, 447 subtests passed in 2040.60s (0:34:00). Wall 2046s.

Five of the six failures also fail on origin/develop (2667ef75): missing data/ fixture for the two TestBidsPreproc tests on host jamming; #579 float32 average reference (max_abs 0.161 µV here, 0.109 µV on develop, atol 1e-05); Picard AMARI 5.403292e-05 on both heads (atol 1e-05); and #580 current-figure mismatch ([[1]] vs [[2]]).

test_reference_runica_extended failed in that full session (0.01546 vs tolerance 0.0145) and passed when rerun alone on develop and again alone on a later 594 head (1 passed in 2.05s). This PR does not change runica.

About 32 of the 55 skips are heavy tests that need --run-heavy-reference (the workflow command also omits that flag). The rest are missing plugins, AMICA, a headless pop_chanedit lookup, and similar environment skips.

Nightlies and targeted tests at 5d46ea3bbca12241bdc7bdb1ec1b7b292f2d7cdb

Same EEGLAB, eeglab_tests, and MATLAB. Worktree updated to this head ([fuzz] Close an owned MATLAB backend from one run_session). Imported source was /home/suraj3/eegprep-bench/pr594-ref/src/eegprep. run_session is one function. Both run_session and run_repro restore option_single in a finally by calling MatlabBackend.close() when they created the backend. close() writes the snapshotted options file back and reloads it into the session (resume_eeg_options). The harness has no __enter__, __exit__, atexit hook, or context manager. Run 2026-11-11 06:20:50 to 06:23:46 America/Los_Angeles (UTC-8), one batch server under flock ~/matlab.lock.

~/eeg_options.m sha256 was a8b00dde3a4c616b9585a9435da719c5402d39f139d5a80855521c46b202a506 (option_single = 1) before the run, after the three nightlies, after the pytest suite, after the transport confirm, and after MATLAB stopped.

python -m tests.fuzz run --output ... --seed SEED --examples 4 --shrink-budget 12 --max-shrinks 4

All three default nightlies completed with harness_ok=True, empty sanity, 52 cases, and exit 0 (walls 45s, 49s, 47s). Confirmed findings: 0 on every seed. #582 was recorded as known on 20261110 only, still with identifier MATLAB:badsubscript and stack through fit_eeg_distribution line 395 (reference length 124, oracle returned the input). #583 did not appear.

The former pipeline|pop_select:transport|input case is absent (pipeline 4 examples, 0 divergences). A direct reproduce of that 20261110 repro JSON at this head returned error_class=match, detail=pop_epoch: 0 trials, same input hash. Other written non-finding items: repair_bursts:NoYulewalk on 20261108 (one) and 20261109 (two); both-error Filter order too low on 20261108 (order 106) and 20261109 (order 212); both-error empty pop_epoch range on 20261110. --file-issues was omitted.

MATLAB-backed tests, after the nightlies and in this order, on the same batch directory: tests/test_fuzz_*.py, tests/test_eeglabcompat.py, tests/test_matlab_batch_engine.py. Result: 148 passed, 0 failed, 0 skipped in 20.46s, exit 0. test_run_repro_restores_eeg_options and test_matlab_backend_restores_eeg_options_bytes both passed.

Fixes #576
Fixes #577
Fixes #578
Fixes #581
Fixes #582
Fixes #583
Fixes #584

Open in Web Open in Cursor 

Restore EEG.data from a double MAT variable after pop_loadset, compare
NaN and infinities separately, and file MATLAB failures by cause. The
zero-width ASR fit and the one-channel clean_windows sort stay known
EEGLAB defects.

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

cursor Bot commented Nov 11, 2026

Copy link
Copy Markdown

🤖 Specification for the draft PR.

Problem. MatlabWrapper sent the oracle input through pop_saveset, which writes a float32 .fdt. MATLAB then compared rounded data with EEGPrep's float64 input. That is #576, #577, #578, #581, and #584. #582 is asr_calibrate.m indexing a zero fit width after reference selection (round(3*(0.578:-0.01:0.1445))), which clean_artifacts.m catches and answers by returning the input. #583 is clean_windows.m calling sort(wz) with no dimension, so one channel is sorted across time.

Approach. The bridge writes EEG.data to a double MAT variable, assigns it after pop_loadset, and saves the array MATLAB actually holds. The harness rejects a shape, dtype, NaN, +Inf, -Inf, or value mismatch before any numeric comparison. An identity case carries values float32 cannot represent. Oracle exceptions keep their identifier and stack. A MATLAB exception, or pop_clean_rawdata returning its input, is an oracle failure. The zero-width fit is recognized from the selected reference length, the effective thresholds, and the fit_eeg_distribution stack. The one-channel sort is recognized only for a direct one-channel clean_asr whose selection is not itself a two- or three-window fit. Issues group by cause and input hash. Flatline draws place a run below, at, and above max_flatline_duration * srate, with jitter measured against max_allowed_jitter * eps.

Tests. No MATLAB is available here. tests/test_eeglabcompat.py checks the double round trip and that the restore runs after load and before the target. Harness tests cover separate non-finite masks, transport mismatch, the identity signal, both ASR classifiers, repro identifier and stack, and cause grouping. test_three_rms_windows_skip_zero_fit_widths and test_one_channel_sorts_across_channels lock the EEGPrep behavior. Tolerances are unchanged.

On a MATLAB machine, with EEGLAB and clean_rawdata 85eab7d22f00f1ed36392c96eb0774752d62bd11:

cd /path/to/eegprep
export EEGPREP_EEGLAB_ROOT=/path/to/eeglab
BATCH_DIR=/tmp/eegprep-matlab-batch
mkdir -p "$BATCH_DIR"
# start tests/matlab/eegprep_batch_engine_serve.m against BATCH_DIR and wait for $BATCH_DIR/ready
export EEGPREP_MATLAB_BATCH_DIR="$BATCH_DIR"
uv run python -m tests.fuzz run \
  --output /tmp/fuzz-transport \
  --seed 20261110 \
  --examples 2 \
  --shrink-budget 4 \
  --max-shrinks 2 \
  --functions clean_channels,clean_flatlines,clean_asr,pop_clean_rawdata

Success is harness_ok true and no float32 numeric or shape signatures for those functions. #582 and #583 should not be filed. A remaining ASR oracle failure should keep oracle_identifier and oracle_stack in fuzz-out/repros.

cursoragent and others added 2 commits November 11, 2026 09:20
Record the lasterror clean_artifacts catches, and store that identifier,
stack, selected reference length, and thresholds with the known-defect
outcome and repro.

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

clean_asr replaced a clean_windows selection under 64 samples with the
whole recording, so calibration succeeded on data the reference step had
rejected. asr_calibrate.m:191 errors when that selection is shorter than
round(0.5*srate). Pass the selection through and raise ASRCalibrationError.

Co-authored-by: Suraj Ranganath <[email protected]>
@cursor cursor Bot changed the title [fuzz] Preserve float64 oracle input and classify EEGLAB ASR defects [fuzz] Preserve float64 oracle input and reject a short ASR reference Nov 11, 2026
… sort defect

MATLAB save -v7 stores an integer-valued double in smaller storage while the
array class stays double. Load that class so the pop_reref sanity check does
not report dtype uint8. A correct one-channel sort keeps the 37-sample
reference, so the short-reference error is the #583 outcome and the fit stack
stays on the known defect.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 10:23

@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 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 2m 45s —— View job


Code review

  • Overall assessment: Needs changes. The float64 transport (save_double_input, matlab_restore_input, matlab_capture_input), the separate NaN/+Inf/-Inf masks, the identity sanity case, and the removal of the clean_asr short-reference fallback all look correct. Only a clean_windows error falls back to the whole signal, which matches clean_asr.m, and the moved check matches asr_calibrate.m:188-191. Two issues remain: one changes how nightly findings are grouped and filed, the other is about merge evidence.
  • Highest-risk area: Outcome.signature in tests/fuzz/harness.py, which now includes the input hash for every finding that is not grouped by cause.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  1. A numeric, shape, mask, or exception-mismatch finding now gets a new signature for every input (tests/fuzz/harness.py:205, Outcome.signature). The fallback identity is now self.input_sha256 instead of rounded_magnitude(...). Only transport, oracle-unchanged, and oracle:* causes leave out the hash.

    • publish_findings (tests/fuzz/issues.py:117-140) finds existing issues by exact signature. A recurring EEGPrep numeric defect gets a new issue each night, because every seed shrinks to a different input. The cap of three issues per night hides some of this, but the run never comments on the existing issue. Open [fuzz] issues filed with the old report|numeric|<magnitude> signatures will never match either.
    • In the same run, by_signature (harness.py:971) now keeps one outcome per input, not one per mechanism. Several draws that hit the same mismatch are each shrunk separately and use up the shrink budget and the issue cap.
    • Suggested fix: keep the hash in the issue body and the repro, which the PR already does with - Input sha256:. Key the signature on the mechanism, for example f"{self.mechanism}|{rounded_magnitude(...)}" for numeric and self.mechanism otherwise. Then the _mechanism_key stripping in shrink is no longer needed. If grouping by input hash is intended, say how a defect that recurs across nights is supposed to be deduplicated. Fix this →
  2. The PR description has no MATLAB reference-suite run, and this PR changes core processing code. clean_asr.py drops the fallback to the whole recording when clean_windows returns an empty selection or fewer than 64 samples. asr_calibrate.py moves the S < N check ahead of filtering. A short selected reference used to calibrate on the whole recording. It now raises ASRCalibrationError, and clean_artifacts/pop_clean_rawdata then skip the burst stage. AGENTS.md (Testing) requires running eeglab-reference.yml, or --eeglab-backend=matlab locally, for PRs that change core functions. The command, commits, pass/fail/skip counts, and runtime belong in the PR description before a human approves the merge. The spec comment's "No MATLAB is available here" also means the fuzz-run success criteria have not been checked yet. Suggested fix: dispatch eeglab-reference.yml on this branch and paste the result into the PR description.

Nits

None.

Test gaps

  • test_three_rms_windows_skip_zero_fit_widths (tests/test_clean_asr.py) asserts matlab_window_offsets == [0, 22, 44] and a fit_eeg_distribution call on [1.0, 1.1, 0.9]. These steps only check how the test is built and do not test the zero-width skip. The final asr_calibrate(signal, ...) asserts are the actual regression lock. Consider dropping the setup asserts so unrelated helper changes do not break this test.

EEGLAB parity notes

There is also an inline comment on tests/fuzz/harness.py:205. I did not run tests; this is a read-only review.

Comment thread tests/fuzz/harness.py Outdated
return f"{self.report}|{self.error_class}|{magnitude}"
if _groups_by_cause(self.cause):
return self.mechanism
identity = self.input_sha256 or rounded_magnitude(self.max_abs if self.max_abs > 0 else self.max_rel)

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.

Important: a non-cause finding now gets a new signature for every input.

This line replaces the magnitude bucket with input_sha256 for numeric, shape, nan-mask, exception-mismatch:*, and python-only:* outcomes. Two places look these signatures up:

  • publish_findings matches open issues by exact signature (
    open_issues = [issue for issue in tracker.list_open() if not is_dashboard(issue)]
    by_signature = {}
    for issue in open_issues:
    signature = signature_of(issue)
    if signature and signature not in by_signature:
    by_signature[signature] = issue
    created = 0
    for outcome in findings:
    signature = outcome.signature
    existing = by_signature.get(signature)
    if existing is not None:
    tracker.comment(existing.number, _comment_body(outcome, seed, run_url))
    result.commented.append(existing.number)
    logger.info("fuzz comment on #%s for %s", existing.number, signature)
    continue
    if created >= cap:
    result.unfiled.append(signature)
    logger.info("fuzz cap left %s unfiled", signature)
    continue
    number = tracker.create(
    _issue_title(outcome), _issue_body(outcome, seed, run_url), ["fuzz", "fuzz-unconfirmed"]
    )
    result.created.append(number)
    logger.info("fuzz issue #%s for %s", number, signature)
    by_signature[signature] = OpenIssue(number, _issue_title(outcome), _issue_body(outcome, seed, run_url))
    created += 1
    ). A recurring numeric defect shrinks to a different input on each seed, so it opens a new issue every night instead of commenting on the existing one. Open [fuzz] issues with the old report|numeric|<magnitude> signatures will never match.
  • by_signature in the same run (
    survey.extend(found)
    by_signature: dict[str, Outcome] = {}
    for outcome in survey:
    if outcome.diverged and outcome.signature not in by_signature:
    by_signature[outcome.signature] = outcome
    ordered = sorted(by_signature.values(), key=lambda item: item.max_abs, reverse=True)[:max_shrinks]
    ) now keeps one outcome per input. Several draws that hit one mismatch are each shrunk, and they use up the shrink budget and the cap of three issues.

Suggested fix: the body and repro already record Input sha256. Key the signature on the mechanism, for example f"{self.mechanism}|{rounded_magnitude(...)}" for numeric and self.mechanism otherwise. That also makes _mechanism_key unnecessary in shrink.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 A signature is the identity of a defect, so it has to be stable across nights and across inputs that hit that defect. The magnitude bucket is a bad key: it split one defect across sizes and merged unrelated inputs. The input sha is also a bad key: each seed shrinks to a different input, so publish_findings opens a new issue instead of commenting on the existing one, and by_signature shrinks every draw and spends the shrink budget and the three-issue cap. The signature is now the target function, the mechanism, and the locus. For numeric, shape, and mask that locus is the output field or the nonfinite aspect (data, NaN, +Inf, -Inf, a mask or meta field). For an exception mismatch it is the exception-class pair. For an oracle error it is the MATLAB identifier and the top stack frame. The input sha stays in the issue body and the repro only. Two inputs that hit one defect share a signature and dedupe; two defects in one function do not.

The setup asserts in test_three_rms_windows_skip_zero_fit_widths stay. They check that the fixture really produces three RMS windows and a zero fit width. Without that, the later asr_calibrate asserts can pass for a fixture that never reaches the defect, and the regression test goes vacuous.

cursoragent and others added 5 commits November 11, 2026 10:35
A signature is the function, the mechanism, and the locus. The input hash
and the error magnitude stay in the issue body and the repro, so one defect
dedupes across inputs and nights.

Co-authored-by: Suraj Ranganath <[email protected]>
A 2-D epoch array and a two-file trailing singleton do not have the same
size after MATLAB loads them, so the identity check compared the wrong array.

Co-authored-by: Suraj Ranganath <[email protected]>
A zero-trial epoch cannot reload through an empty .fdt, so the next
step's size check compared [20 600 0] with [0 600 0].

Co-authored-by: Suraj Ranganath <[email protected]>
clear functions leaves the eeg_options script cached, so the session
kept option_single at 0 and a later pop_editoptions wrote that back.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 13:21
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 13:22
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Needs changes (one item, not blocking). I checked the float64 bridge, the clean_asr/asr_calibrate reference changes, the new signature keying, and the MATLAB reference evidence. The two items from the last review are resolved:
    • Outcome.signature is now function + mechanism + locus. The input sha is only in the body and the repro.
    • The PR description now includes the full --eeglab-backend=matlab run: EEGLAB d0963be9, eeglab_tests fec88f9f, 6 failed / 3647 passed / 55 skipped. Five of the six failures also fail on develop, and the runica one passes when rerun alone.
  • Highest-risk area: MatlabWrapper in src/eegprep/functions/adminfunc/eeglabcompat.py, which is runtime package code reached through get_eeglab().
  • Merge recommendation: Needs changes. This PR changes core functions, so it also needs human approval.

Blocking

None.

Important

  1. Fuzz-harness instrumentation now lives in the runtime bridge (eeglabcompat.py:357-362, MatlabWrapper.wrapper). Only tests/fuzz/harness.py reads last_input_data and last_caught_error, through _seen_input and _caught_evidence.
    • Every roundtrip call now does an extra MATLAB save -v7 and a Python loadmat of the whole EEG.data.
    • getattr(self.engine, "last_caught_error", None) probes for an attribute that a real matlab.engine or Octave engine never has. Only the test BatchEngine sets it. AGENTS.md says: "No ad-hoc compatibility hacks such as hasattr(obj, "old_attr")."
    • Suggested fix: keep save_double_input and matlab_restore_input, which are the actual fix. Move the observation hooks into tests/, either as a harness-side capture after the restore or by reading BatchEngine.last_caught_error directly. Then drop last_input_data, last_caught_error, matlab_capture_input, and load_seen_input from the package. Details are in the inline comment. Fix this →

Nits

None.

Test gaps

None. test_three_rms_windows_skip_zero_fit_widths and test_one_channel_sorts_across_channels lock the two documented departures. The author's reason for keeping the setup asserts (so the fixture can't go vacuous) is fair.

EEGLAB parity notes

  • clean_asr.py no longer falls back to the whole recording when the selection is empty or under 64 samples. This now matches clean_asr.m, where only a clean_windows exception falls back. The S < N check now runs before filtering (asr_calibrate.m:188-191), so S = 0 gives a clear ASRCalibrationError before any filtering work.
  • The double restore makes the oracle see EEG.data as EEGLAB holds it with option_single = 0. For two-file one-trial sets and flattened epochs, matlab_held_data follows the eeg_getdatact.m/eeg_checkset.m reshape rules.

Comment on lines +357 to +362
self.engine.eval(matlab_capture_input(seen_filename), nargout=0)
self.last_input_data = load_seen_input(seen_filename)

logger.debug("Running in MATLAB/Octave: %s", eval_str)
self.engine.eval(eval_str, nargout=0)
self.last_caught_error = getattr(self.engine, "last_caught_error", None)

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.

Important: fuzz-harness instrumentation now lives in the runtime bridge.

MatlabWrapper is what the public get_eeglab() returns (

# optionally wrap the engine in a file-roundtripping wrapper
if auto_file_roundtrip:
if rt == 'oct':
engine = MatlabWrapper(engine)
elif rt == 'mat':
engine = MatlabWrapper(engine)
else:
). These lines add three things that only tests/fuzz/harness.py reads (_seen_input, _caught_evidence):

  • matlab_capture_input + load_seen_input: every roundtrip call does an extra MATLAB save -v7 and a Python loadmat of the whole EEG.data. Nothing in src/ reads last_input_data.
  • getattr(self.engine, "last_caught_error", None): a real matlab.engine or Octave engine never has this attribute. Only the test BatchEngine sets it. AGENTS.md (Code Style) says: "No ad-hoc compatibility hacks such as hasattr(obj, "old_attr"); update call sites consistently."

The double restore (save_double_input + matlab_restore_input) is the real fix and belongs here. The observation hooks don't.

Suggested fix: keep save_double_input/matlab_restore_input in MatlabWrapper. Have the harness capture the seen input itself, either with an eegprep_identity-style call after the restore or by reading backend._engine.engine.last_caught_error directly from the BatchEngine. Then drop last_input_data, last_caught_error, matlab_capture_input, and load_seen_input from the package (or move them to tests/).

MatlabWrapper still restores the double array before the call. The fuzz
harness records that array and the target call's caught error, so public
roundtrips no longer save EEG.data or read a test-only engine field.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 13:48
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 13:48
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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


  • Pre-review gate and head check (a644ee0, open, not draft)
  • Read the diff since the last review
  • Review passes and validation
  • Post review

Code review

  • Overall assessment: Looks good. The one Important item from the last review is fixed in a644ee0. MatlabWrapper keeps only the double restore (save_double_input and matlab_restore_input). The capture of the input MATLAB saw, the second save -v7/loadmat, and the getattr(self.engine, "last_caught_error", None) probe have moved out of src/ into the harness _InputObserver. Public get_eeglab() roundtrips no longer pay for fuzz instrumentation.
  • Highest-risk area: _InputObserver in tests/fuzz/harness.py. It recognizes calls by matching the eval strings MatlabWrapper sends. I checked those strings against eeglabcompat.py:276-338:
    • Every wrapper call starts with args = load( or args.args = {};, so the observer state resets once per call.
    • _RESTORE_MARK appears only in the matlab_restore_input string.
    • _TARGET_CALL matches every target eval_str. For nargout > 1 it matches through the trailing OUT = {...}. It does not match the _stash_double_eeg_data, pop_saveset, or save evals that follow. So last_caught_error comes from the target call, not from a later roundtrip eval.
  • Merge recommendation: Safe to merge after human approval. This PR changes core functions (clean_asr.py, asr_calibrate.py), and the PR description has the full --eeglab-backend=matlab run that approval needs. Five of its six failures also fail on develop, and the sixth (runica) passes when rerun alone.

Blocking

None.

Important

None.

Nits

  1. _observed has three lookup paths, and only one runs in production (tests/fuzz/harness.py:1776-1787). The isinstance(engine, _InputObserver) branch and the __dict__ probe exist only for the _SeenEngine test fake. Cutting it down to backend._engine.engine and changing the fake to SimpleNamespace(engine=...) removes the attribute-sniffing. Details are in the inline comment.

Test gaps

None. test_observer_records_the_restored_input_and_the_target_error covers the reset at call start, the capture after the restore, and a stale last_caught_error from a later eval.

EEGLAB parity notes

None new since the last review.

I did not run any tests; this is a read-only review.

Comment thread tests/fuzz/harness.py Outdated
Comment on lines +1776 to +1787
def _observed(backend, name: str):
engine = getattr(backend, "_engine", None)
if isinstance(engine, _InputObserver):
return getattr(engine, name)
if engine is not None and not isinstance(engine, MatlabWrapper):
values = getattr(engine, "__dict__", None)
if isinstance(values, dict) and name in values:
return values[name]
inner = getattr(engine, "engine", None) if engine is not None else None
if isinstance(inner, _InputObserver):
return getattr(inner, name)
return None

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: _observed has three lookup paths, and only one runs in production.

connect_matlab always sets backend._engine to a MatlabWrapper whose .engine is the _InputObserver (

engine = get_eeglab()
engine.engine = _InputObserver(engine.engine)
# eeg_checkset applies option_single on pop_loadset, before the called
# function runs. Leave the recording in double for the session, then
# MatlabBackend.close writes the original options file back.
return engine, suspend_option_single(engine.engine)
). The direct isinstance(engine, _InputObserver) branch and the __dict__ probe only exist so _SeenEngine in tests/test_fuzz_harness.py works. Probing __dict__ for a test double is the kind of attribute-sniffing AGENTS.md (Code Style) warns about: "No ad-hoc compatibility hacks such as hasattr(obj, "old_attr"); update call sites consistently."

Suggested fix: keep only the production path, and have _TransportBackend build SimpleNamespace(engine=<object with last_input_data/last_caught_error>), the way line 747 already does.

def _observed(backend, name: str):
    engine = getattr(backend, "_engine", None)
    observer = getattr(engine, "engine", None)
    return getattr(observer, name, None) if isinstance(observer, _InputObserver) else None

(If the fake stays a plain object, drop the isinstance and use getattr(observer, name, None).)

cursoragent and others added 2 commits November 11, 2026 13:51
The harness looks at backend._engine.engine when that object is the
input observer. Test doubles use the same shape.

Co-authored-by: Suraj Ranganath <[email protected]>
run_repro() suspended option_single and returned without close(), so a
later backend snapshotted the leaked file. Close a backend this module
creates, including run_session, and restore on context exit.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 14:15
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 14:15
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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


  • Pre-review gate and head check (091fc23, open, not draft)
  • Read the diff since the last review (a644ee0..091fc23)
  • Review passes and validation
  • Post review

Code review

  • Overall assessment: Looks good, with two small nits. The nit from the last review is fixed in 5fdc80b. _observed now reads only backend._engine.engine, and the test fakes build a real _InputObserver inside SimpleNamespace(engine=...). Commit 091fc23 fixes a real leak: run_repro and run_session used to create a MatlabBackend and never close it, so option_single stayed suspended after a direct repro. Both now close a backend they created in a finally, and leave a backend the caller passed in alone. The CLI path, where main owns the backend and closes it, still closes it exactly once.
  • Highest-risk area: The cleanup of a MatlabBackend in tests/fuzz/harness.py (run_session, run_repro, MatlabBackend.close). test_run_repro_restores_eeg_options covers both the direct run_repro call and main(["reproduce", ...]).
  • Merge recommendation: Safe to merge after human approval. This PR changes core functions (clean_asr.py, asr_calibrate.py). The approval evidence is the full --eeglab-backend=matlab run in the PR description at 88f5744. The two commits since then touch only tests/.

Blocking

None.

Important

None.

Nits

  1. MatlabBackend.__enter__/__exit__ and the atexit hook are unused (tests/fuzz/harness.py:787-824).
    • All three owners of a backend (run_session, run_repro, the CLI main) already close it in a finally. Nothing uses with MatlabBackend(), and no test exercises the atexit path.
    • AGENTS.md says: "No speculative configurability, future-proofing, or error handling for impossible states."
    • Suggested fix: drop __enter__, __exit__, atexit, _restore_at_exit, and _drop_exit_hook. Also update the PR description, which says __exit__ calls resume_eeg_options.
  2. _run_session_body repeats all 16 keyword parameters and their defaults from run_session (tests/fuzz/harness.py:1029-1074). A changed default has to be edited in both places, and if only the inner one changes, the wrapper's default silently wins. Suggested fix: keep one function and wrap its body in try/finally, as run_repro does, or use contextlib.ExitStack to keep the current indentation.
  3. The new test imports inside the function body (tests/test_fuzz_harness.py:775, from tests.fuzz.__main__ import main). There is no import cycle, and AGENTS.md says: "All imports go at the top. No local imports except for circular dependency breaks or optional dependency guards." Suggested fix: move it to the module imports.

Test gaps

None. test_run_repro_restores_eeg_options checks that eeg_options.m is byte-for-byte restored and that option_single is back to 1, both for run_repro and for the reproduce CLI.

EEGLAB parity notes

None new since the last review. The two commits since a644ee0 change only tests/fuzz/harness.py and tests/test_fuzz_harness.py.

I did not run any tests; this is a read-only review. Nits 1 and 2 also have inline comments.

Comment thread tests/fuzz/harness.py Outdated
Comment on lines +787 to +805
@@ -676,14 +802,26 @@ def run(self, case: FuzzCase, eeg: dict) -> SideResult:
def engine(self):
if self._engine is None:
self._engine, self._options = connect_matlab()
atexit.register(self.close)

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: __enter__/__exit__ and the atexit hook have no caller that needs them.

All three owners of a MatlabBackend already close it in a finally:

  • run_session:

    eegprep/tests/fuzz/harness.py

    Lines 1029 to 1053 in 091fc23

    owns_oracle = oracle_backend is None
    if owns_oracle:
    oracle_backend = MatlabBackend()
    try:
    return _run_session_body(
    seed_value=seed_value,
    output_dir=output_dir,
    examples=examples,
    shrink_budget=shrink_budget,
    max_shrinks=max_shrinks,
    issue_cap=issue_cap,
    python_backend=python_backend,
    oracle_backend=oracle_backend,
    strategies=strategies,
    sanity=sanity,
    materialize=materialize,
    tolerances=tolerances,
    tracker=tracker,
    run_url=run_url,
    summary_path=summary_path,
    functions=functions,
    )
    finally:
    if owns_oracle:
    oracle_backend.close()
  • run_repro:

    eegprep/tests/fuzz/harness.py

    Lines 1225 to 1242 in 091fc23

    owns_oracle = oracle_backend is None
    if owns_oracle:
    oracle_backend = MatlabBackend()
    try:
    outcome = evaluate_case(
    case,
    materialize or materialize_eeg,
    python_backend or PythonBackend(),
    oracle_backend,
    load_tolerances(),
    )
    expected = payload.get("input_sha256", "")
    if expected and outcome.input_sha256 != expected:
    raise RuntimeError(f"input hash {outcome.input_sha256} does not match saved {expected}")
    return outcome
    finally:
    if owns_oracle:
    oracle_backend.close()
  • the CLI main:
    python = PythonBackend()
    if args.oracle == "fake":
    oracle = FakeOracle(args.fake_mode, python)
    else:
    oracle = MatlabBackend()
    try:
    return _run(args, python, oracle)
    finally:
    close = getattr(oracle, "close", None)
    if close is not None:
    close()

Nothing in the repo uses with MatlabBackend(), and no test exercises the atexit path. AGENTS.md (Code Style) says "Do not add features beyond what was asked. No speculative configurability, future-proofing, or error handling for impossible states." The hook also adds _restore_at_exit/_drop_exit_hook state just to undo itself.

Suggested fix: drop __enter__, __exit__, atexit, _restore_at_exit, and _drop_exit_hook, and keep close() as it was at a644ee0. The finally blocks in run_session and run_repro are what fixes the repro leak. Also update the PR description, which says __exit__ calls resume_eeg_options.

Comment thread tests/fuzz/harness.py Outdated
Comment on lines +1029 to +1074
owns_oracle = oracle_backend is None
if owns_oracle:
oracle_backend = MatlabBackend()
try:
return _run_session_body(
seed_value=seed_value,
output_dir=output_dir,
examples=examples,
shrink_budget=shrink_budget,
max_shrinks=max_shrinks,
issue_cap=issue_cap,
python_backend=python_backend,
oracle_backend=oracle_backend,
strategies=strategies,
sanity=sanity,
materialize=materialize,
tolerances=tolerances,
tracker=tracker,
run_url=run_url,
summary_path=summary_path,
functions=functions,
)
finally:
if owns_oracle:
oracle_backend.close()


def _run_session_body(
*,
seed_value: int,
output_dir: Path,
examples: int = 6,
shrink_budget: int = 12,
max_shrinks: int = 4,
issue_cap: int = 3,
python_backend=None,
oracle_backend=None,
strategies: dict | None = None,
sanity: list[FuzzCase] | None = None,
materialize: Materialize | None = None,
tolerances: dict[str, Tolerance] | None = None,
tracker=None,
run_url: str = "",
summary_path: Path | None = None,
functions: tuple[str, ...] | None = None,
) -> SessionResult:

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: _run_session_body copies the whole 16-keyword signature and its defaults just to add a finally.

The signature is now written twice, with defaults (examples=6, shrink_budget=12, max_shrinks=4, issue_cap=3) in both places. A new option, or a changed default, has to be edited in both places. If only one is updated, the wrapper's value silently wins.

Suggested fix: keep a single function. Create the backend at the top of run_session and wrap the existing body in try: ... finally: if owns_oracle: oracle_backend.close(), the way run_repro does it in this same commit. If the extra indentation is the concern, contextlib.ExitStack with stack.callback(oracle_backend.close) when owns_oracle keeps the body at its current indentation.

Drop the duplicated session signature, the unused context manager, and the
atexit hook. run_repro and run_session still restore option_single in finally.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 14:27
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 14:27
@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

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


  • Pre-review gate and head check (5d46ea3, open, not draft)
  • Read the diff since the last review (091fc23..5d46ea3)
  • Review passes and validation
  • Post review

Code review

  • Overall assessment: Looks good. Commit 5d46ea3 fixes the two inline nits from the last review:
    • MatlabBackend no longer has __enter__/__exit__, the atexit hook, _restore_at_exit, or _drop_exit_hook. close() is back to snapshot, clear, then resume_eeg_options, and it does nothing the second time it runs. Nothing in tests/ still refers to the removed names.
    • _run_session_body is gone. run_session is one function again, with its body inside try/finally, the same way run_repro does it. I checked the body after re-indenting it. All three early return failed paths, and the normal return, go through the finally. The backend is closed only when run_session created it (owns_oracle). The only other changes are line wraps from ruff.
  • Highest-risk area: Restoring option_single when the harness owns the backend (run_session and run_repro at tests/fuzz/harness.py:1008-1187). test_run_repro_restores_eeg_options and test_matlab_backend_restores_eeg_options_bytes cover it. The PR description reports both passing against MATLAB at this head, and ~/eeg_options.m had the same sha256 before and after every run.
  • Merge recommendation: Safe to merge after human approval. This PR changes core functions (clean_asr.py, asr_calibrate.py). The approval evidence is the full --eeglab-backend=matlab run at 88f5744 in the PR description. All commits since then change only tests/.

Blocking

None.

Important

None.

Nits

None. I dropped my earlier nit about the import inside the function body (tests/test_fuzz_harness.py:775). It follows the existing from tests.fuzz.__main__ import main at line 1285 on develop, so it matches local style.

Test gaps

None.

EEGLAB parity notes

None new since the last review. This commit changes only tests/fuzz/harness.py.

Checked for correctness bugs, regressions in the session and repro cleanup paths, and CLAUDE.md/AGENTS.md compliance. I did not run any tests; this is a read-only review.

@suraj-ranganath
suraj-ranganath merged commit f0b9fd5 into develop Nov 11, 2026
10 checks passed
cursor Bot pushed a commit that referenced this pull request Nov 11, 2026
Keep the #594 changelog entries and caught-error payload. The fake
server still publishes that result by rename, and restart still
deletes leftover res_*.mat.

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

2 participants