Repository navigation
fix: harden ingest, audit, and streaming edge cases - #179
Conversation
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>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe 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. ChangesAudit and ingestion behavior
Estimated code review effort: 3 (Moderate) | ~25 minutes Merge Risk: ⚪ Minimal · up to 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
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (6)
tests/test_cli.py (1)
185-192: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAlso assert the CLI exit code.
The test verifies that
audit_two_samplereceivedn_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. Addassert 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 valueHoist the
Decimalimport out of the per-value hot path.
_normalize_ijson_anycalls_normalize_ijson_valuefor every leaf. That function runsfrom decimal import Decimalinside atry/except ImportErroron each call.decimalis part of the standard library, so the guard cannot trigger, and the repeated import lookup adds cost on large streamed files. ImportDecimalonce 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 winExtract the duplicated top-level-array streaming loop.
_load_json_streamedand_suite_from_json_streamedcontain a byte-identical block: theijson.items(fh, "item")loop, the non-dictisinstancecheck and its error text, the_normalize_ijson_dictcall, theexcept parse_errors: return Nonefallback, and the empty-rowsUnknownFormatError. The two copies only differ in what they do withrowsafterwards. 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 beforedetect_adapter(rows).parse(rows).src/evaltrust/core/ingest.py#L430-L445: replace the duplicated loop with a call to the same helper, then continue withdicts_to_recordsandrecords_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 tradeoffThe line-adapter branch still materialises the whole file.
rows = peek + list(gen)builds the complete row list in memory before callingparse_lines. For a multi-gigabyte JSONL file that matches a registered line adapter, this removes the memory benefit that_stream_records_from_jsonlpromises in its docstring. TheLineAdapter.parse_linesprotocol acceptsrows: list[dict], so a fix requires an iterator-accepting variant of the protocol.Two options: widen
parse_linesto 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 valueAdd
strict=to thezip()calls flagged by Ruff.Ruff reports B905 on line 261 and line 373. Both loops pair
normal.exampleswithstreamed.examples. The precedingn_examplesassertions already guard the lengths, sostrict=Trueis safe and it silences the lint. The repository already usesstrict=Trueintests/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 winBound the log volume and update the now-stale docstring wording.
paired_run_differencesemits 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 atdebugand the summary atwarning.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
📒 Files selected for processing (16)
CHANGELOG.mdpyproject.tomlsrc/evaltrust/adapters/generic.pysrc/evaltrust/api.pysrc/evaltrust/audit/contamination.pysrc/evaltrust/audit/repeatability.pysrc/evaltrust/cli.pysrc/evaltrust/core/ingest.pysrc/evaltrust/core/schema.pytests/test_api.pytests/test_cli.pytests/test_contamination.pytests/test_ingest_streaming.pytests/test_preference.pytests/test_repeatability.pytests/test_two_sample_audit.py
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>
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
ijsonextra (1210 / 1204 tests).Ingest
winner/preferencecolumn 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.MODEL_KEYS/SCORE_KEYSalias tables, so columns likecandidate,rating, orgradeare recognised instead of silently falling to the wide-format path.ijsoninstalled, 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 onlyexamplesstreamed, and every object was parsed twice). Malformed arrays fall back to a cleanjsonerror, and Decimal normalisation is now fully recursive.LINE_REGISTRYwith a bounded look-ahead, so an OpenAI Evalsspecrow that follows leading event rows is still recognised in large files.Audit
Public API / CLI
audit(..., win_rate=True)is now accepted (previously raisedTypeError).audit_run_levelpasses a confidence level consistent withalphaso its interval and decision use the same error rate.n_resamplesinstead of a hard-coded 10,000.Dev
EvalData.paired_run_differences()warns when it truncates unequal run lists.ijsonadded to thedevextra so the streaming path is exercised by the tests.🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes