Repository navigation
feat(evalbench): materialize versioned EvalBench snapshots and failed-session contract (#435) - #451
Conversation
…-session contract (GoogleCloudPlatform#435) The GoogleCloudPlatform#435 v3 MVP needs an immutable EvalBench event+score snapshot and a failed-session denominator. The reader (`from_bigquery` + `to_agent_event_rows`) already existed; this adds the missing writer. - `EvalBenchRun.materialize()` publishes events, imported scores, and a manifest row into BQAA-owned tables (`evalbench_agent_events`, `evalbench_scores_imported`, `evalbench_import_manifest`) in an optional cross-project target. The ADK plugin `agent_events` table is never written. Rows are staged with load jobs and published by a single multi-statement transaction, so a failed re-import cannot leave a partial corpus and there is no delete-then-append window. - `import_version` defaults to a content fingerprint of results/scores/ configs: unchanged source is a no-op, changed source is a new version, and an explicit version with drifted fingerprints raises unless `replace=True`. The manifest records counts, fingerprints, target tables, snapshot and import timestamps. - `from_bigquery(snapshot_at=...)` reads all three source tables `FOR SYSTEM_TIME AS OF` one instant so a still-running job cannot mix versions across sequential reads. - W0.4 failed-session contract: `EvalScorePolicy` (per-comparator min score hook), `failed_sessions_sql()` pinned to one import_version, and `classify_sessions()` as the in-memory reference. `returncode == 0` means completed, not passed; completed-but-low-scoring sessions and process failures are both counted. - `bq-agent-sdk evalbench-import` CLI as a thin wrapper. - docs/evalbench.md describes materialize, the manifest, and the contract.
caohy1988
left a comment
There was a problem hiding this comment.
Reviewer: Kimi
Verdict: Request changes (one P1, rest can wait)
Reviewed the full diff plus the head-branch source and tests locally (worktree at b5c45a0). Ran python3 -m pytest tests/test_evalbench_importer.py tests/test_cli_evalbench_import.py — 39/39 pass.
Slice-1 contract check:
- BQAA-owned tables only: defaults are
evalbench_agent_events/evalbench_scores_imported/evalbench_import_manifest; the atomicity test explicitly asserts no destination contains.agent_events. ✓ - Atomic (job_id, import_version) publish: staging load jobs (managed storage, not the streaming buffer — the code comment is correct and this matters) + one multi-statement
BEGIN…DELETE×3…INSERT×3…COMMITtransaction; staging always dropped infinally; mapping errors raised before any BQ write. ✓ - Failed-session contract:
returncode==0only feedsstatus='ERROR'when non-zero;failed_sessions_sqlnever readsreturncode;missing_score_fails=Trueby default;classify_sessionsand the SQL are pinned to each other by tests. ✓ - CLI
evalbench-import: registered on thebq-agent-sdkapp, exit 0 for imported/replaced/unchanged, exit 2 on errors. ✓
P1
evalbench.py:661-672 — the "unchanged" no-op trusts fingerprints only and can return a false table pointer. When a manifest row exists with matching fingerprints, materialize() returns status="unchanged" with events_table/scores_table set to the caller's requested refs — without checking they match the manifest's stored events_table/scores_table. Repro: import a job with defaults, then re-import the identical source with --events-table evalbench_agent_events_v2 (same manifest table, so same (job_id, import_version) key). The second call is a no-op that reports events_table=…evalbench_agent_events_v2, but that table was never created or written. Any consumer that follows result.events_table (or the docs' guidance to point get_session_trace at it) silently reads an empty/nonexistent table. Fix options: compare stored vs requested events_table/scores_table before the no-op and raise on mismatch, or proceed to publish into the new tables. A test mirroring test_materialize_same_job_and_version_is_a_noop with a different events_table would pin it.
P2 (should fix, not blocking)
evalbench.py:973-978(_score_scenario_id) vs_scenario_id: score rows only probe top-levelid/eval_id/scenario_id/prompt_id, while result rows also look into nestedscenario/eval_results. A score row whose id is only nested getssession_id=Noneand silently drops out of the score gate; under the default policy the session then fails as "missing score" — conservative, but misattributes the failure and undercounts the denominator's evidence. Mirror the nested lookup or document the asymmetry.evalbench.py:590/cli.py:2248:--events-table agent_eventsis accepted (segment regex allows it). Defaults are safe and the target dataset is caller-chosen, but the "never the productionagent_eventstable" promise would be more robust with an explicit guard rejecting that reserved name.
Nits / can wait
cli.py:369imports the privateevalbench._parse_timestamp— fine for now, consider promoting it.- No live-BQ integration test for
materialize(); docs already flag this as a boundary. Acceptable for the MVP slice given the stubbed-client tests pin the transaction shape well. - Taxonomy, localization, other harnesses,
evalbench-score: correctly out of scope per the PR description.
The P1 is a small, well-scoped fix; everything else about the atomicity and failed-session design looks right.
caohy1988
left a comment
There was a problem hiding this comment.
Reviewer: Codex
Verdict: Request changes. The targeted tests pass, but five P1 findings break the slice-1 ownership, immutability, failed-session, or consumer contracts.
P0
- None.
P1
-
src/bigquery_agent_analytics/evalbench.py:604- The reservedagent_eventstarget is still accepted.events_tableis checked only for identifier syntax and then used directly to formevents_ref, so both the public API and--events-table agent_eventscan target the ADK production table despite the hard "neveragent_events" contract. Reject the reserved name for every destination argument before any BigQuery operation, and add API/CLI regression tests. -
src/bigquery_agent_analytics/evalbench.py:610- Retained import versions reuse the same trace identity.session_idandtrace_iddepend only on(job_id, scenario_id), while changed source data creates a new retainedimport_version. Existing readers such asClient._GET_TRACE_QUERY(src/bigquery_agent_analytics/client.py:157) filter only bytrace_id, so pointing them at the mirror table combines rows from multiple versions into one duplicated or inconsistent trace. Make published trace/session identities version-specific (and keep score joins aligned), or provide a required pinned-version consumer surface instead of claiming existing readers work unchanged. -
src/bigquery_agent_analytics/evalbench.py:642- The manifest check is outside the publish transaction. Two first-time imports with different source fingerprints and the same explicit version can both observe no manifest row; if one commits before the other's transaction starts, the later unconditionalDELETE/INSERToverwrites the committed immutable version even withreplace=False. Move the existence/fingerprint decision into the transaction (or use an equivalent compare-and-swap guard) and add a deterministic two-importer interleaving test. -
src/bigquery_agent_analytics/evalbench.py:651- Theunchangeddecision compares only fingerprints and ignores the destination refs stored in the manifest. Re-running the same(job_id, import_version)with a differentevents_tableorscores_tablereturnsunchangedand reports the newly requested refs even though nothing was published there;replace=Truecan also orphan rows in the old destination. Require requested destinations to match the manifest, or define an explicit relocation contract. -
src/bigquery_agent_analytics/evalbench.py:1449- Non-emptystderris promoted toerror_messageonly when_failed_returncode(returncode)is true. A completed row withreturncode == 0, a final response, andstderrtherefore emitsstatus = 'OK'and can pass, contrary to the documented process-failure contract. Handle usablestderrindependently of return code and test the Python and SQL denominator paths.
P2
-
src/bigquery_agent_analytics/evalbench.py:181-classify_sessions()collapses duplicate failing rows for one comparator to a single minimum-valued mapping entry, while the SQLARRAY_AGGreturns every failing duplicate. Pre-aggregate per(session_id, comparator)and add an executed parity fixture. -
src/bigquery_agent_analytics/evalbench.py:713- An unguarded staging-table delete can raise afterCOMMIT, causing the CLI to report failure for a committed import. It can also mask the original publication error and stop cleanup of later staging tables. Preserve the primary result/error, attempt all cleanup operations, and give staging tables an expiration fallback. -
src/bigquery_agent_analytics/evalbench.py:1667-_json_safe()passesNaNand infinities into JSON-valued staging rows. Those serialize as non-standard JSON tokens and can make BigQuery reject the load. Normalize or reject non-finite values before fingerprinting/loading, with strict-JSON tests.
What can wait
- Taxonomy, localization, benchmark harnesses, dashboards, and D4 remain out of scope as stated.
- A module split and broader edge-case coverage (scoreless imports, explicit replace with changed source, and null-score branches) would improve maintainability but need not block this slice after the contract defects above are fixed.
- A live BigQuery transaction/parity suite is valuable follow-up; the current recording-fake tests do not validate lock conflicts or execute
failed_sessions_sql().
Validation
python3 -m pytest -q tests/test_evalbench_importer.py tests/test_cli_evalbench_import.py: 39 passed.- Independent correctness, security, API-contract, reliability, adversarial, testing, and maintainability passes were deduplicated and revalidated against PR head
b5c45a09f2b09b9d60b3969047e395f4638180be.
…PR 451 P1s Addresses the P1 review findings on GoogleCloudPlatform#451 (issue GoogleCloudPlatform#435 slice 1): - Reject the reserved ADK `agent_events` name for every destination table before any BigQuery operation, in `materialize` and in the CLI (`--events-table agent_events` exits 2 before reading the source). - Published `session_id`/`trace_id` are now version-specific (`evalbench:{job_id}:{import_version}:{scenario_id}`), and span and invocation ids derive from them, so retained import versions of one job never collapse into one trace for readers that filter only by `trace_id` (`Client.get_trace` / `_GET_TRACE_QUERY`). Score rows use the same identity so joins stay aligned; plain reads keep the GoogleCloudPlatform#97 identity. - The manifest existence/fingerprint decision is repeated inside the publish transaction as a compare-and-swap guard (`RAISE` before any DELETE), so two first-time importers racing on one explicit version cannot both commit different content. The guard also pins the destination tables; `replace=True` skips only the fingerprint check. A deterministic two-importer interleaving test drives the guard through the stub client. - A version is bound to the `events_table`/`scores_table` in its manifest: re-importing with other destination tables raises (even with `replace=True`) instead of returning `unchanged` for tables that were never written or orphaning the old rows. - Usable `stderr` is a process failure independent of `returncode`: a completed row with returncode 0, a final response, and stderr publishes `status=ERROR` and fails the denominator in both `classify_sessions` and `failed_sessions_sql`. P2s folded in: nested scenario-id lookup parity for score rows, per-comparator aggregation in the SQL so duplicate score rows match `classify_sessions`, best-effort staging cleanup that cannot mask a committed publish plus a six-hour staging expiration, and NaN/Infinity handling in `_json_safe`.
caohy1988
left a comment
There was a problem hiding this comment.
Reviewer: Kimi
Verdict: Approve (comment) — my P1 is fixed, and all of Codex's P1s landed with regression tests
Re-reviewed the full fix commit 7e47def against b5c45a0 locally: source diff of evalbench.py, cli.py, docs/evalbench.md, and the ~500 lines of new tests. Ran python3 -m pytest -q tests/test_evalbench_importer.py tests/test_cli_evalbench_import.py — 59/59 pass (was 39 at b5c45a0; the 20 new tests cover each finding).
My P1 — false table pointer on unchanged re-import: FIXED
materialize() now calls _check_destination_binding (evalbench.py:726) before the fingerprint no-op: if the manifest's stored events_table/scores_table differ from the requested refs it raises ValueError (even with replace=True), instead of returning unchanged pointing at tables that were never written. Pinned by test_materialize_unchanged_source_rejects_other_destination_tables and test_materialize_replace_cannot_relocate_a_version. The in-transaction guard also carries the destination predicate, so a racing importer cannot relocate a version either.
Codex's P1s — all addressed, none rubber-stamped
- Reserved
agent_events:_validate_destination_tablerejects it before any BigQuery call, on both the API path (materialize) and the CLI path (cli.py:2327). Tests on both. - Versioned identities: published rows use
evalbench:{job_id}:{import_version}:{scenario_id}forsession_id/trace_id, with span/invocation ids derived from it andattributes.evalbench_import_versionset; score rows use the same identity so joins stay aligned.to_agent_event_rows()without a version keeps the old unversioned identity, so plain reads are unchanged.test_materialize_publishes_version_specific_identitiesasserts v1/v2 trace/span/invocation id sets are disjoint — exactly theClient.get_tracemerge hazard Codex flagged. - Txn guard: the manifest conflict check moved inside the publish script (
SET … IF … RAISEbefore the DELETEs), withreplace=Truekeeping the destination binding while waiving fingerprint drift. The concurrent-first-import test pins the interleaving. One honest caveat: the "later transaction re-reads and raises" claim rests on BigQuery's documented serializability of conflicting DML on the same table; the fake-client tests can't prove that, and the docs still correctly flag live-BQ integration tests as a follow-up boundary. Not blocking. - Destination-binding: same fix as my P1 above.
- stderr independent of returncode:
_source_error_messagenow collects usablestderrregardless ofreturncode, soreturncode==0+ final response + stderr publishesstatus='ERROR'. Pinned bytest_stderr_is_a_process_failure_even_when_returncode_is_zero.
Codex's P2s are also in: staging tables get a 6h expiration and best-effort cleanup that can't mask a committed publish (_drop_staging_tables), _json_safe normalizes NaN/Infinity to strings, _score_scenario_id shares the nested scenario-id lookup with results, and the SQL comparator_gate pre-aggregates per (session_id, comparator) so duplicate score rows match the Python classify_sessions collapse (test_classify_sessions_and_sql_collapse_duplicate_comparator_rows). I checked the new gate SQL by hand: MIN(IF(sc.score < p.min_score, sc.score, NULL)) matches Python's min(failing) / None semantics under both missing_score_fails branches.
No new regressions found
_load_stagingswitched toWRITE_APPEND, but staging refs carry a per-runuuid4suffix, so append-on-fresh-table is safe.except ValueError: raisein the publish path keeps pre-existingValueErrorsemantics intact; the conflict-message remap toValueErroris CLI-compatible (exit 2).- Docs (
docs/evalbench.md) were updated to match every behavioral change, including the version-binding table.
Remaining (all previously noted, non-blocking)
- No live-BQ integration test for
materialize()/failed_sessions_sql()— known boundary, still worth a follow-up. cli.pystill imports privateevalbench._parse_timestamp(and now_validate_destination_table) — cosmetic.
Ship it.
caohy1988
left a comment
There was a problem hiding this comment.
Reviewer: Codex
Verdict: Request changes. Two P1 defects remain at 7e47def; no P0 was found. The requested tests pass: 59 passed.
P1
-
src/bigquery_agent_analytics/evalbench.py:681- A custom manifest table bypasses version immutability.manifest_tableremains caller-selectable, and both the pre-read and the in-transaction conflict guard consult only that selected table. Publishjob/v1to events/scores plus manifestM1, then publish changed source for the samejob/v1to the same events/scores with manifestM2andreplace=False:M2has no row, so the transaction deletes and replaces the shared event/score rows whileM1remains stale. For the MVP, reject non-default manifest tables, or add one canonical registry/namespace that every import checks before deleting shared destination rows. Add a regression for this two-manifest sequence. -
src/bigquery_agent_analytics/evalbench.py:1139- The new versioned identity is not collision-safe for legal inputs. It concatenates unescaped components with:, whileimport_versionexplicitly permits:and scenario/job IDs are not delimiter-restricted. For one job,(import_version="release:1", scenario_id="case")and(import_version="release", scenario_id="1:case")both becomeevalbench:job:release:1:case;Client.get_trace, which filters bytrace_idonly, can still merge retained versions. Encode the identity tuple unambiguously (for example, a canonical tuple hash or escaped/length-prefixed components) and add delimiter-collision tests for event, score, span, and invocation IDs.
Prior P1 re-check
- Reserved
agent_events: fixed; every destination argument is rejected before BigQuery work, with API and CLI coverage. - Version-specific session/trace IDs: simple versions are fixed, but the collision above leaves the contract incomplete.
- Manifest decision outside the transaction: fixed; the conflict check now runs inside the publish transaction. BigQuery may cancel a conflicting transaction rather than return the custom conflict message, but atomicity is preserved.
unchangedignoring destination refs: fixed for the stored event/score refs; the alternate-manifest path above still bypasses the immutable binding.stderrconditional on failed return code: fixed; usablestderrindependently emits an error and fails both Python and SQL classification paths.
Validation: python3 -m pytest -q tests/test_evalbench_importer.py tests/test_cli_evalbench_import.py -> 59 passed in 3.11s.
Addresses the two remaining P1s from the Codex re-review of 7e47def on PR GoogleCloudPlatform#451 (issue GoogleCloudPlatform#435 slice 1). - The import manifest is now the single registry per target dataset (`evalbench.MANIFEST_TABLE`, `evalbench_import_manifest`) and is no longer a `materialize` argument. Every import into a dataset, whatever `events_table`/`scores_table` it writes, pre-reads and CAS-guards the same registry, so changed source for an existing `(job_id, import_version)` cannot be routed through a second manifest to delete and replace shared event/score rows while the first manifest stays stale. Passing `manifest_table` is a `TypeError` before any BigQuery call. - Session/trace identities encode the `(job_id, import_version, scenario_id)` tuple injectively: `:` and `\` inside a component are escaped (`\:`, `\\`). `(import_version="release:1", scenario_id="case")` and `(import_version="release", scenario_id="1:case")` no longer share `evalbench:job:release:1:case`, so `Client.get_trace` cannot merge retained versions; plain and versioned forms differ in component count and cannot alias either. `_stable_id` length-prefixes its parts so span and invocation ids stay injective even when a session id contains the joiner. Tests: caller-selected manifest table rejected with no BigQuery calls; custom events/scores tables still consult the canonical registry; the two-manifest sequence (fresh and stale pre-read) leaves the first manifest and shared rows intact; delimiter-collision coverage for session, trace, invocation, span, parent span, and score identities; `_stable_id` boundary test. Docs describe the fixed registry and the escaping rule.
caohy1988
left a comment
There was a problem hiding this comment.
Reviewer: Kimi
Verdict: Approve (comment) — both remaining P1s are fixed, no new P0/P1 found
Re-reviewed the fix commit e2448fd against 7e47def locally: full source diff of evalbench.py, docs, and the ~200 lines of new tests. Ran python3 -m pytest -q tests/test_evalbench_importer.py tests/test_cli_evalbench_import.py — 67/67 pass (was 59 at 7e47def; the new tests pin both findings). Also swept for stale manifest_table references across Python, docs, examples, and SQL — none remain outside the fixed-registry internals.
Codex P1 #1 — custom manifest_table bypasses version immutability: FIXED
The manifest_table parameter is gone from materialize() entirely; the registry is now the module constant MANIFEST_TABLE = "evalbench_import_manifest" (evalbench.py:76), so every import into a target dataset — whatever events_table/scores_table it writes — consults the same registry in both the pre-read and the in-transaction guard. Passing manifest_table= now raises TypeError before any BigQuery call (test_materialize_rejects_caller_selected_manifest_table). Removing the argument (rather than validating it against the default) is the right call: it eliminates the bypass class instead of policing one value. The exact two-manifest attack sequence Codex described is pinned by test_changed_source_cannot_replace_shared_rows_via_second_manifest, which covers both the fresh pre-read path and the stale-read/in-transaction rollback path. result.manifest_table still reports the canonical ref, and the CLI never exposed a manifest flag, so nothing else needed changing.
Codex P1 #2 — versioned ids not collision-safe with :: FIXED
_session_identity (evalbench.py:1162) now escapes \ → \\ and : → \: in every component before joining, making the tuple encoding injective and decodable — (import_version="release:1", scenario_id="case") and (import_version="release", scenario_id="1:case") now produce …:release\:1:case vs …:release:1\:case. The related _stable_id hash also length-prefixes its parts, closing the same boundary ambiguity for derived span/invocation ids. Coverage is thorough: exact-string escape tests (including backslash-roundtrip and the plain-read-vs-published aliasing case across component counts), plus parametrized disjointness of session_id/trace_id/invocation_id/span_id (and parent span ids) between the two colliding runs, and score rows both disjoint across versions and still joining their own version's events.
Regression re-check — no breakage
- Unversioned identity is unchanged for plain reads (
test_unversioned_reader_identity_is_unchangedstill passes), and components without:/\render verbatim, so the documented readable form is preserved for the common case. - All prior fixes from
7e47def(reservedagent_eventsrejection, destination binding, in-transaction guard, stderr contract, staging expiry,_json_safe) are untouched and their tests still pass. - Docs (
docs/evalbench.md) updated to match: the escaping rule with the exact collision example, and the manifest now described as the fixed per-dataset registry.
Remaining (previously noted, still non-blocking)
- No live-BQ integration test for
materialize()/failed_sessions_sql()— the serializability claim still rests on documented BigQuery behavior; worth a follow-up, not a blocker. cli.pyimporting privateevalbenchhelpers — cosmetic.
Ship it.
caohy1988
left a comment
There was a problem hiding this comment.
Reviewer: Codex
Verdict: Request changes. The two P1s filed on 7e47def are fixed in their direct forms, but one immutable-first-publish race remains and e2448fd introduces an unversioned-ID compatibility regression. The requested tests pass: 67 passed in 3.04s.
P1
-
src/bigquery_agent_analytics/evalbench.py:171- The in-transaction manifest check is not a compare-and-swap for two truly concurrent first imports. BigQuery transactions use snapshot isolation, so if both transactions begin before either commits, both guards see no manifest row. Their keyedDELETEs affect zero rows and both transactions then append their staged events, scores, and manifest rows. BigQuery documents that reads/appends can run concurrently and thatINSERTnever conflicts; the current unit test runs the publishes sequentially and its fake checks the live Python store, so it cannot reproduce this snapshot race. The result can be duplicate manifests plus mixed event/score corpora for one supposedly immutable(job_id, import_version). Use a serialization primitive that always mutates an existing lock/sentinel row (or an equivalent real claim mechanism), and cover the simultaneous-first-import case with a live BigQuery concurrency test. References: transaction snapshot/concurrency semantics, DML conflict semantics. -
src/bigquery_agent_analytics/evalbench.py:1174and:1894- The collision fix changes identifiers from the existing v0.5.1 publicto_agent_event_rows()path even whenimport_versionis omitted. A legal scenariov1:casepreviously producedevalbench:job-123:v1:caseand now producesevalbench:job-123:v1\:case;_stable_id()also changed globally, so even delimiter-free sessions get different invocation/span IDs (forevalbench:job-123:case, invocationf567e6f5a86a69f608edb2751cc3771cbecomes7e1929eab2ee7be1f2750377e1280c73). Re-mapping an existing run after upgrade therefore breaks stored trace references and can create a second logical trace for the same source run. Preserve the legacy unversioned encoding/hash contract and put published/versioned IDs in a distinct injective namespace/framing, with golden v0.5.1 compatibility vectors for session, trace, invocation, span, and parent IDs.
Codex P1 (concurrency): the in-transaction manifest check was not a real
compare-and-swap. BigQuery transactions use snapshot isolation and only
cancel a transaction that mutates rows another concurrent transaction has
mutated; reads, appends, and keyed DELETEs that match nothing never
conflict. Two first-time imports of one (job_id, import_version) that both
began before either committed could therefore both commit, leaving two
manifests and a mixed corpus under one immutable version.
The publish transaction now claims a fixed per-dataset lock first: it
UPDATEs the pre-existing sentinel row in `evalbench_import_lock` (seeded by
its own committed job before the transaction starts, guarded by
`@@row_count`), so at most one concurrent publish survives and the loser is
cancelled with BigQuery's "concurrent update" error, which materialize()
reports as ValueError with nothing written. The manifest guard stays as
defence in depth for a stale pre-read whose transaction started later.
The fake client now models snapshot isolation (both transactions start
from one snapshot; only a mutation of the sentinel conflicts) and the new
test drives two truly concurrent first imports through it. This is a stub
model of the documented BigQuery rules, not a live concurrency test; the
docs say so.
Codex P1 (compatibility): restore the v0.5.1 public unversioned contract.
Plain `to_agent_event_rows()` again emits the unescaped
`evalbench:{job_id}:{scenario_id}` identity and the legacy `_stable_id`
hash, pinned by golden vectors for session, trace, invocation, span, and
parent ids. Published versions move to the distinct injective namespace
`evalbench-import:{job_id}:{import_version}:{scenario_id}` with escaped
components and `_published_stable_id` framing, so the two families can
never alias each other.
caohy1988
left a comment
There was a problem hiding this comment.
Reviewer: Kimi
Verdict: Approve (comment) — both P1s on e2448fd are fixed, no new P0/P1 found
Re-reviewed the fix commit 3cd1dc7 against e2448fd locally at HEAD: full diff of evalbench.py (+251/-~60), the ~330 lines of new/changed tests, and the docs update. Ran python3 -m pytest -q tests/test_evalbench_importer.py tests/test_cli_evalbench_import.py — 75/75 pass (was 67 at e2448fd).
Codex P1 #1 — in-transaction manifest check is not a CAS under snapshot isolation: FIXED
The publish transaction now claims a real serialization primitive before anything else (_PUBLISH_SCRIPT, evalbench.py:216): the first statement after BEGIN TRANSACTION is an UPDATE of a pre-existing sentinel row in the fixed per-dataset evalbench_import_lock table, guarded by IF @@row_count = 0 THEN RAISE. The sentinel is seeded by its own committed job before the transaction starts (_seed_import_lock, evalbench.py:1408), so the row is in every transaction's snapshot. Under BigQuery's documented concurrency rules, two first-time imports that both began from a pre-commit snapshot now conflict on the sentinel mutation and BigQuery cancels one; the loser gets the "concurrent update" error, which materialize() remaps to a ValueError with re-run guidance (evalbench.py:886) and nothing written. The in-transaction manifest guard is kept as defence in depth for the stale-pre-read/later-transaction-start case. Seeding itself is INSERT-only and idempotent (WHERE NOT EXISTS); two racing seeds producing two sentinel rows is harmless because the claim UPDATE matches every sentinel row, so the conflict still fires.
The tests model this honestly rather than claiming a live proof: the fake client implements snapshot isolation explicitly (_FakeSnapshot taken at BEGIN, reads see the snapshot, appends and no-op DELETEs never conflict, only the sentinel mutation conflicts), and test_materialize_concurrent_first_imports_serialize_on_lock_sentinel drives two importers sharing one pre-commit snapshot through it — the loser's staged rows never reach the published tables, no mixed corpus, and a clean retry reports the fingerprint conflict (or unchanged for identical content). test_materialize_lock_claim_requires_seeded_sentinel pins the @@row_count abort. The commit message and test docstrings state plainly that this is a stub model of documented BQ behavior, not a live concurrency test — the same live-BQ follow-up boundary flagged in every round so far.
Codex P1 #2 — unversioned v0.5.1 identities must be preserved; versioned IDs in a distinct injective namespace: FIXED
The two identity families are now fully separated (_session_identity, evalbench.py:1257):
- Plain
to_agent_event_rows()restores the v0.5.1 public contract verbatim: unescapedevalbench:{job_id}:{scenario_id}and the frozen legacy_stable_idhash (\x1f-join, no length prefix). A scenariov1:caseagain yieldsevalbench:job-123:v1:case, and the invocation id forevalbench:job-123:caseis back tof567e6f5a86a69f608edb2751cc3771c— Codex's exact regression example. - Published versions live in the distinct
evalbench-import:{job_id}:{import_version}:{scenario_id}namespace with\-escaping (injective and decodable), and span/invocation ids use_published_stable_id, which is length-prefixed and tagged with the published namespace so it can never reproduce a legacy digest either. The namespaces cannot alias: plain identities always startevalbench:, published alwaysevalbench-import:(test_published_identities_never_alias_plain_readscovers even the contrivedimport:job-123:...scenario id).
I independently recomputed all three golden vectors in _V051_IDENTITY_VECTORS (session/trace, invocation, root/tool/completed span ids, plus parent-span wiring) from the v0.5.1 hash formula — all match, so test_unversioned_identities_match_v051_golden_vectors and test_legacy_stable_id_hash_is_frozen genuinely pin the old behavior rather than the new code's own output. test_published_identities_differ_from_unversioned_ones proves the two families share no session/trace/invocation/span id for the same run.
Regression re-check — no breakage from e2448fd's fixes
- Fixed manifest registry (
MANIFEST_TABLEconstant,manifest_table=raisesTypeError), reservedagent_eventsrejection, destination binding (includingreplace=True), in-transaction fingerprint guard, stderr-independence, staging expiry/cleanup,_json_safe, comparator-gate dedup: all untouched and their tests still pass. - Error-mapping order in
materialize()is correct: the custom conflict message is checked before theconcurrent updatemarker, and neither message contains the other's substring; other exceptions propagate unchanged (except ValueError: raisepreserved). - Docs (
docs/evalbench.md) updated for the lock table, the@@row_countguard, and the two identity namespaces.
Remaining (previously noted, non-blocking)
- Still no live-BQ integration/concurrency test for
materialize()— the cancellation claim rests on documented BigQuery behavior plus a faithful stub model; worth a follow-up, not a blocker (Codex asked for a live test here, but this matches the boundary every prior round accepted). cli.pyimporting privateevalbenchhelpers — cosmetic.
Ship it.
caohy1988
left a comment
There was a problem hiding this comment.
Reviewer: Codex
Verdict: Request changes. Both P1s from the review on e2448fd are fixed, and the targeted suite passes, but one P1 backward-compatibility regression remains at 3cd1dc7.
P1
src/bigquery_agent_analytics/evalbench.py:353- Addingsnapshot_atbetweenlocationandresultschanges the generated positional constructor of the publicEvalBenchRundataclass. A valid v0.5.1 call such asEvalBenchRun(project, dataset, job, location, results, scores, config_rows)now assignsresultstosnapshot_at, shifts the remaining tuples, and can silently return zero event rows. Preserve the existing positional field order by movingsnapshot_atafterconfig_rows, or make the new field keyword-only, and add a regression test that constructs the run with the v0.5.1 positional arguments.
Prior P1 re-check
- First-publish serialization: fixed. The publish transaction first
UPDATEs the pre-seededevalbench_import_locksentinel, so overlapping BigQuery transactions mutate the same existing table row and one conflicting transaction is cancelled under BigQuery's documented transaction-concurrency behavior. The manifest guard remains inside the transaction. - Unversioned ID compatibility: fixed. Omitting
import_versionretains the v0.5.1evalbench:{job_id}:{scenario_id}encoding and legacy\x1f-joined hash. Versioned identities use the separate escapedevalbench-import:namespace and length-framed hashes. Golden tests cover session, trace, invocation, span, and parent-span IDs.
Validation: python3 -m pytest -q tests/test_evalbench_importer.py tests/test_cli_evalbench_import.py -> 75 passed in 3.10s.
snapshot_at was inserted between location and results, so a v0.5.1 positional call EvalBenchRun(project, dataset, job, location, results, scores, config_rows) silently assigned results to snapshot_at and left results empty. Declare snapshot_at last so the v0.5.1 positional order is stable, and add a regression test that constructs EvalBenchRun with the v0.5.1 argument order.
caohy1988
left a comment
There was a problem hiding this comment.
Reviewer: Kimi
Verdict: APPROVE — Codex's P1 is fixed, no new P0/P1 in a8e8b5c
(Note: posting this as a comment review since I previously approved 3cd1dc7; this re-review covers the delta 3cd1dc7..a8e8b5c.)
P1 re-check: snapshot_at positional-order regression — FIXED
In src/bigquery_agent_analytics/evalbench.py, snapshot_at is now declared last in the frozen dataclass, after config_rows (evalbench.py:362-364), with an explicit comment pinning the v0.5.1 positional order. The v0.5.1 call shape
EvalBenchRun(project, dataset, job, location, results, scores, config_rows)binds results correctly again — verified directly at HEAD:
EvalBenchRun('p','d','j','US', results)→resultslands in.results,snapshot_at is None.EvalBenchRun('p','d','j','US', results, scores, config_rows, snapshot_at)→snapshot_ataccepted as the 8th positional,resultsintact.
A new regression test test_evalbench_run_keeps_v051_positional_argument_order (tests/test_evalbench_importer.py:101) locks both the 7-arg v0.5.1 order and the 8-arg form with snapshot_at appended.
Call-site audit
All EvalBenchRun(...) construction sites in the tree (from_bigquery in evalbench.py, plus the two test helpers at tests/test_evalbench_importer.py:91 and :704) use keyword arguments, so the field reorder is safe internally.
Tests
python3 -m pytest -q tests/test_evalbench_importer.py tests/test_cli_evalbench_import.py
76 passed in 3.85s
Scope of the delta
The commit touches only the dataclass field order and adds the regression test — minimal, exactly the fix requested. No other behavior changed since my approval of 3cd1dc7.
No remaining P0/P1 findings. LGTM.
caohy1988
left a comment
There was a problem hiding this comment.
Reviewer: Codex
Verdict: Request changes. The snapshot_at positional-constructor P1 is fixed, but one P1 remains in the stale-read publish path. No P0 was found.
P1
src/bigquery_agent_analytics/evalbench.py:225- A stale pre-read can still rewrite an immutable version withoutreplace=True. If importer B reads no manifest before A commits, finishes staging after A commits, and only then starts its transaction, its lock claim does not conflict. The in-transaction guard compares only source-row fingerprints and destination refs; equal source rows from another source project or dataset therefore pass even thoughsource_project/source_datasetchange the manifest and the publishedattributes.evalbench_source_*values. B then unconditionally deletes and reinserts A's(job_id, import_version)and returnsimportedinstead of preserving A and returningunchanged. After claiming the lock, make the transaction distinguish absent, identical, and conflicting manifests; include every output/provenance-affecting input in that decision, and add the stale-pre-read/equal-fingerprint regression case.
Prior P1 re-check
- Fixed:
EvalBenchRunnow declaressnapshot_atafterresults,scores, andconfig_rows, preserving the v0.5.1 seven-position constructor. The new regression test also covers the optional eighth positional value.
Validation: python3 -m pytest -q tests/test_evalbench_importer.py tests/test_cli_evalbench_import.py -> 76 passed in 3.04s.
…sion Codex P1 on a8e8b5c: an importer whose pre-publish manifest read was stale but whose transaction started after another importer committed could still rewrite an immutable (job_id, import_version) without replace=True. The in-transaction guard compared only source-row fingerprints and destination refs, so equal source rows read from a different EvalBench project or dataset passed the guard even though source_project/source_dataset change the manifest and every published attributes.evalbench_source_* value; the stale importer then deleted and re-inserted the first publish and reported "imported" instead of preserving it and reporting "unchanged". The publish transaction now classifies the committed manifest row for the version as absent, identical, or conflicting: * conflicting now also covers source_project/source_dataset drift (without replace) via a new provenance predicate bound as query parameters, next to the fingerprint and destination predicates; * identical without replace raises a dedicated "unchanged" message so the script rolls back (lock claim included) and materialize() re-reads the committed manifest and returns status "unchanged", leaving the first publish's rows, manifest, and imported_at untouched; * replace=True keeps the destination binding only and re-publishes in place, as before. The pre-publish Python path uses the same drift set (_manifest_drift), so a fresh pre-read reports provenance drift before staging anything, naming the differing source project/dataset. Tests: the fake client models the provenance predicate and the identical guard, and stale pre-reads now only affect reads before the client's first transaction. New regressions cover stale pre-read + equal fingerprints + different source project or dataset (conflict, nothing written, replace override records the new provenance) and stale pre-read + identical publish (unchanged, first publish preserved, lock claim rolled back).
caohy1988
left a comment
There was a problem hiding this comment.
Reviewer: Kimi
Verdict: APPROVE — the provenance-drift P1 is fixed, no new P0/P1 in 2e64fdb
(Posted as a comment review, consistent with the prior rounds; this re-review covers the delta a8e8b5c..2e64fdb.)
Re-reviewed the fix commit locally at HEAD 2e64fdb: full diff of evalbench.py (+219/-~55) and the ~166 lines of new/changed tests. Ran python3 -m pytest -q tests/test_evalbench_importer.py tests/test_cli_evalbench_import.py — 79/79 pass (was 76 at a8e8b5c).
Codex P1 — stale pre-read with equal fingerprints but different provenance rewrites an immutable version: FIXED
All three required pieces are in place:
-
Absent / identical / conflicting inside the transaction. The publish script now computes
existing_manifest_rowsandconflicting_manifest_rowsafter the lock claim (_PUBLISH_SCRIPT, evalbench.py:252-290). Withoutreplace: a conflicting row (fingerprints, provenance, or destinations differ) RAISEs the conflict message; an identical row RAISEs_PUBLISH_UNCHANGED_MESSAGE, rolling the transaction back — including the lock claim — so A's rows, manifest, and originalimported_atare left exactly as published instead of being deleted and re-inserted.materialize()maps that rollback tostatus="unchanged"and re-reads the committed manifest (evalbench.py:933-953), so the result reflects what is actually published. Ordering is pinned: conflict guard before identical guard before the DELETEs (test_publish_script_guards_manifest_inside_the_transaction). -
Provenance is part of the decision.
_PROVENANCE_CONFLICT_PREDICATE(source_project != @source_project OR source_dataset != @source_dataset) joins the conflict predicate withoutreplace, fed by new@source_project/@source_datasetparameters fromself.project_id/self.evalbench_dataset(_publish_parameters, evalbench.py:1234). The pre-read path uses the same comparison via_manifest_drift(evalbench.py:1261), which reports the drifted field and both values in theValueError. The reasoning for excludingsource_snapshot_at/imported_at/counts from the identity decision is documented in the code comment at evalbench.py:162-169 and is sound: none of them change any published event/score row. -
Regression coverage for the exact attack.
test_materialize_stale_pre_read_provenance_drift_is_a_conflictparametrizes bothproject_idandevalbench_dataset, asserts the fingerprints really are equal, and verifies: the stale importer's transaction rolls back with nothing rewritten (A's manifest, events, and single lock claim survive; B's staging tables are dropped), a fresh pre-read raises before any staging, andreplace=Trueremains the explicit override that re-publishes with the new provenance in both the manifest andattributes.evalbench_source_*.test_materialize_stale_pre_read_identical_publish_is_unchangedpins the twin case: identical content and provenance through a stale pre-read reportsunchangedwith A's manifest untouched. The fake client was updated honestly for this — stale reads only apply before the client's first transaction, so the post-rollback manifest re-read sees committed state, and the fake now models the identical-guard rollback.
Regression re-check — no breakage
replace=Truecorrectly keeps the destination binding while waiving fingerprint, provenance, and the identical guard (test_publish_script_replace_skips_fingerprint_guard_only)._unchanged_resultreports the requestedevents_ref/scores_ref; this is safe on the in-transaction path because destination refs are part of the conflict predicate, so reaching the unchanged rollback implies they matched the stored row.- Error-mapping order is correct: the unchanged message is checked before the conflict and concurrent-update markers, and the three messages share no substrings;
except ValueError: raiseis preserved. - All prior fixes (lock sentinel, v0.5.1 positional order and golden identity vectors, fixed manifest registry, reserved
agent_events, stderr contract) are untouched and their tests still pass. - No CLI changes were needed; no new flags.
Nit (non-blocking)
docs/evalbench.mdwas not updated in this commit: the idempotency table (docs/evalbench.md:263-271) still says "identical fingerprints → unchanged" without mentioning that equal fingerprints from a different source project/dataset are now a conflict. Worth a one-row doc touch-up in a follow-up.
Remaining (previously noted, still non-blocking)
- No live-BQ integration/concurrency test for
materialize()— the stub models documented snapshot-isolation behavior; known boundary since the first round. cli.pyimporting privateevalbenchhelpers — cosmetic.
Ship it.
caohy1988
left a comment
There was a problem hiding this comment.
Reviewer: Codex
Verdict: Approve. The P1 reported on a8e8b5c is fixed, and I found no new P0/P1 at 2e64fdb.
- Prior P1 re-check: fixed. Fresh manifest reads now treat
source_project/source_datasetdrift as a conflict via_manifest_drift(). The stale-read path binds those values as query parameters and includes them in the in-transaction conflict predicate before anyDELETE; identical committed versions roll back and returnunchangedinstead of being rewritten. - Regression coverage: the new tests exercise stale pre-reads with equal fingerprints but different source project or dataset, verify that the first manifest and published rows remain intact, and verify the explicit
replace=Trueoverride. The absent / identical / conflicting paths and destination binding remain covered. - Validation:
python3 -m pytest -q tests/test_evalbench_importer.py tests/test_cli_evalbench_import.py->79 passed in 3.74s. GitHub CI is green across package build, formatting, and Python 3.10-3.14 tests.
No remaining P0/P1 findings.
… upgrade slice-1 manifests Superseded-generation ownership no longer derives from the view's own pin: every publish (replace) and every committed policy change appends the generation it supersedes -- id and view_policy -- to the manifest row's new `superseded_generations` history, and `_read_managed_view` renders the expected body for a pinned generation only from that committed record (or the row's current generation). A well-formed pin naming a generation the manifest never committed is refused, never authenticated and replaced. `_ManagedView` no longer carries the view's policy claim, so nothing downstream can act on it. Manifests created by slice 1 (GoogleCloudPlatform#451) are upgraded in place before any manifest read or publish: `_ensure_manifest_schema` adds the missing `generation_id` / `view_policy` / `superseded_generations` columns through an ETag-conditional tables-API update (re-read and retried under a concurrent upgrade, bounded, fail closed) and backfills a generation for every row from its key (`TO_HEX(MD5(...))`), so concurrent upgraders converge on the same id and the backfill is idempotent. A row still lacking a generation after an interrupted upgrade is backfilled by the import that touches it and by view reconciliation. `generation_id` is declared NULLABLE only so it can be added to an existing table; every row the importer writes carries one. Tests: the forged-stale-view regression now asserts refusal under every import path; a superseded view is verified from the history and any other gate under a real superseded generation is refused; slice-1 schema upgrade, interrupted-upgrade completion and concurrent-upgrade convergence / fail-closed exhaustion are covered against a fake that enforces the live manifest schema on every DML.
2459c0f
into
GoogleCloudPlatform:main
…ogleCloudPlatform#435) Slice 2 of GoogleCloudPlatform#435, stacked on GoogleCloudPlatform#451. - materialize() keeps an `evalbench_failed_sessions` VIEW in the target dataset whose body is failed_sessions_sql() with the job's latest successful import (newest manifest imported_at) rendered as literals, so SQL consumers never scan another import_version. The pin lives in a leading SQL comment that is read back before publishing: a view pinned to another job, or any object the importer did not create, is refused before anything is written. Unchanged re-imports leave the view alone; a missing view is created; DDL failures after a commit raise with the published version named so a re-run retries the view. - failed_sessions() resolves exactly one (job_id, import_version) from the manifest before reading events and runs the parameterized contract over the tables that version is bound to; each EvalBenchSession carries the versioned session_id/trace_id and trace_selector()/get_trace() for Client.get_session_trace drill-down. - failed_sessions_sql(job_id=, import_version=) renders the pin as escaped literals for view definitions. - CLI: `evalbench-failed-sessions` (--job-id, --import-version, --min-score, --include-passed; exit 0/2) and --failed-sessions-view / --skip-failed-sessions-view / --min-score on `evalbench-import`. - Tests: view DDL pin and escaping, latest-import tracking, cross-job and foreign-object refusal, classify_sessions parity, version isolation, manifest-bound tables, drill-down selector, CLI wiring. The stub client now commits each publish's own staged rows so several versions can flow through one fake. - docs/evalbench.md and CHANGELOG updated.
… upgrade slice-1 manifests Superseded-generation ownership no longer derives from the view's own pin: every publish (replace) and every committed policy change appends the generation it supersedes -- id and view_policy -- to the manifest row's new `superseded_generations` history, and `_read_managed_view` renders the expected body for a pinned generation only from that committed record (or the row's current generation). A well-formed pin naming a generation the manifest never committed is refused, never authenticated and replaced. `_ManagedView` no longer carries the view's policy claim, so nothing downstream can act on it. Manifests created by slice 1 (GoogleCloudPlatform#451) are upgraded in place before any manifest read or publish: `_ensure_manifest_schema` adds the missing `generation_id` / `view_policy` / `superseded_generations` columns through an ETag-conditional tables-API update (re-read and retried under a concurrent upgrade, bounded, fail closed) and backfills a generation for every row from its key (`TO_HEX(MD5(...))`), so concurrent upgraders converge on the same id and the backfill is idempotent. A row still lacking a generation after an interrupted upgrade is backfilled by the import that touches it and by view reconciliation. `generation_id` is declared NULLABLE only so it can be added to an existing table; every row the importer writes carries one. Tests: the forged-stale-view regression now asserts refusal under every import path; a superseded view is verified from the history and any other gate under a real superseded generation is refused; slice-1 schema upgrade, interrupted-upgrade completion and concurrent-upgrade convergence / fail-closed exhaustion are covered against a fake that enforces the live manifest schema on every DML.
…) (#452) * feat(evalbench): failed_sessions view and version-pinned consumer (#435) Slice 2 of #435, stacked on #451. - materialize() keeps an `evalbench_failed_sessions` VIEW in the target dataset whose body is failed_sessions_sql() with the job's latest successful import (newest manifest imported_at) rendered as literals, so SQL consumers never scan another import_version. The pin lives in a leading SQL comment that is read back before publishing: a view pinned to another job, or any object the importer did not create, is refused before anything is written. Unchanged re-imports leave the view alone; a missing view is created; DDL failures after a commit raise with the published version named so a re-run retries the view. - failed_sessions() resolves exactly one (job_id, import_version) from the manifest before reading events and runs the parameterized contract over the tables that version is bound to; each EvalBenchSession carries the versioned session_id/trace_id and trace_selector()/get_trace() for Client.get_session_trace drill-down. - failed_sessions_sql(job_id=, import_version=) renders the pin as escaped literals for view definitions. - CLI: `evalbench-failed-sessions` (--job-id, --import-version, --min-score, --include-passed; exit 0/2) and --failed-sessions-view / --skip-failed-sessions-view / --min-score on `evalbench-import`. - Tests: view DDL pin and escaping, latest-import tracking, cross-job and foreign-object refusal, classify_sessions parity, version isolation, manifest-bound tables, drill-down selector, CLI wiring. The stub client now commits each publish's own staged rows so several versions can flow through one fake. - docs/evalbench.md and CHANGELOG updated. * fix(evalbench): authoritative view ownership and concurrency-safe pin Review fixes for #435 slice 2 (PR #452, f31b612). - Ownership is proven by the view definition, not the pin comment: the pin now records the SHA-256 of the query below it, and a view is the importer's only when that hash matches. A copied marker over foreign SQL, a marker without the hash, or a managed view whose body was edited is refused before anything is written -- including before the import tables are created (the binding check moved above _ensure_import_tables). - The view is no longer written with CREATE OR REPLACE VIEW. It is created through the tables API with create-if-absent (Conflict on a race) and replaced with an ETag-conditional update_table (PreconditionFailed on a race); each attempt re-reads the view (ownership, job, ETag) and *then* the job's latest manifest row, so a delayed writer never overwrites a newer pin or another job's view. Races re-decide a bounded number of times and then fail closed with the published version named. - The pin carries the rendered score policy, and the write is skipped only when the rendered definition is identical, so a same-version re-import that adds, changes, or drops the policy re-renders the gate instead of leaving stale gate SQL behind. - Tests: forged/copied markers and edited bodies refused, whitespace-only differences still owned; policy add/change/drop on one version; same-job create-race and ETag-guarded update-race keep the newer pin; cross-job race fails closed; bounded retries. The fake client models the tables API with per-view ETags and a one-shot before-write hook. - docs/evalbench.md and CHANGELOG updated. * fix(evalbench): verify view ownership against the manifest; pin policy to the latest import Two P1s from the Codex re-review of #452. View ownership was self-authenticating: the pin carried a SHA-256 of the SQL below it, and both were supplied by the existing view, so a foreign view with a same-job marker over arbitrary SQL plus a freshly computed digest passed as managed and was replaced through the ETag update path. The digest is gone. A view is now the importer's only when its pin (job, version, strictly parsed policy) names a version that job committed to the manifest and the body is exactly (modulo whitespace) what the importer renders for that manifest row and policy. The rendering is canonical (sorted, float thresholds) so it is a pure function of (manifest row, policy pin). The ownership lookup is labelled for the view feature. An ETag retry could attach an older caller's policy to a newer version: the retry re-read `latest` and rendered it with the original invocation's policy, undoing a policy removal the newer version's own import had just made. Policy is now authoritative only while the invocation's version is the latest import. Otherwise a view already pinned to the latest version is left as is; a view that is absent or behind is created or advanced carrying the gate it already had (none for a new view), never this caller's. Regressions: foreign SQL with a correctly recomputed digest (with and without a policy pin), a contract-shaped body for an unpublished version or over other tables, malformed policy pins, canonical policy rendering, the deterministic v1-policy / v2-no-policy ETag interleaving, and the older-version advance/create cases. * fix(evalbench): compare view bodies byte-for-byte; pin the manifest generation Two P1s from the PR #452 re-review of 7b44ce6. Whitespace normalization accepted semantically changed SQL: collapsing whitespace also collapsed it inside rendered literals, so a foreign view carrying the genuine pin but filtering on job_id = "job x" instead of "job x" passed the ownership check and was left in place as "unchanged". BigQuery returns view_query verbatim, so ownership and the no-op check now compare the stored and re-rendered bodies exactly; a reformatted managed view is refused like an edited one. Same-version replacements could attach an older caller's policy: policy authority was keyed to import_version, but two replace=True calls of one version publish two manifest generations (imported_at). The pin now records the generation it renders, authority is decided by (import_version, imported_at) against the latest manifest row, and _read_managed_view re-renders a pin's claimed generation so a view left behind by an earlier generation is still recognized as the importer's. Because every generation changes the view text, the newer replacement always rewrites the view and bumps its ETag even when version, gate and SQL are otherwise identical, so a delayed older caller's conditional replace fails and re-decides instead of landing its stale gate -- this covers the variant where the newer replacement previously left the view untouched and no 412 was raised. Regression tests: literal-whitespace forgery refused (and reformatting refused), deterministic same-version replace race keeps the newer generation's policy, and non-canonical or missing generation pins are refused. Existing exact-pin assertions gain imported_at. * fix(evalbench): trust committed policy metadata and unique publish generation Codex on a20f137 found two P1s in the failed_sessions view ownership: 1. Circular policy ownership. The pin's policy was parsed from the untrusted view and then used to render the "authoritative" expected body, so a foreign view could take a committed manifest row, pick any canonical gate, render the matching SQL + pin, and pass the byte-for-byte check; a later non-latest-version materialize even preserved the forged gate. 2. (import_version, imported_at) is not a unique generation. imported_at is caller-supplied, so two same-version replace=True calls could share it, and a delayed older caller retrying after a 412 mistook the newer caller's row for its own generation and overwrote its policy. The manifest row now carries the authority for both: - generation_id: an opaque uuid4 hex minted by every publish (replace included) and by every committed policy change; nothing shares one. - view_policy: the canonical JSON of the gate the view renders. The view body is a pure function of the latest manifest row. A view whose pin names the row's current generation must equal that rendering with the row's own view_policy -- the pin's policy claim is never the reference -- so a canonical rendering of the current generation under another gate is refused from every later call, an older version's unchanged re-import included. A view pinned to a superseded generation is verified against its pinned generation and policy over the row's tables and only ever advanced to the committed rendering, never preserved. An unchanged re-import that names another policy commits it with an UPDATE keyed on the generation it read (landing on nothing once a concurrent replace re-published the row) under a new generation, and the view is then reconciled from the latest row; the reconcile no longer takes a caller policy or generation at all. Tests: canonical-policy forgery regression (fail closed for the latest, an older, and a new version; a forged gate under an unknown generation is re-rendered, not kept), the same-version replace race parametrized over distinct and equal imported_at values, malformed generation_id pins, committed view_policy assertions, and the fake client emulates the generation-conditioned UPDATE. Docs and CHANGELOG updated. * fix(evalbench): authenticate superseded views from committed history; upgrade slice-1 manifests Superseded-generation ownership no longer derives from the view's own pin: every publish (replace) and every committed policy change appends the generation it supersedes -- id and view_policy -- to the manifest row's new `superseded_generations` history, and `_read_managed_view` renders the expected body for a pinned generation only from that committed record (or the row's current generation). A well-formed pin naming a generation the manifest never committed is refused, never authenticated and replaced. `_ManagedView` no longer carries the view's policy claim, so nothing downstream can act on it. Manifests created by slice 1 (#451) are upgraded in place before any manifest read or publish: `_ensure_manifest_schema` adds the missing `generation_id` / `view_policy` / `superseded_generations` columns through an ETag-conditional tables-API update (re-read and retried under a concurrent upgrade, bounded, fail closed) and backfills a generation for every row from its key (`TO_HEX(MD5(...))`), so concurrent upgraders converge on the same id and the backfill is idempotent. A row still lacking a generation after an interrupted upgrade is backfilled by the import that touches it and by view reconciliation. `generation_id` is declared NULLABLE only so it can be added to an existing table; every row the importer writes carries one. Tests: the forged-stale-view regression now asserts refusal under every import path; a superseded view is verified from the history and any other gate under a real superseded generation is refused; slice-1 schema upgrade, interrupted-upgrade completion and concurrent-upgrade convergence / fail-closed exhaustion are covered against a fake that enforces the live manifest schema on every DML.
… bullet Addresses Codex review 5061312355 on GoogleCloudPlatform#454 (two P1s): - docs/agentforensics_mvp_plan.md: PRs GoogleCloudPlatform#451, GoogleCloudPlatform#452, GoogleCloudPlatform#453 are all merged on main (2459c0f, 2779b7e, a18ee18); the status list no longer calls 452/453 open. - CHANGELOG.md: add the missing Unreleased/Added bullet for GoogleCloudPlatform#451 (materialize() versioned snapshots + W0.4 failed-session contract), above the existing slice-2 and slice-3 bullets.
Two Codex P1s on GoogleCloudPlatform#454 were left unshipped when GoogleCloudPlatform#454 squash-merged: - docs/agentforensics_mvp_plan.md still listed GoogleCloudPlatform#452 and GoogleCloudPlatform#453 as open. Mark GoogleCloudPlatform#451–GoogleCloudPlatform#454 merged with merge SHAs; note GoogleCloudPlatform#455 (e2e demo) is open at a8c694c and not on main. - CHANGELOG Unreleased had GoogleCloudPlatform#452 and GoogleCloudPlatform#453 bullets but no dedicated GoogleCloudPlatform#451 bullet. Add one covering EvalBenchRun.materialize() into BQAA-owned evalbench_* tables (never ADK agent_events), staging + single transaction on (job_id, import_version), the W0.4 failed-session contract (returncode == 0 means completed, not passed), and the bq-agent-sdk evalbench-import CLI. Docs only. Six-week clock not started; partner job / D4 / taxonomy parked.
…456) Two Codex P1s on #454 were left unshipped when #454 squash-merged: - docs/agentforensics_mvp_plan.md still listed #452 and #453 as open. Mark #451–#454 merged with merge SHAs; note #455 (e2e demo) is open at a8c694c and not on main. - CHANGELOG Unreleased had #452 and #453 bullets but no dedicated #451 bullet. Add one covering EvalBenchRun.materialize() into BQAA-owned evalbench_* tables (never ADK agent_events), staging + single transaction on (job_id, import_version), the W0.4 failed-session contract (returncode == 0 means completed, not passed), and the bq-agent-sdk evalbench-import CLI. Docs only. Six-week clock not started; partner job / D4 / taxonomy parked.
…luators Version bump 0.5.1 -> 0.5.2 and the changelog cut for everything merged since v0.5.1 (2026-08-29), 19 commits. In the wheel: the versioned EvalBench import pipeline (#451-#453: immutable snapshots with the W0.4 failed-session contract, the version-pinned failed_sessions view, evalbench-score), the native agent_events snapshot writer (#464), the failure taxonomy frozen at G1 v0.1.0 and its span-level localisation layer with persisted span labels (#467, #470), the evaluator API unification behind PerformanceEvaluator with compatibility aliases (#123), and the canonical metric factories plus opt-in policy scorecard (#91). Repo side: skill-evolution host hooks and auditable patch provenance (#395, #477), the scheduled skill-evolution Cloud Run Job (#472), the OKF adapter example (#474), the AgentForensics Week 0 freeze and sealed preregistration (#435, #473), and the EvalBench demo and CLI-discoverability follow-ups. Entries the Unreleased section lacked are added in this cut: #91, #123 (its bullets move under Changed with the PR number), #395, #472, #474, #476.
…478) * chore(release): 0.5.2 — EvalBench snapshots, G1 taxonomy, unified evaluators Version bump 0.5.1 -> 0.5.2 and the changelog cut for everything merged since v0.5.1 (2026-08-29), 19 commits. In the wheel: the versioned EvalBench import pipeline (#451-#453: immutable snapshots with the W0.4 failed-session contract, the version-pinned failed_sessions view, evalbench-score), the native agent_events snapshot writer (#464), the failure taxonomy frozen at G1 v0.1.0 and its span-level localisation layer with persisted span labels (#467, #470), the evaluator API unification behind PerformanceEvaluator with compatibility aliases (#123), and the canonical metric factories plus opt-in policy scorecard (#91). Repo side: skill-evolution host hooks and auditable patch provenance (#395, #477), the scheduled skill-evolution Cloud Run Job (#472), the OKF adapter example (#474), the AgentForensics Week 0 freeze and sealed preregistration (#435, #473), and the EvalBench demo and CLI-discoverability follow-ups. Entries the Unreleased section lacked are added in this cut: #91, #123 (its bullets move under Changed with the PR number), #395, #472, #474, #476. * chore(release): file the skill-evolution bullets as repo-side scripts/skill_evolution.py is not in the wheel (which ships only src/bigquery_agent_analytics and src/bigquery_ontology), so the #395 and #397 entries move from Added to their own repo-side section, matching the Deploy section this cut already uses for #472.
Summary
Slice 1 of #435: BQAA-owned EvalBench snapshot writer + failed-session contract (#97 subset).
EvalBenchRun.materialize()writes versionedevalbench_agent_events,evalbench_scores_imported, andevalbench_import_manifest(never the default ADKagent_eventstable).(job_id, import_version).EvalScorePolicy,classify_sessions(),failed_sessions_sql().returncode==0means completed, not passed.bq-agent-sdk evalbench-import.Out of scope (deliberate)
Taxonomy, localization/#429, KramaBench/LakeQA/Spider harnesses, dashboards, D4, live-trace smoke (
BQAA_LIVE).Test plan
tests/test_evalbench_importer.pyandtests/test_cli_evalbench_import.pyCloses nothing yet. Progress on #435 / #97.