Skip to content

feat(views): add compaction windows view (#216) - #494

Merged
haiyuan-eng-google merged 2 commits into
GoogleCloudPlatform:mainfrom
sunpan9209:main
Sep 25, 2026
Merged

haiyuan-eng-google merged 2 commits into
GoogleCloudPlatform:mainfrom
sunpan9209:main

Conversation

@sunpan9209

Copy link
Copy Markdown
Collaborator

Summary

Add compaction_windows to the cross-event registry introduced in #489. The view reads EVENT_COMPACTION rows and exposes their ranges under the full telemetry identity, preserving fractional epoch seconds.

Fixes #216.
Refs #190.

Behavior

  • Expose app_name, user_id, session_id, invocation_id, typed start_ts / end_ts, and raw start_seconds / end_seconds.
  • Convert float seconds through microseconds using safe multiplication, casts, and SAFE.TIMESTAMP_MICROS.
  • Return one row per distinct identity and source-boundary pair. Exact duplicate windows collapse; overlapping and disjoint windows stay separate. Equal boundaries are retained.
  • Exclude incomplete identities and missing, non-numeric, non-finite, out-of-range, or reversed boundaries without failing valid rows.
  • Deploy through the existing ViewManager, views create compaction_windows, and views create-all paths. Existing per-event SQL is unchanged.

No producer or base-table schema changes. This view describes compaction ranges, not token savings or affected-event counts. The remaining work under parent #190 is outside this PR.

Acceptance and coverage

  • Fractional fixture: 1.234s to 1.235s remains a 1ms window.
  • Full-identity isolation, exact duplicates, overlapping/disjoint ranges, and equal boundaries.
  • Null-safe pre-2.0 behavior and invalid-boundary handling.
  • Custom table/prefix, CLI deployment, combined-registry ordering, and existing per-event SQL compatibility.
  • SDK documentation and changelog updated.

Validation

On macOS / Python 3.13:

  • pytest -q tests/test_compaction_windows.py tests/test_cross_event_views.py tests/test_views.py tests/test_adk2_event_types.py tests/test_cli.py: 277 passed, 1 skipped.
  • Full repository suite on the same implementation: 5,276 passed, 84 skipped. The successful run allowed the process inspection and local browser server needed by existing tests.
  • pyink --check and isort --check-only on the four changed Python files: passed.
  • git diff --check: passed.

Live BigQuery validation has not been run. Local behavior tests execute the generated SELECT through SQLite adapters for BigQuery-specific functions; deployment tests mock the BigQuery client. These tests do not establish actual BigQuery execution success.

An opt-in test_compaction_windows_bigquery_contract is included for follow-up validation if requested. It uses inline synthetic fixtures, reads no production tables, creates no persistent tables or views, and sets a 10 MiB maximum-bytes-billed limit. No cloud query was executed for this PR.

Preserve fractional compaction boundaries and full telemetry identity through the existing ViewManager and CLI deployment path. Add null-safe range handling, behavioral fixtures, an opt-in BigQuery probe, and documentation.

Refs GoogleCloudPlatform#216.

@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

Independent blind review by Astra (Codex), on behalf of caohy1988, of 645a6f82d8cf329281386688108f2df1be53179a against 652b006d29b46ed0348d1c284de2c2d799a648ef, using the PR description and the contracts in #216 and #190. No existing PR reviews or review comments were consulted.

Findings introduced by this PR:

  • P0: None found.
  • P1: None found.
  • P2: None found.

The implementation matches #216: the full (app_name, user_id, session_id, invocation_id) identity participates in deduplication; fractional epoch seconds are converted through microseconds; invalid/incomplete rows are filtered; exact duplicate source ranges collapse while overlapping, disjoint, and equal-boundary ranges remain valid (views.py:340-377). This is a set of source ranges, so arrival order does not affect its semantics and no event-pairing order is needed. Empty inputs and sessions without compaction yield no windows. Distinct source boundaries remain distinct even when they round to the same microsecond timestamps.

Registration, configured table/prefix handling, and the existing Python/CLI deployment paths are consistent with the shared manager. The six-file diff is focused, and the new documentation accurately describes the code (SDK.md:1448-1474, CHANGELOG.md:10-17).

Validation:

  • Python 3.13.5: pytest -q -p no:cacheprovider tests/test_compaction_windows.py tests/test_views.py tests/test_cross_event_views.py — 98 passed, 1 skipped in 4.94s. The skipped test is the opt-in BigQuery probe; live-query and golden-update environment flags were explicitly disabled for this run.
  • These tests do exercise generated SQL filtering, projection, and DISTINCT through SQLite adapters, plus mocked Python/CLI deployment and preservation of existing per-event SQL; they are not solely string snapshots (test_compaction_windows.py:91-258, test_cross_event_views.py:182-250). Supplementary checks using the same SQLite harness passed for empty input, sessions without compaction, all 24 permutations of a four-event fixture, modern epoch microseconds, and distinct raw boundaries with identical rounded timestamps.
  • Pyink 25.12.0 (<26) and isort --check-only passed on all four changed Python files; git diff --check passed. The worktree remains clean.
  • CI for this exact head succeeded, including Python 3.10–3.14, formatting, build, and browser smoke. The reported CLA/security checks passed; four conditional zizmor jobs were skipped. No reported failures or pending checks.

Two nonblocking caveats:

  • BigQuery execution remains unverified. The SQL appears valid BigQuery Standard SQL on static inspection, including the nested safe conversion chain (views.py:353-358). However, the SQLite harness replaces the dialect-specific functions and cannot establish native BigQuery behavior. A useful follow-up is to run the included opt-in probe with BQAA_LIVE_BQ=1 and BQAA_LIVE_BQ_PROJECT set, and retain its result (test_compaction_windows.py:302-360). No cloud query was run during this review.
  • Identifiers retain the existing trust boundary. The shared renderer interpolates project/dataset/table/prefix configuration without identifier validation (views.py:424-443, views.py:493-496). I verified this behavior already exists in the pinned base; this PR introduces no new caller-controlled interpolation source. Backtick quoting alone does not make arbitrary untrusted identifiers safe. Continue treating these as trusted deployment configuration; a separate hardening change should validate identifiers in the shared manager and add rejection tests.

Thank you for the focused change and the explicit disclosure of the live-validation limitation. This is a COMMENT review only; no formal approval or change-request event is submitted.

@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

Thanks for a careful, well-scoped PR. The SQL matches the #216 / #190 contract (full telemetry identity, TIMESTAMP_MICROS over CAST(seconds * 1000000 AS INT64) in SAFE form, null-safe pre-2.0 handling, fractional fixture), it uses the #489 registry/CLI plumbing as intended, and the tests execute the generated SELECT rather than snapshotting strings. Nothing below is blocking: the P1 is a design question for the maintainers to settle, and the P2s are small polish items.

What I verified (worktree at 645a6f8, Python 3.13.5)

  • pytest tests/test_compaction_windows.py tests/test_cross_event_views.py tests/test_views.py tests/test_adk2_event_types.py tests/test_cli.py: 277 passed, 1 skipped (matches the description).
  • pyink 25.12.0 --check, isort --check-only, git diff --check on the changed files: clean. CI: all checks green.
  • BigQuery validation (the gap the description calls out): I dry-ran the rendered SELECT over the PR's 18-event inline fixture. It is valid Standard SQL, 0 bytes, and the output schema is STRING x4, TIMESTAMP x2, FLOAT64 x2. I then ran the opt-in test_compaction_windows_bigquery_contract against a scratch project (BQAA_LIVE_BQ=1): passed, 3 rows as expected. So SAFE_MULTIPLY / SAFE_CAST / SAFE.TIMESTAMP_MICROS and the NaN / Infinity / out-of-range exclusions behave in real BigQuery exactly as the SQLite harness predicts. No tables or views were created.

P0

None.

P1

  1. No partition-prunable column (src/bigquery_agent_analytics/views.py:361-368). agent_events is DAY-partitioned on timestamp (the ADK plugin creates it that way), and every per-event view, including adk_event_compactions, projects timestamp, so consumers can bound their scans. This view projects only JSON-derived columns, so any query through it (even WHERE start_ts >= ...) reads every partition of the six source columns, and a table with require_partition_filter=true could not be queried through it at all. Not a correctness issue and not required by #216, but it is cheaper to decide now than after the column set is public. Options: (a) add DATE(timestamp) AS event_date to the DISTINCT projection so a consumer filter on it can prune, and note that exact duplicates then collapse per day; or (b) keep the shape and add one sentence to SDK.md (near line 1463) saying queries through this view are not partition-pruned and pointing date-bounded consumers at adk_event_compactions. Either is fine by me; (b) is the smaller change.

P2

  1. Clarify what invocation_id means (SDK.md:1459). On an EVENT_COMPACTION row it is the invocation that emitted the compaction event (ADK's summarizer even mints a fresh Event.new_id() for it), not the invocation(s) whose events fall inside start_ts..end_ts. A reader following #190's "compaction-aware token totals" idea could join on all four identity columns plus the time range and silently under-count. Suggested wording: "invocation_id is the invocation that recorded the compaction; to find the events a window covers, join on (app_name, user_id, session_id) and timestamp BETWEEN start_ts AND end_ts."

  2. "Every view retains the standard headers" is no longer true (src/bigquery_agent_analytics/views.py:19-21, :56, SDK.md:1380). This view has no timestamp / event_type / agent. Suggest "Every per-event view retains ..." and "included in every per-event view". (Optional, same theme: examples/event_semantics_views_bigframes_demo.ipynb prints Total: {len(vm.available_event_types)} views right before create_all_views(), which now returns 26 entries.)

  3. CHANGELOG dash style (CHANGELOG.md:12). Every other entry uses ** — (em dash); this one uses ** - .

  4. Pin the shipped cross-event key set (tests/test_views.py:175; tests/test_cross_event_views.py:188, :198, :215, :246). The rewritten assertions derive their expectation from _CROSS_EVENT_VIEW_DEFS itself, so an accidental extra registration would deploy to every user's dataset without failing a test (before this PR the hard-coded + 1 caught that). One line in tests/test_compaction_windows.py, e.g. assert vm.available_cross_event_views == ["compaction_windows"], restores the tripwire; each future view then updates that list deliberately.

  5. Make the SQLite rewrites fail loudly (tests/test_compaction_windows.py:100-108). The harness swaps BigQuery functions by exact-string replace. If the INT64 stage ever drifts (say SAFE_CAST becomes CAST), the replace silently no-ops and SQLite runs its own CAST(... AS INT64), which never raises, so the Infinity / 1e308 cases keep passing offline while BigQuery would abort on the same rows. Suggest assert "SAFE_CAST" not in query and "SAFE." not in query after the rewrites.

  6. Close the in-memory connections (tests/test_compaction_windows.py:111). with sqlite3.connect(...) only commits or rolls back; it does not close, so pytest -W error::ResourceWarning tests/test_compaction_windows.py gives 1 failed + 3 errors. with contextlib.closing(sqlite3.connect(":memory:")) as connection: fixes it. The same idiom exists in tests/test_categorical_views.py, so this is optional consistency.

  7. Oracle rounding (tests/test_compaction_windows.py:171-173, :354). timedelta(seconds=float(x)) rounds half-to-even, while SAFE_CAST(... AS INT64) (and your own _safe_int) rounds half away from zero. Harmless for the current fixtures, but a tie such as 2.5e-6 would fail against correct SQL. Optional: derive the expected values through _safe_int / _safe_timestamp_micros.

Nice work on the invalid-boundary matrix and the opt-in live probe; they made independent verification straightforward.

@haiyuan-eng-google
haiyuan-eng-google merged commit a51c39a into GoogleCloudPlatform:main Sep 25, 2026
15 checks passed
haiyuan-eng-google pushed a commit that referenced this pull request Sep 29, 2026
…st (#501)

* chore(release): 0.5.4 — compaction_windows view, smoke-test unpickling allowlist

Bump the version to 0.5.4 and cut the CHANGELOG for the ten PRs merged
since v0.5.3 (#490–#497, #499, #500). [Unreleased] is left empty; the
#494 entry moves into [0.5.4].

* docs(changelog): tighten 0.5.4 compatibility notes

List every incidental name #490/#496 removed and where each lives
now, fix the permission repair to `chmod go-w`, scope the log-dir
symlink rule to logs outside the state directory, and qualify the
tracing checks' platform fallbacks.

* chore(release): date 0.5.4 for 2026-09-29
haiyuan-eng-google pushed a commit that referenced this pull request Sep 30, 2026
…ghtly) (#502)

* audit: document compaction_windows partition limitation in SDK.md (nightly)

The 0.5.4 CHANGELOG (#501) records a known limitation of the
compaction_windows view (#494): it exposes no event `timestamp`
column, so a query through it reads every partition of the events
table and fails on a table that sets `require_partition_filter`.
SDK.md's compaction_windows section, the view's reference doc, did
not say so.

Add the limitation to SDK.md, with a pointer to the
adk_event_compactions per-event view for time-bounded queries. A new
test ties the note to the view: it fails while the view has no
`timestamp` column and SDK.md omits the limitation, and it fails once
a `timestamp` column is added, so the note goes away with that fix.

* audit: scope compaction_windows doc test to its SDK.md section (nightly)

Review of c3c5cc8 found that test_partition_limitation_is_documented
searched all of SDK.md for `require_partition_filter`. The test still
passed after the limitation paragraph was deleted, as long as the token
appeared anywhere else in the file.

Scope the search to the "Cross-event views" section, and require one
paragraph there to name both `require_partition_filter` and the
`adk_event_compactions` pointer. A renamed heading now raises
ValueError instead of widening the search.

SDK.md now also says that `adk_event_compactions` is not a drop-in
replacement: it does not deduplicate windows or skip malformed
boundaries, and it has `agent` rather than `app_name`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants