Repository navigation
feat(failure_judge): blind dossier, quote-verified LLM judge, and the engine/judge agreement rule (#435) - #607
yihuang0830 wants to merge 5 commits into
Conversation
|
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
left a comment
There was a problem hiding this comment.
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:457filters 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 anagreed, accepted=Truediagnosis 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:833sends a full HTTPS endpoint URL (whichAI.GENERATEaccepts) down theML.GENERATE_TEXTremote-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
left a comment
There was a problem hiding this comment.
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") |
There was a problem hiding this comment.
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.
| 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]) |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
|
@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! |
|
@haiyuan-eng-google Sure, will do! We'll also share it within our club. |
… 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.
7f6a04e to
42bc2f6
Compare
|
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:
From #609 I also fixed 3, 4, 6, 7, 8, 10, 12, 13 and 14. Items 11 and 15 stay open there. |
caohy1988
left a comment
There was a problem hiding this comment.
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.
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.ToolStep.index, so "step 4" is the same call in a rule's evidence and in the judge's answer.SessionDossier.stepsmaps each step to its realspan_id.SessionFacts), close a code fence, fake a cut marker, or close the<trace_data>tag the prompt wraps it in.contextcarries 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.evidence_quoteis copied verbatim from the dossier (not from its own headings) without crossing a cut.quote_locationsays where it was found. A rejected reply goes back once with the reason.DEFAULT_RUBRICis a benchmark-agnostic version of our labeling guide, with synthetic examples.rubric=replaces it.JudgeBackendonly sends prompts (system, prompt, output schema) and returns the raw text and the model that answered.BigQueryJudgeBackendis the built-in backend and the one the docs lead with. It sends a batch as one query, split when it exceedsmax_request_bytes. A Gemini endpoint runs throughAI.GENERATEwithoutput_schemaand an optionalconnection_id. Aproject.dataset.modelendpoint runs throughML.GENERATE_TEXT, so a remote model over another family stays in BigQuery.from_client()reuses aClient's endpoint and connection.CallableJudgeBackendwrapsfn(system, prompt, output_schema)for a judge outside BigQuery, with no new dependency.judge_modelandjudge_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 isdisagreed,engine_only,judge_only,excludedornone, and both opinions are kept for review.same_familyflags a judge from the agent's own model family, read fromattributes.modelon the session'sLLM_REQUESTrows. It does not changeaccepted.Plus
docs/failure_diagnosis.mdand a CHANGELOG entry.Results through this code
The same 44 human-gold runs, a deepseek-flash judge through
CallableJudgeBackend, and the built-in rules:agreedDEFAULT_RUBRIC, no contextDEFAULT_RUBRIC+ scoring rule and data sourcescontext.agreedis 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.checks(feat(rule_taxonomy): rule-based span attribution for failed sessions #594). Added aschecks(simulated from its saved output, with the built-in rules still first),agreedcovers 27 of 44 runs (61%) and 23 are right (85%), withDEFAULT_RUBRICand context. PR 3 will show how to write suchchecks.Evaluation status
Two gaps from the plan in #435, which we're closing in follow-ups:
Design calls
JudgeFailureLabelbesideRuleFailureLabel, with the sameas_tuple().RuleFailureLabelsays rules infer it, andSpanFailureLabeltakes only three categories.AI.GENERATEhas no multi-turn chat.evaluation_run_id.Testing
pyteston Python 3.13 (macOS): 12055 passed, 87 skipped. I deselected the 4browser_smokeLooker Studio tests because they hang on macOS.bash autoformat.shleaves no diff.AI.GENERATEquery is valid.ML.GENERATE_TEXTquery parses, but we have no remote model, so the check stops at model lookup. Could someone with a remote model try it?ML.GENERATE_TEXTtemplates call the function as a scalar and readml_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.