Skip to content

feat(evalbench): materialize versioned EvalBench snapshots and failed-session contract (#435) - #451

Merged
haiyuan-eng-google merged 6 commits into
GoogleCloudPlatform:mainfrom
caohy1988:feat/435-evalbench-mvp-snapshot
Aug 30, 2026
Merged

haiyuan-eng-google merged 6 commits into
GoogleCloudPlatform:mainfrom
caohy1988:feat/435-evalbench-mvp-snapshot

Conversation

@caohy1988

Copy link
Copy Markdown
Collaborator

Summary

Slice 1 of #435: BQAA-owned EvalBench snapshot writer + failed-session contract (#97 subset).

  • EvalBenchRun.materialize() writes versioned evalbench_agent_events, evalbench_scores_imported, and evalbench_import_manifest (never the default ADK agent_events table).
  • Atomic publish via staging tables + a single transaction keyed on (job_id, import_version).
  • Failed-session contract: EvalScorePolicy, classify_sessions(), failed_sessions_sql(). returncode==0 means completed, not passed.
  • CLI: 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

  • 39 new unit tests in tests/test_evalbench_importer.py and tests/test_cli_evalbench_import.py
  • Reviewers (Codex, Kimi) review this PR on GitHub
  • Human: partner job / D4 still blocked; do not start the 6-week clock

Closes nothing yet. Progress on #435 / #97.

…-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 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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…COMMIT transaction; staging always dropped in finally; mapping errors raised before any BQ write. ✓
  • Failed-session contract: returncode==0 only feeds status='ERROR' when non-zero; failed_sessions_sql never reads returncode; missing_score_fails=True by default; classify_sessions and the SQL are pinned to each other by tests. ✓
  • CLI evalbench-import: registered on the bq-agent-sdk app, 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-level id/eval_id/scenario_id/prompt_id, while result rows also look into nested scenario/eval_results. A score row whose id is only nested gets session_id=None and 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_events is accepted (segment regex allows it). Defaults are safe and the target dataset is caller-chosen, but the "never the production agent_events table" promise would be more robust with an explicit guard rejecting that reserved name.

Nits / can wait

  • cli.py:369 imports the private evalbench._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 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

  1. src/bigquery_agent_analytics/evalbench.py:604 - The reserved agent_events target is still accepted. events_table is checked only for identifier syntax and then used directly to form events_ref, so both the public API and --events-table agent_events can target the ADK production table despite the hard "never agent_events" contract. Reject the reserved name for every destination argument before any BigQuery operation, and add API/CLI regression tests.

  2. src/bigquery_agent_analytics/evalbench.py:610 - Retained import versions reuse the same trace identity. session_id and trace_id depend only on (job_id, scenario_id), while changed source data creates a new retained import_version. Existing readers such as Client._GET_TRACE_QUERY (src/bigquery_agent_analytics/client.py:157) filter only by trace_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.

  3. 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 unconditional DELETE/INSERT overwrites the committed immutable version even with replace=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.

  4. src/bigquery_agent_analytics/evalbench.py:651 - The unchanged decision compares only fingerprints and ignores the destination refs stored in the manifest. Re-running the same (job_id, import_version) with a different events_table or scores_table returns unchanged and reports the newly requested refs even though nothing was published there; replace=True can also orphan rows in the old destination. Require requested destinations to match the manifest, or define an explicit relocation contract.

  5. src/bigquery_agent_analytics/evalbench.py:1449 - Non-empty stderr is promoted to error_message only when _failed_returncode(returncode) is true. A completed row with returncode == 0, a final response, and stderr therefore emits status = 'OK' and can pass, contrary to the documented process-failure contract. Handle usable stderr independently 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 SQL ARRAY_AGG returns 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 after COMMIT, 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() passes NaN and 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 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

  1. Reserved agent_events: _validate_destination_table rejects it before any BigQuery call, on both the API path (materialize) and the CLI path (cli.py:2327). Tests on both.
  2. Versioned identities: published rows use evalbench:{job_id}:{import_version}:{scenario_id} for session_id/trace_id, with span/invocation ids derived from it and attributes.evalbench_import_version set; 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_identities asserts v1/v2 trace/span/invocation id sets are disjoint — exactly the Client.get_trace merge hazard Codex flagged.
  3. Txn guard: the manifest conflict check moved inside the publish script (SET … IF … RAISE before the DELETEs), with replace=True keeping 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.
  4. Destination-binding: same fix as my P1 above.
  5. stderr independent of returncode: _source_error_message now collects usable stderr regardless of returncode, so returncode==0 + final response + stderr publishes status='ERROR'. Pinned by test_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_staging switched to WRITE_APPEND, but staging refs carry a per-run uuid4 suffix, so append-on-fresh-table is safe.
  • except ValueError: raise in the publish path keeps pre-existing ValueError semantics intact; the conflict-message remap to ValueError is 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.py still imports private evalbench._parse_timestamp (and now _validate_destination_table) — cosmetic.

Ship it.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Reviewer: Codex

Verdict: Request changes. Two P1 defects remain at 7e47def; no P0 was found. The requested tests pass: 59 passed.

P1

  1. src/bigquery_agent_analytics/evalbench.py:681 - A custom manifest table bypasses version immutability. manifest_table remains caller-selectable, and both the pre-read and the in-transaction conflict guard consult only that selected table. Publish job/v1 to events/scores plus manifest M1, then publish changed source for the same job/v1 to the same events/scores with manifest M2 and replace=False: M2 has no row, so the transaction deletes and replaces the shared event/score rows while M1 remains 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.

  2. src/bigquery_agent_analytics/evalbench.py:1139 - The new versioned identity is not collision-safe for legal inputs. It concatenates unescaped components with :, while import_version explicitly 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 become evalbench:job:release:1:case; Client.get_trace, which filters by trace_id only, 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.
  • unchanged ignoring destination refs: fixed for the stored event/score refs; the alternate-manifest path above still bypasses the immutable binding.
  • stderr conditional on failed return code: fixed; usable stderr independently 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 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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_unchanged still passes), and components without :/\ render verbatim, so the documented readable form is preserved for the common case.
  • All prior fixes from 7e47def (reserved agent_events rejection, 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.py importing private evalbench helpers — cosmetic.

Ship it.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

  1. 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 keyed DELETEs affect zero rows and both transactions then append their staged events, scores, and manifest rows. BigQuery documents that reads/appends can run concurrently and that INSERT never 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.

  2. src/bigquery_agent_analytics/evalbench.py:1174 and :1894 - The collision fix changes identifiers from the existing v0.5.1 public to_agent_event_rows() path even when import_version is omitted. A legal scenario v1:case previously produced evalbench:job-123:v1:case and now produces evalbench:job-123:v1\:case; _stable_id() also changed globally, so even delimiter-free sessions get different invocation/span IDs (for evalbench:job-123:case, invocation f567e6f5a86a69f608edb2751cc3771c becomes 7e1929eab2ee7be1f2750377e1280c73). 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 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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: unescaped evalbench:{job_id}:{scenario_id} and the frozen legacy _stable_id hash (\x1f-join, no length prefix). A scenario v1:case again yields evalbench:job-123:v1:case, and the invocation id for evalbench:job-123:case is back to f567e6f5a86a69f608edb2751cc3771c — 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 start evalbench:, published always evalbench-import: (test_published_identities_never_alias_plain_reads covers even the contrived import: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_TABLE constant, manifest_table= raises TypeError), reserved agent_events rejection, destination binding (including replace=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 the concurrent update marker, and neither message contains the other's substring; other exceptions propagate unchanged (except ValueError: raise preserved).
  • Docs (docs/evalbench.md) updated for the lock table, the @@row_count guard, 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.py importing private evalbench helpers — cosmetic.

Ship it.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

  1. src/bigquery_agent_analytics/evalbench.py:353 - Adding snapshot_at between location and results changes the generated positional constructor of the public EvalBenchRun dataclass. A valid v0.5.1 call such as EvalBenchRun(project, dataset, job, location, results, scores, config_rows) now assigns results to snapshot_at, shifts the remaining tuples, and can silently return zero event rows. Preserve the existing positional field order by moving snapshot_at after config_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-seeded evalbench_import_lock sentinel, 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_version retains the v0.5.1 evalbench:{job_id}:{scenario_id} encoding and legacy \x1f-joined hash. Versioned identities use the separate escaped evalbench-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 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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) → results lands in .results, snapshot_at is None.
  • EvalBenchRun('p','d','j','US', results, scores, config_rows, snapshot_at) → snapshot_at accepted as the 8th positional, results intact.

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 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

  1. src/bigquery_agent_analytics/evalbench.py:225 - A stale pre-read can still rewrite an immutable version without replace=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 though source_project/source_dataset change the manifest and the published attributes.evalbench_source_* values. B then unconditionally deletes and reinserts A's (job_id, import_version) and returns imported instead of preserving A and returning unchanged. 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: EvalBenchRun now declares snapshot_at after results, scores, and config_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 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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:

  1. Absent / identical / conflicting inside the transaction. The publish script now computes existing_manifest_rows and conflicting_manifest_rows after the lock claim (_PUBLISH_SCRIPT, evalbench.py:252-290). Without replace: 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 original imported_at are left exactly as published instead of being deleted and re-inserted. materialize() maps that rollback to status="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).

  2. Provenance is part of the decision. _PROVENANCE_CONFLICT_PREDICATE (source_project != @source_project OR source_dataset != @source_dataset) joins the conflict predicate without replace, fed by new @source_project/@source_dataset parameters from self.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 the ValueError. The reasoning for excluding source_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.

  3. Regression coverage for the exact attack. test_materialize_stale_pre_read_provenance_drift_is_a_conflict parametrizes both project_id and evalbench_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, and replace=True remains the explicit override that re-publishes with the new provenance in both the manifest and attributes.evalbench_source_*. test_materialize_stale_pre_read_identical_publish_is_unchanged pins the twin case: identical content and provenance through a stale pre-read reports unchanged with 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=True correctly keeps the destination binding while waiving fingerprint, provenance, and the identical guard (test_publish_script_replace_skips_fingerprint_guard_only).
  • _unchanged_result reports the requested events_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: raise is 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.md was 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.py importing private evalbench helpers — cosmetic.

Ship it.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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_dataset drift 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 any DELETE; identical committed versions roll back and return unchanged instead 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=True override. 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.

caohy1988 added a commit to caohy1988/BQAA-SDK-fork that referenced this pull request Aug 30, 2026
… 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.
@haiyuan-eng-google
haiyuan-eng-google merged commit 2459c0f into GoogleCloudPlatform:main Aug 30, 2026
15 checks passed
caohy1988 added a commit to caohy1988/BQAA-SDK-fork that referenced this pull request Aug 30, 2026
…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.
caohy1988 added a commit to caohy1988/BQAA-SDK-fork that referenced this pull request Aug 30, 2026
… 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.
haiyuan-eng-google pushed a commit that referenced this pull request Aug 30, 2026
…) (#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.
caohy1988 added a commit to caohy1988/BQAA-SDK-fork that referenced this pull request Aug 30, 2026
… 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.
caohy1988 added a commit to caohy1988/BQAA-SDK-fork that referenced this pull request Aug 30, 2026
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.
caohy1988 added a commit that referenced this pull request Sep 4, 2026
…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.
caohy1988 added a commit that referenced this pull request Sep 5, 2026
…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.
haiyuan-eng-google pushed a commit that referenced this pull request Sep 5, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants