Repository navigation
[fuzz] Preserve float64 oracle input and reject a short ASR reference - #594
Conversation
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]>
|
🤖 Specification for the draft PR. Problem. Approach. The bridge writes Tests. No MATLAB is available here. On a MATLAB machine, with EEGLAB and clean_rawdata 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_rawdataSuccess is |
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]>
… 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]>
There was a problem hiding this comment.
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 finished @suraj-ranganath's task in 2m 45s —— View job Code review
BlockingNone. Important
NitsNone. Test gaps
EEGLAB parity notes
There is also an inline comment on |
| 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) |
There was a problem hiding this comment.
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_findingsmatches open issues by exact signature (). 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. OpenLines 116 to 141 in ac710a0
[fuzz]issues with the oldreport|numeric|<magnitude>signatures will never match.by_signaturein the same run () 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.Lines 970 to 975 in ac710a0
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.
There was a problem hiding this comment.
🤖 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.
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]>
Co-authored-by: Suraj Ranganath <[email protected]>
|
Claude finished @suraj-ranganath's task in 1m 3s —— View job Code review
BlockingNone. Important
NitsNone. Test gapsNone. EEGLAB parity notes
|
| 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) |
There was a problem hiding this comment.
Important: fuzz-harness instrumentation now lives in the runtime bridge.
MatlabWrapper is what the public get_eeglab() returns (
eegprep/src/eegprep/functions/adminfunc/eeglabcompat.py
Lines 530 to 536 in d180812
tests/fuzz/harness.py reads (_seen_input, _caught_evidence):
matlab_capture_input+load_seen_input: every roundtrip call does an extra MATLABsave -v7and a Pythonloadmatof the wholeEEG.data. Nothing insrc/readslast_input_data.getattr(self.engine, "last_caught_error", None): a realmatlab.engineor Octave engine never has this attribute. Only the testBatchEnginesets it. AGENTS.md (Code Style) says: "No ad-hoc compatibility hacks such ashasattr(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]>
|
Claude finished @suraj-ranganath's task in 1m 16s —— View job
Code review
BlockingNone. ImportantNone. Nits
Test gapsNone. EEGLAB parity notesNone new since the last review.
I did not run any tests; this is a read-only review. |
| 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 |
There was a problem hiding this comment.
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 (
Lines 904 to 909 in a644ee0
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).)
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]>
|
Claude finished @suraj-ranganath's task in 1m 15s —— View job
Code review
BlockingNone. ImportantNone. Nits
Test gapsNone. EEGLAB parity notesNone new since the last review. The two commits since I did not run any tests; this is a read-only review. Nits 1 and 2 also have inline comments. |
| @@ -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) | |||
There was a problem hiding this comment.
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:Lines 1029 to 1053 in 091fc23
run_repro:Lines 1225 to 1242 in 091fc23
- the CLI
main:eegprep/tests/fuzz/__main__.py
Lines 48 to 59 in 091fc23
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.
| 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: |
There was a problem hiding this comment.
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]>
|
Claude finished @suraj-ranganath's task in 39s —— View job
Code review
BlockingNone. ImportantNone. NitsNone. I dropped my earlier nit about the import inside the function body ( Test gapsNone. EEGLAB parity notesNone new since the last review. This commit changes only 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. |
Co-authored-by: Suraj Ranganath <[email protected]>
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]>
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 underflock ~/matlab.lock. Times are America/Los_Angeles.Full suite at
88f574484138334de05ddb595bcb66b05a76c99fd0963be9d81acc5b66e84f8d3d7c89e3ce127cc4fec88f9ffe7c225eb1de8924db8b6a3e0d53a4d9Five of the six failures also fail on
origin/develop(2667ef75): missingdata/fixture for the twoTestBidsPreproctests on hostjamming; #579 float32 average reference (max_abs0.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_extendedfailed 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 changerunica.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 headlesspop_chaneditlookup, and similar environment skips.Nightlies and targeted tests at
5d46ea3bbca12241bdc7bdb1ec1b7b292f2d7cdbSame 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_sessionis one function. Bothrun_sessionandrun_reprorestoreoption_singlein afinallyby callingMatlabBackend.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__,atexithook, or context manager. Run 2026-11-11 06:20:50 to 06:23:46 America/Los_Angeles (UTC-8), one batch server underflock ~/matlab.lock.~/eeg_options.msha256 wasa8b00dde3a4c616b9585a9435da719c5402d39f139d5a80855521c46b202a506(option_single = 1) before the run, after the three nightlies, after the pytest suite, after the transport confirm, and after MATLAB stopped.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 identifierMATLAB:badsubscriptand stack throughfit_eeg_distributionline 395 (reference length 124, oracle returned the input). #583 did not appear.The former
pipeline|pop_select:transport|inputcase is absent (pipeline4 examples, 0 divergences). A direct reproduce of that 20261110 repro JSON at this head returnederror_class=match,detail=pop_epoch: 0 trials, same input hash. Other written non-finding items:repair_bursts:NoYulewalkon 20261108 (one) and 20261109 (two); both-errorFilter order too lowon 20261108 (order 106) and 20261109 (order 212); both-error emptypop_epochrange on 20261110.--file-issueswas 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_optionsandtest_matlab_backend_restores_eeg_options_bytesboth passed.Fixes #576
Fixes #577
Fixes #578
Fixes #581
Fixes #582
Fixes #583
Fixes #584