Repository navigation
fix: implement --plain, --md, --html for --run-level audits (#152) - #162
Conversation
|
Warning Review limit reached
Next review available in: 34 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughRun-level audits now support Markdown, ASCII plain-text, and standalone HTML output through shared renderers. The CLI renders finding statuses, guidance, and optional explanations. Tests cover formatting, escaping, file output, and warning removal. ChangesRun-level audit formats
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant User
participant AuditCLI
participant RunLevelFindings
participant ReportRenderers
participant HTMLFile
User->>AuditCLI: invoke audit --run-level with format
AuditCLI->>RunLevelFindings: collect run-level findings
AuditCLI->>ReportRenderers: pass subtitle, findings, and explain option
ReportRenderers-->>AuditCLI: return Markdown, plain text, or HTML
AuditCLI->>HTMLFile: write rendered HTML
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 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: 2
🧹 Nitpick comments (2)
tests/test_two_sample_audit.py (1)
750-759: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winSeveral
--explain/section-presence tests assert on strings that are always present, so they can't catch regressions. Each test below checks for a substring that appears in the output unconditionally, independent of the feature it claims to verify.
tests/test_two_sample_audit.py#L750-L759:"detail" in content.lower()also matches the always-embedded.detail/.detail-itemCSS selectors in_CSS(cli.py), so this passes even with--explain's Detail block removed. Assert on concrete detail content instead, e.g."detail-item" in contentcombined with escapedwhy/how_detectedtext, or check for>Detail<inside an<h2>.tests/test_two_sample_audit.py#L612-L629:"Statistical Validity" in r.outputis printed unconditionally before any--explainbranching. Assert on the actual Detail-section content (e.g. the finding'show_detected/whytext) that only appears when--explainis set.tests/test_two_sample_audit.py#L671-L681: only checks"# EvalTrust" in r.output, which is always true. Since the fixture uses identical scores (deterministic given a fixed seed), assert directly for"## What to do"instead of hedging.🤖 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_two_sample_audit.py` around lines 750 - 759, Strengthen the three explain/section-presence tests in tests/test_two_sample_audit.py: for test_run_level_html_explain_adds_detail_section (lines 750-759), assert concrete Detail content such as detail-item plus escaped why/how_detected text or an h2 containing >Detail<; for lines 612-629, replace the unconditional Statistical Validity assertion with finding how_detected/why text that requires --explain; and for lines 671-681, replace the unconditional # EvalTrust check with a direct ## What to do assertion. No other sites require changes.src/evaltrust/cli.py (1)
220-292: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftConsider extracting md/plain/html run-level rendering into dedicated functions.
These three branches duplicate the same status-badge iteration, "What to do"/"To check more" list-building, and optional-detail logic three times inline inside
audit(), whereas the standard path just below (lines 466-489) delegates torender_markdown/render_plain/render_html. Extractingrender_run_level_markdown/render_run_level_plain/render_run_level_htmlhelpers would reduce duplication, shrink an already-largeaudit()function, and make each format independently unit-testable (mirroringrender_markdown, etc.).Also applies to: 318-406
🤖 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/cli.py` around lines 220 - 292, Extract the inline run-level Markdown, plain-text, and HTML rendering branches from audit() into dedicated render_run_level_markdown, render_run_level_plain, and render_run_level_html helpers, mirroring the existing render_markdown/render_plain/render_html functions. Move each format’s status iteration, actionable and optional lists, and explain-detail handling into its helper, then have audit() delegate to them while preserving the current output and typer.echo behavior.
🤖 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/cli.py`:
- Around line 220-236: Update the --md output construction in the md branch to
escape Markdown-special characters in rl_data.model_a, rl_data.model_b, and each
finding’s f.title before interpolation. Reuse an existing Markdown-escaping
helper if available; otherwise add a focused escape step that prevents
formatting and link interpretation while preserving the intended displayed text.
- Around line 261-264: Fix the duplicate smart-quote keys in the _ASCII
translation table by mapping both intended single quotation mark characters,
U+2018 and U+2019, to the ASCII apostrophe. Preserve the existing mappings so
--plain continues converting all supported Unicode punctuation to ASCII.
---
Nitpick comments:
In `@src/evaltrust/cli.py`:
- Around line 220-292: Extract the inline run-level Markdown, plain-text, and
HTML rendering branches from audit() into dedicated render_run_level_markdown,
render_run_level_plain, and render_run_level_html helpers, mirroring the
existing render_markdown/render_plain/render_html functions. Move each format’s
status iteration, actionable and optional lists, and explain-detail handling
into its helper, then have audit() delegate to them while preserving the current
output and typer.echo behavior.
In `@tests/test_two_sample_audit.py`:
- Around line 750-759: Strengthen the three explain/section-presence tests in
tests/test_two_sample_audit.py: for
test_run_level_html_explain_adds_detail_section (lines 750-759), assert concrete
Detail content such as detail-item plus escaped why/how_detected text or an h2
containing >Detail<; for lines 612-629, replace the unconditional Statistical
Validity assertion with finding how_detected/why text that requires --explain;
and for lines 671-681, replace the unconditional # EvalTrust check with a direct
## What to do assertion. No other sites require changes.
🪄 Autofix (Beta)
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: 2588e737-0d54-4eeb-a7c9-af3d0b440ffa
📒 Files selected for processing (2)
src/evaltrust/cli.pytests/test_two_sample_audit.py
|
this works and the tests are solid, thanks. one thing before merge: it reimplements the markdown, plain, and html rendering inline here, but the normal audit path a few lines up already calls the shared render_markdown / render_plain / render_html from report/. having a second copy will drift over time. the reason it can't reuse them directly is those renderers take an AuditReport with a verdict, and the run-level path has none. could you refactor them to render from a header plus findings (no verdict required) so both paths share one implementation? that keeps the run-level output in sync with the main one for free. |
Done — refactored in the latest push. Extracted three shared functions:
The existing All 1079 tests pass. |
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tests/test_two_sample_audit.py (1)
750-759: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winThis assertion can never fail.
_CSSinsrc/evaltrust/report/html.pyis inlined into every page and contains.detail,.detail h2, and.detail-item, so"detail" in content.lower()is true even without--explain. Assert on the rendered section instead.💚 Proposed fix
- content = open(out, encoding="utf-8").read() - assert "detail" in content.lower() + content = Path(out).read_text(encoding="utf-8") + assert "<div class='detail'><h2>Detail</h2>" in content + assert "detail-item" in content🤖 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_two_sample_audit.py` around lines 750 - 759, Update test_run_level_html_explain_adds_detail_section to assert on the rendered Detail section rather than the globally inlined CSS: use an HTML marker or structure unique to the generated explanation content, so the assertion fails when --explain does not add the section.
🧹 Nitpick comments (7)
tests/test_two_sample_audit.py (4)
671-680: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTest name and docstring promise a
## What to doassertion that isn't made.The body only asserts
# EvalTrust, which the header check at Line 640-ish already covers. Either assert"## What to do" in r.outputfor this identical-scores fixture, or rename the test to reflect what it verifies.🤖 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_two_sample_audit.py` around lines 671 - 680, Update test_run_level_md_what_to_do_section_present_when_findings_warn to assert that “## What to do” appears in r.output for the identical-scores fixture. Remove the fallback wording that permits all-pass output, while preserving the existing exit-code and Markdown header checks.
741-747: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTolerating exit code 2 makes the escaping assertions skippable.
If loading ever starts rejecting
<ModelA>, the test silently passes without checking any escaping. Since the fixture is a valid wide CSV, assertr.exit_code in (0, 1)and drop the conditional.🤖 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_two_sample_audit.py` around lines 741 - 747, Update the audit invocation assertions to require exit_code 0 or 1, since the valid wide CSV fixture should not produce exit code 2. Remove the conditional guarding the HTML content checks so the escaping assertions always execute, and preserve the existing file read and escaping expectations.
797-811: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDocstring contradicts the intended behaviour.
render_markdown_from_partsdeliberately renders finding titles verbatim (library-authored). This test actually asserts "no accidental linkification", which is fine — just fix the docstring so nobody later "fixes" the renderer to escape titles.🤖 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_two_sample_audit.py` around lines 797 - 811, Update the docstring of test_run_level_md_escapes_markdown_special_chars_in_finding_title to describe preventing accidental Markdown linkification while preserving finding titles verbatim; do not change render_markdown_from_parts or the test assertions.
612-628: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDead scaffolding and the assertion doesn't test
--explain.Line 619
tmp_path / "eq.csv" if False else tmp_pathplus the unusedp2,path, andimport tempfile, osare leftovers. More importantly, asserting only"Statistical Validity"passes with or without--explain, so the test's stated purpose (per-finding why / how_detected) is unverified.💚 Proposed cleanup
def test_run_level_plain_explain_adds_detail(tmp_path): """--explain must append per-finding why / how_detected text in --plain mode.""" - path = _rl_csv(tmp_path) - # Use data that yields at least one non-pass finding so Detail section fires. - # Near-equal scores → inconclusive → warn/fail findings. - a = [0.70] * 15 - b = [0.70] * 15 - p2 = _rl_csv(tmp_path / "eq.csv" if False else tmp_path, a_scores=a, b_scores=b) - import tempfile, os rows = ["alpha,beta"] + ["0.70,0.70"] * 5 pf = tmp_path / "eq.csv" pf.write_text("\n".join(rows), encoding="utf-8") r = _runner.invoke(_app, ["audit", str(pf), "--run-level", "--plain", "--explain"]) assert r.exit_code in (0, 1) - # When there are warn/fail findings the Detail section appears. - # With identical scores every finding should be warn or fail. - assert "Statistical Validity" in r.output + assert "Statistical Validity" in r.output + assert "Detail" in r.output + # --explain must add content the non-explain run does not have. + base = _runner.invoke(_app, ["audit", str(pf), "--run-level", "--plain"]) + assert len(r.output) > len(base.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_two_sample_audit.py` around lines 612 - 628, Clean up test_run_level_plain_explain_adds_detail by removing the unused path, p2, dead conditional expression, and tempfile/os imports. Keep only the CSV setup needed for the invocation, and strengthen the assertions to verify that --explain output includes per-finding why/how_detected detail, not merely the always-present “Statistical Validity” section.src/evaltrust/report/terminal.py (1)
384-392: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueHoist
reto a module-level import.The function-local
import re as _reruns on every call and hides the dependency.♻️ Proposed refactor
+_MD_SPECIAL = re.compile(r'([\\`*_{}\[\]()#+\-.!|])') + + def _md_escape(s: str) -> str: @@ - import re as _re - return _re.sub(r'([\\`*_{}\[\]()#+\-.!|])', r'\\\1', str(s)) + return _MD_SPECIAL.sub(r'\\\1', str(s))(add
import reat the top of the module)🤖 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/report/terminal.py` around lines 384 - 392, Move the regular-expression dependency out of _md_escape by adding the module-level re import and removing the function-local import alias. Update _md_escape to use the module-level symbol while preserving its existing escaping pattern and behavior.src/evaltrust/report/html.py (1)
104-105: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low valueDocument
preamble_htmlas a trusted raw-HTML parameter.It's the only argument inserted without
_e(). Today the sole caller escapes model names itself, but the docstring doesn't state the contract, so a future caller can easily pass user-controlled text here.♻️ Suggested docstring addition
``verdict_color`` / ``verdict_label`` / ``verdict_summary`` are omitted, the verdict block is skipped, keeping run-level output in sync with the main path. + + ``preamble_html`` is inserted verbatim; callers must escape any + user-controlled content before passing it. """🤖 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/report/html.py` around lines 104 - 105, Update the docstring for the function containing the preamble_html handling to explicitly document that preamble_html must contain trusted raw HTML and is not escaped by the function. Preserve the existing p(preamble_html) behavior and clarify that callers are responsible for escaping any user-controlled content before passing it.src/evaltrust/cli.py (1)
243-244: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftReaching into private terminal helpers from the CLI.
_grouped,_SYMBOL(and_display_title) are module-private. Given this PR's goal of one shared implementation per format, consider exposing arender_rich_from_parts(subtitle, findings, *, explain)inreport/terminal.pyand calling that here, instead of re-implementing the Rich loop against private names.🤖 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/cli.py` around lines 243 - 244, Replace the CLI’s direct use of private terminal helpers such as _grouped, _SYMBOL, and _display_title with a public render_rich_from_parts(subtitle, findings, *, explain) API in report/terminal.py. Move the shared Rich rendering logic into that function and update the CLI call site to use it, preserving the existing output and explain behavior.
🤖 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/cli.py`:
- Around line 250-261: Update the Rich rendering loop around _grouped findings
to use _display_title(f) instead of f.title, and check skipped findings with
f.status is Status.SKIP. Add the same “What to do” and “To check more” sections
emitted by render_plain_from_parts, render_markdown_from_parts, and
render_html_from_parts, preserving their ordering and content so default output
matches the shared renderers.
In `@src/evaltrust/report/terminal.py`:
- Around line 411-419: Update the report-rendering docstring near the lines
construction in the terminal output function to state only that the
user-controlled subtitle is Markdown-escaped. Remove claims that finding titles
or how_to_fix text are escaped, preserving the existing implementation and
nearby comment describing those fields as verbatim.
- Around line 464-468: Update the preamble construction in the terminal report
rendering to apply _md_escape to each model name in others before joining them
into the Markdown text. Preserve the existing preamble wording, model count, and
None behavior when others is empty.
In `@tests/test_two_sample_audit.py`:
- Around line 854-867: Update
test_run_level_plain_ascii_translation_has_ten_distinct_keys to inspect the
canonical _ASCII translation table from src/evaltrust/report/terminal.py instead
of constructing a duplicate literal mapping. Keep the existing length and
code-point assertions so duplicate-key regressions in _ASCII fail the test.
---
Outside diff comments:
In `@tests/test_two_sample_audit.py`:
- Around line 750-759: Update test_run_level_html_explain_adds_detail_section to
assert on the rendered Detail section rather than the globally inlined CSS: use
an HTML marker or structure unique to the generated explanation content, so the
assertion fails when --explain does not add the section.
---
Nitpick comments:
In `@src/evaltrust/cli.py`:
- Around line 243-244: Replace the CLI’s direct use of private terminal helpers
such as _grouped, _SYMBOL, and _display_title with a public
render_rich_from_parts(subtitle, findings, *, explain) API in
report/terminal.py. Move the shared Rich rendering logic into that function and
update the CLI call site to use it, preserving the existing output and explain
behavior.
In `@src/evaltrust/report/html.py`:
- Around line 104-105: Update the docstring for the function containing the
preamble_html handling to explicitly document that preamble_html must contain
trusted raw HTML and is not escaped by the function. Preserve the existing
p(preamble_html) behavior and clarify that callers are responsible for escaping
any user-controlled content before passing it.
In `@src/evaltrust/report/terminal.py`:
- Around line 384-392: Move the regular-expression dependency out of _md_escape
by adding the module-level re import and removing the function-local import
alias. Update _md_escape to use the module-level symbol while preserving its
existing escaping pattern and behavior.
In `@tests/test_two_sample_audit.py`:
- Around line 671-680: Update
test_run_level_md_what_to_do_section_present_when_findings_warn to assert that
“## What to do” appears in r.output for the identical-scores fixture. Remove the
fallback wording that permits all-pass output, while preserving the existing
exit-code and Markdown header checks.
- Around line 741-747: Update the audit invocation assertions to require
exit_code 0 or 1, since the valid wide CSV fixture should not produce exit code
2. Remove the conditional guarding the HTML content checks so the escaping
assertions always execute, and preserve the existing file read and escaping
expectations.
- Around line 797-811: Update the docstring of
test_run_level_md_escapes_markdown_special_chars_in_finding_title to describe
preventing accidental Markdown linkification while preserving finding titles
verbatim; do not change render_markdown_from_parts or the test assertions.
- Around line 612-628: Clean up test_run_level_plain_explain_adds_detail by
removing the unused path, p2, dead conditional expression, and tempfile/os
imports. Keep only the CSV setup needed for the invocation, and strengthen the
assertions to verify that --explain output includes per-finding why/how_detected
detail, not merely the always-present “Statistical Validity” section.
🪄 Autofix (Beta)
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: d89b8530-8f2b-4bdf-a076-8ff8ca210fc0
📒 Files selected for processing (4)
src/evaltrust/cli.pysrc/evaltrust/report/html.pysrc/evaltrust/report/terminal.pytests/test_two_sample_audit.py
|
the shared render_*_from_parts refactor is exactly right, thanks for that. one thing i caught before merge: escaping the subtitle also changes the existing main audit path. a name like gpt-4[preview] now renders as gpt-4[preview] in the markdown output, and there's no test on the subtitle so it slipped through. two asks:
once that's sorted this is good to go. |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 `@tests/test_two_sample_audit.py`:
- Around line 863-869: Update the assertions in the test around the model-name
escaping checks to inspect bold_line exclusively. Remove the r.output fallback
from both the bracket and underscore assertions while preserving their existing
expected escaped substrings and failure messages.
🪄 Autofix (Beta)
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: 4884f910-067a-4702-8a5b-22b268b579bc
📒 Files selected for processing (3)
src/evaltrust/cli.pysrc/evaltrust/report/terminal.pytests/test_two_sample_audit.py
🚧 Files skipped from review as they are similar to previous changes (2)
- src/evaltrust/cli.py
- src/evaltrust/report/terminal.py
k-dickinson
left a comment
There was a problem hiding this comment.
appreciate the pr and fixes; lgtm
Closes #152
What
Brings the
--run-levelaudit path to output-format parity with the standard paired path.Changes
src/evaltrust/cli.py— replaced the stubelif plain or md:block (which printed a warning and fell back) and the no-op--htmlblock with full implementations:--plain: ASCII-only, bracket marks[ok ]/[warn]/[fail], same_ASCIItranslation table used elsewhere, supports--explain--md:# EvalTrustheading,**[pass]**/**[warn]**/**[fail]**badges,## What to dosection when relevant, optional## Detailwith--explain--html: self-contained file with inlined CSS, badge spans, HTML-escaped model names, supports--explaindetail sectiontests/test_two_sample_audit.py— 19 new tests covering all three formats (exit codes, no spurious warnings, structure, ASCII/Unicode enforcement, HTML escaping,--explainbehaviour)Testing
Summary by CodeRabbit
New Features
Bug Fixes