Skip to content

[core] Fix correctness bugs, silent failures & misleading contracts (Fable 5 Phase 3) - #203

Merged
suraj-ranganath merged 1 commit into
fable5/epicfrom
fable5/phase3-correctness
Jun 12, 2026
Merged

suraj-ranganath merged 1 commit into
fable5/epicfrom
fable5/phase3-correctness

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Replace silent fallbacks with real dispatch, make validated-but-ignored options take effect or fail loudly, and fix index/boundary errors across loading, event/channel selection, sigproc, the GUI/console session, the CLI, and the ASR/clean pipeline. Each fix lands with a test that reproduces the bug first. Notable: pop_loadset/pop_fileio stop swallowing load errors, the console now zero-bases pop_select numeric channels so 1-based history replays correctly, epoch()/eegrej() boundary math is corrected, asr_calibrate/clean_artifacts/asr_process stop silently degrading, and CLI schema/exit-code contracts match behavior.

Fixes #196

Part of the Fable 5 Findings epic (#193); addresses issue #196.

Replace silent fallbacks with real dispatch, make ignored options take
effect or fail loudly, and fix index/boundary errors — each with a test
that reproduces the bug first.

- Loading: pop_loadset dispatches HDF5 vs scipy by the actual file instead
  of swallowing every error into an HDF5 retry; pop_fileio dispatches .mat
  by content instead of silently importing a broken .set as a raw array;
  pop_loadset_h5 drops the hard-coded emoji fixture and decodes by one rule.
- Indexing/events: pop_select chantype selection no longer crashes
  (eeg_decodechan return unpacked) and the console zero-bases pop_select
  numeric channels so 1-based history replays correctly; eeg_eegrej no
  longer drops first/last events by latency; pop_editeventvals epoched
  latency display/edit is symmetric (ms<->points) and no longer raises.
- sigproc: epoch() boundary check fixed (no negative-index slice); eegrej()
  shifts boundary latencies by base region spans; runamica() cleans its
  temp dir on failure without swallowing the error.
- Session: console CURRENTSET reassignment guarded by a regression test;
  IMPLEMENTED_ACTIONS now has a test enforcing it matches dispatch routing;
  GUI dataset commit applies history only after the abort check; the
  headplot menu action commits its spline edit through the session.
- CLI: pipeline gains the negative-edge filter guard the subcommand has;
  --quiet/--verbose/--no-progress are wired; the self-describing schema
  covers all required params and stops marking --output required under
  --overwrite; bids dispatches by format and propagates exit codes.
- ASR/clean: clean_flatlines walrus precedence fixed; asr_calibrate raises
  on unsupported sample rates; clean_artifacts/clean_asr/asr_process no
  longer swallow failures and re-insert ignored channels per EEGLAB.
- Other: newtimef _is_on uses correct whitelist semantics and its dead
  params fail loudly; compute_pac passes through title/vert/newfig;
  std_precomp recompute and std_makedesign delfiles take effect; EEGobj
  raises on unknown attributes; gen_derived_fpath honors ${root}; ICLabel
  validates icawinv before dereferencing it.
@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Specification (PR >500 LOC; full per-finding detail in #196, epic #193)

Problem. 38 confirmed findings where the running program produced a wrong result, crashed, silently did the wrong thing, or silently ignored input: except Exception blocks that masked real .set load failures behind an HDF5/raw-array retry; a pop_select chantype crash and a 1-based-history vs 0-based-API off-by-one that mis-selects channels on replay; off-by-one boundary math in epoch()/eegrej(); ASR/clean code that silently degraded (trivial filter for unsupported srate, broad excepts disabling artifact removal, dropped channel re-insertion); options validated and recorded but never applied (std_precomp recompute, std_makedesign delfiles, newtimef overlap/plotphase); CLI schemas that contradict the CLI; and guards that ran after the value they protect was dereferenced.

Approach. For silent fallbacks: dispatch on the real condition (file format / content) or narrow the except so genuine failures surface. For ignored options: implement the documented effect, or fail loudly when set to a non-default. For schema/contract mismatches: make the self-describing contract match behavior. For index bugs: make the MATLAB-1-based / Python-0-based boundary explicit and correct (the console converter now zero-bases pop_select numeric channels exactly as it already did for pop_reref, keeping history 1-based for EEGLAB parity while replay selects the right channels). Each finding was reproduced by a failing test before the fix.

Scope discipline. Work was split across 9 file-clusters with hard per-cluster allowlists; both reviewers confirmed zero out-of-allowlist source edits and no weakened/deleted tests. Three findings were correctly deferred as out-of-allowlist and are noted below.

Tests. Full affected suite (28 source files + new/updated tests, incl. 3 new test modules): 645 passed, MATLAB-gated skips only, 0 failures; ruff and pre-commit clean. long_task.py logger and the console CURRENTSET-overwrite findings were verified already-resolved upstream (6cb7e14 "Address console stack review findings") and are now covered by regression guard tests rather than re-fixed.

Deferred to follow-ups (out of this phase's allowlist; flagged in-code):

  • newcrossf.py has the identical _is_on blacklist bug as newtimef — covered by the Phase 4 is_on() consolidation.
  • pop_load_frombids.py leaves EEG['etc'] as an array so .set files cannot receive BIDS sidecar metadata (root cause behind the CLI bids IndexError; the CLI now dispatches by format to avoid it).
  • clean_channels.py omits clean_channel_mask when it removes zero channels (handled defensively in clean_artifacts here).

@claude

claude Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

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


Code Review — PR #203

  • Gather diff vs origin/fix/fresh-uv-console
  • Correctness & regression pass
  • EEGLAB parity & data-structure pass
  • Test coverage pass
  • Post review

Code review

  • Overall assessment: Safe to merge.
  • Highest-risk area: Contract/return-type changes (eeg_compare, eeg_decodechan/eeg_lat2point tuple unpacking) and the console pop_select 1-based→0-based conversion.
  • Merge recommendation: Safe to merge.

I verified the changes that can't be judged from the diff alone against their surrounding context. The fixes are sound and each lands with a reproducing test:

  • eeg_decodechan / eeg_lat2point tuple unpacking — confirmed both functions return tuples ((chaninds, chanlist_out) and (newlat, flag)). The prior inds = eeg_decodechan(...) in pop_select and float(eeg_lat2point(...)) in pop_editeventvals were latent bugs (the latter only hit when trials > 1); the new inds, _ = … / newlat, _ = …; float(newlat.item()) are correct.
  • eegrej.py boundary math — base_durations is defined (L123) before the new len(base_durations) > 1 block; shifting later boundaries by base spans rather than augmented durations matches EEGLAB eegrej.m.
  • runamica.py cleanup — shutil is imported and tmp_created/outdir are bound before the try; the except BaseException re-raises, so no double-removal with the later if cleanup block.
  • pop_spectopo.py — numeric_vector and Any are both imported; the new guard rejects unsupported plotchan/icamode instead of silently ignoring them.
  • _is_boundary_event guard in eeg_eegrej — exists and is used consistently; the guard correctly prevents dropping genuine stimulus events at sample 0 / pnts.
  • EEG_BIDS/bids.py ${root} → {root} — genuine fix: the rest of the package (bids_preproc.py) uses {root} with .format(root=…), so the old ${root} default never substituted. os.path.join also removes the brittle f-string path joins.
  • newtimef._is_on stricter semantics — checked the call sites (plot/plotersp/plotitc default "on", plotphase default "off"); all defaults map identically under the new {"1","on","true","yes"} rule, so no default flips.
  • clean_artifacts removal of EEG['event'] = [] — no remaining event handling exists in the function, so the old # will be restored later comment described code that never ran; events now flow through pop_select (which doesn't disturb time-based latencies on channel selection). This is a correctness improvement, not a regression.
  • eeg_compare bool→str return — the only caller (redefine_functions.py:45) just passes the value through, so the contract change is safe.

Blocking

None.

Important

None.

Nits

  • discovery.py: the capability key requires_output was renamed to requires_output_or_overwrite. This is intentional (contract-matches-behavior), and it's only consumed within discovery.py, but any external tooling that introspected the old key name will need updating. Worth a line in the CLI migration/contract docs if such consumers exist.
  • console.py::_convert_pop_select only zero-bases positional 'channel'/'nochannel'/'rmchannel' name/value pairs (not keyword-arg form). This is the right call — it exactly mirrors the existing _convert_pop_reref behavior and history is emitted positionally — so no change requested; flagging only so the symmetry is intentional and documented.

Test gaps

None. Coverage is appropriately scoped: tuple-unpacking fixes (test_pop_select, test_pop_editeventvals), boundary math (test_sigproc_eegrej, test_eeg_eegrej, test_epoch), format dispatch (test_pop_loadset, test_cli_*), ASR loud-failure paths (test_utils_asr, test_clean_asr, test_clean_artifacts, test_clean_flatlines), and the console 1-based replay (test_console_workspace).

EEGLAB parity notes

  • The console pop_select numeric-channel conversion keeps history 1-based (EEGLAB-facing) while replay selects 0-based — consistent with the existing pop_reref handling and the correct boundary discipline per AGENTS.md.
  • asr_calibrate now raises on unsupported sampling rates (mirroring MATLAB's asr_calibrate:NoYulewalk) rather than silently degrading to a difference filter — better parity and no silent miscalibration.

Checked for correctness bugs, EEGLAB parity, data-structure compatibility, changed-behavior tests, and CLAUDE.md/AGENTS.md compliance.
• Branch: fable5/phase3-correctness

@suraj-ranganath
suraj-ranganath changed the base branch from fix/fresh-uv-console to fable5/epic June 12, 2026 04:32
@suraj-ranganath
suraj-ranganath merged commit cde0d38 into fable5/epic Jun 12, 2026
1 check passed
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.

1 participant