Skip to content

feat(failure_judge): blind dossier, quote-verified LLM judge, and the engine/judge agreement rule (#435) - #607

Open
yihuang0830 wants to merge 5 commits into
GoogleCloudPlatform:mainfrom
yihuang0830:feat/failure-judge
Open

yihuang0830 wants to merge 5 commits into
GoogleCloudPlatform:mainfrom
yihuang0830:feat/failure-judge

Conversation

@yihuang0830

Copy link
Copy Markdown
Contributor

Summary

PR 2 of #435: a blind dossier, a quote-verified LLM judge, and a rule that accepts a label only when the judge and the failure rules (#594) agree. It follows the design in your #435 reply: one small backend interface, BigQuery by default, a pluggable client for judges outside BigQuery, and the judge model recorded on every label.

What's added

session_dossier: one failed session as plain text, for a judge or a human labeler.

  • It shows the task, the expected answer when given, how the run ended, every tool call with its arguments, code and result, and the final response. It holds no rule output, so the judge is blind to the rules.
  • Steps are ToolStep.index, so "step 4" is the same call in a rule's evidence and in the judge's answer. SessionDossier.steps maps each step to its real span_id.
  • The trace is untrusted input. It can't add a step (step numbers come from SessionFacts), close a code fence, fake a cut marker, or close the <trace_data> tag the prompt wraps it in.
  • context carries what only the caller knows, such as the scoring rule or the reference data sources.

failure_judge: shared prompt, validation and quote check, plus two backends.

  • A reply becomes a label only if the category is a frozen name, the step is one the dossier can anchor to a span, and evidence_quote is copied verbatim from the dossier (not from its own headings) without crossing a cut. quote_location says where it was found. A rejected reply goes back once with the reason.
  • DEFAULT_RUBRIC is a benchmark-agnostic version of our labeling guide, with synthetic examples. rubric= replaces it.
  • A JudgeBackend only sends prompts (system, prompt, output schema) and returns the raw text and the model that answered.
    • BigQueryJudgeBackend is the built-in backend and the one the docs lead with. It sends a batch as one query, split when it exceeds max_request_bytes. A Gemini endpoint runs through AI.GENERATE with output_schema and an optional connection_id. A project.dataset.model endpoint runs through ML.GENERATE_TEXT, so a remote model over another family stays in BigQuery. from_client() reuses a Client's endpoint and connection.
    • CallableJudgeBackend wraps fn(system, prompt, output_schema) for a judge outside BigQuery, with no new dependency.
  • Every result and label records judge_model and judge_id (model plus prompt hash).

failure_diagnosis: the combined rule.

  • agreed (accepted) when the rules' primary label and the judge name the same category. Otherwise the outcome is disagreed, engine_only, judge_only, excluded or none, and both opinions are kept for review.
  • same_family flags a judge from the agent's own model family, read from attributes.model on the session's LLM_REQUEST rows. It does not change accepted.

Plus docs/failure_diagnosis.md and a CHANGELOG entry.

Results through this code

The same 44 human-gold runs, a deepseek-flash judge through CallableJudgeBackend, and the built-in rules:

Rubric and context Judge category First error step agreed
DEFAULT_RUBRIC, no context 66% 80% 9 runs, 8 right
DEFAULT_RUBRIC + scoring rule and data sources 75% 75% 8 runs, 7 right
Our full labeling guide, same context 77% 77% 9 runs, 8 right
Two human labelers (13 runs) 85% 92%
  • The generic rubric does about as well as our full guide once the judge knows how the run was scored and what data the reference used. The docs tell users to pass that through context.
  • On the 10 runs where two humans agreed, the judge got 10/10 with context. On the 13 runs where our two LLM labelers disagreed on category or step (the hard slice), it got 8 to 10 of 13 on category.
  • agreed is right on 7 of 8 to 8 of 9 runs with the built-in rules, but rare: it fires on about a fifth of the runs. The built-in rules only see what the event stream shows (tool errors, the call limit, repeated calls, a reported or unreported reference value, previews only), which covers four categories. Most failures here are wrong source, execution/computation or task/planning, and telling those apart takes either reading the task and the code, which is the judge's job, or benchmark ground truth.
  • Our own engine has that ground truth for KramaBench: which files the reference solution reads, the expected answer of each sub-step, and a replay of the agent's code on the right data. That is benchmark-specific, so it stays out of the SDK and plugs in through checks (feat(rule_taxonomy): rule-based span attribution for failed sessions #594). Added as checks (simulated from its saved output, with the built-in rules still first), agreed covers 27 of 44 runs (61%) and 23 are right (85%), with DEFAULT_RUBRIC and context. PR 3 will show how to write such checks.
  • Our original pipeline scored 84%; ported with the same guide and context it scores 77%. Six runs flip between the two, and five of them are runs the gold marks as judgement calls (30 of the 44 are), such as execution/computation vs turn-waste. n = 44, so read these as a range, not point estimates.
  • These numbers use a DeepSeek judge, because the agents under test ran on Gemini and Qwen. The built-in BigQuery backend with Gemini has not been measured on this set.

Evaluation status

Two gaps from the plan in #435, which we're closing in follow-ups:

  • Double labels. Three of five labelers returned in time, so 14 of the 45 runs have two independent labels (13 comparable; in one, a labeler excluded the run). I adjudicated those and labeled or reviewed the rest. More labels are coming, and I'll update the agreement numbers on RFC: AgentForensics collaboration — automated failure taxonomy and span-level trace auditing over BQAA traces #435 when they're in.
  • Silver labels. The two LLM labelers behind the earlier silver numbers were both Claude models. We'll relabel with two models from different families (also different from the judge's), keep their disagreements as the hard slice, and rerun the larger-set numbers. This PR's numbers are scored against the human gold only; the hard slice above is defined by the old labelers' disagreements and will be redrawn.

Design calls

  1. A new JudgeFailureLabel beside RuleFailureLabel, with the same as_tuple(). RuleFailureLabel says rules infer it, and SpanFailureLabel takes only three categories.
  2. Repair rounds are one prompt. The rejected reply and the reason are appended to the prompt, since AI.GENERATE has no multi-turn chat.
  3. Not in this PR: the remote-model branch for the categorical path (a separate small PR, as you suggested), and persisting judge results with an evaluation_run_id.

Testing

  • 182 new tests on synthetic sessions with fake backends and a mocked BigQuery client. They cover step and span mapping, the injection cases, budgets, every validation rejection, the repair round, batching and splitting, the generated SQL and its parameters and labels, model families, and each outcome of the combined rule.
  • Full pytest on Python 3.13 (macOS): 12055 passed, 87 skipped. I deselected the 4 browser_smoke Looker Studio tests because they hang on macOS.
  • bash autoformat.sh leaves no diff.
  • BigQuery dry runs in our project:
    • The AI.GENERATE query is valid.
    • The ML.GENERATE_TEXT query parses, but we have no remote model, so the check stops at model lookup. Could someone with a remote model try it?
  • The existing ML.GENERATE_TEXT templates call the function as a scalar and read ml_generate_text_result. That looks like the dry-run failure I noted in fix(trace): read final_response from the current invocation and parse the plugin's parts #601. This PR uses the table-valued form, and I can file the old templates separately.

This is team work from AgentForensics. @ma-nikki wrote the first version of the dossier builder. @ma-nikki, @beckettj and @syokoo17 labeled the human gold set these numbers rest on. Thanks also to @retepViolet and @bryanphanny, who built the trace parser the rules and dossier grew from. The rubric is adapted from our labeling guide.

@google-cla

google-cla Bot commented Nov 25, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this. The structure is clear and the tests are good: all 183 new tests pass, they cover every diagnosis outcome, repair and unanchorable steps, results come back in input order even when rows are reversed, trace text stays in query parameters, and the new modules import offline with no new dependencies. isort and pyink are clean on the changed files.

Approving. I hit a few things while probing that I'd like to see fixed in a follow-up (the issue is linked below). The first three are the important ones:

  • The quote check can accept text the judge didn't take from the trace. failure_judge.py:457 filters patterns in the quote, then line 460 searches the whole formatted dossier, so a substring of a heading or a cut annotation ("Final response", "the last invocation", "chars shown") passes and can give an agreed, accepted=True diagnosis on an ordinary session. Matching only the first occurrence also rejects a real task quote that happens to appear in the session title first. Recording the ranges of the original field values while rendering and matching only inside them would fix both.
  • Endpoint classification by dot count. failure_judge.py:833 sends a full HTTPS endpoint URL (which AI.GENERATE accepts) down the ML.GENERATE_TEXT remote-model branch and drops the connection. A trailing dot with an empty model component also passes validation.
  • Connection and endpoint strings are escaped and interpolated (failure_judge.py:845-853) rather than bound or validated as identifiers. Also, the output schema passed to callbacks at line 648 is the same mutable object the SQL is built from, so one callback can change later queries.

Smaller ones: the default max_output_tokens=8192 is above the 4,096 limit for partner and open models on the remote-model path the docs recommend; custom error event names go into the dossier without the one-line and delimiter handling other fields get (session_dossier.py:432); the repair prompt repeats reply-controlled text (like the rejected category) in the instruction text; max_request_bytes doesn't count keys or parameter overhead and a single oversized prompt is still sent; a user task stored only in content_parts[].text renders as "(no task text recorded)"; and a decoder RecursionError on one reply aborts the whole batch.

Follow-ups: #609

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

A fuller pass on this head confirmed four of the issues from my earlier review as real blockers, so this replaces that approval. Details are inline:

  • A custom error event name goes into the dossier unescaped and can break its structure (session_dossier.py:432).
  • Heading text and fragments of cut markers are accepted as evidence (failure_judge.py:455-463).
  • One deeply nested reply aborts the whole batch (failure_judge.py:692).
  • Full endpoint URLs take the remote-model query branch (failure_judge.py:833).

max_request_bytes is worth fixing in the same pass. Keys are counted with len(str) rather than their encoded bytes, and a single request that's already over the limit is still sent (around line 867). Everything else stays tracked in #609.

lines.append(_fenced(_untrusted(message or "(no message)", limit)))
elif facts.abort_row is not None:
span = facts.spans[facts.abort_row]
lines.append(f"The run stopped on an error ({span.event_type}):\n")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

span.event_type goes in raw here, while every other trace-derived value goes through _untrusted() / _one_line(). An ERROR row whose event type contains newlines, </trace_data>, a ### Step heading or a cut marker reproduces all three injections the dossier is meant to prevent. Running it through the same one-line conversion and delimiter neutralization would close it.

Comment on lines +455 to +463
if MARKER_START_RE.search(needle) or _CUT_RE.search(needle):
return None
if len(_WORD_CHARS_RE.findall(GENERATED_RE.sub(" ", needle))) < 4:
return None
haystack, offsets = _normalized(dossier.text)
found = haystack.find(needle)
if found < 0:
return None
return dossier.locate(offsets[found])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The checks above only reject a quote that contains a complete marker or keeps enough words after GENERATED_RE strips it. The search then runs over the whole formatted dossier, so a quote that starts inside a cut marker, or a complete step heading for a tool whose name has spaces, matches generated text and returns a valid location. That's enough for an agreed diagnosis with no evidence from the trace. Recording the ranges of the original field values while rendering and only accepting matches inside them would fix both cases, and also the first-match problem when the same text appears earlier in the title.

continue
try:
parsed = _parse_reply(reply.text)
except ValueError:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Deeply nested JSON makes json.loads raise RecursionError, which isn't a ValueError. It escapes this loop, so one malformed reply never gets its repair round and the caller loses the results for every other session in the batch. Catching it here as an invalid reply would keep it per-key.

@property
def is_remote_model(self) -> bool:
"""True when ``endpoint`` is a ``project.dataset.model`` reference."""
return self.endpoint.count(".") >= 2

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

A full endpoint URL (https://…aiplatform.googleapis.com/…) has at least two dots, so from_client() sends it down the ML.GENERATE_TEXT branch with the URL as a MODEL reference and drops the connection. AI.GENERATE accepts those URLs directly. Checking for the documented URL forms first, and validating that a project.dataset.model reference has three non-empty parts, would avoid it. Right now a trailing dot also passes.

@haiyuan-eng-google

Copy link
Copy Markdown
Collaborator

@yihuang0830 and team please help star the repo once you have time to help promote this repo, really appreciate your contribution to make BQAA better!

@yihuang0830

Copy link
Copy Markdown
Contributor Author

@haiyuan-eng-google Sure, will do! We'll also share it within our club.

yihuang0830 and others added 2 commits November 30, 2026 12:50
… engine/judge agreement rule (GoogleCloudPlatform#435)

Add session_dossier, failure_judge (BigQuery and callable backends) and
failure_diagnosis. A label is accepted only when the rules' primary
label and the judge name the same category.

Thanks to Beckett (beckettj) for labeling the human gold set.

Co-authored-by: Nikki Ma <228136455+ma-nikki@users.noreply.github.com>
Co-authored-by: Sophie <228806754+syokoo17@users.noreply.github.com>
…ges, endpoints, request size)

Blockers from the review of GoogleCloudPlatform#607:
- session_dossier: the event type of a run-ending error is one-lined,
  neutralized and cut like other labels.
- Quotes: the dossier records where each value from the session or
  the caller sits (SessionDossier.quotable). verify_quote accepts a
  quote only inside one of those ranges and tries every occurrence, so
  headings, labels, tool and event names, fences and cut markers never
  pass, and a task quote that also appears in the title matches the
  task. GENERATED_RE is removed.
- A reply nested too deeply to decode is an invalid reply for its key
  and gets its repair round, instead of aborting the batch.
- classify_endpoint: a Vertex AI https URL or projects/... name, then
  project.dataset.model with three non-empty parts, then a model name;
  anything else raises. AI.GENERATE takes endpoint, connection_id and
  output_schema only as literals, so endpoint and connection are
  validated.
- max_request_bytes counts JSON-escaped bytes of keys and prompts plus
  overhead, computed once per request; a request over the limit alone
  gets an error reply and is not sent.

From GoogleCloudPlatform#609: per-request copies of the output schema and SQL built from
a frozen copy (3); max_output_tokens defaults to 4096 for remote models
(4); rejection reasons no longer repeat reply text, and the rejected
reply is shown as capped data that cannot close its block (6, 7, 10);
the task is read from content_parts (8); family detection, span
agreement across traces, and the label's session are checked (12-14).

Also: zero-width spaces from neutralize are ignored when matching
quotes, uncitable steps have a location (step_ranges), lone surrogates
are replaced, the reply fence regex no longer backtracks, and
BigQueryJudgeBackend rejects duplicate keys.
@yihuang0830

Copy link
Copy Markdown
Contributor Author

Thanks for the second pass. I rebased the branch onto main (same base as your merge) and moved Beckett from a co-author trailer to a thanks line so the CLA check can pass. The review fixes are in their own commit, 42bc2f6, each with regression tests:

  • Error event names (session_dossier.py): kept on one line, neutralized and cut like the other labels.
  • Quote check: while rendering, the dossier now records where each value from the session or the caller sits (SessionDossier.quotable). verify_quote accepts a quote only inside one of those ranges and tries every occurrence. Headings, labels, tool and event names, fences and cut markers are all outside the ranges, so the heading and marker cases fail. A task quote that also appears in the title now matches the task. The GENERATED_RE filter is gone.
  • Deeply nested replies: a RecursionError now counts as an invalid reply for that key only, and that key gets its repair round.
  • Endpoints: classify_endpoint checks the Vertex https:// URL and projects/... forms first. Next it checks for a project.dataset.model with three non-empty parts, then for a model name, and raises on anything else. Dry runs showed that AI.GENERATE takes endpoint, connection_id and output_schema only as string literals, so these are validated rather than bound.
  • max_request_bytes: sizes are now the JSON-escaped bytes the client actually sends, for keys and prompts, plus overhead. Each size is computed once. A request that is over the limit on its own gets an error reply and is not sent.

From #609 I also fixed 3, 4, 6, 7, 8, 10, 12, 13 and 14. Items 11 and 15 stay open there.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looks good at this head. The rebase and the review fixes hold up: I ran the new tests for the quote ranges, endpoint routing, schema isolation, event names, repair prompts and deep replies, and they pass here and fail without the fixes. Format and import checks are clean.

A few things I'd still like to see tightened, none of them blocking. I'll put them on #609 so they don't get lost.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants