Skip to content

feat: audit cost and latency alongside quality (issue #165) - #175

Merged
k-dickinson merged 7 commits into
k-dickinson:mainfrom
Maqbool61:feat/efficiency-audit-165
Aug 17, 2026
Merged

k-dickinson merged 7 commits into
k-dickinson:mainfrom
Maqbool61:feat/efficiency-audit-165

Conversation

@Maqbool61

@Maqbool61 Maqbool61 commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Closes #165.

The adapters already read token_count and latency, but the audit
pipeline never used them — cost/speed only appeared as vague advice text
("decide on cost or speed"). This PR makes the tradeoff explicit with a
first-class Efficiency pillar.

What changed

New file: src/evaltrust/audit/efficiency.py

  • audit_efficiency(quality_data, model_a, model_b, *, token_count_data, latency_data)
  • Produces one advisory Finding per dataset supplied (token count, latency, or both)
  • Each finding shows the per-model means, the ratio (e.g. "B uses 3.2x the tokens of A"), and the quality delta side-by-side
  • Adapts the how_to_fix text to all four tradeoff cases: better+cheaper, better+pricier, worse+cheaper, worse+pricier
    Modified: src/evaltrust/audit/runner.py
  • Added token_count_data and latency_data kwargs to run_audit() and _comparison()
  • Efficiency block fires at the end of _comparison(), gated on token_count_data is not None or latency_data is not None
    Modified: src/evaltrust/api.py
  • Exposed token_count_data and latency_data on the public audit() function with full docstring entries
    New file: tests/test_efficiency.py
  • 20 tests covering: no data → no findings, token findings, latency findings, both together, all four tradeoff directions, verdict not lowered, existing findings unchanged, missing model data silent skip, JSON serialisability, public API smoke tests

Design decisions

  • Advisory only, always Status.PASS — efficiency findings never lower the confidence verdict. The verdict stays quality-driven.
  • Zero findings when no data — the Efficiency pillar is completely absent from the output when neither token_count_data nor latency_data is passed. Default output for quality-only files is byte-for-byte unchanged.
  • No schema changes — cost/latency are passed as separate EvalData objects alongside the quality EvalData, keeping Example and EvalData clean.
  • Missing model data skips silently — if a cost/latency dataset doesn't have scores for both models (e.g. only one model was logged), the finding is omitted rather than crashing.

Example output

Efficiency
  [ok  ] Token cost: B uses 3.2x the tokens of A
  [ok  ] Latency: B is 4x slower than A
 
What to do
  ...
  - B is better on quality (+10.0 pt quality gain) but costs 3.2x the
    tokens. Decide whether the quality gain justifies the extra cost.
  - B is better on quality (+10.0 pt quality gain) but 4x slower.
    Decide whether the latency increase is acceptable for the quality gain.

Testing

python -m pytest tests/test_efficiency.py -v   # 20 new tests
python -m pytest                               # 1122 total, all passing

Summary by CodeRabbit

  • New Features

    • Added optional efficiency analysis using token usage and latency data.
    • Automatically detects efficiency data in supported audit inputs.
    • Supports single-suite and two-suite comparisons with configurable latency units.
    • Reports ratios, trade-offs, recommendations, and structured efficiency metrics.
    • Efficiency findings are advisory and do not affect overall audit verdicts.
    • Handles missing, non-overlapping, or unavailable data gracefully.
  • Tests

    • Added comprehensive coverage for efficiency analysis, command-line output, serialization, edge cases, and API integration.

Add a first-class Efficiency pillar that shows the token-count and
latency delta next to the quality delta when that data is present.

- New audit/efficiency.py with audit_efficiency() producing advisory
  Finding objects (status=PASS, never lowers the verdict)
- runner.py: wire token_count_data and latency_data through run_audit()
  and _comparison(); efficiency block is a no-op when neither is supplied
- api.py: expose token_count_data and latency_data on the public audit()

Default output for quality-only files is unchanged (0 new findings when
no cost/latency data is passed). 20 new tests, all passing.

Closes k-dickinson#165
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The audit now accepts token-count and latency datasets. Comparison audits generate advisory efficiency findings with quality deltas, ratios, recommendations, and structured metrics. Efficiency findings do not affect verdicts. Quality-only behavior remains unchanged.

Changes

Efficiency audit

Layer / File(s) Summary
Efficiency finding logic
src/evaltrust/audit/efficiency.py, tests/test_efficiency.py
Adds token and latency comparisons with quality deltas, ratios, recommendations, structured metrics, missing-data handling, and advisory PASS findings.
Comparison runner and API integration
src/evaltrust/audit/runner.py, src/evaltrust/api.py, tests/test_efficiency.py
Passes efficiency datasets through comparison paths and the public API. Appends efficiency findings without changing verdicts.
CLI data extraction and integration
src/evaltrust/cli.py, tests/test_cli.py
Extracts token-count and latency data from MLflow-style inputs for two-file and single-file audits. Tests automatic detection, output formats, and quality-only behavior.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant CLI
  participant run_audit
  participant audit_efficiency
  Client->>CLI: MLflow-style quality and efficiency data
  CLI->>run_audit: paired quality, token-count, and latency datasets
  run_audit->>audit_efficiency: compare quality, tokens, and latency
  audit_efficiency-->>run_audit: advisory efficiency findings
  run_audit-->>CLI: findings and verdict
  CLI-->>Client: formatted audit output
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The implementation covers the requested Efficiency pillar, advisory findings, quality deltas, optional data, and quality-only behavior, but a stale observed_ranges reference may break comparisons [#165]. Remove or restore the observed_ranges reference in _comparison, then verify explicit and automatic comparison audits [#165].
✅ 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 identifies the addition of cost and latency auditing alongside quality.
Out of Scope Changes check ✅ Passed The API, runner, CLI integration, efficiency module, and tests directly support the linked issue objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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: 4

🧹 Nitpick comments (5)
src/evaltrust/audit/runner.py (1)

148-149: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The single-model paths drop token_count_data and latency_data silently.

Lines 148-149 accept both datasets on every run_audit call. Only the two _comparison calls forward them. The threshold branch on line 170 and the single-model branch on line 176 discard them without any signal. A caller who passes efficiency data with a threshold audit gets no efficiency finding and no explanation.

Consider documenting that the efficiency pillar applies to two-model comparisons only, or emitting a SKIP finding on the single-model path.

Also applies to: 165-181

🤖 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/audit/runner.py` around lines 148 - 149, Update run_audit so
single-model and threshold audit paths explicitly handle supplied
token_count_data and latency_data: either document that the efficiency pillar is
supported only for two-model comparisons, or emit a SKIP finding explaining that
limitation. Preserve forwarding of both datasets in the existing _comparison
calls and ensure single-model inputs are never silently discarded.
tests/test_efficiency.py (3)

20-47: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

two_model_cost_data duplicates make_data; add strict=True to both zip calls.

The two helpers have identical bodies. Keep one implementation and alias the other so the intent stays readable. Ruff flags both zip() calls (B905). With strict=True, a fixture with mismatched list lengths fails loudly instead of truncating silently.

♻️ Proposed refactor
 def make_data(a_scores, b_scores, models=("A", "B")):
     """Build a two-model EvalData from parallel score lists."""
     examples = [
         Example(id=str(i), scores={models[0]: float(a), models[1]: float(b)})
-        for i, (a, b) in enumerate(zip(a_scores, b_scores))
+        for i, (a, b) in enumerate(zip(a_scores, b_scores, strict=True))
     ]
     return EvalData(models=list(models), examples=examples,
                     source_format="test", metadata={})
@@
-def two_model_cost_data(a_costs, b_costs, models=("A", "B")):
-    """Build a cost/latency EvalData with per-example values for two models."""
-    examples = [
-        Example(id=str(i), scores={models[0]: float(a), models[1]: float(b)})
-        for i, (a, b) in enumerate(zip(a_costs, b_costs))
-    ]
-    return EvalData(models=list(models), examples=examples,
-                    source_format="test", metadata={})
+# A cost/latency dataset has the same shape as a quality dataset.
+two_model_cost_data = make_data
🤖 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_efficiency.py` around lines 20 - 47, Update make_data and
two_model_cost_data to use strict=True in their zip calls so mismatched inputs
fail instead of being truncated, then remove the duplicated implementation by
making two_model_cost_data reuse or alias make_data while preserving the
cost/latency helper’s readable name.

Source: Linters/SAST tools


109-124: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Strengthen these assertions; they pass for every branch.

Line 124 asserts "A" in tf.how_to_fix. The model name "A" is interpolated in most how_to_fix branches, so this assertion cannot detect a wrong branch. Line 115 has the same problem: "prefer" appears in several branches.

Assert on the distinguishing phrase for each branch. Also add an assertion on tf.title for the cheaper case. No test currently checks that title, which is where the inverted ratio in src/evaltrust/audit/efficiency.py lines 136-137 appears.

💚 Proposed assertions
 def test_token_finding_cheaper_and_better_recommends_b():
     quality = make_data([0.7] * 10, [0.9] * 10)
     tokens = two_model_cost_data([300] * 10, [100] * 10)  # B is cheaper
     findings = audit_efficiency(quality, "A", "B", token_count_data=tokens)
     (tf,) = by_check(findings, "efficiency_tokens")
-    # B is better on quality AND cheaper → prefer B
-    assert "cheaper" in tf.how_to_fix.lower() or "prefer" in tf.how_to_fix.lower()
+    # B is better on quality AND cheaper → prefer B
+    assert "Prefer B" in tf.how_to_fix
+    # The title must not claim that B uses more tokens than A.
+    assert "B uses 3x the tokens of A" not in tf.title
@@
     (tf,) = by_check(findings, "efficiency_tokens")
-    # B is worse AND pricier → prefer A
-    assert "A" in tf.how_to_fix
+    # B is worse AND pricier → prefer A
+    assert "Prefer A" in tf.how_to_fix
🤖 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_efficiency.py` around lines 109 - 124, Strengthen the assertions
in test_token_finding_cheaper_and_better_recommends_b and
test_token_finding_worse_and_more_expensive_recommends_a to match each branch’s
distinctive how_to_fix wording rather than generic terms or model names. Add an
assertion for the cheaper case’s tf.title to catch the inverted ratio issue in
the efficiency_tokens result.

257-274: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for a quality dataset that lacks scores for a model.

The serialization tests use json.dumps, which accepts NaN by default and emits the non-standard NaN token. These tests therefore cannot detect the NaN quality_delta case described on src/evaltrust/audit/efficiency.py lines 71-88.

Add a test that builds quality data without scores for one model, then asserts the resulting finding text and that json.dumps(d, allow_nan=False) succeeds.

🤖 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_efficiency.py` around lines 257 - 274, The existing serialization
coverage does not exercise missing model quality scores or reject non-standard
NaN values. Add a test alongside test_token_finding_is_json_serialisable that
constructs quality data lacking scores for one model, runs audit_efficiency, and
asserts the resulting finding text is correct; serialize its to_dict() result
with json.dumps(..., allow_nan=False) and ensure it succeeds.
src/evaltrust/audit/efficiency.py (1)

115-124: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the unused mean_q_a and mean_q_b parameters.

Both helpers receive mean_q_a and mean_q_b but read neither. Only quality_delta is used. Dropping the two parameters keeps the private helper signatures honest.

Separately, line 227 and line 228 hard-code "ms/example" while the docstring on line 59 allows any consistent unit. Consider a neutral label such as "latency units/example".

Also applies to: 202-211

🤖 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/audit/efficiency.py` around lines 115 - 124, Remove the unused
mean_q_a and mean_q_b parameters from _token_finding and the other private
helper with the same unused arguments, updating all call sites accordingly while
retaining quality_delta. Replace hard-coded “ms/example” labels in the latency
findings around the affected helpers with the neutral unit label permitted by
the module docstring, such as “latency units/example”.
🤖 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/efficiency.py`:
- Around line 132-139: Align ratio values with their descriptive direction words
in the efficiency findings. In src/evaltrust/audit/efficiency.py lines 132-139,
update the cheaper token branch around _ratio_str and comparison so the ratio
and sentence subject both describe the same orientation. In lines 232-261, use
the inverse latency ratio in each “faster” branch, consistent with the existing
handling around line 222; preserve the non-faster branches.
- Around line 107-112: Update _quality_delta_str so positive deltas render with
a plus sign and negative deltas render with an ASCII hyphen-minus, while
preserving the zero-change output; remove the no-op replace call. Also update
the function docstring to use an ASCII hyphen instead of the ambiguous Unicode
minus sign.
- Around line 71-88: Handle a NaN quality_delta in audit_efficiency before
invoking _token_finding or _latency_finding. When quality scores are
unavailable, route to a separate finding path that reports the token or latency
ratio without quality-claim text and uses a JSON-safe quality_delta value;
preserve the existing narrative branches for finite deltas.
- Around line 232-261: Update the faster-direction messages in the efficiency
comparison logic to display the inverse latency ratio, matching the existing
faster-ratio calculation used by comparison. Use that corrected value in the
quality-equivalent and quality-worse-but-faster branches, while preserving the
existing b/a ratio for slower branches.

---

Nitpick comments:
In `@src/evaltrust/audit/efficiency.py`:
- Around line 115-124: Remove the unused mean_q_a and mean_q_b parameters from
_token_finding and the other private helper with the same unused arguments,
updating all call sites accordingly while retaining quality_delta. Replace
hard-coded “ms/example” labels in the latency findings around the affected
helpers with the neutral unit label permitted by the module docstring, such as
“latency units/example”.

In `@src/evaltrust/audit/runner.py`:
- Around line 148-149: Update run_audit so single-model and threshold audit
paths explicitly handle supplied token_count_data and latency_data: either
document that the efficiency pillar is supported only for two-model comparisons,
or emit a SKIP finding explaining that limitation. Preserve forwarding of both
datasets in the existing _comparison calls and ensure single-model inputs are
never silently discarded.

In `@tests/test_efficiency.py`:
- Around line 20-47: Update make_data and two_model_cost_data to use strict=True
in their zip calls so mismatched inputs fail instead of being truncated, then
remove the duplicated implementation by making two_model_cost_data reuse or
alias make_data while preserving the cost/latency helper’s readable name.
- Around line 109-124: Strengthen the assertions in
test_token_finding_cheaper_and_better_recommends_b and
test_token_finding_worse_and_more_expensive_recommends_a to match each branch’s
distinctive how_to_fix wording rather than generic terms or model names. Add an
assertion for the cheaper case’s tf.title to catch the inverted ratio issue in
the efficiency_tokens result.
- Around line 257-274: The existing serialization coverage does not exercise
missing model quality scores or reject non-standard NaN values. Add a test
alongside test_token_finding_is_json_serialisable that constructs quality data
lacking scores for one model, runs audit_efficiency, and asserts the resulting
finding text is correct; serialize its to_dict() result with json.dumps(...,
allow_nan=False) and ensure it succeeds.
🪄 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: dbfcc06d-25bf-45a1-b23a-10091dc4e365

📥 Commits

Reviewing files that changed from the base of the PR and between d508963 and dfabaa9.

📒 Files selected for processing (4)
  • src/evaltrust/api.py
  • src/evaltrust/audit/efficiency.py
  • src/evaltrust/audit/runner.py
  • tests/test_efficiency.py

Comment on lines +71 to +88
# Mean quality scores (for the tradeoff narrative).
mean_q_a = _mean(quality_data, model_a)
mean_q_b = _mean(quality_data, model_b)
quality_delta = mean_q_b - mean_q_a # positive means B is better

if token_count_data is not None:
f = _token_finding(token_count_data, model_a, model_b,
mean_q_a, mean_q_b, quality_delta)
if f is not None:
findings.append(f)

if latency_data is not None:
f = _latency_finding(latency_data, model_a, model_b,
mean_q_a, mean_q_b, quality_delta)
if f is not None:
findings.append(f)

return findings

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Handle a NaN quality_delta before it reaches the narrative branches.

_mean returns float("nan") when the quality dataset has no scores for a model. With preference-only data, _comparison still calls audit_efficiency when token_count_data or latency_data is supplied, so quality_delta becomes NaN on a reachable path.

NaN then fails both abs(delta) < 1e-9 and delta > 0, so _token_finding and _latency_finding fall into the "B is worse on quality" branch and emit text such as "worse on quality (nan pt quality drop)". The details["quality_delta"] value is also NaN, which is not JSON-serializable by strict parsers.

Consider treating an unavailable quality delta as a separate case and reporting the cost or latency ratio without a quality claim.

🐛 Proposed guard
     mean_q_a = _mean(quality_data, model_a)
     mean_q_b = _mean(quality_data, model_b)
-    quality_delta = mean_q_b - mean_q_a  # positive means B is better
+    # NaN when either model has no quality scores (e.g. preference-only data).
+    quality_delta = mean_q_b - mean_q_a  # positive means B is better
+    if np.isnan(quality_delta):
+        quality_delta = None  # helpers must render "quality delta unavailable"
🤖 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/audit/efficiency.py` around lines 71 - 88, Handle a NaN
quality_delta in audit_efficiency before invoking _token_finding or
_latency_finding. When quality scores are unavailable, route to a separate
finding path that reports the token or latency ratio without quality-claim text
and uses a JSON-safe quality_delta value; preserve the existing narrative
branches for finite deltas.

Comment thread src/evaltrust/audit/efficiency.py Resolved
Comment thread src/evaltrust/audit/efficiency.py Resolved
Comment thread src/evaltrust/audit/efficiency.py Resolved
- Guard against NaN quality_delta (preference-only data): return []
  immediately rather than emitting 'nan pt quality drop' or storing
  NaN in details (not JSON-serialisable by strict parsers)
- Fix _quality_delta_str sign: drops now render as '-2.0 pt quality
  drop' not '+2.0 pt quality drop'; remove no-op .replace() call;
  fix Unicode minus sign in docstring (RUF002, use ASCII hyphen)
- Fix token cheaper-branch ratio orientation: was emitting '3x' when
  B=100 vs A=300 but calling it 'cheaper' -- inverted. Now correctly
  shows 'B uses 3x fewer tokens than A'
- Fix latency faster-branch ratio: fix strings reused ratio (< 1 when
  B is faster) so printed '0.33x faster'. Now uses the inverse ratio
  (> 1) consistent with the title, e.g. '3x faster'
- Add 12 new tests covering all four bugs (32 total, all passing)

@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: 2

🤖 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/efficiency.py`:
- Around line 148-200: Update the efficiency-reporting helpers in
src/evaltrust/audit/efficiency.py at lines 148-200, 245-252, and 261-295 to
handle equal resource means before calculating or formatting directional ratios:
describe tied token means and latency as equal without “fewer,” “faster,” or
“slower” claims, and base tie-case recommendations solely on quality_delta
rather than arbitrarily preferring model_a. Add regression coverage for resource
ties and zero-mean inputs.
- Around line 255-258: Update the efficiency audit finding construction around
how_detected so it preserves the latency unit supplied by the caller instead of
always labeling means as “ms/example.” Thread the unit through the relevant API
and formatting path, or use unit-neutral wording until milliseconds are
required, and add a regression case covering non-millisecond input such as
seconds.
🪄 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: 2287f63a-3d99-4594-ba62-eefe73061ad0

📥 Commits

Reviewing files that changed from the base of the PR and between dfabaa9 and 40477b5.

📒 Files selected for processing (2)
  • src/evaltrust/audit/efficiency.py
  • tests/test_efficiency.py

Comment thread src/evaltrust/audit/efficiency.py Resolved
Comment thread src/evaltrust/audit/efficiency.py Resolved
- Preserve latency unit in finding: how_detected hardcoded 'ms/example'
  but the API accepts any consistent unit. Added latency_unit='ms' param
  to audit_efficiency(), _latency_finding(), run_audit(), and audit()
  so the label always matches the caller's data (ms, s, us, etc.)
- Treat tied resource means as equal efficiency: no equality branch
  before the directional >= split meant equal means produced '1x fewer'
  or '1x slower' text. Added math.isclose() equality guards for both
  token and latency findings; equal-cost recommendation is now driven
  purely by the quality delta
- Add 10 new tests covering latency_unit and equality branches (42 total)
@k-dickinson

Copy link
Copy Markdown
Owner

the efficiency pillar itself is clean, advisory only so it never touches the verdict, and well tested. nice work there.

one thing before merge though: right now it only works through the Python API. it isn't wired into the CLI, and it doesn't pull the token_count or latency that the adapters already parse. i tested an MLflow file that has a token_count column and got zero efficiency findings, because the caller has to hand build separate EvalData objects and pass them in. that means the original motivation (the adapters read these but nothing audits them) isn't actually closed for someone running evaltrust audit file.json.

could you wire it end to end so a loaded file with token_count or latency surfaces the pillar automatically, and expose it on the CLI? if you'd rather ship the primitive now and connect it separately, that's fine too, just call it out as API only for now and open a follow up so it doesn't get lost.

The efficiency findings were Python-API-only. Running:
  evaltrust audit file.json
on an MLflow file with token_count produced zero efficiency findings
because the CLI called load_comparison/load_suite and then run_audit
without passing the extracted token_count/latency side-channels.

Two paths are now wired:

1. Two-file path (evaltrust audit runA.json runB.json):
   load_suite() is called on each file separately; token_count and
   latency EvalData objects are merged (same label logic as the quality
   merge) and passed to run_audit() as efficiency side-channels.
   Best-effort: if suite extraction fails for any reason, the audit
   proceeds without efficiency findings rather than crashing.

2. Single-file path (evaltrust audit mlflow_run.json):
   When load_suite() returns a suite with len > 1, token_count and
   latency are now extracted from the suite before deciding the audit
   path, and passed to run_audit() when exactly one quality metric
   remains. Multi-quality-metric suites go through audit_suite as
   before (efficiency not yet threaded through the suite report path).

6 new CLI integration tests covering both paths, advisory-only exit
code behaviour, --json output, and finding-status stability.

@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: 3

🤖 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/efficiency.py`:
- Around line 176-177: Remove the unnecessary f-string prefixes from the
constant messages in the audit efficiency output, including the corresponding
messages around the referenced alternate location. Keep the message text and
concatenation behavior unchanged; only use regular string literals where no
interpolation occurs.

In `@src/evaltrust/cli.py`:
- Around line 347-361: Update the efficiency merge calls in the
comparison-loading flow to use the resolved labels from data.models[0] and
data.models[1] for both token-count and latency data, rather than the raw
model_a/model_b values. Keep the existing merge_two inputs and quality-audit
behavior unchanged so identical requested models retain the
load_comparison-resolved “_2” label.

In `@tests/test_cli.py`:
- Around line 850-851: Split the semicolon-separated path assignment and
write_text calls in the affected test setup blocks into separate statements,
including both sites around fa/fb and their corresponding later occurrence, so
Ruff no longer reports E702.
🪄 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: f30d66a1-4794-4659-8b8a-f6289f07e3e4

📥 Commits

Reviewing files that changed from the base of the PR and between 40477b5 and 417869a.

📒 Files selected for processing (6)
  • src/evaltrust/api.py
  • src/evaltrust/audit/efficiency.py
  • src/evaltrust/audit/runner.py
  • src/evaltrust/cli.py
  • tests/test_cli.py
  • tests/test_efficiency.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/evaltrust/api.py
  • src/evaltrust/audit/runner.py
  • tests/test_efficiency.py

Comment on lines +176 to +177
f"The models are equal on both quality and token cost. "
f"Either model is a valid choice."

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove the constant f-string prefixes.

Ruff reports F541 on these four lines. The lint job will fail because none of these strings contains a placeholder.

Proposed fix
-                f"The models are equal on both quality and token cost. "
-                f"Either model is a valid choice."
+                "The models are equal on both quality and token cost. "
+                "Either model is a valid choice."
...
-                f"The models are equal on both quality and latency. "
-                f"Either model is a valid choice."
+                "The models are equal on both quality and latency. "
+                "Either model is a valid choice."

Also applies to: 294-295

🧰 Tools
🪛 Ruff (0.16.1)

[error] 176-176: f-string without any placeholders

Remove extraneous f prefix

(F541)


[error] 177-177: f-string without any placeholders

Remove extraneous f prefix

(F541)

🤖 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/audit/efficiency.py` around lines 176 - 177, Remove the
unnecessary f-string prefixes from the constant messages in the audit efficiency
output, including the corresponding messages around the referenced alternate
location. Keep the message text and concatenation behavior unchanged; only use
regular string literals where no interpolation occurs.

Source: Linters/SAST tools

Comment thread src/evaltrust/cli.py
Comment on lines +347 to +361
la = primary_model(suite_a["token_count"])
lb = primary_model(suite_b["token_count"])
lbl_a = (model_a or data.models[0])
lbl_b = (model_b or data.models[1])
from .core.pairing import merge_two as _merge
token_count_data = _merge(
suite_a["token_count"], suite_b["token_count"],
lbl_a, lbl_b)
if "latency" in suite_a and "latency" in suite_b:
lbl_a = (model_a or data.models[0])
lbl_b = (model_b or data.models[1])
from .core.pairing import merge_two as _merge
latency_data = _merge(
suite_a["latency"], suite_b["latency"],
lbl_a, lbl_b)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use the resolved comparison labels for efficiency data.

If callers pass the same --model-a and --model-b value, load_comparison() changes model B to <label>_2. These lines still pass the same raw label to both sides of merge_two(). The second score then overwrites the first score in the merged efficiency examples, so Efficiency cannot compare the same model pair as the quality audit.

Use data.models[0] and data.models[1] for both resource merges.

Proposed fix
-                    from .core.pairing import primary_model
-                    la = primary_model(suite_a["token_count"])
-                    lb = primary_model(suite_b["token_count"])
-                    lbl_a = (model_a or data.models[0])
-                    lbl_b = (model_b or data.models[1])
+                    lbl_a, lbl_b = data.models
🤖 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 347 - 361, Update the efficiency merge
calls in the comparison-loading flow to use the resolved labels from
data.models[0] and data.models[1] for both token-count and latency data, rather
than the raw model_a/model_b values. Keep the existing merge_two inputs and
quality-audit behavior unchanged so identical requested models retain the
load_comparison-resolved “_2” label.

Comment thread tests/test_cli.py
Comment on lines +850 to +851
fa = tmp_path / "a.json"; fa.write_text(json.dumps(raw_a))
fb = tmp_path / "b.json"; fb.write_text(json.dumps(raw_b))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Split the statements to satisfy Ruff.

Ruff reports E702 at both sites. Put each write_text() call on its own line so the test file passes the reported lint check.

Also applies to: 889-890

🧰 Tools
🪛 ast-grep (0.45.0)

[info] 850-850: use jsonify instead of json.dumps for JSON output
Context: json.dumps(raw_b)
Note: [CWE-116] Improper Encoding or Escaping of Output.

(use-jsonify)

🪛 Ruff (0.16.1)

[error] 850-850: Multiple statements on one line (semicolon)

(E702)


[error] 851-851: Multiple statements on one line (semicolon)

(E702)

🤖 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 850 - 851, Split the semicolon-separated path
assignment and write_text calls in the affected test setup blocks into separate
statements, including both sites around fa/fb and their corresponding later
occurrence, so Ruff no longer reports E702.

Source: Linters/SAST tools

@k-dickinson

Copy link
Copy Markdown
Owner

this is what it needed, thanks. tested it with two files that carry token_count and the efficiency pillar shows up now ("Token cost: X uses 3x the tokens of Y"), and a plain quality-only file still shows nothing. good to merge.

@k-dickinson

Copy link
Copy Markdown
Owner

fix merge conflict then good to merge

@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

🤖 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/runner.py`:
- Line 153: Restore the observed_ranges parameter in _comparison and forward it
through both the explicit and automatic comparison paths into
audit_benchmark_health. Ensure the score-based path no longer references an
undefined name and preserves the public observed_ranges contract.
🪄 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: 7a30a4a1-3942-4774-98c8-752373fb058f

📥 Commits

Reviewing files that changed from the base of the PR and between 76b7ed2 and 6911be4.

📒 Files selected for processing (1)
  • src/evaltrust/audit/runner.py

Comment thread src/evaltrust/audit/runner.py Resolved
@Maqbool61

Copy link
Copy Markdown
Contributor Author

@k-dickinson Any update?

@k-dickinson

Copy link
Copy Markdown
Owner

@Maqbool61 yeah this is good to go, thanks for sorting the rebase. merging it in shortly.

@k-dickinson
k-dickinson merged commit 0405f40 into k-dickinson:main Aug 17, 2026
5 checks passed
@Maqbool61
Maqbool61 deleted the feat/efficiency-audit-165 branch August 17, 2026 05:42
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.

Audit cost and latency, not just quality

2 participants