Skip to content

feat(trace): propagate identity-safe selectors across secondary surfaces (#359 U3) - #375

Merged
haiyuan-eng-google merged 9 commits into
mainfrom
feat/359-secondary-surfaces-u3
Jul 24, 2026
Merged

haiyuan-eng-google merged 9 commits into
mainfrom
feat/359-secondary-surfaces-u3

Conversation

@caohy1988

Copy link
Copy Markdown
Collaborator

Summary

Completes U3 of the #361 sequencing plan by propagating the identity/scope selector and ambiguity contract from #371 through every secondary trace-reading surface.

  • makes GQL reconstruction resolve the authoritative flat identity/scope first and confines graph edges to that exact span population
  • routes BigQueryTraceEvaluator, replay, and comparison through TraceSelector, while pushing evaluator event-type filtering into BigQuery after complete candidate resolution
  • adds identity/scope pins, exact selector JSON retries, and structured AmbiguousSessionError responses to the CLI, Remote Function, and self-monitoring agent example
  • preserves colliding identities/scopes in quality and latency reports, correlates scores and sampled trajectories fail-closed, and completeness-probes explicit session populations instead of silently truncating at 64 candidates
  • documents the migration contract, sensitive retry payloads, mixed-scope behavior, and the intentionally deferred evaluate_categorical: support per-session judge context (golden expected answers) on the server-side paths #358 judge-context and persistence/view work

Correctness details

  • scalar selector pins preserve all three states: omitted/UNSET, explicit SQL NULL, and exact strings
  • retry surfaces carry the complete candidate["selector"], including scope_signature
  • GQL supplies relationships only; event content and attribution remain sourced from the exact flat trace
  • evaluator tool-call extraction remains correct when stable SQL tie-breaks place a terminal tool event before its matching start
  • session-only categorical scores never choose or render one candidate from a reused-session collision
  • report trajectory re-fetches retain only the score-attributed identity/scope population

Verification

  • focused U3/U2 surface suite: 606 passed
  • full offline suite after merging current main: 3948 passed, 48 skipped
  • live BigQuery collision/dry-run suite: 34 passed
  • autoformat.sh: clean
  • git diff --check: clean

Sequencing

This PR follows merged U1 (#362) and U2 (#371). It completes the release-boundary plumbing required before the identity-safe trace work can ship.

The following #358 units remain intentionally separate:

  • U4: bind per-session judge context to resolved identity across AI.GENERATE, retry, and Gemini API fallback
  • U5: migrate persistence cardinality in schema → writer → view order

Closes #359
Updates #361

@caohy1988

Copy link
Copy Markdown
Collaborator Author

U3 round 1 fresh review — no blocking findings

Reviewed exact head 671d333 (PR #375) against main: a full-diff pass over all 28 files, a line-by-line read of the core changes (client.py event-type plumbing and GQL rewrite, trace_evaluator.py resolver migration, CLI/Remote Function ambiguity surfaces, report attribution), and behavioral probes executed against the head. This surface-propagation unit is in much better shape on arrival than U2 was — no P1 or P2 findings; three P3s below.

Verified sound (the load-bearing claims, each checked against the code or by execution):

  • Contract fidelity. Every secondary surface routes through the shared U2 resolver: CLI get-trace (selector options + --selector-json for explicit-null pins), Remote Function analyze (selector object with additive-field conflict rejection), BigQueryTraceEvaluator (async wrapper over get_trace_by_selector), replay/compare (selector pass-through with session-id consistency checks), and the eval-dataset items. Ambiguity payloads round-trip: the CLI emits to_dict() JSON on stdout with exit code 2, the Remote Function attaches details to _error, and TraceSelector(**payload) reconstructs exact pins including explicit nulls.
  • GQL reconstruction is a genuine hardening, not just propagation. The old edge query's OR predicate could pull cross-session edges, and the old span-merge path could fabricate span rows from graph data. Now the flat resolver defines the exact span population, parent/child.span_id IN UNNEST(@span_ids) pins traversal to it, graph rows contribute parent links only onto deep-copied flat spans, duplicate span-ids skip GQL with a warning, and the manager-level convenience path resolves identity-safely (raising on ambiguity instead of broadening). Identity/scope/coverage metadata is preserved on the reconstructed trace.
  • Event-type pushdown stays scope-sound. Candidate discovery is never event-filtered; the restriction applies only to the authoritative span fetch. The mixed path fetches a lightweight attributes-metadata companion (attested, anchored) so coverage and conjunctive Python-only pin verification still see the complete scope population while excluded payloads never cross the wire. _materialize_event_filtered_trace assigns rows with the same exact-payload/local-shared/identity-shared rules as the builder and revalidates identity per row; event_types is normalized through the validating TraceFilter container, closing the lying-container hole at this new boundary.
  • Reports fail closed on collisions. quality_report matches scores to resolved contexts via the reserved SessionScore.details attribution keys, retains colliding rows when attribution disambiguates, warns and refuses to guess when it cannot, and probes listing completeness (doubling the limit until a short page) instead of trusting an exactly-full page. The round-7-era "KNOWN LIMITATION (Trace queries: row scope ignores pass labels and full session identity (session_id reuse mixes traces and judge transcripts) #359)" comments are gone along with the limitation.
  • Docs and release gating. CHANGELOG documents U1+U2+U3 as one release boundary with concrete migration guidance (catch AmbiguousSessionError, pass the complete candidate["selector"], preserve explicit nulls and scope_signature); the evaluator's behavior change (reused session ids now raise instead of silently merging) is covered by that guidance.
  • Verification reproduced: focused surface suites 648 passed; full offline suite 3,892 passed / 15 skipped; live BigQuery suite 34 passed (the test_cli_agent_tool.py collection exclusion is local adk-python environment drift, green in remote CI).

Findings:

  • P3 — the CLI omits the mixed-scope escape hatch that the Remote Function exposes (cli.py get_trace; dispatch.py accepts allow_mixed_scope). A CLI user who hits AmbiguousSessionError on a single-identity multi-scope session gets the structured payload and can retry one exact candidate, but cannot request the conversation-complete KTD4 read at all. Either add --allow-mixed-scope (documenting that cross-identity ambiguity still raises) or note the asymmetry as intended in SDK.md.
  • P3 — event-filtered exact reads flip trace_id to the session fallback when the filter excludes the scope's tagged rows (_materialize_event_filtered_trace, own_trace_ids collected only from tagged rows). Executed: a labels-scoped trace whose tagged row is LLM_RESPONSE reports its genuine trace id unfiltered but trace_id == session_id under event_types=["USER_MESSAGE_RECEIVED"], so the same resolved scope's trace_id varies with the event filter — the round-8 P3-10 consistency family. Consider deriving the id from the unfiltered scope proof (the resolution page already knows the scope exists) or documenting the fallback.
  • P3 — empty-result semantics under event_types are undocumented. Executed: an event filter matching no rows returns a zero-span Trace (identity/scope attached) rather than the "No events found" error the unfiltered read raises, on both the exact and mixed paths. Reasonable semantics, but neither get_trace_by_selector nor get_session_trace documents that an event filter suppresses the not-found error; consumers assuming spans is non-empty (e.g. final_response derivation) should be warned.

Verdict: approve with the three P3s as follow-ups — none blocks merge. After merge, the #361 sequencing gates read satisfied for #359 closure: U2+U3 land at one release boundary and the live collision fixture passes (34/34).

- expose the mixed-scope escape hatch in get-trace

- preserve resolved scope trace IDs under event filtering

- document zero-span filtered trace semantics
@caohy1988

Copy link
Copy Markdown
Collaborator Author

the CLI omits the mixed-scope escape hatch that the Remote Function exposes

Fixed in b1a911b. bq-agent-sdk get-trace now accepts --allow-mixed-scope for both session selectors and --selector-json. It delegates to the shared resolver's KTD4 path, and both CLI help and SDK.md state that cross-identity ambiguity still raises. Combining the flag with --trace-id is rejected because mixed scope is a session-selector operation.

event-filtered exact reads flip trace_id to the session fallback when the filter excludes the scope's tagged rows

Fixed in b1a911b. Candidate discovery now carries the first producer trace_id for each exact tagged scope, ordered with the same stable columns as the authoritative fetch. _materialize_event_filtered_trace() receives that unfiltered scope proof, so filtering out tagged rows—or matching no rows—no longer changes the resolved scope's trace_id. Untagged shared rows still cannot supply a scope-specific ID.

empty-result semantics under event_types are undocumented

Fixed in b1a911b. Both get_session_trace() and get_trace_by_selector() now document that an event filter matching no payload rows returns an attributed zero-span Trace and does not raise the unfiltered not-found error. The behavior is locked by a doc-contract regression alongside the existing behavioral test.

Verification:

  • 676 focused U2/U3 surface tests passed
  • full offline suite: 3,951 passed / 48 skipped
  • modified candidate query passed a table-backed live BigQuery dry run
  • autoformat and git diff --check clean

The full scratch-dataset live fixture was also attempted, but Google API retry remained active for seven minutes and the run was interrupted; it is not included in the pass counts above.

@haiyuan-eng-google
haiyuan-eng-google merged commit 105e74b into main Jul 24, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants