Skip to content

Overhaul README, add documentation indexes, and fix CI issues - #4

Merged
haiyuan-eng-google merged 3 commits into
GoogleCloudPlatform:mainfrom
haiyuan-eng-google:main
Apr 11, 2026
Merged

haiyuan-eng-google merged 3 commits into
GoogleCloudPlatform:mainfrom
haiyuan-eng-google:main

Conversation

@haiyuan-eng-google

Copy link
Copy Markdown
Collaborator

Fix the readme, cl and doc structure

caohy1988 and others added 3 commits April 11, 2026 07:29
Rewrite the root README to follow GCP OSS patterns — add badges,
group features by category, add prerequisites, trim inline code
examples, link to new doc indexes, show logical architecture, and
add a disclaimer. Cross-link ADK BigQuery Trace Exporter plugin.

Create index READMEs for docs/, examples/, and deploy/ so readers
can navigate the 10 design docs, 24 examples, and 4 deployment
surfaces without scanning directory listings.

Add setup guides for deploy/remote_function/ and
deploy/continuous_queries/.

Fix CI: refactor deploy/remote_function/dispatch.py to import
resolve_client_options from the shared _deploy_runtime module
instead of duplicating env-var resolution inline. This fixes
test_remote_and_streaming_import_same_resolver.
docs: overhaul README, add doc indexes, fix CI
@google-cla

google-cla Bot commented Apr 11, 2026

Copy link
Copy Markdown

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

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

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

@haiyuan-eng-google
haiyuan-eng-google merged commit 9f76a1c into GoogleCloudPlatform:main Apr 11, 2026
7 of 8 checks passed
haiyuan-eng-google added a commit that referenced this pull request Apr 13, 2026
evekhm added a commit to evekhm/BigQuery-Agent-Analytics-SDK that referenced this pull request Jul 7, 2026
…lags, fail-fast, artifact/seed/doc fixes

- run_agent: record structured tool_calls_detail [{name,args}] (was count-only) [#1]
- quality_report: carry tool_calls_detail into the scored report (resolved_map + serializer)
- skill_evolution.format_trajectory: show actual tool calls to analysts for TOOL_USAGE/WRONG_TOOL [#2]
- skill_evolution: write sanitized viable candidates (not raw) so _SELECTED tags the returned skill [GoogleCloudPlatform#3]
- skill_evolution CLI: expose --tools/--eval-spec/--artifacts-dir [GoogleCloudPlatform#9]
- analyze_and_evolve: fail fast when --eval-spec is missing or has no tools [GoogleCloudPlatform#7]
- run_sweep: rename seeds->runs (independent repetitions, no RNG seed threaded; SEEDS alias kept) [GoogleCloudPlatform#4]
- compare_runs: tool-selection behavior table from tool_calls_detail (skipped for legacy reports)
- docs: examples/README stale numbers (80q, 28.7->100, ~2.2KB), no-teacher-model->no-managed-optimizer [GoogleCloudPlatform#6,GoogleCloudPlatform#10], engine-reuse + why-BQAA sections
- tests: +3 for tool-call rendering (31 skill_evolution, 130 total pass)
haiyuan-eng-google pushed a commit that referenced this pull request Jul 7, 2026
…on, anti-parroting, declines, and reproducible sweeps (#319)

* [skill_evolution_lab] post-merge: orphan-fence fix, refreshed numbers, detachable sweep runner

Follow-up to #301 (squash-merged). Three changes:

- Engine: strip_code_fences now also removes an orphan opening ``` fence the
  model sometimes inserts right after YAML frontmatter (the matching close is
  lost, leaving an unbalanced fence that would render verbatim in the deployed
  skill). Balanced code blocks in the body are preserved. +2 unit tests (26 total).

- Docs/sample: refresh sample_run/ and all numbers (README, VERIFICATION,
  examples/README, sample_run) from a post-fix 4x3 sweep. No regressions vs the
  pre-fix engine -- equal-or-better across all four models; gemini-3.1-flash-lite
  variance tightened from 90% [71-100] to 97% [95-98].

- run_sweep.sh: hardened into a detachable long-running job -- self-logs to
  runs/SWEEP_<ts>.log (safe to nohup), continues past a single failed run, and
  aggregates whatever completed. Documented (foreground + background) in README.

* [skill_evolution_lab] align run_e2e_demo.sh with run_cycle.sh; quiet SDK logs

Make the demo's logging and CLI consistent with examples/agent_improvement_cycle.

- run_e2e_demo.sh: rewrite to mirror run_cycle.sh's structure -- --flag CLI
  parsing + --help (--agent-model / --analyst-model / --judge-model /
  --judge-location / --concurrency / --with-registry / --skill-id), one run.log
  per run via the same `tee | sed` ANSI-strip, PYTHONWARNINGS/LOGLEVEL + a PY
  var, colored stage banners with per-step timing, a config banner, and a final
  summary. Env vars stay as fallbacks, so run_sweep.sh is unaffected.

- run_agent.py + analyze_and_evolve.py: silence the noisy google_genai / httpx /
  google.auth / google.adk loggers (the same block quality_report.py already
  uses) before the google imports, so the demo flow is readable -- no more
  "AFC is enabled" / "...will take precedence" / "HTTP Request: POST ..." spam.

* skill_evolution_lab: drop hardcoded synonym/keyword mappings; tool-first consolidator

- tools.py: remove _TOPIC_ALIASES/_resolve_topic; lookup_company_policy is
  topic-keyed (exact + substring match) and the model maps the user's everyday
  wording to a topic itself -- no hand-maintained synonym table
- skill_evolution.py: stop emitting Keyword/Terminology Mapping (success-analyst
  prompt, category set, consolidator). Strengthen the consolidator: tool-first
  (rewrite "contact HR" deflection into a tool-first rule), ban fact-baking
  (qualitative and numeric), and generalize per-topic lists into one rule
- refresh sample_run/, VERIFICATION.md, README.md from a clean gemini-3.5-flash
  run (V0 20% -> V1 100%, 2.4KB tool-first skill, no synonym table)

The 4-model sweep numbers refresh in a follow-up.

* skill_evolution_lab: make analysts tool-aware (fix NO_PATCH on deflections)

The error analysts couldn't see that a lookup tool existed, so every single-turn
deflection ("contact HR") came back NO_PATCH -- the tool-first rule was only
sneaking in from the few tool-using successes plus the consolidator, not from the
failures. It was masked because V1 still scored ~100%.

- skill_evolution.py: thread a tools description through evolve_skill ->
  collect_patches -> run_analyst (an <available_tools> block). The error-analyst
  prompt now treats a deflection on a tool-covered topic as a fixable TOOL_USAGE
  patch -- never NO_PATCH and never a baked fact.
- eval_spec.json: add a `tools` field; analyze_and_evolve.py reads it (--eval-spec)
  and passes it to evolve_skill; run_e2e_demo.sh wires it through.
- refresh sample_run/, VERIFICATION.md, README.md from a clean tool-aware run:
  V0 18.5% -> V1 100%, a 1.5KB tool-first skill, and 46/46 patches now pass the
  gate (deflection failures finally produce real "use the tool" rules).

26 tests pass.

* skill_evolution_lab: add a 2nd tool (calculate_disability_pay) -> tool-selection demo

The single-tool demo only showed "use the tool or don't." A second, computing tool
forces the agent to CHOOSE: lookup_company_policy for facts vs calculate_disability_pay
for a personalized short-term-disability payout the lookup can't produce.

- agent/tools.py: add calculate_disability_pay(annual_salary, weeks_out) to AGENT_TOOLS.
- eval: 10 STD-payout calc questions (5 evolve + 5 held-out, with DISTINCT
  salaries/weeks so evolve and test stay disjoint), each in golden_qa with its
  computed answer; eval_spec `tools` field now describes both tools and defines a
  wrong-tool-selection failure.
- refresh sample_run/, VERIFICATION.md, README.md from the multi-tool run:
  V0 20% -> V1 100%, 51/51 patches pass, and V1 learns a real routing rule
  (lookup for facts, calculator for personalized math) -- a richer skill than the
  single-tool version.

26 tests pass.

* skill_evolution_lab: tools.py docstring -- reflect the two-tool (lookup + calculator) setup

* skill_evolution_lab: rename error category KEYWORD_GAP -> WRONG_TOOL (drop keyword baggage)

* [skill_evolution_lab] fix sweep model-override bug; real multi-tool 4-model numbers

- run_e2e_demo.sh: capture env-passed model overrides BEFORE sourcing .env, so a
  caller's AGENT_MODEL=... (and run_sweep.sh's per-model override) wins over the
  value baked into .env instead of being clobbered by it. Precedence is now
  CLI flag > env > .env > default. Without this, every sweep run silently fell
  back to gemini-3.5-flash.
- run_sweep.sh: pass the model via the explicit --agent-model flag (belt and
  suspenders alongside the env fix).
- VERIFICATION.md / examples/README.md: refresh the four-model x 3-seed table with
  the real multi-tool sweep (V0 21-51% -> V1 93-100%) and rewrite the V0-spread
  observation -- the pro models reach for the tool under the flawed skill and start
  higher, the flash models obey it and start lower, and the evolved skill closes
  the gap to 93-100% across the board.

* [skill_evolution_lab] save the V0 skill into every run dir (v0_skill.md)

Each run now writes the flawed V0 baseline as v0_skill.md alongside the evolved
v1_skill.md, so a run is self-contained and you can diff V0 vs V1 directly. Adds
the missing v0_skill.md to the committed sample_run/, and updates the sample_run
and lab READMEs (file list + refreshed headline: V0 20% -> V1 100%, 70-q held-out,
grounding 11% -> 87%, evolved skill ~1.9KB).

* [skill_evolution_lab] commit run.log into sample_run (full console log)

The committed sample_run/ now includes run.log -- the complete stage-by-stage
console log of the recorded run (banner -> 4 steps -> comparison + summary),
matching the data already in sample_run/ (same run, byte-identical reports). Every
live run already writes this log to its runs/<timestamp>/ dir; this curates it into
the committed sample for parity with examples/agent_improvement_cycle.

* [skill_evolution_lab] track sample_run/run.log (gitignore exception)

The committed recorded run was missing its console log because examples/**/*.log
ignores all logs. Add a negation for examples/skill_evolution_lab/sample_run/run.log
so the curated sample keeps its full stage-by-stage log (live runs/ logs stay
ignored). run.log matches the rest of sample_run/ (same recorded run).

* skill_evolution: persist analyst patches, candidates, and prevalence

evolve_skill() gains an optional artifacts_dir= that writes the engine's
intermediate reasoning before returning the selected skill:
  - v1_patches.json    one record per analyst patch (root-cause category + text)
  - v1_candidates/      each best-of-N candidate (selected one tagged _SELECTED)
  - v1_prevalence.txt   root-cause category tally across patches

analyze_and_evolve.py always writes them alongside the evolved skill (the run
output dir), so every run keeps the engine's diagnoses without any extra flag.
Previously only the final v1_skill.md was kept. Adds a unit test for the writer.

* skill_evolution_lab: refresh sample_run with a consistent run incl. engine artifacts

Regenerated sample_run/ from one end-to-end run on the artifact-saving engine,
so the committed patches/candidates match the committed v1_skill.md and its
held-out scoring. Adds v1_patches.json (51 analyst patches), v1_candidates/
(best-of-N, selected tagged), and v1_prevalence.txt; README documents them.
Held-out: V0 18.6% -> V1 100% (70/70).

* skill_evolution_lab: full-dimension scoring + dimension averages in RESULT

run_e2e_demo.sh now scores --dimensions full, so reports carry the five 0-2
quality dimensions (correctness, tool use, specificity, scope, first-time-right)
and failure_attribution per session -- which the analyst fleet already consumes
via format_trajectory. compare_runs.py adds a V0-vs-V1 dimension-averages table
to RESULT.md/RESULT.json. sample_run refreshed from one full-dim run:
held-out V0 18.6% -> V1 98.6% (69/70).

* skill-evolution lab: add out-of-scope questions and score declines

Extend the single-agent demo so the `declined` verdict is exercised end to end:

- new eval/questions_oos.json (8) + questions_oos_heldout.json (10)
- wire the out-of-scope slice into run_e2e_demo.sh (evolve + both held-out runs)
- compare_runs.py: credit a correct decline, add an "Out-of-scope (declined)"
  RESULT row and group (backward-compatible; row omitted when no OOS sessions)
- refresh sample_run/ from a full recorded run: V0 declines OOS by reflex (90%),
  and the evolved V1 learns an "Out-of-Scope Handling" section and declines 100%
- update sample_run/README.md and VERIFICATION.md to match

Held-out set grows 70 -> 80 (adds 10 out-of-scope). The scorer needs no change:
the judge derives `declined` from the eval_spec `scope` field. 27/27 tests pass.

* [skill_evolution_lab] setup.sh: enable the Vertex AI API (was missing)

setup.sh wrote .env and reset the skill but never enabled any GCP API, so a
fresh project would fail at the first Gemini call. Enable the one API this
example actually needs -- aiplatform.googleapis.com (Gemini generateContent, the
text-embedding model for golden-Q&A matching, and the Skill Registry, all served
from *-aiplatform.googleapis.com). No BigQuery is enabled: scoring runs offline
via --conversations-file. Enablement is idempotent and soft-fails with a clear
message if the caller lacks serviceusage rights. Docs/prereqs updated.

* [skill_evolution_lab] clearer golden-rate label, doc currency, strip username from committed log

- print_rate.py: make the one-line rate unambiguous -- "14/70 matched to the
  answer key, of 80 total; 10 out-of-scope" instead of the misleading
  "14/70 golden-matched" (the 70 is the in-scope matched subset, not a
  70-question test).
- sample_run/run.log: strip absolute /home/<user>/... paths (relative now), so
  the committed log no longer leaks a local username. (Only committed data
  touched; run.log generation unchanged.)
- VERIFICATION.md: fix the grounding row -- it had the golden-meaningful counts
  (14/80 -> 70/80) mislabeled as grounding; real tool-call grounding for the
  recorded run is 11% (9/80) -> 79% (63/80).
- README.md: bring current with the multi-tool + out-of-scope demo -- add
  tool-selection and out-of-scope bullets, list the questions_oos*.json files,
  fix runtime (68 evolve + 80 held-out) and the "What you'll see" numbers.
- run_e2e_demo.sh: fail fast with a clear message if PROJECT_ID is unset.

* docs: disambiguate "grounding" -> "golden-graded" for the correctness sense

Reserve "grounding" for the tool-call metric; the ground-truth/correctness sense
is now "golden-graded" (and the "Golden-Q&A grounding" bullet -> "grading"),
matching the companion blog post.

* docs(skill_evolution_lab): show anti-bloat consolidator-prompt rules in README

* Address review: gate registry push on held-out win, honest oos labeling, portability fixes

- run_e2e_demo.sh: registry mirror moved after the STEP 4 comparison and
  gated on V1 beating V0 (compare_runs.py --gate, exit 3 on regression);
  a losing V1 is never pushed as a new revision. BSD-sed-safe ANSI strip
  ($'...' so bash emits the ESC byte). need_val() usage errors for flags
  missing their value; early --with-registry/--skill-id validation.
- analyze_and_evolve.py: --registry-push-only mode (push without
  re-evolving) used by the gated mirror; registry logic factored into
  _mirror_to_registry().
- print_rate.py: out-of-scope counted by the oos_ session-id prefix (same
  convention as compare_runs.py); in-scope sessions that fail the golden
  match now print as 'unmatched' instead of being mislabeled out-of-scope.
- tools.py: the 7-day STD waiting period is documented as unpaid time
  before benefits begin that does NOT reduce the 12 payable weeks
  (docstring, weeks_out arg, policy details, waiting_period_note in the
  tool result) -- the math and the policy text now agree.
- run_sweep.sh: set -euo pipefail restored; the if-guard alone provides
  continue-past-failure for individual runs.
- skill_evolution.py: evolve_skill(version_label=...) so a V1->V2 round
  writes v2_* artifacts, plus <label>_selection.txt recording why a
  candidate won or why the incumbent was kept (audit trail of the guard).
- _quiet.py: shared warning/logger suppression, imported by run_agent.py
  and analyze_and_evolve.py (was duplicated verbatim).
- README: jq listed as an optional dependency; registry docs describe the
  gated push. Tests: 28 passed.

* Address second review: structured tool calls end-to-end, engine CLI flags, fail-fast, artifact/seed/doc fixes

- run_agent: record structured tool_calls_detail [{name,args}] (was count-only) [#1]
- quality_report: carry tool_calls_detail into the scored report (resolved_map + serializer)
- skill_evolution.format_trajectory: show actual tool calls to analysts for TOOL_USAGE/WRONG_TOOL [#2]
- skill_evolution: write sanitized viable candidates (not raw) so _SELECTED tags the returned skill [#3]
- skill_evolution CLI: expose --tools/--eval-spec/--artifacts-dir [#9]
- analyze_and_evolve: fail fast when --eval-spec is missing or has no tools [#7]
- run_sweep: rename seeds->runs (independent repetitions, no RNG seed threaded; SEEDS alias kept) [#4]
- compare_runs: tool-selection behavior table from tool_calls_detail (skipped for legacy reports)
- docs: examples/README stale numbers (80q, 28.7->100, ~2.2KB), no-teacher-model->no-managed-optimizer [#6,#10], engine-reuse + why-BQAA sections
- tests: +3 for tool-call rendering (31 skill_evolution, 130 total pass)

* Address fresh review at c7a090d: truthful tool-detail on BQ path, gate tie, seeds->runs

- quality_report: emit tool_calls_detail only when actually captured (conversations path),
  so BQ/trace-path sessions stay key-absent instead of a false [] [P2.1]
- skill_evolution._format_tool_calls: empty detail + nonzero tool_calls = 'unknown' (say
  nothing), not '(none)' -- avoids misinforming analysts on BQ-sourced reports [P2.2]
- compare_runs --gate: require V1 to *beat* V0 (tie no longer mints a registry revision);
  note it gates on overall rate only [P3.4]
- VERIFICATION.md: seeds -> runs, consistent with run_sweep.sh [P3.3]
- skill_evolution CLI: warn (not fail) when --eval-spec has no tools (nit)
- tests: +1 for the BQ-path unknown case (32 skill_evolution, 131 total pass)

* skill_evolution_lab: two-defect V0 (real parroting), gated --rounds 2, refreshed run + sweep

- V0 gains a second planted defect ("be agreeable: accept the user's figure"):
  correction cases now genuinely parrot at V0 and the analysts emit PARROTING
  patches (v1_prevalence: TOOL_USAGE 18/23, PARROTING 3/23).
- run_e2e_demo.sh --rounds 2: re-runs the evolve set on V1, evolves V1 -> V2
  (analyze_and_evolve --version-label), measures V2 on the held-out set, and
  keeps V2 only when it beats V1 (compare_runs --label0/--label1 --gate); the
  registry mirror pushes whichever version won.
- engine: emit the no-tools warning after logging.basicConfig -- the early
  module-level warning installed an implicit WARNING root handler and muted
  every INFO log for the rest of the run.
- recorded sample_run (gemini-3.5-flash, --rounds 2): V0 67.5% -> V1 97.5%
  overall, corrections 0% -> 100% (parroted 15 -> 0); round-2 V2 tied 97.5%
  and the gate kept the incumbent V1 (RESULT_ROUND2.md + v2_selection.txt).
- 4x3 sweep refreshed on the two-defect V0: V1 in-scope 96-100% on every
  model; all 12 runs score 0% corrections at V0 (universal parroting), zero
  parrots at V1. aggregate_sweep.py column "seeds" -> "runs".
- Docs: lab README / VERIFICATION / examples README rewritten for the
  two-defect story, round 2, and the flash baseline drift (the July endpoint
  grounds on its own where June obeyed the restriction). 32 unit tests pass.

* Feature gemini-3.1-flash-lite as the headline model; refresh sample_run + docs

Model drift made gemini-3.5-flash a poor headline (V0 now ~63% and V1 regresses on
out-of-scope). Switch the featured/default agent to gemini-3.1-flash-lite: it follows
the flawed V0's no-tool restriction most literally, so it starts lowest (~31%) and gives
the biggest CLEAN gain (V1 ~96%, out-of-scope improves 90->100).

- run_e2e_demo.sh: default AGENT_MODEL -> gemini-3.1-flash-lite (so the default run
  reproduces the headline)
- sample_run/: regenerated from a flash-lite run (has tool_calls_detail + the new
  tool-selection table + v1_selection.txt; V0 38.8% -> V1 96.2% overall)
- VERIFICATION.md: reference run + 4-model sweep refreshed from the 2026-07-07 fleet
  (V0 31-63%, V1 94-100%); narrative now notes flash grounds most/starts highest and the
  drift disclosure; internals + evolved skill + before/after updated
- READMEs: headline numbers -> flash-lite; seeds -> runs; ~2.2KB -> ~2.4KB
- aggregate_sweep.py: table column seeds -> runs

* agent_improvement_cycle: strip ANSI on macOS too (bash-produced ESC byte)

BSD sed does not interpret \x1b, so the previous pattern matched the literal
characters and every colour code landed in run.log verbatim on macOS. Produce
the ESC byte in bash via $'...' quoting instead -- same fix run_e2e_demo.sh
already carries.

* skill_evolution_lab: --from-bigquery mode -- score the run through the SDK's BigQuery path

The demo's loop-step-1 story said the plugin logs traces to BigQuery while the
runnable path only ever wrote local JSON. --from-bigquery closes that gap with
the real wiring, verified end-to-end:

- run_agent.py --log-bigquery: walks each chat history in chronological order
  and inserts plugin-schema rows (USER_MESSAGE_RECEIVED / TOOL_STARTING /
  TOOL_COMPLETED / LLM_RESPONSE, JSON content/attributes, root_agent_name +
  per-run custom_tags) into an agent_events table, creating the dataset/table
  on first use with the full producer contract (content_parts included -- the
  SDK trace reader selects it by name).
- run_e2e_demo.sh --from-bigquery: tags every slice with {run, slice} labels
  and scores via quality_report.py --label ... instead of
  --conversations-file, so sessions are read back through the SDK's BigQuery
  trace path.
- quality_report.py: BigQuery-scored sessions now carry tool_calls_detail
  built from the trace's TOOL_* spans (same {name, args} shape as the local
  path), so tool-aware analysts and compare_runs' tool-selection table work
  on both paths; the key is emitted only when spans name their tools, keeping
  key-absence a truthful 'not captured' for older tables.

Smoke-verified on 13 sessions (incl. 5 correction cases): identical verdicts,
parroted sub-trajectory tags, and per-tool detail between the local-JSON and
BigQuery paths. Also: explicit strong-analyst framing in the lab README
(diagnostician on a stronger model; patches carry rules, zero facts).

* skill_evolution_lab: feature gemini-3.1-flash-lite as the default/headline model

Converges the two parallel improvement lines: the two-defect V0 (real
parroting, gated rounds, --from-bigquery) keeps flash-lite as the featured
agent -- it obeys both planted flaws most literally, so it starts lowest and
shows the cleanest lift, and the story stays honest as stronger endpoints
drift (July's flash now grounds on its own; every model still parrots at V0).

- default AGENT_MODEL -> gemini-3.1-flash-lite (run_e2e_demo.sh, setup.sh,
  run_agent.py); README model-overrides + runtime updated
- sample_run/ regenerated from the recorded flash-lite run
  (runs/20260707_085745): V0 37.5% -> V1 97.5% overall (+60pp), single-turn
  36.4% -> 100% (55/55), corrections 0% -> 100% with parroted 11 -> 0
  (including parroting against its own baked PTO-rollover fact), evolved
  skill 2.4KB with a learned Anti-Patterns (anti-parroting) section,
  out-of-scope routing, and derived-rates rule; prevalence TOOL_USAGE 42/48 +
  PARROTING 4/48
- the recorded --rounds 2 run (gemini-3.5-flash, same two-defect V0) moves to
  sample_run/round2/ -- the committed evidence of the gate refusing a tied V2
- VERIFICATION.md: flash-lite reference run + round-2 companion section +
  model-drift note; sample_run/README rewritten; examples README headline
  refreshed

* Autoformat: isort import order in run_agent.py (CI format check)
evekhm added a commit to evekhm/BigQuery-Agent-Analytics-SDK that referenced this pull request Jul 10, 2026
…oudPlatform#4)

- BigQuery configuration is now OPTIONAL for --render-json: the render branch
  dispatches before _load_config(), soft-loading it -- unconfigured envs render
  purely from the JSON (verified under env -i: no config, no queries, dialogue
  fallback blocks intact).
- Trace fetch runs only when the env is explicitly configured (never on bare
  session ids against an unconfigured default), and records its source table
  in Execution Details (traces_source).
- The ORIGINAL scoring run's provenance (project, dataset, eval model,
  elapsed) is carried from the JSON's details into the rendered report,
  plus rendered_from -- provenance is preserved instead of dropped.
evekhm added a commit to evekhm/BigQuery-Agent-Analytics-SDK that referenced this pull request Jul 10, 2026
…eCloudPlatform#10)

- The report header reproduces the invocation with absolute path arguments
  reduced to basenames (previously sys.argv verbatim, leaking /home/... into
  publishable artifacts).
- The other leak (details.source_json absolute path) was already replaced by
  the basename-only rendered_from in the P2 GoogleCloudPlatform#4 commit; committed scorecards
  pick both up at the end-of-series regeneration.

Verified: a render invoked with an absolute JSON path emits zero /home/
occurrences; header shows the basename.
evekhm added a commit to evekhm/BigQuery-Agent-Analytics-SDK that referenced this pull request Jul 10, 2026
One regeneration pass now that the series is complete (P2 GoogleCloudPlatform#4-GoogleCloudPlatform#9, P3 GoogleCloudPlatform#10-GoogleCloudPlatform#13):
- span trees re-seeded with plugin-equivalent telemetry (per-turn invocation
  ids, parent spans, proportional latencies) into per-slice tables
- 'Spans reconstructed from the recorded conversation' label on every seeded
  correction block
- zero absolute workstation paths (P3 GoogleCloudPlatform#10), zero trailing whitespace --
  git diff --check clean (P3 GoogleCloudPlatform#12)
- original scoring-run provenance + rendered_from in Execution Details
- round2 scorecards rendered offline (their traffic was never committed, so
  their correction blocks keep the recorded-dialogue form)
The underlying scored JSONs are untouched -- same recorded run, same numbers.
haiyuan-eng-google added a commit that referenced this pull request Jul 21, 2026
…lence, consolidated docs (#351)

* Markdown scorecards everywhere: --render-json, md twin per scored JSON, sample_run scorecards

- quality_report --render-json <report.json>: re-render the full markdown report
  from an existing --output-json file (pure formatting, zero model calls);
  writes <name>.md next to the JSON
- --report + --output-json now writes <name>.md next to <name>.json (stable
  names) instead of only a timestamped file under scripts/reports/
- run_e2e_demo.sh: every scoring pass now writes BOTH the JSON and its
  markdown twin (--report added to score())
- Correction Analysis: sessions without execution spans (conversations path)
  now render the same Before/After correction blocks with the segment's
  dialogue as evidence, instead of dropping the blocks entirely
- JSON output now persists turn_tags + correction_boundaries so scored JSONs
  are self-sufficient for re-rendering; renderer reconstructs both for older
  JSONs
- sample_run/ + round2/: committed the 6 markdown scorecards rendered from the
  existing scored JSONs (no re-scoring; the recorded run is untouched)
- scripts/sample_quality_report.md: replaced the stale May knowledge_supervisor
  sample with the skill-lab V0 held-out scorecard; READMEs updated

* Run autoformat.sh (single-line imports)

* Execution spans in the scorecards: BQ logging always on, seed recorded runs, fetch traces on render

- run_e2e_demo.sh: every run_agent pass now logs sessions to the BQAA events
  table (--log-bigquery on by default in the demo; --from-bigquery now only
  switches the scoring READ path). Logging is best-effort: a BQ failure warns
  and the run continues.
- run_agent --seed-bigquery <traffic.json> [--seed-report <report.json>]:
  seed the events table from an already-recorded traffic file -- rebuilds each
  session's event stream from the recorded dialogue + ordered tool calls, with
  post-correction call placement certified by the report's sub_trajectories
  (recovered = re-query in that segment; parroted/not_recovered = none). Rows
  are tagged custom_tags.seeded so they stay distinguishable.
- quality_report --render-json now fetches execution traces from BigQuery for
  the JSON's session ids and passes them to the writer, so the Before/After
  correction blocks render real span trees (falls back to dialogue when BQ is
  unconfigured).
- sample_run: seeded the recorded run into per-slice tables
  (agent_events_seed_<slice> -- session ids repeat across slices, so per-slice
  tables keep get_session_trace() unambiguous) and re-rendered the scorecards:
  v0/v1 correction blocks now show span trees incl. the post-correction
  lookup_company_policy re-query on every recovered case. round2 has no
  committed traffic, so its scorecards keep dialogue blocks.
- scripts/sample_quality_report.md refreshed (now span-backed); READMEs updated.

* sample_quality_report.md: use the evolved-skill (V1) scorecard as the showcased sample

* Revert "sample_quality_report.md: use the evolved-skill (V1) scorecard as the showcased sample"

This reverts commit ed01e45.

* BigQuery is the demo's only data path: always log + always score from agent_events

- run_e2e_demo.sh: removed --from-bigquery and the local-scoring branch; every
  run logs sessions to the events table and scoring reads them back via the
  SDK's BigQuery trace path ({run, slice} labels). Banner always shows the
  BQ table.
- run_agent.py: BigQuery logging failure is now fatal with a clear cause
  (scoring depends on the events table); docstring/comments reframed -- the
  conversations JSON is the committed diffable artifact, BigQuery is the path.
- setup.sh: enables BigQuery API alongside Vertex AI; removed the
  'no BigQuery required' claim.
- READMEs (lab + sample_run): local-JSON framing removed everywhere; BigQuery
  described as the data path, prerequisites updated with BQ permissions.
  (scripts/README's --conversations-file docs stay: that's the generic SDK
  scorer feature, separate from this lab.)

* prevalence summary: explain the STRONG/moderate/weak consensus flag

Readers misread STRONG as tied to the percentage (4/48 STRONG next to
42/48 STRONG looks inconsistent). The label is an absolute consensus
threshold: >=3 independent analysts converging on the same root cause.
Append a one-line legend to the summary output, update the committed
sample artifacts and VERIFICATION.md to match.

* prevalence: add VERY STRONG tier for majority consensus

STRONG lumped 42/48 and 4/48 together. Split the top tier: VERY STRONG
= >=3 analysts converged AND a majority of all patches; STRONG stays
>=3. Update the legend, sample artifacts, and VERIFICATION.md; add a
boundary test for the new tier.

* lab README + VERIFICATION: fold in blog-only content

README: evolution pipeline diagram and design choices, integration
conventions (session_id prefixes, freeform tools field, fixed taxonomy),
red-flag checklist, and a Taking-it-to-production section (input caveats,
multi-tool scaling, production shape, known limitation).
VERIFICATION: per-tool call split in the results table, in-scope
saturation note.

* README: drop the source-reading quip

* fix trace merging across scoring passes on the BigQuery path

Three bugs surfaced by an end-to-end run of the skill evolution lab
where the same session_ids repeat across scoring passes (v0_test /
v1_test) in one agent_events table:

1. Trace queries selected sessions with the label filter but fetched
   every row for those sessions unfiltered, merging scoring passes into
   one trace (duplicated user turns, phantom multi-turn sessions, broken
   single-turn/corrections slicing). TraceFilter.row_scope_where() now
   applies label/experiment conditions to the row scan in
   _LIST_TRACES_QUERY, and quality_report threads custom_labels into
   the resolve fetch.
2. run_agent's event capture missed the final LLM_RESPONSE when
   get_history() omits the final model text part (seen with thinking
   models) -- the judge then scored an answerless conversation. The
   final reply is now backfilled from the captured conversation.
3. Golden matching on the BigQuery path keyed off the LAST user message,
   so correction sessions matched their pushback text and never found
   their golden pair (corrections slice stuck at 0). Matching now uses
   the first user message, consistent with the conversations-file path.

Verified: full e2e run on the BigQuery path -- corrections 0/15 -> 15/15,
parrots 12 -> 0, single-turn slicing restored; 221 unit tests pass.

* README: link the published Medium post, fix the post title

* ground the BigQuery-path judge with per-session golden expected answers

Addresses review P1 #1: the server-side AI.GENERATE judge never received
the matched golden expected answer, so matched_meaningful_rate -- the
promotion gate's input -- was not expected-answer-grounded and a fluent
wrong answer could pass.

The injection now works on every execution mode:
- build_ai_generate_query() gains a session-context mode: LEFT JOIN
  UNNEST(@session_contexts) (ARRAY<STRUCT<session_id, context>>) splices
  each session's expected answer between the shared rubric and its
  transcript.
- evaluate_categorical(per_session_context=...) threads the map through
  AI.GENERATE, the per-session NULL-retry, and the API fallback (which
  already supported it); the AI.CLASSIFY shortcut is skipped when
  context is present since CLASSIFY cannot carry it.
- run_evaluation() now fetches traces and matches golden Q&A BEFORE
  evaluation and passes the matched expected answers to the judge --
  same grounding as the conversations-file path. The 'server-side judge
  cannot take per-session expected answers' warning is gone.

Verified with a full e2e run on the BigQuery path: judge justifications
cite the injected golden answers; corrections 0/15 -> 15/15, parrots
14 -> 0; 475 unit tests pass incl. new SQL-builder and client tests.

* Gate over the exact expected session set (review P1 #2)

A worker exception used to shrink the denominator: error=True records are
skipped by _write_bigquery, never reach the scored report, and the gate
compared whatever survived -- so a flaky candidate could improve
matched_meaningful_rate by timing out on hard cases.

- compare_runs.py --questions <file> (repeatable): the question files define
  the exact denominator. Sessions missing from a report become failing
  placeholders in their slice (single-turn / corr_ / oos_), stray sessions
  outside the expected set are excluded, and the RESULT reports the missing
  count when nonzero.
- run_e2e_demo.sh: both compare/gate calls (V0->V1 and V1->V2) pass the
  held-out question files.
- tests/test_compare_runs.py: exact-set semantics incl. the survivor-bias
  scenario (dropping a hard case lowers the rate, never raises it).

Verified: committed sample_run reproduces identically (all sessions present,
denominators unchanged); doctored report with one dropped session scores
77/80 with 'missing=1' reported instead of 77/79.

* Fix test_sdk_client fallback stubs for the per_session_context kwarg

da52c54 added per_session_context to the API-fallback call path
(classify_sessions_via_api); the two fake_api stubs still had the old
3-arg signature and raised TypeError on every Python version in CI.
Stubs now accept **kwargs. Full test_sdk_client suite: 67 passed.

* Fix compare_runs module collision in tests

Two examples ship a compare_runs.py (skill_evolution_lab and
self_evolving_agent_demo); tests importing both under the bare module name
collided via sys.modules depending on test order. test_compare_runs.py now
loads the skill-lab module by explicit file path under a unique name.
Full suite: 3375 passed, 31 skipped.

* Keep PR example-scoped: withdraw all SDK-core (src/) changes in favor of GH issues

Per project decision, this PR changes only scripts/ and examples/; SDK-core
changes need their own review by the SDK owners. Withdrawn and filed instead:

- da52c54 core part (client.py per_session_context threading into the
  server-side judge) -> issue #358, with the full design as the suggested fix.
  scripts/quality_report.py adapted: the BigQuery path no longer passes
  per_session_context; the pre-existing limitation is documented inline and
  warned at runtime, citing #358. The conversations-file path keeps golden
  grounding (upstream classify_sessions_via_api already supports it).
- 94ff0e7 core part (TraceFilter.row_scope_where + _LIST_TRACES_QUERY label
  scoping) and the composite-identity design from review P1 #3 -> issue #359.
  quality_report.py documents the trace-mixing limitation inline, citing #359.
- Core tests reverted with the code (test_client_labels, test_sdk_trace,
  test_categorical_evaluator, test_sdk_client fake_api stubs -- the old
  3-arg signature is correct again against upstream core).

src/ is now byte-identical to upstream/main. Remaining tests/ delta is
example-side only (test_compare_runs.py, test_skill_evolution.py).
Full suite: 3368 passed, 31 skipped.

* render-json runs offline and preserves provenance (review P2 #4)

- BigQuery configuration is now OPTIONAL for --render-json: the render branch
  dispatches before _load_config(), soft-loading it -- unconfigured envs render
  purely from the JSON (verified under env -i: no config, no queries, dialogue
  fallback blocks intact).
- Trace fetch runs only when the env is explicitly configured (never on bare
  session ids against an unconfigured default), and records its source table
  in Execution Details (traces_source).
- The ORIGINAL scoring run's provenance (project, dataset, eval model,
  elapsed) is carried from the JSON's details into the rendered report,
  plus rendered_from -- provenance is preserved instead of dropped.

* Plugin-equivalent demo telemetry (review P2 #5)

The logged event rows were synthetic in every dimension the reviewer listed;
each is now real or honestly labeled:

- Real timestamps: run_agent measures each turn's (start, end) wall-clock and
  places events inside that window -- USER at turn start, LLM_RESPONSE at turn
  end, tool events interpolated. (1ms spacing remains only as fallback for
  records without measured windows, i.e. seeded legacy traffic.)
- Real latency: LLM_RESPONSE rows carry {total_ms: <measured turn duration>}.
- Invocation identity: one invocation_id per user turn (shared by that turn's
  events), matching plugin semantics -- previously a fresh uuid per event.
- Trace identity: one unique trace_id per session per run -- previously the
  reusable question id.
- Parent spans: the turn's USER_MESSAGE span is the turn root; the turn's
  TOOL_*/LLM_RESPONSE events nest under it.
- Seeded reconstructions are labeled: scorecard span trees for sessions whose
  rows carry custom_tags.seeded now print 'Spans reconstructed from the
  recorded conversation (seeded from <file>)' -- reconstructed telemetry can
  never be mistaken for live capture (addresses the placement-heuristic
  thread as well).

Verified live (2-question smoke run, scratch table): 1-turn session = 1
invocation / 1 trace / child span + measured 1705ms; 2-turn session = 2
invocations / 1 trace / 2 latencies. Seeder re-verified end-to-end; the
reconstructed label renders in all 5 correction blocks.

* Bound scoring scans and batch the trace fetch (review P2 #6)

- run_e2e_demo.sh score() passes --time-period 24h, so each scoring pass
  prunes to recent partitions instead of scanning the table's full history
  (labels select the logical rows; the timestamp bound prunes partitions --
  the events table is day-partitioned on timestamp).
- _fetch_session_traces now issues ONE list_traces query for the whole
  session batch instead of one get_session_trace query per session (the N+1
  pattern flagged for rendering). Verified live: 80 traces fetched via a
  single query, rendered output unchanged.

* Run autoformat (missed by pre-commit hook on the #6 commit)

* Idempotent seeding + collision-safe run labels (review P2 #7)

- seed_bigquery now checks for rows already seeded from the same traffic file
  (custom_tags.seeded = <basename>) and skips with a clear message -- the
  documented command can be re-run without ever duplicating spans. Re-seeding
  requires a fresh TABLE_ID or deleting the tagged rows (explicit choice, no
  silent appends). Verified live: second seed of the same file skipped, row
  count unchanged (218).
- RUN_LABEL gains PID + RANDOM, so runs started within the same second (e.g.
  a parallel sweep) can no longer share a label and cross-select sessions.

* Backfill the final reply against the final turn only (review P2 #8)

The final-response backfill searched for identical text ANYWHERE in history,
so an agent that repeated the same answer before and after a correction (with
get_history dropping only the last text part) lost its actual final turn --
the judge then scored a conversation whose trace ends mid-correction.

The check is now scoped to the final turn's events: an identical earlier
answer no longer suppresses the backfill. Verified with the exact scenario:
same text in turn 0, final turn's reply missing from history -> backfilled
into the final turn.

* First-run scorecards include the execution-span trees (review P2 #9)

score() now passes --trajectory-samples 500, so the markdown scorecard
written during scoring carries the Before/After span trees the README and
blog promise -- previously they appeared only after a separate --render-json
pass. Cost is one batched list_traces query per scoring pass (see P2 #6).

Verified live against a real scored run: correction blocks render nested
span trees with measured latencies (LLM_RESPONSE [1.6s] under its turn's
USER_MESSAGE_RECEIVED root) straight from the first scoring pass.

* Never leak workstation paths into generated markdown (review P3 #10)

- The report header reproduces the invocation with absolute path arguments
  reduced to basenames (previously sys.argv verbatim, leaking /home/... into
  publishable artifacts).
- The other leak (details.source_json absolute path) was already replaced by
  the basename-only rendered_from in the P2 #4 commit; committed scorecards
  pick both up at the end-of-series regeneration.

Verified: a render invoked with an absolute JSON path emits zero /home/
occurrences; header shows the basename.

* VERY STRONG prevalence requires a strict majority (review P3 #11)

An exact 50/50 split labeled BOTH categories VERY STRONG while the legend
said 'a majority of all patches' -- half is consensus for neither side. The
tier now requires count/total > 0.5 (tie stays STRONG); legend reworded to
'strict majority (more than half)'. Regression test covers the 3/3 tie and
the 4/2 majority.

* Generated scorecards pass git diff --check (review P3 #12)

The markdown writer now strips trailing whitespace per physical line at the
single write point -- conversation text frequently carries trailing spaces
that landed verbatim in committed scorecards (195 whitespace errors across
the committed set). The writer never relies on trailing-double-space GFM
line breaks, so the strip is lossless. Verified: rendered output contains
zero trailing-whitespace lines; committed artifacts pick this up at the
end-of-series regeneration.

* setup.sh IAM comment lists the required BigQuery roles (review P3 #13)

The header claimed roles/aiplatform.user sufficed; BigQuery is the data path
(logging + scoring + traces), so roles/bigquery.dataEditor and
roles/bigquery.jobUser are required too -- matching the lab README's
prerequisites.

* Seeder reconstructs proportional turn windows from recorded latency (review P2 #5 follow-up)

Seeded sessions had no measured turn windows, so their rows fell back to 1ms
spacing with meaningless latency. The seeder now splits each session's
RECORDED total latency_s evenly across its turns (anchored at seed time), so
reconstructed spans carry plausible, proportional timings -- still labeled
reconstructed via custom_tags.seeded and the scorecard note. Verified live:
95 LLM_RESPONSE rows with latency (avg 0.8s), 123 parented child spans.

* Regenerate committed scorecards with all review fixes applied

One regeneration pass now that the series is complete (P2 #4-#9, P3 #10-#13):
- span trees re-seeded with plugin-equivalent telemetry (per-turn invocation
  ids, parent spans, proportional latencies) into per-slice tables
- 'Spans reconstructed from the recorded conversation' label on every seeded
  correction block
- zero absolute workstation paths (P3 #10), zero trailing whitespace --
  git diff --check clean (P3 #12)
- original scoring-run provenance + rendered_from in Execution Details
- round2 scorecards rendered offline (their traffic was never committed, so
  their correction blocks keep the recorded-dialogue form)
The underlying scored JSONs are untouched -- same recorded run, same numbers.

* Hybrid scoring + per-slice event tables, pending SDK #358/#359 (cleanup: #360)

Two disclosed, TODO(#360)-marked workarounds that unblock fresh sample runs
with full data quality:

- score() judges on the conversations file (the only path whose judge
  receives each session's matched golden expected answer), so correctness
  and the promotion gate are answer-key-graded today -- server-side BigQuery
  judging returns when #358 lands. Logging to BigQuery stays always-on, and
  the scorecards' span trees are fetched during scoring
  (--trajectory-samples) from this run's tables.
- Each slice logs to its own table (agent_events_<run>_<slice>): the demo
  reuses session ids across slices and the SDK trace fetch selects by id
  alone, so separate tables make V0/V1 span mixing physically impossible --
  collapses to one shared table when #359 lands.

Banner and README state both workarounds with their issue numbers; issue
#360 is the pickup checklist for reverting them. Verified live: local-judged
scoring produced golden_eval-matched sessions AND span trees from the slice
table in a single pass.

* Refresh sample_run with a hybrid-scoring --rounds 2 recording (flash-lite)

Replace the committed sample_run with a fresh end-to-end
./run_e2e_demo.sh --rounds 2 run on gemini-3.1-flash-lite, recorded on
the hybrid scoring path (golden-grounded judge on the conversations
file pending #358; span trees read from per-slice BigQuery tables
pending #359, see #360 for the cleanup checklist).

- Round 2 is now part of the same run and model: the old round2/
  companion recording (gemini-3.5-flash) is removed and its artifacts
  (v1_evolve_*, v2_*, RESULT_ROUND2.*) live flat in sample_run/.
- Headline: V0 36.2% -> V1 97.5% overall (single-turn 34.5% -> 100%,
  corrections 0/15 -> 15/15 with parroted sub-trajectories 11 -> 0).
- Round 2: 68 successes / 0 failures on the V1 replay, V2 ties V1 on
  every held-out row, and the strict-win gate keeps V1.
- VERIFICATION.md, README.md, and sample_run/README.md updated to the
  new numbers, quotes, and flat layout; scripts/sample_quality_report.md
  regenerated from the new V0 held-out report.

* sample_run/README: align scoring provenance with the hybrid path

BigQuery is the write path and the span-tree read path; judging runs on
the conversations file so the judge receives each session's matched
golden answer (pending #358). Also correct the trace provenance: this
recording logged live telemetry; seeding is only for re-rendering.
Addresses the provenance mismatch flagged in #360.

* skill_registry: mint tokens from ADC before falling back to the gcloud CLI

The client shelled out to 'gcloud auth application-default
print-access-token' for every token, which fails inside Cloud Run and
Agent Engine containers where the gcloud CLI is not installed. Try
google.auth Application Default Credentials first (always present in
those runtimes) and keep the gcloud subprocess as the last resort for
workstations without google-auth configured. SKILL_REGISTRY_TOKEN env
override and the 50-minute cache are unchanged.

* skill_registry: get_latest() reads the newest revision's payload

GetSkill can keep serving an older revision after UpdateSkill calls
(observed live: nine revisions in, GetSkill still returned revision two's
payload). ListSkillRevisions is newest-first and GetSkillRevision returns
the revision payload under 'skill', so get_latest() is the deterministic
read for the last published content, with a GetSkill fallback.

---------

Co-authored-by: Haiyuan Cao <haiyuan@google.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants