Skip to content

diag: tag analytics queries by surface so D1 Insights can attribute them - #4

Merged
scobb merged 1 commit into
mainfrom
diag/d1-surface-tagging
Sep 4, 2026
Merged

scobb merged 1 commit into
mainfrom
diag/d1-surface-tagging

Conversation

@scobb

@scobb scobb commented Sep 4, 2026

Copy link
Copy Markdown
Owner

Summary

We cut ~54% of D1 rows read in #3, but we still don't know what generates the ~114,000 analytics renders a month (~3,800/day, ~2.6/minute sustained) that multiply every remaining query.

The reason is mundane: D1 Insights groups by query text, and the two dashboards issue textually identical SQL.

-- /public/:site_id  and  /dashboard/sites/:id/analytics  both send exactly this
SELECT COUNT(*) as count FROM pageviews WHERE site_id = ? AND timestamp >= ? AND timestamp < ?

So they collapse into one row, and the data that would attribute them is destroyed before it reaches the dashboard. A trailing SQL comment splits them.

Verified inert first

On a 365,000-row dataset, with and without the tag:

  • identical result (29000 both ways)
  • byte-identical EXPLAIN QUERY PLAN — SEARCH pageviews USING COVERING INDEX idx_pageviews_site_timestamp
  • valid after a trailing LIMIT

No plan change, no cost, no behaviour change.

Changes

  • taggedSql(sql, surface) in lib/analytics.ts, with AnalyticsSurface = 'public' | 'app'
  • Five statements tagged per surface:
    • the pageview-count statement — one per render, so its execution count is the render count per surface
    • the three custom_events statements — the remaining ~29% of rows read (~2.48B/month) that perf(d1): cut ~54% of D1 rows read from analytics page loads #3 deliberately left alone
    • the on-demand json_each query, so we also learn how often anyone actually opens the panel
  • buildEventPropertiesQuery(surface) now takes its calling surface

Why the custom_events ones too

#3 left ~2.48B rows/month on the table. Tagging those tells us which surface to fix before anyone writes more query code. If it's all public-dashboard traffic, the answer is probably a robots.txt disallow and a Cache-Control header — not query optimisation.

Test plan

  • npm run typecheck passes
  • npm test — 123 tests, 119 pass, 0 fail (4 pre-existing skips)
  • npm run test:smoke — 128/128 pass
  • Verified against wrangler dev: both dashboards render, on-demand endpoint serves correct data, all three empty states unaffected

Guards are proven, not assumed: removing a single tag from a statement that still typechecks makes two tests fail, and they pass again once restored. That's the realistic regression — a future edit rewriting the query and dropping the tag — and it's caught.

Reading the result

24–48h after deploy, D1 Insights should show the pageview-count statement as two rows instead of one. Their execution counts are the render split. Expect them to sum to roughly the current ~114k.

A strong prior worth stating: 3,800 renders/day on the authenticated dashboard would mean about two people loading analytics ~1,900 times each per day. Implausible — so beam:public is the likely answer. But an earlier guess in this investigation (that the 60s self-reload was on the public dashboard, when it was actually on /embed/:siteId) turned out wrong, which is exactly why this measures rather than reasons.

🤖 Generated with Claude Code

D1 Insights groups by query text. /public/:site_id and
/dashboard/sites/:id/analytics issue textually identical SQL, so their
execution counts and rows-read merge into a single row. That is precisely why
~114,000 analytics renders a month (~3,800/day, ~2.6/min sustained) currently
have no identifiable source: the data to attribute them is being collapsed
before we ever see it.

A trailing SQL comment splits them. Verified on a 365k-row dataset that the tag
is inert: identical result and byte-identical EXPLAIN QUERY PLAN with and
without it, including after a trailing LIMIT.

Tags five statements per surface — the pageview-count statement (one per
render, so it counts renders) and the three custom_events statements plus the
on-demand json_each query. The custom_events statements are the remaining ~29%
of rows read (~2.48B/month) that the previous PR deliberately left alone;
tagging them shows which surface to fix before writing any more query code.

The `beam:public` vs `beam:app` split answers the open question directly. If it
turns out to be the public dashboard, the fix is likely a robots.txt disallow
and a Cache-Control header rather than further query work.

Guards assert the tags survive: removing one tag from a statement that still
typechecks makes two tests fail, verified.

Test plan:
  - npm run typecheck passes
  - npm test: 123 tests, 119 pass, 0 fail (4 pre-existing skips)
  - npm run test:smoke: 128/128 pass
  - Verified against wrangler dev: both dashboards render, the on-demand
    endpoint serves correct data, and all three empty states are unaffected.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@scobb

scobb commented Sep 4, 2026

Copy link
Copy Markdown
Owner Author

Full QA round completed

The initial submission had unit tests, smoke, and basic 200-checks, but skipped the systematic matrix that PR #3 got. That mattered here because the tags were applied by string replacement inside the query batch — if a replacement had landed on the wrong occurrence, panels would silently shift. Now covered.

Batch integrity — the one that mattered

Against a fingerprinted dataset where every dimension has a distinct signature and distinct visitor counts, so a one-index shift is unmistakable:

OK   Top Pages         /alpha/5/50  ||  /beta/3/30  ||  /gamma/1/13
OK   Countries         US/5         ||  DE/3        ||  JP/1
OK   Browsers          Chrome/5     ||  Firefox/3   ||  Safari/1
OK   Devices           desktop/5/56% || mobile/3/33% || tablet/1/11%
OK   Referrer Sources  news.ycombinator.com/5 || google.com/3 || Direct/1

No shift. Every panel holds its own dimension in the right order.

Matrix — 23/23

  • Ranges: today/7d/30d × authed dashboard, public dashboard, on-demand endpoint — 9/9
  • Filters: six segment filters individually plus all combined — 7/7
  • Auth & tenancy: authed endpoint without cookie → 302; another user against a private site → 404; public endpoint against a non-public site → 404; unknown site → 404
  • Empty states: all three branches correct on the authed dashboard

Checks specific to this change

  • Tag never reaches a user. Zero occurrences of beam:public/beam:app in the rendered HTML of the public dashboard, authed dashboard, on-demand endpoint, embed widget, /demo, and the landing page — confirmed in the DOM at runtime too, before and after loading the panel.
  • Tags reach the real SQL. Runtime guards confirm the public surface issues ≥4 beam:public statements and zero beam:app. Statically: 5 tagged statements per file, zero cross-contamination in either direction.
  • All 10 tagged statements execute — every range, filter and endpoint above returned 200 against real D1.

Browser, mobile, error path

Check Result
Click to load 3 rows, trigger removes itself
XSS through innerHTML 0 img, 0 script, 0 onerror — hostile value renders as inert text
Mobile 375px no overflow, 68px tap target, scroll container present
Forced 500 button re-enables, relabels "Could not load — retry", body not wiped
Retry after failure succeeds, loads 3 rows
Console 0 errors

Plus the original evidence: tag proven inert (identical result, byte-identical EXPLAIN QUERY PLAN), guards proven against a surgical tag removal on a still-typechecking build, 123 unit tests / 128 smoke green.

@scobb
scobb merged commit 7a1fd38 into main Sep 4, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant