Repository navigation
fix(grafana): resolve non-blocking issues (count distinct, 72-hour window enforcement) - #433
Conversation
… bounds
- Switch
llm_calls_total to count distinct span keys instead of rows to prevent overcounting streaming chunks, gracefully
falling back on NULLs.
- Enforce a strict half-open 72-hour window (< CURRENT_TIMESTAMP()) across all public-demo queries so future
events and partitions are not prematurely scanned.
- Update the sync CI script to strictly enforce both time bounds per table-scan branch.
Patches the public-demo CI script to catch comment-hidden bounds and unquoted table leaks. Adds regression tests to prove guard efficacy and updates documentation to explicitly define the text-level scope and accepted limitations.
caohy1988
left a comment
There was a problem hiding this comment.
PR Review: #433
Status: LGTM / Approve ✅
Summary of Changes
-
Accurate LLM Call Counting (
llm_calls_total.sql):- Switched from
COUNT(*)to distinct span counting:
COUNT(DISTINCT CONCAT(trace_id, '|', span_id)) + COUNTIF(trace_id IS NULL OR span_id IS NULL)
in both interactive (grafana/queries/llm_calls_total.sql) and public-demo (grafana/queries/public-demo/llm_calls_total.sql) queries. - Prevents streaming chunks from being counted as multiple calls while safely falling back to 1-per-row for records lacking span IDs.
- Preserves the
HAVING COUNT(*) > 0contract for clean empty-state rendering ("No matching data"). - Aligns Grafana call counting with Looker Studio conventions.
- Switched from
-
Strict Half-Open 72-Hour Scan Window:
- Enforced
AND timestamp < CURRENT_TIMESTAMP()alongsidetimestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 72 HOUR)across all 18 public-demo SQL queries andgrafana/bqaa-public-demo.json. - Protects public demo instances from scanning future partitions or prematurely querying future-dated events.
- Handled properly across multiple table scans (e.g. both
UNION ALLbranches intool_errors.sql).
- Enforced
-
CI Sync & Security Guardrails (
scripts/check_grafana_queries_sync.py):- Updated
active_sql()to strip block comments (/* ... */) and line comments (#,--), ensuring commented-out bounds do not satisfy the lint. - Enhanced foreign table detection to capture unquoted, segment-quoted (
`proj`.`dataset`.`table`), and mixed-quoted table paths. - Added branch-level predicate counting to require both time bounds per table-scan branch.
- Updated
-
Regression & Policy Test Suite (
tests/test_check_grafana_queries_sync.py):- Comprehensive test suite covering baseline queries, shipped queries, block comment stripping, foreign table leak variations, and explicitly pinning documented limits (e.g.,
WHERE ... OR TRUE).
- Comprehensive test suite covering baseline queries, shipped queries, block comment stripping, foreign table leak variations, and explicitly pinning documented limits (e.g.,
-
Documentation:
- Updated
grafana/README.md,grafana/queries/README.md, andgrafana/queries/public-demo/README.mdto document the half-open window, span counting semantics, and CI scope.
- Updated
Verification
python3 scripts/check_grafana_queries_sync.pypasses:Grafana dashboard JSON is valid and 37 queries are in sync (19 interactive, 18 public demo).
pytest tests/test_check_grafana_queries_sync.pypasses (11 passed).- Formatted and compliant with
pyinkandisort.
caohy1988
left a comment
There was a problem hiding this comment.
Verdict: Approve. The PR does exactly what it claims, resolves the two P2 follow-ups from the #373 review (streaming-chunk overcounting; missing upper time bound) plus the lint-bypass findings, and defers the OR TRUE gap with an explicit rationale, a pinning test, and README documentation. Everything below was verified by running the code at this head, not just reading the diff.
Verified locally (all pass on PR head)
python3 scripts/check_grafana_queries_sync.py→ exit 0, "37 queries in sync (19 interactive, 18 public demo)". All 18 public-demo files and both dashboard JSONs carry both halves of the half-open window.pytest tests/test_check_grafana_queries_sync.py→ 11/11 pass.autoformat.sh(pyink + isort, same as the CI format gate) → no changes on either touched Python file.- Schema claim:
trace_id/span_idare NULLABLE standard-header columns projected into every typed view includingllm_responses(src/bigquery_agent_analytics/views.py,seed_events.py), so theCOUNTIF(... IS NULL)fallback rationale is sound. - CI wiring:
ci.ymlruns pytest unfiltered on every PR, so the new regression tests always run even whengrafana-sync-check.yml's path filter doesn't fire. - The mutant tests are genuinely negative regressions: block-comment mutant, four quoting variants of the foreign-path leak (backticked, bare, segment-quoted, mixed), and the
OR TRUEgap pinned as not caught so a future fix must consciously flip the test.
Design points I like
- The per-table-scan predicate count is strictly stronger than the old "at least one lower-bound line" check — it forces both bounds and catches a new
UNIONarm shipping unbounded, and the README states its global-not-positional limitation accurately instead of overclaiming. continueafter the placeholder-count failure kills the cascading-error noise the old code would have produced.- The docs were rewritten from "the check enforces safety" to "the check is a lint that catches honest mistakes, not deliberate ones" — that honesty is worth more than the code change.
- Deferring the
OR TRUEbypass is the right call for the stated threat model (accidents, not malicious SQL authorship), and it is deferred visibly — test + README + docstring all name it.
Findings (all minor, none blocking)
1. Foreign-path error message includes a spurious '.' entry for segment-quoted paths. For `customer-prod`.`private`.`agent_events`, the backtick regex r"`([^`]*\.[^`]*)`" captures the bare dots between quoted segments, so foreign_paths comes out as ['.', 'customer-prod.private.agent_events'] and the error message reports both. The real path is now named (the point of the fix), but the '.' is noise. A one-line filter — drop candidates containing no \w character — would clean it up. Cosmetic.
2. UNQUOTED_TABLE_PATH misses digit-leading segments in mixed quoting. Continuation segments require [A-Za-z_] as the first char, so proj.`2024_data`.events (dataset legally starting with a digit, quoted) strips to proj.2024_data.events and matches nothing — and the backtick scan doesn't see it either (no dot inside any single backtick pair). If that arm carries no time bounds, the predicate count also stays balanced, so the path escapes the lint entirely. This sits inside the deliberate-bypass territory the PR explicitly defers, so not blocking — but the fix is one character class ((?:\.[\w][\w-]*)+ for continuation segments) if you want it.
3. "Same distinct-span definition the Looker Studio build uses" is a slight overstatement. Looker's version (dashboard/looker_studio/oracle/queries/usage-llm-call-trends.sql) is COUNT(DISTINCT CONCAT(trace_id, '|', span_id)) with no NULL fallback — it silently drops NULL-key rows the Grafana version adds back. The Grafana version is the better one; the two builds will just disagree on installations with NULL span keys. Consider softening to "same distinct-span key as the Looker Studio build, plus a NULL fallback."
4. Cosmetic: the main() docstring's rewritten item 8 has an awkward mid-sentence wrap ("…variable or macro, and / names its tables…").
5. Theoretical, not actionable: the '|' delimiter in CONCAT(trace_id, '|', span_id) could collide if ids ever contained |; OTel ids are hex and the Looker build uses the identical shape, so consistency wins. Similarly, empty-string (non-NULL) ids would collapse into one key — same behavior as Looker.
Nothing here needs to hold up the merge; items 1–3 would make fine "if you're touching it anyway" tweaks or a tiny follow-up.
🤖 Reviewed with Claude Code
Code Review ResultsScope: PR #433, head Reviewers: correctness, testing, maintainability, security, performance, adversarial
Actionable FindingsActionable findings: none. Coverage
Residual risks:
Testing gaps:
Verdict
Actionable findings: none. |
bd6e8a0
into
GoogleCloudPlatform:main
…configurator (#450) * chore(release): 0.5.1 — evalbench reader, canonical rubrics, single-input configurator Version bump 0.5.0 -> 0.5.1 and the changelog cut for everything merged since v0.5.0 (2026-08-11). In the wheel: the EvalBench BigQuery run reader (#444), canonical evaluation rubrics in core (#431), and the CLI judge-feedback escaping fix (#438). Repo/live-template side: the single fully-qualified table-ID configurator entrance (#449), Console table-link paste (#424), the attested external-access contract with its staleness workflow (#446), the end-user manual (#425), Grafana metric and scan-bound fixes (#433) with the one-command local run (#422), and the documentation and CI follow-ups. * chore(release): fold #432 golden-matching into the 0.5.1 cut The release branch was cut one commit before #432 landed on main; the synthetic merge CI builds would already ship golden_matching.py in the 0.5.1 wheel, so the module and its three top-level exports must be in the release section. Merges main and documents the module in Release highlights and Added.
Resolve non-blocking issues from #373
gracefully falling back on NULLs.
events and partitions are not prematurely scanned.
SQL Bypass guardrail is deferred for now- two reasons: (1) Addressing the bypass would require additional parsing and checks that may constitute as over-engineering and (2) Target audience: this bypass can only be performed by future contributors who can directly modify the source SQL and other files.
The goal is to capture and prevent accidents as opposed to defend against intentional & malicious contributors. For example, the following are too intentional to be accidents: