Skip to content

fix(grafana): resolve non-blocking issues (count distinct, 72-hour window enforcement) - #433

Merged
haiyuan-eng-google merged 3 commits into
GoogleCloudPlatform:mainfrom
whuang602:grafana-fix
Aug 20, 2026
Merged

haiyuan-eng-google merged 3 commits into
GoogleCloudPlatform:mainfrom
whuang602:grafana-fix

Conversation

@whuang602

@whuang602 whuang602 commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Resolve non-blocking issues from #373

  • 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, check for block comment bypass, capture real table ID leak
  • Negative regression test

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:

  • OR TRUE bypass
  • Comma Cross-Joins
  • Dot (.) separated table paths + Comment embedding
… 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.
@whuang602 whuang602 changed the title fix(grafana): address PR feedback on llm calls counting and 72-hour… Aug 18, 2026
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 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.

PR Review: #433

Status: LGTM / Approve ✅


Summary of Changes

  1. 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(*) > 0 contract for clean empty-state rendering ("No matching data").
    • Aligns Grafana call counting with Looker Studio conventions.
  2. Strict Half-Open 72-Hour Scan Window:

    • Enforced AND timestamp < CURRENT_TIMESTAMP() alongside timestamp >= TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 72 HOUR) across all 18 public-demo SQL queries and grafana/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 ALL branches in tool_errors.sql).
  3. 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.
  4. 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).
  5. Documentation:

    • Updated grafana/README.md, grafana/queries/README.md, and grafana/queries/public-demo/README.md to document the half-open window, span counting semantics, and CI scope.

Verification

  • python3 scripts/check_grafana_queries_sync.py passes:

    Grafana dashboard JSON is valid and 37 queries are in sync (19 interactive, 18 public demo).

  • pytest tests/test_check_grafana_queries_sync.py passes (11 passed).
  • Formatted and compliant with pyink and isort.

@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.

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_id are NULLABLE standard-header columns projected into every typed view including llm_responses (src/bigquery_agent_analytics/views.py, seed_events.py), so the COUNTIF(... IS NULL) fallback rationale is sound.
  • CI wiring: ci.yml runs pytest unfiltered on every PR, so the new regression tests always run even when grafana-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 TRUE gap 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 UNION arm shipping unbounded, and the README states its global-not-positional limitation accurately instead of overclaiming.
  • continue after 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 TRUE bypass 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

@caohy1988

Copy link
Copy Markdown
Collaborator

Code Review Results

Scope: PR #433, head b83086b against main at a0add5b (26 files)
Intent: Correct LLM call counts, enforce a half-open 72-hour public-demo window, and strengthen the text-level safety lint without turning it into a malicious-SQL parser.
Mode: markdown report-only

Reviewers: correctness, testing, maintainability, security, performance, adversarial

  • Testing: the PR adds a regression module and changes lint behavior.
  • Maintainability: the diff has 331 executable changed lines and expands the lint abstraction.
  • Security: the anonymous dashboard and real-table-path guard affect accidental data exposure.
  • Performance: the timestamp bounds and distinct aggregation affect BigQuery cost.
  • Adversarial: the CI guard can fail green while public SQL is unsafe.

Actionable Findings

Actionable findings: none.

Coverage

  • Validation: pytest -q tests/test_check_grafana_queries_sync.py -> 11 passed.
  • Validation: python3 scripts/check_grafana_queries_sync.py -> passed; 37 queries are synchronized.
  • Formatting: Pyink and isort passed with the repository's pyproject.toml.
  • GitHub checks currently report check-changes and CLA success. The normal CI matrix and Grafana workflow are not reported on this fork PR, so they still need to run before merge.
  • Validator batch: one merged P1 candidate was rejected. Comma cross-joins are technically a bypass, but the PR body and README explicitly defer that intentional pattern.
  • Mode-aware demotion: three single-reviewer P2 test-coverage candidates moved to Testing gaps.
  • Suppressed: one fast-pass candidate at confidence 50.
  • Preliminary fast-pass items withdrawn: 1. The file-wide, non-positional bound count is explicitly documented outside the lint guarantee.
  • Cross-model coverage: no peer pass ran for this remote-only reviewed tree; the adversarial lens ran in-process against the fetched PR refs.
  • Project standards: not run because the reviewed repository has no applicable AGENTS.md or CLAUDE.md.
  • Reviewer health: all six selected reviewers completed; no malformed returns.
  • No matching plan artifact was discovered, so settlement-conflict suppression was not evaluated.

Residual risks:

  • The text lint intentionally leaves logical SQL review to humans, including OR TRUE, comma cross-joins, globally balanced bounds in the wrong UNION arm, and comment markers inside string literals.
  • The LLM call expression treats empty trace_id/span_id strings as a shared valid key. Historical or custom-producer rows with empty identifiers could be undercounted.

Testing gaps:

  • No BigQuery-executed fixture covers repeated span keys plus NULL or empty identifiers for the new LLM call metric.
  • The lint tests do not independently isolate a missing upper bound or the new # line-comment stripping path.
  • No representative BigQuery dry-run or job-plan measurement records partition pruning and the cost of the new distinct aggregation.

Verdict

Ready to merge

No actionable defect survived intent-aware validation. The focused regression tests, sync checker, and repository-configured format checks pass. Let the repository's normal CI and Grafana workflow report before merging.

Actionable findings: none.

@haiyuan-eng-google
haiyuan-eng-google merged commit bd6e8a0 into GoogleCloudPlatform:main Aug 20, 2026
16 checks passed
haiyuan-eng-google pushed a commit that referenced this pull request Aug 30, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants