Skip to content

fix: harden ingest, audit, and streaming edge cases - #179

Merged
k-dickinson merged 2 commits into
mainfrom
fix/ingest-audit-hardening
Aug 24, 2026
Merged

k-dickinson merged 2 commits into
mainfrom
fix/ingest-audit-hardening

Conversation

@k-dickinson

@k-dickinson k-dickinson commented Aug 11, 2026 •

Copy link
Copy Markdown
Owner

A set of correctness fixes found in a review pass over the recent adapter / audit / streaming work. Each fix is locked in with tests; the full suite passes with and without the optional ijson extra (1210 / 1204 tests).

Ingest

  • Preference columns using winner words. A winner/preference column whose values are winner words (won/lost/win/loss/accept/reject/positive/negative/good/bad) is read as pairwise preference data again, instead of being misclassified as a wide model-score column and silently dropped. The same words remain valid pass/fail scores in ordinary score columns.
  • Run-level JSON validation scope. Only the two compared models are validated for finite scores; an unrelated extra model with bad data no longer blocks a valid comparison (matches the CSV paths).
  • Run-level CSV column aliases. Long-format run-level CSV detection reuses the canonical MODEL_KEYS / SCORE_KEYS alias tables, so columns like candidate, rating, or grade are recognised instead of silently falling to the wide-format path.
  • Large object-shaped JSON streaming. With ijson installed, a large JSON object wrapped under any recognised key (e.g. {"results": [...]}), not just {"examples": [...]}, streams in a single pass — the record array is parsed once and the raw file string is never materialised (previously only examples streamed, and every object was parsed twice). Malformed arrays fall back to a clean json error, and Decimal normalisation is now fully recursive.
  • Large OpenAI Evals logs. Streaming JSONL detects tool-specific line formats through the shared LINE_REGISTRY with a bounded look-ahead, so an OpenAI Evals spec row that follows leading event rows is still recognised in large files.

Audit

  • Repeatability wording on a tie. When two models are tied on average across reruns (mean gap exactly 0), the stability finding no longer names an arbitrary "winner" that "wins consistently." It reports the tie honestly and, when the per-run direction merely flips around zero, flags it as unstable rather than passing.
  • Contamination false positives on empty items. Benchmark or reference items that are empty after normalisation are skipped in both exact- and near-match detection, instead of an empty item matching another empty item (exact) or scoring ratio 1.0 (near).

Public API / CLI

  • audit(..., win_rate=True) is now accepted (previously raised TypeError).
  • audit_run_level passes a confidence level consistent with alpha so its interval and decision use the same error rate.
  • The run-level CLI honours the configured n_resamples instead of a hard-coded 10,000.

Dev

  • EvalData.paired_run_differences() warns when it truncates unequal run lists.
  • ijson added to the dev extra so the streaming path is exercised by the tests.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added optional win-rate reporting for audits.
    • Added configurable run-level resampling based on audit settings.
    • Improved streaming support for large and wrapped JSON files, including nested numeric values and OpenAI Evals logs.
    • Expanded CSV aliases and JSONL adapter detection.
  • Bug Fixes

    • Improved preference-column recognition and tie-aware repeatability reporting.
    • Prevented empty entries from being flagged as contamination.
    • Limited run-level validation to the selected model pair.
    • Added warnings for mismatched paired-run lengths.

A set of correctness fixes found in a review pass over the recent
adapter/audit/streaming work, each locked in with tests.

Ingest:
- Preference columns using winner words (won/lost/accept/reject/...) are
  read as pairwise preferences again instead of being misclassified as
  wide score columns and silently dropped.
- Run-level JSON validation only checks the two compared models, so an
  unrelated extra model with bad data no longer blocks a valid comparison
  (matches the CSV paths).
- Long-format run-level CSV detection reuses the canonical MODEL_KEYS /
  SCORE_KEYS alias tables (candidate, rating, grade, ... now recognised).
- Large object-shaped JSON streams in a single ijson pass under any
  wrapper key, not just "examples"; the record array is parsed once and
  the raw file string is never materialised. Malformed arrays fall back
  to a clean json error, and Decimal normalisation is fully recursive.
- Streaming JSONL routes tool-specific line formats through LINE_REGISTRY
  with a bounded look-ahead, so an OpenAI Evals spec row after leading
  event rows is still detected.

Audit:
- Repeatability no longer names a false "winner" when models are tied on
  average; it reports the tie honestly and flags an unstable direction.
- Contamination skips items that are empty after normalisation in both
  exact- and near-match detection (no more ratio-1.0 false positives).

Public API / CLI:
- audit(..., win_rate=True) is accepted (previously a TypeError).
- audit_run_level passes a confidence level consistent with alpha.
- The run-level CLI honours the configured n_resamples, not a hard-coded
  10,000.

Dev:
- EvalData.paired_run_differences warns when it truncates unequal run
  lists.
- ijson added to the dev extra so the streaming path is exercised in CI.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 50b8bcdb-0484-4f8b-a850-bd945ad2dd9e

📥 Commits

Reviewing files that changed from the base of the PR and between 90b9528 and 6bd53e2.

📒 Files selected for processing (2)
  • src/evaltrust/audit/repeatability.py
  • tests/test_repeatability.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/evaltrust/audit/repeatability.py

📝 Walkthrough

Walkthrough

The pull request updates preference parsing, tie-aware repeatability and contamination audits, run-level configuration handling, and streaming JSON/JSONL ingestion. It adds regression tests and documents the changes.

Changes

Audit and ingestion behavior

Layer / File(s) Summary
Preference parsing and API wiring
src/evaltrust/adapters/generic.py, src/evaltrust/api.py, tests/test_api.py, tests/test_preference.py, CHANGELOG.md
Preference words are treated as preference evidence. The API accepts win_rate and passes it to AuditConfig. Run-level auditing passes confidence derived from alpha.
Tie and contamination reporting
src/evaltrust/audit/contamination.py, src/evaltrust/audit/repeatability.py, tests/test_contamination.py, tests/test_repeatability.py, CHANGELOG.md
Empty normalized entries are skipped. Repeatability findings distinguish ties from unstable or ranked outcomes.
Streaming JSON and JSONL ingestion
src/evaltrust/core/ingest.py, tests/test_ingest_streaming.py, pyproject.toml, CHANGELOG.md
ijson supports arbitrary object wrappers, recursive Decimal normalization, bounded adapter detection, and generic suite records.
Run-level validation and configuration
src/evaltrust/cli.py, src/evaltrust/core/ingest.py, src/evaltrust/core/schema.py, tests/test_cli.py, tests/test_two_sample_audit.py, CHANGELOG.md
Run-level audits use configured resampling counts. JSON validation checks only selected models, CSV detection uses shared aliases, and unequal run counts emit warnings.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Merge Risk: ⚪ Minimal · up to 6bd53

This PR hardens ingest, audit, streaming, and CLI edge cases with accompanying tests; no actionable merge-blocking risk remains beyond normal checks and review.

Sequence Diagram(s)

sequenceDiagram
  participant JSONLLoader
  participant detect_adapter
  participant OpenAIEvalsAdapter
  JSONLLoader->>JSONLLoader: Buffer up to 50 rows
  JSONLLoader->>detect_adapter: Detect adapter from buffered rows
  detect_adapter->>OpenAIEvalsAdapter: Select matching adapter
  OpenAIEvalsAdapter->>JSONLLoader: Parse buffered and remaining rows
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.53% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the pull request's main changes to ingest, audit, and streaming edge cases.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/ingest-audit-hardening

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (6)
tests/test_cli.py (1)

185-192: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Also assert the CLI exit code.

The test verifies that audit_two_sample received n_resamples=123, but it does not check that the command completed successfully. A regression that fails after the audit call, for example during JSON rendering, would leave this test green. Add assert result.exit_code == 0, result.output.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_cli.py` around lines 185 - 192, Add an assertion after the CLI
invocation in the audit test to require result.exit_code == 0, passing
result.output as the failure message, while preserving the existing
audit_two_sample spy and n_resamples assertion.
src/evaltrust/core/ingest.py (3)

298-311: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Hoist the Decimal import out of the per-value hot path.

_normalize_ijson_any calls _normalize_ijson_value for every leaf. That function runs from decimal import Decimal inside a try/except ImportError on each call. decimal is part of the standard library, so the guard cannot trigger, and the repeated import lookup adds cost on large streamed files. Import Decimal once at module scope.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/evaltrust/core/ingest.py` around lines 298 - 311, Move the Decimal import
from _normalize_ijson_value to module scope, removing the per-call try/except
ImportError guard. Update _normalize_ijson_value to use the module-level Decimal
directly while preserving its existing leaf normalization behavior.

381-399: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the duplicated top-level-array streaming loop. _load_json_streamed and _suite_from_json_streamed contain a byte-identical block: the ijson.items(fh, "item") loop, the non-dict isinstance check and its error text, the _normalize_ijson_dict call, the except parse_errors: return None fallback, and the empty-rows UnknownFormatError. The two copies only differ in what they do with rows afterwards. Any correction to the error-handling interaction must be applied in both places, and the two error messages will drift.

  • src/evaltrust/core/ingest.py#L381-L399: extract the array-reading loop into a shared helper, for example _ijson_load_rows(ijson, path, parse_errors) -> list[dict] | None, and call it from this branch before detect_adapter(rows).parse(rows).
  • src/evaltrust/core/ingest.py#L430-L445: replace the duplicated loop with a call to the same helper, then continue with dicts_to_records and records_to_suite.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/evaltrust/core/ingest.py` around lines 381 - 399, Extract the duplicated
top-level-array parsing logic into a shared helper such as
_ijson_load_rows(ijson, path, parse_errors), preserving the existing ijson.items
loop, non-dict validation, normalization, parse-error fallback, and empty-row
UnknownFormatError. In src/evaltrust/core/ingest.py lines 381-399, call the
helper before detect_adapter(rows).parse(rows); in lines 430-445, replace the
duplicate loop with the same helper and retain the existing dicts_to_records and
records_to_suite flow.

766-772: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoff

The line-adapter branch still materialises the whole file.

rows = peek + list(gen) builds the complete row list in memory before calling parse_lines. For a multi-gigabyte JSONL file that matches a registered line adapter, this removes the memory benefit that _stream_records_from_jsonl promises in its docstring. The LineAdapter.parse_lines protocol accepts rows: list[dict], so a fix requires an iterator-accepting variant of the protocol.

Two options: widen parse_lines to accept an iterable and adapt the registered adapters, or state the memory limit explicitly in the docstring so callers know line-adapter inputs are not bounded.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/evaltrust/core/ingest.py` around lines 766 - 772, Update the line-adapter
path in _stream_records_from_jsonl and the LineAdapter.parse_lines protocol to
accept an iterable of rows, then pass peek followed by gen without materialising
the complete file; adapt each registered line adapter to consume the iterable
while preserving existing parsing results and metadata.
tests/test_ingest_streaming.py (1)

261-263: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add strict= to the zip() calls flagged by Ruff.

Ruff reports B905 on line 261 and line 373. Both loops pair normal.examples with streamed.examples. The preceding n_examples assertions already guard the lengths, so strict=True is safe and it silences the lint. The repository already uses strict=True in tests/test_preference.py.

♻️ Proposed change
-        for ex_n, ex_s in zip(normal.examples, streamed.examples):
+        for ex_n, ex_s in zip(normal.examples, streamed.examples, strict=True):

Apply the same change at line 373.

Also applies to: 373-374

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_ingest_streaming.py` around lines 261 - 263, Add strict=True to
both zip() calls pairing normal.examples with streamed.examples in the affected
test loops, including the loop near the second occurrence, while preserving the
existing assertions and comparisons.

Source: Linters/SAST tools

src/evaltrust/core/schema.py (1)

142-147: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Bound the log volume and update the now-stale docstring wording.

paired_run_differences emits one warning per mismatched example. If every example in a large dataset has unequal run counts, this produces one log line per example in a library call path. Collect the mismatch count and emit a single warning after the loop, or log per-example detail at debug and the summary at warning.

The docstring above still states that the longer list "is silently truncated". That is no longer accurate after this change. Update that sentence.

♻️ Proposed change
         out: list[np.ndarray] = []
+        mismatches: list[str] = []
         for ex in self.examples:
             if not ex.runs:
                 continue
             a_runs = ex.runs.get(model_a)
             b_runs = ex.runs.get(model_b)
             if not a_runs or not b_runs:
                 continue
             r = min(len(a_runs), len(b_runs))
             if r == 0:
                 continue
             if len(a_runs) != len(b_runs):
-                logger.warning(
-                    "Example %r: %s has %d runs but %s has %d; "
-                    "truncating to %d paired differences.",
-                    ex.id, model_a, len(a_runs), model_b, len(b_runs), r,
-                )
+                mismatches.append(ex.id)
+                logger.debug(
+                    "Example %r: %s has %d runs but %s has %d; "
+                    "truncating to %d paired differences.",
+                    ex.id, model_a, len(a_runs), model_b, len(b_runs), r,
+                )
             a = np.array(a_runs[:r], dtype=float)
             b = np.array(b_runs[:r], dtype=float)
             out.append(b - a)
+        if mismatches:
+            logger.warning(
+                "%d of %d examples have unequal run counts for %s vs %s; "
+                "each was truncated to the shorter list (first: %r).",
+                len(mismatches), len(out), model_a, model_b, mismatches[0],
+            )
         return out
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/evaltrust/core/schema.py` around lines 142 - 147, Update
paired_run_differences to stop emitting a warning for each mismatched example:
track the number of mismatches during the loop, optionally move per-example
details to debug, and emit one aggregated warning after processing. Revise the
function’s docstring to state that longer run lists are truncated with mismatch
information reported, rather than silently truncated.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/evaltrust/audit/repeatability.py`:
- Around line 66-74: In src/evaltrust/audit/repeatability.py lines 66-74,
replace the exact overall == 0.0 check with one documented np.isclose-based tied
flag, use that flag for flip calculation, and pass it to _stability; update the
related logic at lines 92-135 so near-zero aggregates do not select a winning
model. In tests/test_repeatability.py lines 64-86, add a cancellation regression
case using gaps such as [0.1, 0.2, -0.3] and assert that no model is named as
the winner.

---

Nitpick comments:
In `@src/evaltrust/core/ingest.py`:
- Around line 298-311: Move the Decimal import from _normalize_ijson_value to
module scope, removing the per-call try/except ImportError guard. Update
_normalize_ijson_value to use the module-level Decimal directly while preserving
its existing leaf normalization behavior.
- Around line 381-399: Extract the duplicated top-level-array parsing logic into
a shared helper such as _ijson_load_rows(ijson, path, parse_errors), preserving
the existing ijson.items loop, non-dict validation, normalization, parse-error
fallback, and empty-row UnknownFormatError. In src/evaltrust/core/ingest.py
lines 381-399, call the helper before detect_adapter(rows).parse(rows); in lines
430-445, replace the duplicate loop with the same helper and retain the existing
dicts_to_records and records_to_suite flow.
- Around line 766-772: Update the line-adapter path in
_stream_records_from_jsonl and the LineAdapter.parse_lines protocol to accept an
iterable of rows, then pass peek followed by gen without materialising the
complete file; adapt each registered line adapter to consume the iterable while
preserving existing parsing results and metadata.

In `@src/evaltrust/core/schema.py`:
- Around line 142-147: Update paired_run_differences to stop emitting a warning
for each mismatched example: track the number of mismatches during the loop,
optionally move per-example details to debug, and emit one aggregated warning
after processing. Revise the function’s docstring to state that longer run lists
are truncated with mismatch information reported, rather than silently
truncated.

In `@tests/test_cli.py`:
- Around line 185-192: Add an assertion after the CLI invocation in the audit
test to require result.exit_code == 0, passing result.output as the failure
message, while preserving the existing audit_two_sample spy and n_resamples
assertion.

In `@tests/test_ingest_streaming.py`:
- Around line 261-263: Add strict=True to both zip() calls pairing
normal.examples with streamed.examples in the affected test loops, including the
loop near the second occurrence, while preserving the existing assertions and
comparisons.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: ffd4a184-075f-4c3a-ae82-cd0ce949b466

📥 Commits

Reviewing files that changed from the base of the PR and between 420c382 and 90b9528.

📒 Files selected for processing (16)
  • CHANGELOG.md
  • pyproject.toml
  • src/evaltrust/adapters/generic.py
  • src/evaltrust/api.py
  • src/evaltrust/audit/contamination.py
  • src/evaltrust/audit/repeatability.py
  • src/evaltrust/cli.py
  • src/evaltrust/core/ingest.py
  • src/evaltrust/core/schema.py
  • tests/test_api.py
  • tests/test_cli.py
  • tests/test_contamination.py
  • tests/test_ingest_streaming.py
  • tests/test_preference.py
  • tests/test_repeatability.py
  • tests/test_two_sample_audit.py

Comment thread src/evaltrust/audit/repeatability.py Resolved
The tie check used exact `overall == 0.0`, but averaging per-run gaps can
leave a floating-point residue (e.g. gaps [0.1, 0.2, -0.3] -> 1.85e-17) even
when the models are genuinely tied. That slipped into the winner-naming
branch and reported a false leader, the exact behaviour the tie handling was
added to prevent.

Detect the tie with a tolerance (np.isclose, atol=1e-12, matching
audit/predictive_rerun.py), compute it once, and thread it into _stability
instead of recomputing == 0.0. Adds a cancellation regression test.

Addresses CodeRabbit review on #179.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@k-dickinson
k-dickinson merged commit 7871b94 into main Aug 24, 2026
5 checks 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