Repository navigation
feat: add native Grafana dashboard integration (#339) - #373
Conversation
|
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
left a comment
There was a problem hiding this comment.
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
- JSON validity:
python3 -m json.tool grafana/bqaa-dashboard.json→ valid, schemaVersion 39, 19 panels, 4 rows, 7 template variables. - Query sync check: extracted every panel query and variable query from
bqaa-dashboard.jsonand compared them tografana/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 inqueries/. - Local Grafana import:
- Installed
grafana-bigquery-datasourcev3.2.0 viagrafana cli. - Started Grafana 12.3.0 on
localhost:3131with a clean temp data dir and a provisioned dummy BigQuery data source. - Imported
grafana/bqaa-dashboard.jsonvia/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.)
- Installed
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}*_completionsviews 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 betweenERROR_SQL_PREDICATEandseed_events.py. - Missing telemetry degrades safely: token sums
IFNULL(..., 0), latency aggregates stayNULLso 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.yamlonly contains placeholders, with the private key insecureJsonData.
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 agentOn 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.yamlto/etc/grafana/provisioning/datasources/datasource.yaml, but the file name in the repo isdatasource.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.
There was a problem hiding this comment.
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.pypasses; dashboard and provisioning YAML parse.pyinkandisortpass for the new Python checker.- Full repository suite: 3,739 passed, 36 skipped.
git diff --checkfinds only four trailing-space lines ingrafana/README.md.
The detailed correctness, security, setup, and CI findings are attached inline.
| branches: [main] | ||
|
|
||
| jobs: | ||
| grafana-query-sync: |
There was a problem hiding this comment.
[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.
|
|
||
| 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: |
There was a problem hiding this comment.
[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.
|
|
||
| ## 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. |
There was a problem hiding this comment.
[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.
|
|
||
| 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: |
There was a problem hiding this comment.
[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.
| 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). |
There was a problem hiding this comment.
[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.
| COUNT(DISTINCT e.session_id) AS sessions, | ||
| COUNT(*) AS events, | ||
| SAFE_DIVIDE( | ||
| COUNTIF(UPPER(e.status) = 'ERROR'), |
There was a problem hiding this comment.
[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.
| SELECT | ||
| tool_name, | ||
| COUNT(*) AS invocations | ||
| FROM `${project}.${dataset}.${view_prefix}tool_completions` |
There was a problem hiding this comment.
[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.
| -- 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 |
There was a problem hiding this comment.
[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
left a comment
There was a problem hiding this comment.
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
zizmor-outputis red because the new workflow has nopermissions:block — inline comment with the two-line fix. This is the actual cause of the CI failure.cla/googleis 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 canonicalERROR_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
definitioncopy) 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, |
There was a problem hiding this comment.
[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 toREGEXP_CONTAINS(agent, '^${agent:regex}$')-style filtering, or - guard the predicate:
AND ('${agent:raw}' = '' OR agent IN (${agent:sqlstring})).
| "skipUrlSync": false | ||
| }, | ||
| { | ||
| "type": "textbox", |
There was a problem hiding this comment.
[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-tableat 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).
| "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", |
There was a problem hiding this comment.
[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, |
There was a problem hiding this comment.
[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.
| COUNT(*) AS events | ||
| FROM `${project}.${dataset}.${table}` | ||
| WHERE $__timeFilter(timestamp) | ||
| AND agent IN (${agent:sqlstring}) |
There was a problem hiding this comment.
[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.)
| session_id, | ||
| MIN(timestamp) AS started_at, | ||
| MAX(timestamp) AS last_event_at, | ||
| TIMESTAMP_DIFF(MAX(timestamp), MIN(timestamp), SECOND) AS duration_s, |
There was a problem hiding this comment.
[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.
| CAST(JSON_VALUE(latency_ms, '$.total_ms') AS INT64) AS total_ms, | ||
| error_message | ||
| FROM `${project}.${dataset}.${table}` | ||
| WHERE session_id = ${session_id:sqlstring} |
There was a problem hiding this comment.
[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.
| panels[panel_id] = panel | ||
|
|
||
| for panel_id, panel in panels.items(): | ||
| if panel.get("type") == "row": |
There was a problem hiding this comment.
[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 = { |
There was a problem hiding this comment.
[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.
| .DS_Store | ||
| .DS_Store? | ||
| ._* | ||
| grafana/datasource.yaml |
There was a problem hiding this comment.
[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.
| FROM `${project}.${dataset}.${view_prefix}tool_completions` | ||
| WHERE $__timeFilter(timestamp) | ||
| AND agent IN (${agent:sqlstring}) | ||
| AND UPPER(status) = 'ERROR' |
There was a problem hiding this comment.
[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.
|
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 From the CHANGES_REQUESTED review (canonical for): scope check vs #339 acceptance, workflow permissions/zizmor, IAM scoping, public-sharing spike + snapshot privacy, YAML From my review (10 kept + 1 added, non-overlapping):
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 |
caohy1988
left a comment
There was a problem hiding this comment.
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.
| - 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 |
There was a problem hiding this comment.
[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: |
There was a problem hiding this comment.
[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.
|
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. Regarding Snapshot Public Demo:
Currently exploring & working on addressing the rest of the issue requirements:
|
…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
Re-review at
|
| python-version: "3.12" | ||
|
|
||
| - name: Validate dashboard JSON and embedded queries | ||
| run: python3 scripts/check_grafana_queries_sync.py |
There was a problem hiding this comment.
[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.
| Then create the typed views the dashboard queries: | ||
|
|
||
| ```bash | ||
| bq-agent-sdk views create-all --project-id YOUR_PROJECT --dataset-id YOUR_DATASET |
There was a problem hiding this comment.
[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.
| "value": [ | ||
| { | ||
| "title": "Pin this session", | ||
| "url": "?${__url_time_range}&${agent:queryparam}&${user_id:queryparam}&${event_type:queryparam}&var-session_id=${__data.fields.session_id}", |
There was a problem hiding this comment.
[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
left a comment
There was a problem hiding this comment.
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). | |||
There was a problem hiding this comment.
[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). | |||
There was a problem hiding this comment.
[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.
|
|
||
| - **Overview:** sessions, events, error rate, latency, volumes | ||
| - **LLM & FinOps:** tokens, latency percentiles, tokens by model, estimated cost | ||
| - **Tools & Execution:** invocations, latency, errors |
There was a problem hiding this comment.
[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
Fresh full review at head
|
caohy1988
left a comment
There was a problem hiding this comment.
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.listis 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;
editableis 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_DATASETThat 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.pypasses 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.
Note on .gitignore request
Dashboard Error
|
…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.
Fresh full review at head
|
|
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: |
caohy1988
left a comment
There was a problem hiding this comment.
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_IDare backticked. It does not reject any additional fully-qualified table.
I ran the current function against three adversarial queries. All three returned errors=0:
- the required time predicate present only inside a block comment;
WHERE <required predicate> OR TRUE;- 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
left a comment
There was a problem hiding this comment.
Approved. The findings recorded in my preceding review remain visible as non-blocking follow-up items.



Introduces a zero-infrastructure Grafana dashboard alternative to dashboard_v2 for visualizing BigQuery Agent Analytics telemetry. Resolves #339.
Visual:
Verfication Performed and Results: