Skip to content

Set up parity testing harness for agentic development - #43

Closed
suraj-ranganath wants to merge 9 commits into
developfrom
feat/parity-harness-foundation
Closed

suraj-ranganath wants to merge 9 commits into
developfrom
feat/parity-harness-foundation

Conversation

@suraj-ranganath

@suraj-ranganath suraj-ranganath commented Apr 30, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR sets up the foundational testing harness needed to guide agentic development of EEGPREP toward EEGLAB parity.

  • Adds a new eegprep.parity package for manifest loading, known deviations, oracle backend selection, comparison utilities, and parity reporting.
  • Adds manifest-driven parity governance via packaged TOML resources for tolerance profiles, parity cases, tiers, oracle modes, and approved deviations.
  • Adds reusable comparators for numeric outputs, EEG structures, events/epochs, workflow traces, stage outputs, and visual outputs.
  • Adds oracle backend abstractions for live MATLAB Engine, MATLAB batch CLI, and artifact-backed references.
  • Adds a pytest-based harness smoke test suite and pytest configuration.
  • Updates CI to install test dependencies, validate the parity manifest, and run tests through pytest.
  • Documents the harness architecture and MATLAB MCP parity-debugging workflow in HARNESS.md.

Why

The goal is to make EEGPREP a production-quality Python equivalent of EEGLAB. Before broad agentic conversion work, we need a rigorous harness that makes expected parity behavior explicit and continuously testable across math, data structures, workflows, saved artifacts, and eventually visual/UI behavior.

Validation

  • Ran harness smoke tests locally during implementation.
  • Verified python -m eegprep.parity --format json manifest inspection path.
  • Verified MATLAB MCP setup separately on the development server for interactive oracle/debug workflows.

@claude

claude Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Code Review: PR #43 — Parity Testing Harness

This is a well-structured infrastructure PR that establishes the right foundations for agentic EEGLAB parity work. The architecture is sound and the layering (config → compare → oracle → report) is clean. Below is detailed feedback organized by file and theme.


Overview

The PR introduces:

  • eegprep.parity package with config, comparison, oracle, and reporting layers
  • TOML manifest + deviation registry for governance
  • Smoke test suite in tests/test_parity_harness.py
  • CI switch from unittest to pytest

Issues and Suggestions

compare.py

Fragile positional indexing in stage_comparison.py (medium severity)

The refactored compare_eeg_data() accesses result.children[0] by position:

data_result = result.children[0]

compare_stage_outputs() builds children in a fixed order [data_result, struct_result, event_result, epoch_result] today, but if that order changes, this breaks silently. Consider indexing by label or using a named attribute approach.

Duplicate failures propagation in _compare_mapping() (low severity)

if not child.passed:
    failures.extend(child.failures)

Failures are bubbled from children into the parent's failures list and also accessible via children. This leads to duplicate failure messages in to_dict() output — the parent lists them and each child repeats them. A reader looking at the top-level result will see the same message multiple times. Consider only keeping failures at the leaf level, or at least documenting the intention.

Broad exception suppression in _is_numeric_array() (low severity)

try:
    arr = np.asarray(value)
except Exception:
    return False

Silently catching all exceptions can hide legitimate errors (e.g., memory errors, keyboard interrupts). At minimum use except (TypeError, ValueError).

Visual comparison tolerances are overly strict by default

compare_visual_output() defaults to atol=0.0, which means even a 1-bit rendering difference will fail. Since plot rendering is non-deterministic across platforms/font renderers, the zero tolerance will cause spurious failures in CI unless all agents run on identical systems. Consider defaulting to a small non-zero atol (e.g. 1/255 for 8-bit images), or document explicitly that callers must set this.

Missing file path test for compare_visual_output

The isinstance(image, (str, Path)) branch in _visual_array() (triggering mpimg.imread) is never exercised in the test suite. This is a real code path that needs a test.


config.py

Inconsistent type annotation style (style)

The file mixes Dict[str, Any] / Optional[float] (from typing) with dict[str, Any] / str | Path. With from __future__ import annotations at the top, all of these are strings at runtime, but the inconsistency is confusing. Pick one style — for Python 3.10+, prefer the built-in forms (dict, str | None, etc.) and drop from typing import Dict, Optional.

Fragile resource path resolution (low severity)

def _resource_path(filename: str) -> Path:
    return Path(__file__).resolve().parent.parent / "resources" / filename

This relies on the module's location in the installed package tree. If the package is restructured or resources are moved, this silently returns a wrong path. The idiomatic approach for packaged resources is importlib.resources (Python 3.9+) or importlib.files() (3.9+):

from importlib.resources import files
def _resource_path(filename: str) -> Path:
    return files("eegprep.resources").joinpath(filename)

oracle.py

Overly complex resolve_oracle_backend() logic (medium severity)

order = [preferred_backend] if preferred_backend else [
    OracleBackend.LIVE_MATLAB_ENGINE,
    OracleBackend.LIVE_MATLAB_BATCH,
    OracleBackend.ARTIFACT_ORACLE,
]
if preferred is None and artifact_root is None:
    order = [OracleBackend.LIVE_MATLAB_ENGINE, OracleBackend.LIVE_MATLAB_BATCH]

When preferred is None, preferred_backend is also None, so the else branch always executes and sets order to the full 3-item list — which is then immediately overwritten by the if preferred is None block. The first else branch's ARTIFACT_ORACLE entry is dead code when preferred is None and artifact_root is None. This should be simplified:

if preferred_backend is not None:
    order = [preferred_backend]
elif artifact_root is not None:
    order = [OracleBackend.LIVE_MATLAB_ENGINE, OracleBackend.LIVE_MATLAB_BATCH, OracleBackend.ARTIFACT_ORACLE]
else:
    order = [OracleBackend.LIVE_MATLAB_ENGINE, OracleBackend.LIVE_MATLAB_BATCH]

ArtifactOracle.load_json() double-reads text (minor)

return json.loads(self.resolve(relative_path).read_text())

Opening as binary (rb) and using json.load(fh) is more memory-efficient for large artifacts. Or at minimum pass encoding='utf-8' to read_text().

Long line in MatlabBatchOracle.run()

The method signature exceeds 100 characters. Break it across lines for readability.


report.py

Missing encoding='utf-8' (portability)

target.write_text(...)

Both write_markdown_report() and write_json_report() should pass encoding='utf-8' to avoid platform-dependent behavior on Windows.


__main__.py

info.__dict__ breaks encapsulation

"backends": {backend.value: info.__dict__ for backend, info in backends.items()},

dataclasses.asdict(info) is the correct approach and is safe against future class changes. __dict__ can include unexpected internal state.


Top-level __init__.py

Heavy namespace pollution (design concern)

Exporting 20 parity symbols directly into eegprep.* means every import eegprep now loads the entire parity subpackage. For downstream users who don't use parity utilities, this adds unnecessary import overhead and clutters eegprep.__all__. Consider keeping parity utilities under eegprep.parity and only re-exporting the 2-3 most commonly needed symbols (e.g., OracleBackend, ComparisonResult) at the top level, if any.


HARNESS.md

Machine-specific paths should not be committed

The MATLAB MCP section documents absolute paths specific to a developer's machine:

/data/projects/suraj/repos/matlab-mcp-tools
/home/suraj/.mcp/matlab/scripts/eegprep_bootstrap.m
/data/projects/suraj/eeglab

These will not work for any other contributor and will become stale. Extract the workflow description into a template-style format (e.g., $EEGPREP_ROOT, $EEGLAB_ROOT) or move machine-specific configuration to a gitignored file.


parity_known_deviations.toml

issue = "TBD" should not merge (blocking)

Both registered deviations have issue = "TBD". Before this is promoted from draft, each deviation should reference a real GitHub issue number. The governance value of the deviation registry is undermined if issues are untracked.


Test Coverage Gaps

  • compare_events_epochs() has no test
  • Error paths in _compare_mapping() (missing keys, extra keys) have no test
  • write_markdown_report() is not tested (only render_markdown_report())
  • compare_visual_output() with a file path (the mpimg.imread branch) has no test
  • load_manifest() and load_deviations() with custom paths have no tests
  • MatlabEngineOracle.eval() and MatlabBatchOracle.run() have no tests (MATLAB-gated tests are fine, just need a @pytest.mark.matlab guard)

pytest.ini / CI

  • pytest.ini could benefit from filterwarnings = error (or at least default::DeprecationWarning) to catch future compatibility issues early.
  • The tests optional group should perhaps include pytest-cov for coverage tracking.
  • Consider adding minversion = 8.0 to pytest.ini to document the minimum pytest version requirement.

Summary

Category Status
Architecture ✅ Well-layered, clean separation
Type annotations ⚠️ Inconsistent (Dict vs dict, Optional vs |)
Resource loading ⚠️ Should use importlib.resources
resolve_oracle_backend() logic ⚠️ Dead code branch, needs simplification
Top-level namespace ⚠️ 20 parity symbols exported — consider narrowing
Known deviations ❌ issue = "TBD" must be resolved before merge
Machine paths in HARNESS.md ❌ Should not be committed as absolute paths
Test coverage ⚠️ Several code paths missing coverage
Security ✅ Path traversal check in ArtifactOracle is correct
CI wiring ✅ Parity manifest inspection step is a good gate

The harness design is solid. The two blocking items before leaving draft are the issue = "TBD" deviations and the machine-specific paths in HARNESS.md. The remaining items are improvements rather than blockers.

Reviewed by Claude Sonnet 4.6

Copy link
Copy Markdown
Member Author

Addressed the review feedback in 6104430.

Changes made:

  • Fixed compare_numeric so equal_nan=True does not poison diff metrics with NaN values.
  • Made compare_eeg_data fail explicitly on shape-mismatch comparisons instead of returning zero-valued metrics.
  • Hardened ArtifactOracle.resolve() against absolute paths and .. path traversal outside the artifact root.
  • Converted OracleBackend to a string enum and added artifact-oracle availability reporting.
  • Added a targeted error when ARTIFACT_ORACLE is requested without artifact_root.
  • Moved matplotlib image loading to a lazy import so import eegprep.parity does not require matplotlib at module import time.
  • Re-exported OracleBackend from top-level eegprep.
  • Replaced the confusing field(default_factory=tuple) with an immutable tuple default.
  • Made CLI text output genuinely human-readable while keeping JSON output machine-readable.
  • Replaced placeholder broken GitHub issue URLs with TBD until real tracking issues exist.
  • Rewrote the parity smoke tests as native pytest tests and added regression coverage for the review issues.

Validation:

  • python -m pytest tests/test_parity_harness.py -q passed: 19 tests.
  • python -m eegprep.parity --format json passed.
  • python -m eegprep.parity --format text passed.
  • git diff --check passed.
  • A broader pytest tests -q run was attempted, but the existing full suite blocked in a MATLAB-backed path; a second run with EEGPREP_SKIP_MATLAB=1 timeout 180s ... also exceeded the timeout after progressing through the suite. The review-specific harness tests completed cleanly.

Copy link
Copy Markdown
Member Author

Pushed a1bb8d6 to address the CI failure in tests/test_fixtures.py::TestFixturesFunctions::test_cleanup_matplotlib.

Root cause: cleanup_matplotlib() called plt.close('all') and then plt.clf() / plt.cla(). In pyplot, those calls can create or keep a current empty figure after closing all figures, so the cleanup helper could leave one figure open. Under the new pytest ordering this surfaced as 1 not less than or equal to 0.

Fix: cleanup_matplotlib() now only calls plt.close('all'), which is the correct operation for test isolation.

Validation:

  • EEGPREP_SKIP_MATLAB=1 python -m pytest tests/test_fixtures.py::TestFixturesFunctions::test_cleanup_matplotlib tests/test_parity_harness.py -q passed: 20 tests.
  • A full local EEGPREP_SKIP_MATLAB=1 timeout 420s python -m pytest tests -q progressed past the prior failing test_cleanup_matplotlib area without reproducing the failure, then hit the local timeout before completing. GitHub Actions should re-run the full suite on the pushed commit.

@suraj-ranganath

Copy link
Copy Markdown
Member Author

@claude review

@claude

claude Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Code Review: Parity Testing Harness (#43)

Overall this is a well-architected PR. The manifest-driven governance model, oracle backend abstraction, and recursive comparator design are all solid choices. The notes below are ranked roughly by severity.


Potential Bugs / Correctness

compare_eeg_data changes exception type (breaking)
stage_comparison.py:1490 — the old implementation raised ValueError on data shape mismatch. The new path calls data_result.raise_if_failed(), which raises AssertionError. Any caller catching ValueError specifically will silently miss the error after this change. Worth auditing call sites or documenting the new exception contract.

compare_stage_outputs double-compares data
compare.py:795–833 — compare_eeg_struct recurses over the entire EEG dict (including the data field), so data is compared twice: once via the dedicated compare_numeric("stage.data") call and again inside compare_eeg_struct. The struct comparison should likely set ignore_fields={"data", ...} so the separate data comparison is the authoritative one and metrics aren't redundant.

Deviation tolerances are stored but never enforced
parity_known_deviations.toml defines max_atol = 200.0 on runica_component_permutation, and ParityDeviation stores max_rtol/max_atol. But nothing in compare_stage_outputs or any comparator reads those fields. The deviation acts as documentation only right now. If it's intentionally deferred, a TODO comment in compare_stage_outputs would prevent future confusion.

MatlabBatchOracle.run silently returns non-zero exits
oracle.py:1140–1156 — subprocess.run(..., check=False) means callers get back a CompletedProcess without any indication of MATLAB failure. The method docstring should document that callers must inspect .returncode, or the method should accept a check: bool = False parameter.


Code Quality

_is_numeric_array swallows all exceptions (compare.py:453)

except Exception:
    return False

A broad except Exception here can hide real programming bugs (e.g., a broken __array__ method). Narrowing to (TypeError, ValueError) or at least (Exception,) with a logged warning would be safer.

compare_visual_output default atol=0.0 is fragile
compare.py:594–602 — exact pixel matching will fail on minor rendering differences across platforms or matplotlib versions. Given the visual_strict tolerance profile already defines atol=1e-8, using that as the default (or at least documenting the pixel-exact expectation prominently) would prevent mysterious CI failures when matplotlib point releases change rendering.

nonfinite_mismatch_count logic is subtle
compare.py:515 — the variable name nonfinite_mismatch_count is computed as int(np.count_nonzero(mismatched & ~valid_metric_mask)). A one-line comment explaining what this counts (mismatched positions whose difference is non-finite, distinct from positions where the values are non-finite) would help future readers.

zero_metrics logic is hard to follow
compare.py:517 — the compound expression handling empty arrays and the all-matching-but-no-finite-diffs case is difficult to reason about. Extracting it into a named helper or at least adding two intermediate booleans (all_matched, is_empty) would improve clarity.


Performance

compare_stage_outputs loads each file before compare_eeg_struct recurses
compare.py:783–786 — two full pop_loadset calls are made, then the struct comparator recursively walks every field. For large EEG files this is fine, but the data array ends up compared twice (see double-compare note above). Fixing the double-compare also removes the redundant O(N) data pass.


Test Coverage

test_compare_eeg_data_raises_on_shape_mismatch tests AssertionError, not the old ValueError
test_parity_harness.py:1718–1738 — the test correctly captures the new behavior, but there's no test for the case where the parity result passed but metrics are None (the second raise ValueError path at stage_comparison.py:1491). Worth adding to keep that branch from regressing silently.

test_resolve_prefers_batch_when_engine_unavailable uses ad-hoc anonymous classes
test_parity_harness.py:1749–1757 — using type("Avail", (), {...})() as a stand-in for BackendAvailability means the test will silently pass even if BackendAvailability grows new required fields. Constructing real BackendAvailability instances would be more robust.

No test for compare_stage_outputs double-compare behavior
There's no test asserting that the stage.struct child doesn't re-report data mismatches that are already captured in stage.data. If the struct walk is ever changed, this could produce misleading duplicate failures with no test catching it.


Minor / Style

  • config.py:853–854 — the tomllib = None pattern at module scope with the # type: ignore is correct but worth a one-line comment noting that _load_toml handles the None case at call time.
  • pyproject.toml — tests optional dependency section comment is good; dev section mirrors [all,tests] with no additions — consider whether a lint, mypy, or pre-commit dependency belongs here for completeness.
  • pytest.ini — testpaths = tests intentionally excludes tests_matlab. A brief comment in pytest.ini or HARNESS.md noting this split would help contributors who notice it and wonder if it's accidental.
  • fixtures.py:1514 — removing the redundant plt.clf()/plt.cla() after plt.close('all') is a clean fix and clearly correct.

Summary

The harness foundation is solid. The manifest-driven approach, oracle backend abstraction, and path-traversal protection in ArtifactOracle are all good engineering decisions. The most actionable items before merge are:

  1. Confirm or fix the ValueError → AssertionError change in compare_eeg_data's public contract.
  2. Exclude data from compare_eeg_struct inside compare_stage_outputs to avoid double-counting.
  3. Document (or wire up) deviation tolerance enforcement so max_atol in the TOML isn't silent dead configuration.

@suraj-ranganath suraj-ranganath changed the title Set up parity testing harness for agentic development [WIP] Set up parity testing harness for agentic development Apr 30, 2026
@suraj-ranganath suraj-ranganath changed the title [WIP] Set up parity testing harness for agentic development Set up parity testing harness for agentic development Apr 30, 2026
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review April 30, 2026 10:43
@suraj-ranganath
suraj-ranganath marked this pull request as draft May 1, 2026 10:41
@suraj-ranganath

Copy link
Copy Markdown
Member Author

Closing because this PR is no longer relevant.

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