Skip to content

feat: add native Grafana dashboard integration (#339) - #373

Merged
haiyuan-eng-google merged 8 commits into
GoogleCloudPlatform:mainfrom
whuang602:main
Aug 4, 2026
Merged

haiyuan-eng-google merged 8 commits into
GoogleCloudPlatform:mainfrom
whuang602:main

Conversation

@whuang602

@whuang602 whuang602 commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Introduces a zero-infrastructure Grafana dashboard alternative to dashboard_v2 for visualizing BigQuery Agent Analytics telemetry. Resolves #339.

Changes included:
- grafana/bqaa-dashboard.json: An interactive, 23-panel (19 visual panels + 4 layout rows) dashboard featuring FinOps tracking, session auditing, latency metrics, and error rates.
- grafana/queries/*.sql: The authoritative SQL queries backing all dashboard panels.
- grafana/README.md: End-to-end setup documentation including Service Account IAM permissions, BigQuery plugin configuration, and public sharing via Snapshots.

Visual:

grafana_overview_wide grafana_llm finops grafana_tools_sessions traces

Verfication Performed and Results:

  • Grafana Cloud
  • Self-Managed Grafana (Docker)
  • Self-Managed Grafana (CLI)
  • Externally-shareable snapshot (Cloud)
  • Externally-shareable dashboard for unauthenticated user (Cloud)
@google-cla

google-cla Bot commented Jul 20, 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.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review: Grafana dashboard alternative (PR #373)

Reviewed the full diff, compared every embedded dashboard query against the canonical grafana/queries/*.sql files, and ran an end-to-end import test in a local Grafana 12.3.0 instance.

E2E validation performed

  1. JSON validity: python3 -m json.tool grafana/bqaa-dashboard.json → valid, schemaVersion 39, 19 panels, 4 rows, 7 template variables.
  2. Query sync check: extracted every panel query and variable query from bqaa-dashboard.json and compared them to grafana/queries/*.sql. All 15 panel queries match their source files byte-for-byte (after whitespace normalization). The variable queries are dashboard-specific and not expected to live in queries/.
  3. Local Grafana import:
    • Installed grafana-bigquery-datasource v3.2.0 via grafana cli.
    • Started Grafana 12.3.0 on localhost:3131 with a clean temp data dir and a provisioned dummy BigQuery data source.
    • Imported grafana/bqaa-dashboard.json via /api/dashboards/db.
    • Result: import succeeded (uid: bqaa-dashboard, version: 1), dashboard loads with 19 panels across the 4 documented rows, all 7 template variables present, and the BigQuery data source recognized.
    • No import errors or schema warnings in the server log.
    • (Real query execution against BigQuery was not tested because no live project/credentials were available.)

What looks good

  • The dashboard is a clean, lightweight alternative to dashboard_v2; the "parallel option" framing in the README is correct.
  • SQL follows the SDK's view conventions: uses typed ${view_prefix}*_responses/${view_prefix}*_completions views wherever possible, falls back to the raw table only for session rollups and trace detail.
  • Casing-safe UPPER(status) = 'ERROR' predicate is used consistently, matching the documented disagreement between ERROR_SQL_PREDICATE and seed_events.py.
  • Missing telemetry degrades safely: token sums IFNULL(..., 0), latency aggregates stay NULL so charts show gaps rather than fake zeros.
  • ${session_id:sqlstring} and ${agent:sqlstring} template syntax is correct for the BigQuery data source and prevents injection.
  • README covers Grafana Cloud, Docker, and bare-metal paths; warns against committing service-account keys; explains public Snapshot sharing correctly.
  • datasource.example.yaml only contains placeholders, with the private key in secureJsonData.

Actionable feedback

1. Add a CI check to keep bqaa-dashboard.json in sync with queries/*.sql (recommended)

grafana/queries/README.md says the .sql files are the source of truth and the JSON embeds copies, but there is nothing enforcing this. Over time the two will drift. A small script in .github/workflows/ or scripts/ that extracts the panel queries from bqaa-dashboard.json and diffs them against grafana/queries/ would prevent silent divergence.

2. overview_totals.sql does a second full scan of llm_responses

The avg_llm_latency_ms subquery:

SELECT AVG(r.total_ms)
FROM `${project}.${dataset}.${view_prefix}llm_responses` AS r
WHERE $__timeFilter(r.timestamp)
  AND r.agent IN (${agent:sqlstring})

runs independently of the outer agent_events scan. For large datasets this is expensive and the dashboard already has a dedicated latency panel. Consider moving the stat to its own query/panel, or document that the Overview row runs an extra scan.

3. Agent variable query scans the full table without a time filter

SELECT DISTINCT agent
FROM `${project}.${dataset}.${table}`
WHERE agent IS NOT NULL
ORDER BY agent

On a high-volume table this can be slow/costly. Consider limiting it to the dashboard time range with $__timeFilter(timestamp), accepting that newly inactive agents may disappear from the filter when the time window is narrow.

4. tool_errors.sql UNION ALL may double-count error completions

It unions the dedicated TOOL_ERROR view with TOOL_COMPLETED WHERE UPPER(status) = 'ERROR'. If a single tool failure emits both a TOOL_ERROR and an error-status TOOL_COMPLETED, the same logical error appears twice. That may be intentional (separate telemetry paths), but worth a comment if so.

5. Cost panel rates are US-market placeholders only

estimated_cost.sql hard-codes $1.25 / $5.00 per 1M tokens. The README and query comments note this, but the dashboard UI text "Estimated Cost" could be clearer that it is a rough projection, not invoicing-grade. Consider appending "(placeholder rates)" to the panel title or adding a text panel with the caveat.

6. Minor README wording

  • Step 0 says "with the options of leveraging a specialized account and the default" — the "and the default" wording is unclear. Recommend: "using either a dedicated service account or Application Default Credentials (if Grafana runs in GCP)."
  • The Docker command mounts datasource.yaml to /etc/grafana/provisioning/datasources/datasource.yaml, but the file name in the repo is datasource.example.yaml. Mention copying/renaming explicitly.

Nit

  • The panel title in JSON is "Tool invocations" while the queries README maps it as "Tool invocations by tool". Align the two.

Verdict

Approved with minor feedback. The dashboard imports cleanly, the queries match their canonical files, the documentation is complete, and the security guidance is correct. The only item I'd actually block on is adding the sync CI check (or at least a script), because the "source of truth in SQL, copy in JSON" design is a drift magnet. The rest can be addressed in follow-ups.

Introduces a zero-infrastructure Grafana dashboard alternative to dashboard_v2 for visualizing BigQuery Agent Analytics telemetry.

    Changes included:
    - grafana/bqaa-dashboard.json: An interactive, 19-panel dashboard featuring
      FinOps tracking, session auditing, latency metrics, and error rates.
    - grafana/queries/*.sql: The authoritative SQL queries backing all dashboard panels.
    - grafana/README.md: End-to-end setup documentation including Service Account
      IAM permissions, BigQuery plugin configuration, and public sharing via Snapshots.

    Resolves #339
… UI layout

Addressed all PR review feedback and restructured the Grafana dashboard for improved backend efficiency and frontend UI responsiveness.

    Architectural Improvements:
    - Execution Optimization: Eliminated 3 redundant BigQuery executions by configuring the 'Events', 'Error rate', and 'Avg LLM latency' panels to read from the 'Sessions'
  panel via the Dashboard data source.
    - Dynamic UI Redesign: Shrunk the 'Estimated cost' panel height from 8 to 4 units to prevent massive text auto-scaling, and stacked a new 'Total tokens' stat panel in the
  remaining space. The new panel also leverages the Dashboard data source to reuse the cost panel's telemetry without incurring additional BigQuery scan costs.
    - FinOps Optimization: Added $__timeFilter(timestamp) to trace_detail.sql to ensure BigQuery prunes historical partitions rather than executing a full table scan across
  the entire raw event history.

    CI & Synchronization:
    - Created a robust check_grafana_queries_sync.py python script and GitHub Actions workflow to strictly enforce synchronization between the grafana/queries/*.sql canonical
  files and the embedded rawSql inside bqaa-dashboard.json.
    - Implemented a dynamic set-subtraction check that breaks the CI pipeline if any unmapped SQL files are detected in the queries directory.
    - Implemented a reverse-mapping check that breaks the CI pipeline if any rawSql is dropped directly into the JSON dashboard without a corresponding .sql file and
  PANEL_QUERIES mapping.
    - Implemented an automatic unified diff engine that renders line-by-line drift analysis directly into the CI logs for effortless debugging.

    Documentation & Safety:
    - Documented the explicit mapping CI architecture and the developer workflow for adding new queries in grafana/queries/README.md.
    - Documented the intentional extra llm_responses scan in overview_totals.sql and the UNION ALL double-counting behavior in tool_errors.sql.
    - Fixed the Agent template variable query to properly respect $__timeFilter(timestamp) and configured the 'All' value to prevent BigQuery syntax errors.
    - Added grafana/datasource.yaml to .gitignore to prevent secret leakage.
    - Renamed panels to clarify metric intent: 'Tool invocations by tool' and 'Estimated cost (placeholder rates)'.
- Pinned actions/checkout and actions/setup-python to specific commit SHAs in
  grafana-sync-check.yml to satisfy the zizmor blanket policy for unpinned-uses.
    - Ran bash autoformat.sh to ensure code formatting consistency.
    - Addressed outstanding workflow check errors.

@caohy1988 caohy1988 left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Fresh review of 056e5df.

Requesting changes: 9 findings (7 P1, 2 P2).

Scope check — requirements missing (P1, confidence 10/10): the PR body says Resolves #339, so merging it will close the tracker, but the issue's explicit acceptance contract is not complete. The current diff does not ship a variable-free bqaa-public-demo.json or a recorded, reproducible P0 public-sharing spike/fallback; it also omits the requested event_type/user_id filters and the session-table drill-down link. Either complete the remaining acceptance items here, or change Resolves #339 to Partially addresses #339 and open/link a follow-up that owns the remaining deliverables. The public-sharing path must be resolved before this can accurately close #339.

Validation performed on this exact head:

  • Read all 19 changed files and compared the dashboard wiring with the SDK schema, typed views, seed-event behavior, and canonical error semantics.
  • python3 scripts/check_grafana_queries_sync.py passes; dashboard and provisioning YAML parse.
  • pyink and isort pass for the new Python checker.
  • Full repository suite: 3,739 passed, 36 skipped.
  • git diff --check finds only four trailing-space lines in grafana/README.md.

The detailed correctness, security, setup, and CI findings are attached inline.

branches: [main]

jobs:
grafana-query-sync:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] (confidence: 10/10) This workflow inherits the default GITHUB_TOKEN permissions, and the repository's mandatory zizmor check is already failing here with excessive-permissions. Add an explicit least-privilege block such as top-level permissions:\n contents: read. This is not theoretical: the current zizmor-output job is red.

Comment thread grafana/README.md Outdated

1. In the Google Cloud Console, go to **IAM & Admin → Service Accounts**.
2. Click **Create Service Account** (e.g., name it `grafana-bqaa-viewer`).
3. Grant it the following two roles on your project:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] (confidence: 10/10) Granting both roles on the project gives the Grafana credential read access to every BigQuery dataset in that project. #339's least-privilege contract requires roles/bigquery.jobUser on the query project but roles/bigquery.dataViewer only on the BQAA dataset (or the specific table/views). Please split the scopes in these steps and the YAML guidance. If the plugin's project picker is required, document resourcemanager.projects.get separately instead of broadening data access.

Comment thread grafana/README.md Outdated

## 4. Sharing Publicly (Snapshots)

Because BigQuery is an enterprise data source that requires underlying authentication, Grafana Cloud Free does **not** allow you to share live, interactive BigQuery dashboards publicly.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] (confidence: 10/10) The advertised Grafana Cloud Free public path is not established by this statement. Grafana currently lists BigQuery as unconfirmed, not unsupported, for externally shared dashboards; its Cloud docs also say publishing to snapshots.raintank.io is disabled by default. #339 explicitly requires a P0 incognito public-link spike. Run and record that test on Cloud Free, then document the actually available fallback (verified local snapshot, or screenshot/export if external snapshots are unavailable). References: external sharing and snapshot behavior.

Comment thread grafana/README.md Outdated

Because BigQuery is an enterprise data source that requires underlying authentication, Grafana Cloud Free does **not** allow you to share live, interactive BigQuery dashboards publicly.

If you want to share your dashboard with external stakeholders who do not have a Grafana account, you must use the **Snapshot** feature:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] (confidence: 10/10) This can publish real telemetry to anyone with the URL. A snapshot strips queries, but preserves visible values; this dashboard visibly contains session/invocation/span IDs and error_message. The setup flow currently permits real traffic and then tells the operator to publish it. Require a dedicated bqaa seed-events/redacted demo dataset, inspection of every visible panel, a short expiry, and an incognito verification before sharing. Also replace “static image”: a snapshot is a public point-in-time dashboard containing the visible data, not an image.

Comment thread grafana/datasource.example.yaml Outdated
processingLocation: US # match your dataset's location, e.g. US, EU
secureJsonData:
# Paste ONLY the private_key field from the service-account JSON key
# (keep the \n escapes exactly as they appear in the JSON file).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] (confidence: 10/10) Keeping the JSON field's literal \\n escape sequences inside a YAML | block produces a key containing backslashes instead of PEM line breaks, so JWT authentication fails. Tell users to decode/copy the key as an actual multiline PEM (as the block below demonstrates), or mount the PEM and use privateKeyPath. Grafana's provisioning docs explicitly require preserved newlines for secureJsonData.privateKey.

Comment thread grafana/queries/overview_totals.sql Outdated
COUNT(DISTINCT e.session_id) AS sessions,
COUNT(*) AS events,
SAFE_DIVIDE(
COUNTIF(UPPER(e.status) = 'ERROR'),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] (confidence: 10/10) This implements only one branch of the SDK's canonical error definition, so the headline error rate silently misses _ERROR events and rows with error_message when status is null/non-error. Preserve the casing fix, but count ENDS_WITH(e.event_type, '_ERROR') OR e.error_message IS NOT NULL OR UPPER(e.status) = 'ERROR'. Apply the same three-branch predicate to errors_over_time.sql and recent_sessions.sql, their dashboard copies/descriptions, and add a regression that covers each branch. The source of truth is event_semantics.py:66-70.

Comment thread grafana/queries/tool_usage.sql Outdated
SELECT
tool_name,
COUNT(*) AS invocations
FROM `${project}.${dataset}.${view_prefix}tool_completions`

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] (confidence: 10/10) A panel titled “Tool invocations” cannot count only tool_completions: failed calls are omitted. The shipped seed path proves the gap (TOOL_STARTING is followed by TOOL_ERROR, with no TOOL_COMPLETED). Count ${view_prefix}tool_starts for invocation volume, or explicitly union/deduplicate terminal rows if the intended metric is terminal attempts. Update the embedded JSON query and source description too.

Comment thread grafana/queries/estimated_cost.sql Outdated
-- labeled "Estimated Cost" for this reason; token counts are the
-- primary FinOps signal.
SELECT
SUM(IFNULL(usage_prompt_tokens, 0)) / 1e6 * 1.25 -- $ / 1M prompt tokens

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] (confidence: 10/10) IFNULL inside SUM handles null fields, but SUM over zero rows still returns NULL; a time range with no LLM responses makes both Estimated cost and Total tokens show N/A despite the documented zero-degradation contract. Wrap each aggregate instead: IFNULL(SUM(usage_prompt_tokens), 0), likewise for completion and total tokens, then sync the embedded query and add the empty-range case to coverage.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Full review — 16 findings (2 blocking, 6 P2, 8 P3) + verification notes

Reviewed at head 056e5df (up to date with main): all 19 files read in full, embedded dashboard SQL diffed against the canonical files, column references validated against views.py / the event schema, the sync script executed locally (passes), README CLI commands verified against pyproject.toml + cli.py, action SHAs checked, and the failing CI runs diagnosed. Two additional independent adversarial/security passes were run; where they converged the finding says so.

Blocking

  1. zizmor-output is red because the new workflow has no permissions: block — inline comment with the two-line fix. This is the actual cause of the CI failure.
  2. cla/google is red — @whuang602 needs to sign the Google CLA (https://cla.developers.google.com/) before this can merge; no code change involved.

Main themes in the inline comments

  • Error semantics: UPPER(status)='ERROR' fixes the casing mismatch (verified real) but drops two legs of the SDK's canonical ERROR_SQL_PREDICATE — error panels/stats can undercount. One superset predicate fixes it everywhere.
  • First-run + filter correctness: empty agent options make All interpolate to IN () (all panels error on a fresh install); NULL-agent rows are silently excluded from all panels including the totals.
  • Security hardening: viewer-editable textbox identifier variables allow querying anything the SA can read (two review passes converged on this) — pair constant/allowlisted variables with a dataset-scoped IAM grant; and the Snapshots section needs a data-sensitivity warning since telemetry contains prompts/tool args/errors.
  • Sync-checker robustness: no recursion into collapsed-row panels, and template-variable SQL (with its duplicated definition copy) is entirely outside the check.

Verified clean (so you don't re-litigate): embedded rawSql byte-identical to all 12 canonical files; all view/column references exist (usage_*_tokens, total_ms, ttft_ms, model_version, tool_name); $__timeGroup(timestamp, $__interval) works with the BigQuery plugin's macro parser; UNION ALL + trailing ORDER BY/LIMIT, SAFE_DIVIDE, APPROX_QUANTILES all-NULL behavior are all correct; stat-panel field regexes match real column names; Dashboard-datasource reuse wiring (3/4/5→2, 20→12) is consistent between JSON and script; action SHAs match their version comments; the README's bqaa seed-events / bq-agent-sdk views create-all commands and flags are real; the pull_request-triggered workflow is safe against fork-PR content (no secrets, read token, script only parses repo-relative JSON).

Nice work overall — the queries-as-source-of-truth + CI sync check design is exactly right, the :sqlstring escaping on value variables shows care, and the panel-reuse via the Dashboard datasource keeps BigQuery load down. The findings above are about making the numbers trustworthy (error semantics, NULL/empty edge cases) and the sharing/IAM story safe by default.

(Submitted as COMMENT; the P1 workflow fix + CLA are the two things that must land before merge.)

"definition": "SELECT DISTINCT agent FROM `${project}.${dataset}.${table}` WHERE agent IS NOT NULL AND $__timeFilter(timestamp) ORDER BY agent",
"refresh": 2,
"multi": true,
"includeAll": true,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] (confidence: 7/10) First-run breakage: empty agent list makes every panel a SQL syntax error.

The agent variable is "multi": true, "includeAll": true with no allValue, and its options come from a time-filtered query (SELECT DISTINCT agent ... AND $__timeFilter(timestamp)). On a fresh install with an empty agent_events table — or simply a time range with no data — the options list is empty, Grafana expands All to nothing, and every panel's AND agent IN (${agent:sqlstring}) interpolates to AND agent IN (), which is invalid BigQuery. All 12 panels then show query errors instead of "No data" — precisely during the first-run walkthrough the README describes (before bqaa seed-events is run).

Fix options (either works; both need the matching change in the 12 .sql files + embedded copies):

  • give the variable a custom allValue (e.g. .*) and switch the predicate to REGEXP_CONTAINS(agent, '^${agent:regex}$')-style filtering, or
  • guard the predicate: AND ('${agent:raw}' = '' OR agent IN (${agent:sqlstring})).
Comment thread grafana/bqaa-dashboard.json Outdated
"skipUrlSync": false
},
{
"type": "textbox",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] (confidence: 8/10, two independent review passes converged on this) Free-text identifier variables are a SQL-injection / data-exfiltration surface for dashboard viewers.

project, dataset, table, and view_prefix are textbox variables interpolated raw into identifier position in all 12 queries (FROM \${project}.${dataset}.${table}`). Unlike ${session_id:sqlstring} (nicely escaped), identifiers cannot be sqlstring-escaped — and Grafana lets any dashboard **viewer** change textbox variables, including via URL params (?var-table=..., skipUrlSync: false`). A viewer can therefore:

  • repoint var-dataset/var-table at any dataset the service account can read and browse it through the panels, or
  • include a backtick in the value to break out of the quoted identifier and run arbitrary SQL as the service account.

Combined with the README's project-level BigQuery Data Viewer grant, the blast radius is every dataset in the project.

Fix: for shared deployments, convert these four to constant/hidden variables (or query/custom variables with an allowlist of exact values) so viewers can't supply arbitrary identifiers, and add a README warning for anyone keeping them editable. Pairs with scoping the SA grant to the dataset (see README comment).

Comment thread grafana/bqaa-dashboard.json Outdated
"refId": "tempvar",
"editorMode": "code",
"rawQuery": true,
"rawSql": "SELECT session_id FROM `${project}.${dataset}.${table}` WHERE $__timeFilter(timestamp) AND agent IN (${agent:sqlstring}) GROUP BY session_id ORDER BY MAX(timestamp) DESC LIMIT 200",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] (confidence: 7/10) The session_id variable query lacks session_id IS NOT NULL (the column is NULLABLE in the event schema, and the sibling agent variable does filter agent IS NOT NULL). A NULL group yields a blank/null dropdown option; selecting it interpolates WHERE session_id = ${session_id:sqlstring} into an equality that can never match a NULL row — a dead option rendering an empty Trace detail panel. Add AND session_id IS NOT NULL.

{
"type": "barchart",
"title": "Tokens by model",
"id": 11,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] (confidence: 6/10) Panel 11 plots every numeric column returned by tokens_by_model.sql, which includes COUNT(*) AS responses (order 10^2) on the same axis as token sums (10^5–10^7) — an invisible bar plus a misleading legend entry — and total_tokens visually double-counts prompt+completion within each group. Consider an excludeByName transformation (or custom.hideFrom override) for responses and total_tokens, keeping them in the canonical file for ad-hoc use.

Comment thread grafana/queries/events_over_time.sql Outdated
COUNT(*) AS events
FROM `${project}.${dataset}.${table}`
WHERE $__timeFilter(timestamp)
AND agent IN (${agent:sqlstring})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] (confidence: 8/10) NULL-agent rows are silently excluded from every panel — including the Overview totals.

agent is NULLABLE in the event schema (("agent", "STRING", "NULLABLE") in seed_events.py), and the variable's option query filters WHERE agent IS NOT NULL — so with All selected, AND agent IN (${agent:sqlstring}) still drops any row written without an agent, on all 12 panels. The Sessions/Events/Error-rate totals will then disagree with a plain COUNT(*) over agent_events, which is exactly the kind of quiet mismatch a totals row shouldn't have.

Fix: make All a true no-op — AND (agent IN (${agent:sqlstring}) OR agent IS NULL) — or document the exclusion explicitly in queries/README.md if NULL-agent rows are considered out of scope. (Combines naturally with whichever fix you pick for the empty-list IN () issue flagged on the dashboard JSON.)

Comment thread grafana/queries/recent_sessions.sql Outdated
session_id,
MIN(timestamp) AS started_at,
MAX(timestamp) AS last_event_at,
TIMESTAMP_DIFF(MAX(timestamp), MIN(timestamp), SECOND) AS duration_s,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] (confidence: 6/10) Session rollups are clipped to the dashboard window: TIMESTAMP_DIFF(MAX(timestamp), MIN(timestamp), SECOND) over only the in-window rows reports a shortened duration_s, a false started_at, and undercounted events/errors for any session straddling the window boundary. If full-session aggregation is too costly, consider renaming to duration_in_window_s (and friends) so the semantics are honest — cheap and unambiguous.

Comment thread grafana/queries/trace_detail.sql Outdated
CAST(JSON_VALUE(latency_ms, '$.total_ms') AS INT64) AS total_ms,
error_message
FROM `${project}.${dataset}.${table}`
WHERE session_id = ${session_id:sqlstring}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] (confidence: 6/10) AND $__timeFilter(timestamp) quietly truncates the timeline for sessions that straddle the window boundary, while the header comment promises "every event type appears in one timeline." Since the query is already keyed by session_id with LIMIT 500, consider dropping the time filter here (documenting the wider scan tradeoff) or noting the truncation in the panel description.

Comment thread scripts/check_grafana_queries_sync.py Outdated
panels[panel_id] = panel

for panel_id, panel in panels.items():
if panel.get("type") == "row":

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] (confidence: 9/10) The panel walk doesn't recurse into row panels — one UI click defeats the drift check.

for panel in dashboard["panels"] iterates only the top level, and if panel.get("type") == "row": continue skips rows without descending into row["panels"]. Grafana relocates child panels under the row object the moment a row is collapsed and the dashboard re-exported (all four rows are currently "collapsed": false, so this is one click away). Consequences: (a) a new BigQuery panel added inside a collapsed row becomes invisible to the reverse-mapping check, so its rawSql can drift forever; (b) existing mapped panels nested under a collapsed row produce spurious missing panel id N failures with no actual drift.

Fix: flatten before checking — extend the iteration with panel.get("panels", []) for type == "row" entries, then run all checks over the flattened set.

# source and are checked separately below. Likewise, panel 12 embeds the cost
# query and panel 20 (Total tokens) reuses its result, so it adds no BigQuery
# load.
PANEL_QUERIES = {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] (confidence: 9/10) Two template variables embed real BigQuery SQL that this check never sees: agent and session_id each carry a query.rawSql plus a duplicate in the sibling definition key (templating.list in the dashboard JSON). Neither has a canonical .sql file — contradicting queries/README.md's "source of truth" claim — and neither cross-revision drift nor rawSql-vs-definition divergence is detected. Suggest grafana/queries/var_agent.sql + var_session_id.sql, a TEMPLATE_VARIABLE_QUERIES = {name: filename} map here, and an assertion that definition == query.rawSql.

Comment thread .gitignore
.DS_Store
.DS_Store?
._*
grafana/datasource.yaml

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] (confidence: 6/10) This covers the provisioning copy, but README Step 0 has users download a full service-account JSON key, and nothing ignores that file if they drop it in the repo (a natural spot when mounting it into the Docker container next to datasource.yaml). Consider also ignoring likely key paths (e.g. grafana/*.json with an exception for the dashboard, or **/service-account*.json, *-key.json) and adding a one-line README warning to keep the downloaded key outside the repo tree.

Comment thread grafana/queries/tool_errors.sql Outdated
FROM `${project}.${dataset}.${view_prefix}tool_completions`
WHERE $__timeFilter(timestamp)
AND agent IN (${agent:sqlstring})
AND UPPER(status) = 'ERROR'

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] (confidence: 7/10) Completion of the three-branch error predicate for this file. The predicate finding on overview_totals.sql names errors_over_time/recent_sessions, but this file has the same gap in its second arm: a TOOL_COMPLETED row whose failure is recorded only via error_message (status NULL/ok) is not listed in the Tool errors table. When applying the three-branch fix, extend this arm to AND (error_message IS NOT NULL OR UPPER(status) = 'ERROR') — ENDS_WITH(event_type, '_ERROR') is unnecessary here since the first arm already reads the tool_errors view.

@caohy1988

Copy link
Copy Markdown
Collaborator

Review dedup note — my second review landed minutes after the CHANGES_REQUESTED review and overlapped it on six findings. I've deleted my six duplicate inline comments (workflow permissions: block, three-branch error predicate ×3, dataset-scoped IAM, snapshot data-sensitivity) — the earlier review's versions stand as canonical for those. What remains is one non-overlapping set:

From the CHANGES_REQUESTED review (canonical for): scope check vs #339 acceptance, workflow permissions/zizmor, IAM scoping, public-sharing spike + snapshot privacy, YAML \n PEM breakage in datasource.example.yaml, three-branch error predicate, tool_usage missing failed invocations, SUM-over-zero-rows NULL in estimated_cost.

From my review (10 kept + 1 added, non-overlapping):

  • Empty agent options → All interpolates to IN () — every panel errors on a fresh install (dashboard:157)
  • Viewer-editable textbox identifier variables → arbitrary SQL / dataset browsing as the SA (dashboard:54)
  • NULL-agent rows silently excluded from every panel incl. the Overview totals (events_over_time:8)
  • session_id variable missing IS NOT NULL (dashboard:178)
  • Sync script doesn't recurse into collapsed-row panels (check script:154) and never checks template-variable SQL / definition copies (check script:21)
  • Window-clipped session rollups (recent_sessions:9) and truncated trace timeline (trace_detail:22)
  • Panel 11 plots responses/total_tokens on the token axis (dashboard:712)
  • .gitignore gap for the downloaded SA JSON key (.gitignore:38)
  • tool_errors.sql second arm needs the error_message leg of the predicate fix (tool_errors:28)

One CI observation for the author: the new Grafana query sync check workflow never executed on this PR (it's absent from the checks list — likely pending first-time-contributor workflow approval). I ran scripts/check_grafana_queries_sync.py locally at 056e5df and it passes (12 queries in sync), but it should run in CI here before merge.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Follow-up pass after reviewing all existing threads — the items below are the only ones from my re-review not already covered above.

For the record, I re-verified at 056e5df8: the sync check passes locally (including a negative test that fails loudly with a unified diff), the dashboard JSON is valid (schemaVersion 39), the pinned SHAs match the real actions/checkout@v4 / actions/setup-python@v5 tags, and every SQL column/CLI command referenced by the dashboard and README exists in the SDK source.

PR body nit (not inline-able): the description still says "19-panel dashboard" — after the commit-2 layout change the JSON has 16 content panels + 4 rows (20 entries, including the new Total tokens stat). Please update the body before merge.

Comment thread grafana/README.md Outdated
- A Grafana instance ([Grafana Cloud Free](https://grafana.com/products/cloud/)).
> **Important for new users:** You must install the **Google BigQuery** data source plugin (`grafana-bigquery-datasource`) in Grafana before BigQuery will appear as an available connector.

### 0. Service Account & Auth Setup

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] Heading hierarchy: step 0 is ### 0. nested under ## Prerequisites, while steps 1–4 are top-level ## sections. Promote it to ## 0. so the 0–4 setup sequence reads as one consistent flow.


name: Grafana query sync check

on:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] Consider adding a paths: filter (e.g. grafana/**, scripts/check_grafana_queries_sync.py, and this workflow file) for both push and pull_request. As written, the check runs on every PR even when nothing dashboard-related changed — cheap, but it adds a job to unrelated PRs for no signal.

…dge cases

This commit acts as a comprehensive
  stabilization sweep for the Grafana dashboard architecture, directly addressing the 9 outstanding review findings:

    1. Security & Hardening:
       - Viewer-editable textboxes: Locked down identifier variables to prevent arbitrary SQL browsing by the SA.
       - SQL Injection: Migrated all interpolation to BigQuery ARRAY<STRING> expansion combined with Grafana's :sqlstring formatter.
       - .gitignore: Blocked unintentional SA JSON key commits via grafana/*.json.

    2. First-Run & Null Handling:
       - Empty Agent Options: Replaced the 'IN ()' crash vector on fresh installs with a safe UNNEST(ARRAY) parser and an explicit
  '___ALL___' sentinel.
       - Null-Agent Exclusion: Ensuring NULL-agent rows are no longer silently excluded from the Overview totals when 'All' is selected.
       - Null Sessions: Added IS NOT NULL clauses to session_id variable definitions.

    3. Analytics Accuracy:
       - Window-Clipped Sessions: Renamed session aggregates to '_in_window' and updated trace UI tooltips to honestly reflect time-
  truncated boundaries.
       - Missing Error Predicates: Updated the second arm of tool_errors.sql to explicitly capture 'error_message IS NOT NULL'.
       - Axis Misalignment: Fixed Panel 11 to prevent plotting 'responses' on the 'total_tokens' axis.

    4. Validation Infrastructure:
       - Recursive Sync Checker: Upgraded check_grafana_queries_sync.py to recurse into collapsed-row panels and strictly enforce
  synchronization for both definition and rawSql copies of template variables.
@whuang602

whuang602 commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Initial fixes implemented & workflow failure addressed. Working on addressing rest of requirements and bugs (see bottom)

Snapshot and dashboard links added temporarily to Issue comment.

Updated Visual:
overview
llm finops
tools_sessions traces

Regarding Snapshot Public Demo:

  • While the grafana snapshot does not provide access for live queries, it does expose details that may be sensitive, including the rawSQL, GCP project ID, and BQ dataset name.
  • If we want to proceed with a snapshot for public demo purposes, it may be relevant to create such resource in a centralized instance of grafana as opposed to a personal account

Currently exploring & working on addressing the rest of the issue requirements:

  • Confirm variable-free bqaa-public-demo.json backed by BQ is possible [RESULT: Possible]
  • Reproducible P0 public-sharing spike/fallback is currently implemented in the form of snapshot instructions.
  • event_type / user_id filters
  • session-table drill-down link
  • enforce session filter across the panels, supporting default session selection, multi session, and all sessions.
  • resolve filter dependence side effects for some panels
…ting

    - Add  and  multi-select variables
    - Apply 1000-option caps and custom values to Agent and User ID to protect frontend performance
    - Prevent silent UI resets by dropping the session cascade dependency
    - Ensure empty filter intersections return clean UI states instead of false zeroes
    - Migrate LLM cost rates out of SQL into configurable dashboard constants
    - Expand recent_sessions audit table with token sums, user_id aggregates, and independent session-level LOGICAL_OR filtering
    - Introduce a click-to-pin data link for session trace drill-downs
    - Update README with API prerequisites and cost configuration guide
    - Sync and register all new queries for CI validation
@caohy1988

Copy link
Copy Markdown
Collaborator

Re-review at 846ee8b — approve

Re-reviewed the full PR against every finding from the earlier review rounds, with each resolution verified in the tree (not just the response notes), the sync check and dashboard JSON validated locally, and the full repository suite run on the branch (3,711 passed / 15 skipped; git diff --check clean; the PR is mergeable).

All prior findings verify as fixed — and several resolutions are better than what the review asked for:

  • Scope (P1): the PR body now says Partially addresses feat: add a free public Grafana dashboard for BQAA��#339, so merging no longer closes the tracker with the public-demo JSON and P0 sharing spike outstanding. The requested event_type/user_id filters are shipped as query-driven variables, and the session drill-down exists as a "Pin this session" data link that carries the time range and every other filter along — nicer than the plain link the review asked for.
  • Security/IAM (P1s): the workflow declares least-privilege permissions: contents: read; the README grants jobUser on the project and dataViewer on the BQAA dataset only; the public-sharing section is now an explicitly snapshot-based path with a strong privacy warning ("DO NOT snapshot real production telemetry") and an incognito verification step.
  • Query correctness (P1s/P2s): overview_totals.sql implements the full three-branch canonical error predicate; tool_usage.sql counts TOOL_STARTING so failed calls appear; tool_errors.sql is particularly well done — the TOOL_ERROR view unioned with error-status completions, the disjunctive predicate applied only where it belongs, and the intentional double-record case documented in the header; estimated_cost.sql moved IFNULL outside SUM so empty windows render zeros.
  • Variable hardening (P2s): project/dataset/table/view_prefix are now constant variables (importer-set, not viewer-editable), closing the viewer-facing injection surface; the filter variables interpolate through :sqlstring with the '___ALL___' sentinel — which also quietly fixes the NULL-agent exclusion P3, since the All branch short-circuits before the IN test that NULL could never pass. First-run empty-list breakage is gone.
  • The rest: session_id IS NOT NULL in its variable query; duration_in_window_s renames the clipped rollup honestly; the trace-detail header now explains the DESC-ordering/LIMIT reasoning instead of over-promising; flatten_panels recurses into collapsed rows; the template-variable SQL lives in canonical var_*.sql files covered by the sync check (16 queries in sync); the PEM line-break note, the key-file ignore, and the ## 0. heading are all in place.

One new finding:

  • P3 — grafana/*.json in .gitignore will silently ignore the future public-demo dashboard. The committed bqaa-dashboard.json is unaffected (tracked files bypass ignore rules — verified), and the pattern correctly catches stray credential keys (verified with a probe file). But the very next feat: add a free public Grafana dashboard for BQAA #339 deliverable this PR defers — bqaa-public-demo.json — will be invisible to git add in that directory, and the failure mode is a contributor silently missing a file from their commit. Suggest narrowing the intent: ignore key-shaped names (e.g. grafana/*key*.json, grafana/*credential*.json) or add !grafana/bqaa-*.json beneath the existing pattern.

Verdict: approve. With the honest partial-scope framing, the remaining #339 items (public-demo JSON, the P0 public-sharing spike or its fallback decision) belong to the follow-up, and the one new P3 can ride along with it or land as a one-line fixup here. Thanks for the thorough response to a long review — the filter-sentinel design and the tool-errors union are genuinely good pieces of dashboard SQL.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Fresh exact-head re-review against #339. These are the three actionable findings not already covered by the existing review threads; prior resolved findings are intentionally not repeated.

python-version: "3.12"

- name: Validate dashboard JSON and embedded queries
run: python3 scripts/check_grafana_queries_sync.py

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] (confidence: 10/10) The available live artifact does not validate the current head. The published snapshot was created July 25, before 846ee8b rewrote the dashboard/query behavior on July 28. It still has 200-option caps, a cascading Session query, and hard-coded prices; HEAD has 1000-option caps, an independent Session query, and pricing variables. This workflow only proves JSON/canonical-SQL text synchronization, not Grafana interpolation, BigQuery execution, or rendering—and it is absent from this head's check runs. Please import exact SHA 846ee8b, execute every variable and panel against freshly seeded BigQuery data (including multi-value/contradictory filters and the session drilldown), and attach durable exact-head evidence or a replacement short-lived snapshot before merge.

Comment thread grafana/README.md Outdated
Then create the typed views the dashboard queries:

```bash
bq-agent-sdk views create-all --project-id YOUR_PROJECT --dataset-id YOUR_DATASET

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] (confidence: 10/10) Pass the configured table to view creation. Step 3 explicitly supports changing the dashboard's hidden table constant, but this command omits --table-id; views create-all therefore defaults to agent_events. With a custom table, raw-table panels query the configured table while every LLM/tool panel reads typed views backed by the wrong table (or fails if agent_events is absent). Add --table-id YOUR_TABLE here and state that it must match the dashboard's table constant.

Comment thread grafana/bqaa-dashboard.json Outdated
"value": [
{
"title": "Pin this session",
"url": "?${__url_time_range}&${agent:queryparam}&${user_id:queryparam}&${event_type:queryparam}&var-session_id=${__data.fields.session_id}",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] (confidence: 10/10) Preserve datasource state and URL-encode the clicked session ID. This relative ?… URL replaces the current query string but omits ${datasource:queryparam}, even though datasource is visible and URL-synchronized. It also appends ${__data.fields.session_id} raw, so a legal ID containing &, #, =, or spaces can be truncated or parsed as additional parameters. Carry the datasource query parameter and use Grafana's URL-safe/percent-encoded field-value mechanism for var-session_id; verify with two BigQuery datasources and URL-significant session IDs.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-review at 846ee8b6 against #339 — non-overlap items only

Verified the two new commits resolve every prior thread: canonical three-branch error predicate everywhere, price variables as constant+skipUrlSync, IFNULL(SUM(),0) zero-row handling, event_type/user_id variables with the ___ALL___ allValue pattern (which also fixes the empty-list first-run breakage and the NULL-agent exclusion), session drill-down link, dataset-scoped IAM in the README, snapshot privacy warning, sync CI covering variable queries + collapsed rows, zizmor green, CLA signed. Local gates re-run: JSON valid, check_grafana_queries_sync.py passes (16 queries), zizmor 1.25.2 clean.

Two findings from my pass that are not already on record:

[P2] The P0 spike result is on the wrong tracker. #339's acceptance criteria require the public-sharing spike outcome to be recorded on the issue; #339 currently has zero comments, and the result lives only in this PR comment ("variable-free bqaa-public-demo.json backed by BQ … RESULT: Possible"). One comment on #339 with the outcome and the chosen path closes the criterion.

[P1, new data point on the standing scope item] The CHANGES_REQUESTED scope finding (missing bqaa-public-demo.json) remains open at this head — and the spike outcome strengthens it: the issue sanctioned snapshots/exports as the public-demo fallback only if a variable-free BigQuery panel could not render unauthenticated. The recorded result is that it can. So the snapshot path in README §4 is currently an unsanctioned substitution for a deliverable the spike proved feasible. Either ship bqaa-public-demo.json (with the #339 guardrails: fixed time range, tiny demo dataset, dataset-scoped SA, pause-after-demo) or get explicit maintainer sign-off on #339 for the scope change before Resolves #339 is accurate.

Three smaller non-overlapping items inline.

@@ -0,0 +1,35 @@
-- Panel: Tool errors (Tools row).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] #339 panel 5 asks for top error messages alongside error count/rate and p50/p95. The dashboard has the rate, the time series, and this per-row tool-errors table, but no aggregated error_message ranking (e.g. SELECT error_message, COUNT(*) ... GROUP BY 1 ORDER BY 2 DESC LIMIT 20 over the raw table with the canonical predicate). A small table panel here would complete the issue's panel list.

@@ -0,0 +1,37 @@
-- Panel: Overview stats (Sessions, Events, Error rate, Avg LLM latency).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] #339 panel 1 lists LLM calls as a headline FinOps stat next to sessions/events/tokens. It currently exists only implicitly as the responses column in Tokens by model. A fifth field in this query (COUNTIF(e.event_type = 'LLM_RESPONSE') AS llm_calls, or a count off the llm_responses view) surfaced as a stat panel would close the list — cheap since this query already scans both sources.

Comment thread grafana/README.md Outdated

- **Overview:** sessions, events, error rate, latency, volumes
- **LLM & FinOps:** tokens, latency percentiles, tokens by model, estimated cost
- **Tools & Execution:** invocations, latency, errors

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3, nit] The README calls this row "Tools & Execution" but the dashboard JSON titles it "Tools". Align one with the other so users following the import steps can match what they see.

- Adds 'LLM-call summary', 'Top error messages',
  and 'Events by agent' panels
    - Registers new queries in sync script and README
    - Adds bqaa-public-demo.json optimized for safe, unauthenticated public sharing
@caohy1988

Copy link
Copy Markdown
Collaborator

Fresh full review at head 7a58c9e — approve, with two one-line fixups that should ride in this PR

Re-reviewed the whole PR (not just the delta) with the sync check and dashboard JSON validated locally, an identifier-leak sweep across grafana/, and the new SQL read against the BQAA schema.

The delta commit delivers well

  • The three new queries are exemplary about documenting their own semantics — every exemption and no-data contract is written down and cross-referenced, events_by_agent.sql's NULL-agent handling and alias-grouping are correct, and top_errors.sql's subset scope is honestly stated in the header.
  • recent_sessions.sql's CAST → SAFE_CAST hardening is right.
  • bqaa-public-demo.json is genuinely safe-by-construction for its purpose: zero template variables (no viewer-editable injection surface at all), YOUR_PROJECT_ID.YOUR_DATASET_ID placeholders only, and my leak sweep found no personal projects, emails, or instance URLs anywhere in the PR. The snapshot privacy warning survives intact.
  • Sync check passes (19 queries in sync); no stray files outside grafana/ + the sync script.

Fixups that should land in this PR (both small)

  1. The prior review's P3 is now a fired trap — .gitignore still contains grafana/*.json, and bqaa-public-demo.json evidently had to be force-added past it. The committed files are safe (tracked files bypass ignore), but the next contributor adding a third dashboard JSON hits the same silent-omission failure. The one-line fix from the earlier review still applies: narrow to key-shaped names (grafana/*key*.json, grafana/*credential*.json) or add !grafana/bqaa-*.json.
  2. bqaa-public-demo.json sits outside the sync guard. check_grafana_queries_sync.py covers the main dashboard's 19 queries but not the demo's 18 rawSql panels, which are hand-derived variants of queries/*.sql. That reintroduces exactly the JSON↔SQL drift the script was added to prevent, at 18-query scale. Either extend the script to assert the demo's queries are derivable from the canonical files (even a looser check — same table/filter skeleton, variables stripped), or add a header note in the demo JSON + README stating it is intentionally frozen and NOT covered by the sync check, so drift is at least a documented property rather than a silent one.

Advisory (follow-up material, not blocking)

  1. llm_calls_total.sql counts response rows, not calls. COUNT(*) over adk_llm_responses overcounts on streaming installations (multiple LLM_RESPONSE rows can share one trace_id/span_id), and it diverges from this repo's Looker dashboard, which deliberately counts COUNT(DISTINCT trace_id || span_id) for the same tile concept. The header documents every other design choice — either count distinct spans, or add the streaming caveat to the header so the two dashboards' differing "LLM calls" semantics are on record.

Verdict: approve once items 1–2 land (both are one-liners; item 2's documentation option is also fine). The public-demo dashboard closes the remaining #339 scope this PR had deferred, and the leak-free, variable-free construction is the right way to build it.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Fresh full review at 7a58c9e: requesting changes.

New findings

[P1] The published public demo is currently broken

I cold-loaded the public dashboard twice and waited for network idle:

https://tealcove1904.grafana.net/public-dashboards/99d3e3d27bc244a5aa57831831538352

The shell renders, but every visible panel has Grafana's red Panel status error indicator. The eight loaded query calls for panels 2, 3, 4, 5, 6, 7, 21, and 22 all return HTTP 400. The UI's No matching data / No errors in range text is therefore masking backend query failures, not demonstrating a valid empty-data state.

Because the public demo is part of #339's acceptance evidence, please repair its datasource/query configuration and revalidate all 18 panels with successful backend responses and non-degenerate demo results before merge.

[P1] bqaa-public-demo.json is completely outside the CI drift guard

scripts/check_grafana_queries_sync.py hardcodes only grafana/bqaa-dashboard.json (DASHBOARD_PATH, lines 12–14). It never opens the separately maintained bqaa-public-demo.json, even though that file contains 18 transformed SQL queries plus the public cost/privacy controls.

A future edit can silently reintroduce macros/variables, remove the hard 72-hour predicates, add a Dashboard datasource or trace-detail panel, broaden exposed fields, or drift from the canonical query semantics while CI remains green. Please either generate this file deterministically or add a dedicated validator that asserts at least:

  • templating.list is empty;
  • executable SQL contains no ${...} / $__... macros;
  • every query retains the hard 72-hour predicate;
  • identifier placeholders occur only inside full backticked table/view paths;
  • there is no Dashboard datasource or trace-detail panel;
  • editable is false, the time picker is hidden, and refresh is disabled;
  • the transformed public panels remain mapped to their canonical interactive counterparts.

Previously raised findings still unresolved at this head

[P2] Custom-table setup omits --table-id

grafana/README.md:65 still documents:

bq-agent-sdk views create-all --project-id YOUR_PROJECT --dataset-id YOUR_DATASET

That silently creates views against the default agent_events when the dashboard is configured for a custom source table. Please include --table-id YOUR_TABLE and explain that it must match the dashboard setting.

[P2] The Recent sessions data link loses datasource state and does not encode the session ID

grafana/bqaa-dashboard.json:1533 still builds the link without ${datasource:queryparam} and inserts ${__data.fields.session_id} raw into the query string. A switched datasource is lost, and session IDs containing reserved URL characters can produce a malformed/different filter. Please carry the datasource query parameter and percent-encode the field value.

Verification performed

  • Both dashboard JSON files parse.
  • python3 scripts/check_grafana_queries_sync.py passes for the interactive dashboard and its 19 canonical SQL files.
  • All 18 public SQL queries currently contain the intended 72-hour predicate and no Grafana query macros.
  • The live public artifact nevertheless produces HTTP 400 panel-query responses, which is why the static checks are not sufficient.

The branch is also 14 commits behind current main; I found no textual merge conflict, but it should be updated after these fixes.

@whuang602

whuang602 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor Author

Note on .gitignore request

  • Due to the nature of service account private key file generation, the broad *.json coverage was intentional. Based on my testing, depending on how and where the user generates the key, the file name can follow incredibly environment-specific naming conventions that the .gitignore may not be able to adequately capture if it was any less broad, e.g., {project-id}-{arbitrary-value}.json.
  • In order for a more specific .gitignore capture to work, we would likely need to first request/require the user to intentionally rename the file to follow specific naming conventions. The alternative (current state) is making sure users are truly intentional when committing JSON files. The goal is to prevent user friction or accidental miss of instructions.

Dashboard Error

  • The dashboard error was due to BQ daily query quota being reached. I had intentionally set an extremely strict BQ query limit for verification purposes and to prevent abuse on the public dashboard. Has been lifted to 10 GBs/day and filled with additional mock data, should be less difficult to hit the limit now.
…trols

This commit introduces complete bidirectional CI drift prevention, cloud billing guardrails, and credential
  leak protection for the Grafana public demo dashboard without overengineered syntax linters.

    Key Technical Accomplishments:
    - Canonical Drift Protection: Extracted 18 public demo queries into dedicated .sql files under
  grafana/queries/public-demo/ and updated scripts/check_grafana_queries_sync.py to enforce 100% bidirectional
  synchronization across all 37 queries.
    - Billing & URL Safety Guards: Implemented comment-immune active SQL assertions to guarantee hard 72-hour time
  bounds and prohibited dynamic interpolation syntax (${, $__, [[) to block unbounded scan attacks via public URL
  parameter tampering.
    - Credential Leak Prevention: Enforced backticked placeholder paths (`YOUR_PROJECT_ID.YOUR_DATASET_ID.`)
  across queries and verified complete exclusion of Trace-detail panel ID 19 from the public build.
    - High-Efficiency I/O & Anti-Bloat: Deduplicated dashboard verification loops into a unified driver
  (check_dashboard_sync) and eliminated redundant disk reads, maintaining zero external dependencies or speculative
  AST grammar parsers.
    - Documentation Rationale: Embedded punchy CI architectural design decisions and accurate on-demand BigQuery
  custom quota usage notes into repository READMEs.
@caohy1988

Copy link
Copy Markdown
Collaborator

Fresh full review at head a3f778f — approve

Re-reviewed the whole PR with the sync guard executed locally, a leak re-sweep of the delta, and the new public-demo query files read.

The round-4 P2 is fixed better than asked

a3f778f extracts all 18 public-demo queries into canonical grafana/queries/public-demo/*.sql and extends check_grafana_queries_sync.py to enforce bidirectional sync across all 37 queries (verified locally: "37 queries are in sync (19 interactive, 18 public demo)"). Beyond drift protection, the script now asserts the demo build's safety properties as code: the hard 72-hour scan bound present in every demo query, prohibition of ${/$__/[[ interpolation syntax (closing URL-parameter tampering against a public dashboard), backticked placeholder-path enforcement, and exclusion of the raw-event Trace-detail panel from the public build. That converts the demo's safety story from prose into CI-enforced invariants — genuinely good work.

Still open after two explicit requests: the .gitignore one-liner

grafana/*.json remains in .gitignore unchanged. This is the third review naming it, and it is a fired trap (this PR's own demo JSON had to be force-added past it). The fix is literally one line — narrow to grafana/*key*.json / grafana/*credential*.json, or add !grafana/bqaa-*.json. Please include it before merge; there is no reason to ship a known silent-omission hazard alongside a commit whose whole theme is guarding contributors from silent mistakes.

Advisory (unchanged, not blocking)

llm_calls_total.sql still counts LLM_RESPONSE rows (COUNT(*)), which overcounts on streaming installations and diverges from the Looker dashboard's distinct-span "LLM calls" semantics in this same repo. The header documents every other design decision; either switch to COUNT(DISTINCT trace_id || span_id) in both builds or add the streaming caveat to the header.

Verdict: approve — the substantive engineering is done and done well; please ride the .gitignore line in before merge. CI is green (6/6) and the delta leak-sweep is clean.

@haiyuan-eng-google

Copy link
Copy Markdown
Collaborator

From PR author: "On the .gitignore piece, I am curious about your thoughts on the best practice in this scenario. I have intentionally kept the .gitignore .json coverage broad because:
any specific capture would first rely on the user intentionally naming it a certain way while setting a !grafana/bqaa-
.json exception would require them to intentionally not name it with a "bqaa-" prefix.
It feels like the friction of requiring future developers to force-add a file intentionally is outweighed by the dangers of a user accidentally pushing credentials." I think this is a valid point and we should not block on this

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Fresh full re-review at current head f390057 (the Grafana tree is unchanged from a3f778f; the new head only merges main): requesting changes. These are the remaining/new findings only.

[P1] The public-demo billing/privacy guard is bypassable

check_public_demo_queries() says each anonymous query must bound its scan and use only the shipped table placeholders, but the implementation at scripts/check_grafana_queries_sync.py:358-407 is a set of substring/count checks:

  • active_sql() removes only -- comments, not BigQuery /* ... */ comments;
  • the time check only requires the predicate text to occur somewhere;
  • the table check only verifies occurrences of YOUR_PROJECT_ID.YOUR_DATASET_ID are backticked. It does not reject any additional fully-qualified table.

I ran the current function against three adversarial queries. All three returned errors=0:

  1. the required time predicate present only inside a block comment;
  2. WHERE <required predicate> OR TRUE;
  3. a correctly-placeholdered table unioned with `customer-prod.private.agent_events`.

That means a later dashboard edit can make an anonymously-triggered query unbounded or ship a real project/table reference while the safety job stays green. This is the exact trust boundary the new check claims to enforce, and the public dashboard executes under a shared service account and billing project.

Please make this validation fail closed. The most reliable fix is to parse BigQuery SQL (or use an equivalently conservative statement validator) and assert, per table-scan/UNION branch, that:

  • every fully-qualified table begins with the literal project/dataset placeholders;
  • the time window is an effective conjunct, not merely text in a comment or disjunction;
  • block comments cannot satisfy active-SQL checks.

Commit the three mutants above as negative regression tests.

[P2] The current SQL is not actually bounded to the last 72 hours

All 18 public-demo queries have only this lower bound:

timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 72 HOUR)

There is no upper bound. Future-dated events are reported before they happen, and future partitions remain eligible for scanning, so the README's “locked Last 72 hours” and “hardcoded 72-hour bound” claims are not strictly true.

Please freeze a half-open window in every table-scan branch:

timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 72 HOUR)
AND timestamp < CURRENT_TIMESTAMP()

The safety validator should enforce both sides.

What now verifies

  • The earlier public-dashboard outage is resolved: after lazy-loading every row, all 18 anonymous panel endpoints returned HTTP 200 and the accessibility tree contained real values/tables.
  • The 37-query sync check passes (19 interactive + 18 public).
  • The previous --table-id, public-demo drift, and Recent-sessions data-link findings are fixed.

The remaining blockers are the false-negative safety check and the one-sided time window above.

@caohy1988 caohy1988 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approved. The findings recorded in my preceding review remain visible as non-blocking follow-up items.

@haiyuan-eng-google
haiyuan-eng-google merged commit f149423 into GoogleCloudPlatform:main Aug 4, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants