Repository navigation
Description
π€ Auto-generated from the thermo-nuclear whole-codebase code-quality review at commit 8ba958e (tip of PR #190). Part of the Fable 5 Findings epic #193.
Rationale
Several core-numeric and parity tests cannot fail today β assertions are wrapped in try/except -> skipTest, numerics are mocked down to shape/call-count checks, or tolerances are loose enough to hide divergence. This phase comes first by design: every later phase changes numerics or load/save behavior, and those fixes are only safe if the test suite can actually catch a regression. Until these are fixed, a green CI overstates how well the port is verified.
How to approach
Each item is a place where a passing test does not mean the behavior is correct. Fixes should assert observable EEG-dict / numeric / file outcomes, remove assertion-swallowing wrappers (keep the @skipUnless dependency guard, drop the inner try/except), and tighten tolerances to values justified against the MATLAB oracle.
Findings in this phase (7)
Every item below was confirmed by an independent adversarial verification pass against the working tree. Check items off as they land. Full per-finding detail (with verifier notes and full evidence) is in THERMO_NUCLEAR_REVIEW.md on the review branch.
1. Duplicate create_test_eeg fixtures re-implemented in multiple test modules
-
tests/test_ICL_feature_extractor.py(lines 22-39)- Why: tests/fixtures.py already provides create_test_eeg/create_test_eeg_with_ica, and AGENTS.md says to reuse tests/fixtures.py and avoid duplicate fixtures. Several modules re-declare their own module-level create_test_eeg with partial/divergent field sets, so the canonical EEG-dict shape drifts per file and changes to the shared fixture do not propagate.
- Failure mode: An invariant added to the shared fixture (a new required EEG field, corrected times/xmax) is not reflected in the copies, so the copied-fixture tests exercise a stale/incomplete EEG dict and can diverge from real loadset output.
- Fix: Import create_test_eeg from tests/fixtures.py in these modules (extending the shared fixture if a field is missing) and delete the local copies.
- Evidence:
Module-level def create_test_eeg(...) redefined in test_ICL_feature_extractor.py:22, test_clean_artifacts.py:18, test_clean_flatlines.py:18, test_clean_drifts.py:18, test_eeg_picard.py:68, test_eegoβ¦
2. try/except->skipTest swallows AssertionError, so ~152 core-numeric tests can never fail
-
tests/test_clean_artifacts.py(lines 104-126)- Why: Python AssertionError is a subclass of Exception, so a
try: <asserts> except Exception as e: self.skipTest(...)block converts every failing assertion inside it into a SKIP, not a failure. These wrappers blanket the core clean_rawdata/ICA/MNE numeric tests, which are NOT MATLAB-gated and run in ordinary CI. A real regression (e.g. clean_artifacts mutating data when all criteria are off) reports⦠- Failure mode: A genuine numeric regression in clean_artifacts/clean_drifts/clean_asr/eeg_picard/ICL_feature_extractor lands; the assertion raises AssertionError, is caught, and the test is reported as skipped. CI stays green and the bug ships.
- Fix: Delete the blanket try/except->skipTest wrappers and let assertions fail. Where a genuine optional dependency is the only legitimate skip reason, gate with an explicit @skipUnless(_AVAILABLE) at method/class level and let the body raisβ¦
- Evidence:
test_clean_artifacts_all_off: np.testing.assert_array_equal(EEG['data'], self.test_eeg['data']) ... except Exception as e: self.skipTest(f"clean_artifacts all off not available: {e}"). Pattern couβ¦
- Why: Python AssertionError is a subclass of Exception, so a
3. Cross-implementation autocorr check uses rtol=0.1/atol=0.1, loose enough to hide divergence
-
tests/test_eeg_autocorr_fftw.py(lines 316)- Why: test_consistency_with_regular_autocorr compares eeg_autocorr_fftw against eeg_autocorr on identical input and asserts agreement only within 10% relative + 0.1 absolute. For two implementations of the same autocorrelation this is far looser than the float error they should exhibit, so the cross-check provides little protection.
- Failure mode: A real port bug that makes one autocorr path differ by several percent from the other passes this 'consistency' test silently; the only assertion that would catch it is too coarse to trip.
- Fix: Tighten to a float-realistic tolerance (e.g. rtol
1e-5, atol1e-7) consistent with the parity-style tolerances used elsewhere in the autocorr tests, or document why a 10% band is physically expected. - Evidence:
self.assertTrue(np.allclose(result_fftw, result_regular, rtol=0.1, atol=0.1)) under comment 'Check that they're in the same ballpark'.
4. Redundant try/except->skipTest defeats assertions even though @skipUnless already guards the optional dep
-
tests/test_eeg_mne2eeg.py(lines 54-94)- Why: This file is the clearest proof the blanket-skip pattern is not about optional dependencies: the module sets MNE_AVAILABLE and each test already carries
@unittest.skipUnless(MNE_AVAILABLE, 'MNE not available'). The innertry/except Exception -> skipTesttherefore exists solely to swallow real conversion failures, including the structural assertions on nbchan/pnts/trials/srate. - Failure mode: If eeg_mne2eeg produces wrong nbchan/pnts/srate from an MNE Raw object, asserts at lines 88-91 raise AssertionError, the except catches it, and the test reports 'skipped: eeg_mne2eeg raw conversion not available' instead of failing.
- Fix: Remove the inner try/except->skipTest; rely on the existing @skipUnless(MNE_AVAILABLE) for the dependency guard and let the conversion assertions fail loudly.
- Evidence:
@unittest.skipUnless(MNE_AVAILABLE, "MNE not available") on the method, then self.assertEqual(result['nbchan'], n_channels) ... except Exception as e: self.skipTest(f"eeg_mne2eeg raw conversion nβ¦
- Why: This file is the clearest proof the blanket-skip pattern is not about optional dependencies: the module sets MNE_AVAILABLE and each test already carries
5. Clustering-helper test asserts only shapes/ndim, not partitioning behavior, on otherwise-dead helpers
-
tests/test_study_clustering.py(lines 138-162)- Why: optimal_kmeans/robust_kmeans have no runtime callers, so this test is their only safety net, yet it only checks .shape/.ndim/set-equality. The input data has obvious structure ([0,0],[0.1,0] vs [5,5],[5.1,5] vs far point [20,20]) but the test never asserts the points are grouped correctly or that [20,20] is the detected outlier.
- Failure mode: A regression that returns correctly-shaped but wrongly-clustered labels (e.g. an off-by-one in the label-1 indexing shared with pop_clust, or a broken outlier threshold) passes green. The test gives false confidence that the EEGLAB-canonical algorithms work.
- Fix: Assert observable clustering behavior: that the two tight pairs share labels, the labels differ across pairs, and robust_kmeans flags the far row as the outlier; keep shape checks secondary.
- Evidence:
assert optimal_centers.shape == (2, 2) assert optimal_sumd.shape == (2,) assert optimal_distances.shape == (4, 2)
6. ASR tests inject failures into numpy primitives to assert defensive-fallback log strings
-
tests/test_utils_asr.py(lines 339-407)- Why: test_eigendecomposition_failure_handling, test_reconstruction_matrix_failure and test_component_selection_error_handling patch numpy.linalg.eigh / numpy.linalg.pinv / numpy.sum to raise, then assert specific log substrings ('Eigendecomposition failed', 'Failed to calculate inverse', 'Error in component selection'). These assert the existence and wording of over-protective try/except blocks in prodβ¦
- Failure mode: These tests lock in defensive try/except branches that AGENTS.md explicitly discourages; refactoring asr_process to drop a broad except (or rewording a log line) breaks tests even when ASR output is unchanged and correct, while the tests provide no evidence the numeric fallback is actually right.
- Fix: Drop the log-string/error-injection tests (or replace with a real degenerate-covariance input that exercises the fallback and asserts the cleaned-data output is finite/sane), aligning with the project's stance against testing implementationβ¦
- Evidence:
with patch('numpy.sum', side_effect=Exception("Threshold error")): ... self.assertTrue(any('Error in component selection' in msg for msg in log.output)); similarly mock_eigh.side_effect = np.linalgβ¦
7. calc_projector numerics never validated: sphericalSplineInterpolate mocked, only shapes/call-counts asserted
-
tests/test_utils_ransac.py(lines 116-330)- Why: Every TestCalcProjector and TestRansacIntegration test patches
sphericalSplineInterpolate(the actual spherical-spline interpolation kernel) to return random/ones matrices, then asserts only output shape and mock call_count. The projector-assembly math in calc_projector is therefore never checked against a real interpolation, and the many near-duplicate tests differ only in shape parameters. - Failure mode: A bug in how calc_projector stitches per-subset interpolation results into the projector (indexing, channel mapping, real-part handling) passes all tests as long as the final array shape and the number of interp calls are unchanged.
- Fix: Add at least one test that runs calc_projector with the real sphericalSplineInterpolate on a small montage and validates a known property (e.g. reconstruction of a held-out channel within tolerance). Collapse the redundant shape/count casesβ¦
- Evidence:
with patch('eegprep.plugins.clean_rawdata.private.ransac.sphericalSplineInterpolate', side_effect=mock_interp_func) then self.assertEqual(result.shape, expected_shape) and self.assertEqual(mock_iβ¦
- Why: Every TestCalcProjector and TestRansacIntegration test patches
Generated by automated review; verify each finding from first principles before fixing.
Activity
claude commentedon Jun 12, 2026
π€ Plan:
Research
Issue is actionable: each finding cites a file + line range and describes a concrete failure mode. But the cumulative change is multi-module and far beyond the small-fix threshold, so per the agent ground rules I'm posting analysis instead of opening a PR.
Scope on the working tree (develop @ 09d5e5b):
Relevant code
Proposed Approach (design)
This issue is a meta-fix to the test suite, not a single behavioral bug. I recommend splitting it into 5 small, independently-reviewable PRs landed in this order so each PR's CI signal stays interpretable. Every PR runs `./pre-commit.py --fix` + `uv run pytest` (with `EEGPREP_SKIP_MATLAB=1` locally).
PR A β Consolidate `create_test_eeg` fixtures (finding 1). Make `tests/fixtures.py` the single source. Audit each duplicate for fields the local copy adds (`icaweights`, `icasphere`, custom `chanlocs`, `event`) and extend the shared fixture with explicit kwargs rather than hardcoding new defaults. Delete the module-level/class-method copies in the 9 listed files; switch call sites to `from tests.fixtures import create_test_eeg`. No production code changes. Expected diff ~150 LOC of test code.
PR B β Remove assertion-swallowing skip wrappers, batch 1: non-optional-dep tests (finding 2). Target the files where every `skipTest` reason is structural (`clean_artifacts not available`, `clean_drifts not available`, etc.) β the production code is always importable in CI, so the only purpose of the wrappers is to swallow real failures. Mechanical edit: delete the `try:` line + the `except Exception as e: self.skipTest(...)` tail, dedent the body. Files: `test_clean_artifacts.py` (34), `test_clean_asr.py` (15), `test_clean_drifts.py`, `test_clean_rawdata.py`, `test_eeg_picard.py` (12), `test_ICL_feature_extractor.py` (22), `test_ICL_feature_extractor_parity.py`, `test_eeg_autocorr.py`, `test_eeg_autocorr_fftw.py`, `test_eeg_autocorr_welch.py`, `test_eeg_rpsd_parity.py`, `test_topoplot.py`, `test_runamica.py`, `test_runica.py`. After deletion the suite must still pass; if any test now fails legitimately, that is a Phase 1 success and the fix belongs in Phase 3 (#196) β file a follow-up issue, do not re-wrap. Expected diff ~600 LOC deleted, ~0 added.
PR C β Remove inner try/except under existing `@skipUnless` (finding 4) + batch 2 swallow wrappers in optional-dep tests. Same mechanical edit but the files already gate on `MNE_AVAILABLE` / `MATLAB_AVAILABLE` / etc.: `test_eeg_mne2eeg.py` (16), `test_eeg_mne2eeg_epochs.py`, `test_eeg_eeg2mne.py`, `test_eeglabcompat.py`, `test_matlab_path.py`, `test_parity_rng.py`, `test_firfilt_helpers.py`, `test_pop_*.py` (`comments`, `editset`, `epoch`, `firfilt`, `loadset_h5`, `reref`, `rmbase`). Validate that the `@skipUnless` guard is sufficient (it is for the MNE files; spot-check the others before deleting). Expected diff ~400 LOC deleted.
PR D β Tighten autocorr cross-check tolerance (finding 3). One-line change at `tests/test_eeg_autocorr_fftw.py:316`: replace `rtol=0.1, atol=0.1` with the float-realistic band used in the rest of the file. Before committing the value, run the test locally to see the actual divergence β choose the tightest band that passes, document the value in a comment, and if it must stay >1e-3 then file a Phase 3 issue against `eeg_autocorr_fftw` since two implementations of the same autocorrelation should agree to float precision.
PR E β Replace implementation-locking tests with behavioral tests (findings 5, 6, 7).
Risk note. PRs B + C will almost certainly turn previously-skipped tests into failures β that is the point of Phase 1. Treat each new failure as a finding to triage: real bug β Phase 3 issue (#196); flaky test β tighten the test; outdated expectation β fix and document. Do not revert the unwrap to keep CI green.
Out of scope here. Phase 2 #195 (EEG dict / ICA invariants), Phase 3 #196 (correctness bugs), Phase 4 #197 (architecture), Phase 5 #198 (packaging). Numeric regressions discovered in PRs B+C should be filed against those phases, not fixed here.
Stopping before implementation β please confirm the 5-PR split, the "unskipped failures are a feature" stance, and PR-A's approach of extending the shared fixture vs. accepting fixture-shape differences before I open PR A.
suraj-ranganath commentedon Jun 12, 2026
π€ Closing because Phase 1 was completed by merged PR #200 and is included in epic PR #206.
Phase 1: test-suite integrity β make CI able to fail