Repository navigation
perf(traffic): read the AI Traffic page's data side by side, behind one spinner - #1216
Conversation
…l Trend card AT-008 part A (spec §3.3): the trend card gets a "vs Google clicks" tab. It draws AI visits and Google organic clicks, each indexed to 100 on its first day with data, with markers on the days actions entered the Action Center or prompts were added. - 00180 ai_traffic_google_trend: Search Console clicks per UTC day, the first and latest day it has rows for the brand, and the markers. Security invoker; RLS decides the brand. - The Google line is blank (not 0) before Search Console's history and after Google's latest reported day, which the view names. - A range that starts mid-day leaves out its partial first day so it doesn't set a misleading 100. - The 24-hour range offers "Show last 7 days" (Google reports by day). - Without Search Console the view keeps the AI line and says what the Google line needs (§3.8b). The view shows the "Needs Google Search Console" tag. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ng clicks AT-008 part B (spec §3.6): a Google Search Console section with "Is AI taking Google clicks?" — pages whose impressions rose 15% or more while their CTR fell 20% or more against the period before, most clicks lost first. Each row's next step is the Positions panel of a tracked prompt about the page, or Add prompts when there is none. - 00181: gsc_page_stats (Search Console by page and day, member select policy) and ai_traffic_google_pages. The window keeps the range's length and ends on Google's latest reported day (§3.01). Pages need 100 impressions in the period before. When the page history doesn't reach back to that period, it says so rather than reading every page as rising. Security definer with an organization check (citations). - Server: the daily GSC sync also pulls pages. A brand's first page sync reads 190 days in 28-day steps, later ones the last 28, and the prune keeps 190 days. A failed page step leaves the query rows synced. - Web: the section with its connection states (§3.8b), the "Needed for" list, and the export sheet "Is AI taking Google clicks". Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd Track all AT-009 (spec §3.6): beside "Is AI taking Google clicks?", a card with the top Search Console queries by clicks that no tracked prompt covers. Track adds a query as a prompt; Track all adds the listed ones within the plan's prompt slots (PROMPT-012). The summary line states their number while Search Console is connected (§3.1, §3.8b rule 5). - 00182 ai_traffic_google_queries: queries with clicks between two days, most clicks first, ending on Google's latest reported day (§3.01). - Server: GET /api/prompts/untracked-queries/:brandId drops the queries an active prompt covers, by the rule Prompt Suggestions uses for Google queries, so the two pages agree. Prompts are tokenized once and read past the 1,000-row page. - Web: UntrackedQueriesCard, the summary line's count (counted again after tracking), the export sheet "Untracked Google queries" and the "Needed for" list. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…within a monthly cap AT-010 part A (spec §3.7, §6): the ingestion behind the AI bot report. - 00183: ai_bot_connections (one secret per sender, stored as its SHA-256, hidden from members), ai_bot_events (verified rows, 90 days), ai_bot_daily (bot x page x day counters), ai_bot_usage (per organization and month) and ai_bot_ingest, which stores rows while the month has room and always adds counters, locking the usage row so concurrent batches can't pass the cap. Pages are keyed like the Pages section's. - ai-bots.json: OpenAI, Anthropic and Perplexity's training crawlers, search crawlers and user fetchers. A request counts only when its user agent names one and its IP is in the operator's published ranges, read daily. No IP is kept. - POST /bots/ingest (public, by connection secret) and /api/bots/connections/:brandId (list with this month's use, create with the secret shown once and the Cloudflare Worker, revoke). Admins and managers only; Starter has the report locked. - Plan caps: Growth 2M stored events a month, Enterprise 20M (overridable), Starter 0, self-hosted no cap. Crossing 80% logs the internal alert once a month; past the cap only counters are written. - The daily run prunes rows past their retention. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…bot requests, within a raw cap AT-010 part B (spec §6.1 options B and C, §6.3): /bots/ingest reads the body by the connection's kind. - Cloudflare Logpush: gzipped NDJSON of the http_requests dataset (any timestamp format); the job's test upload reads as no requests. - Vercel drain: a JSON array or NDJSON of log entries; only those with a proxy object are requests, build and function output is skipped. - 00184: ai_bot_usage gains raw_records, and ai_bot_count_raw counts a log sender's batch under the usage row's lock. Batches are read while the month is under the plan's raw cap (Growth 20M, Enterprise 200M), only counted after. Verified events from a whole file are written in chunks of 500. - Creating a Logpush or Vercel connection returns what to copy: a Logpush job filtered at the edge to the bot list with the secret as a header, or a drain's endpoint, header and format. - The sender body is read raw before the app's JSON and form parsers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es strip AT-010 part C (spec §6.1, §6.4, §7): the sources strip's AI bots card opens a dialog to connect the brand's own Cloudflare Worker, Logpush job or Vercel drain. - The card is locked with Upgrade on a plan without the bot report (Starter), offers Connect, then waits for the first request, then shows the last one; Manage opens the same dialog. - The dialog says what each way costs on the customer's own Cloudflare or Vercel bill before connecting. After it, it shows the settings to copy (the Worker, a Logpush job, or a drain's endpoint and header), with the secret in them once. It lists connections with their last request, revokes one in two steps, and shows the month's use and when the cap paused detailed rows. - Server actions in lib/actions/ai-bots.ts and card state helpers in lib/ai-bots.ts. SourceCard moves to its own file. - The dialog's content can't widen past it: long code scrolls inside its box. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… search bot read Co-Authored-By: Claude Opus 5.5 <[email protected]>
…edirect to suggest Co-Authored-By: Claude Opus 5.5 <[email protected]>
… new platform, broken links, unread cited pages Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e and the top three changes Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ards, daily and platform bars Co-Authored-By: Claude Opus 5.5 <[email protected]>
main now has ansvisor#1176 (squash a98c35c, identical to this branch's 27f2ad2) and ansvisor#1193. The conflicts are the files ansvisor#1177 extends after ansvisor#1176: this branch's side kept; schema.sql rebuilt. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…raffic-untracked-queries main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193; merged through feature/traffic-google-pages, which carries it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ure/traffic-bot-ingest main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193; merged through feature/traffic-untracked-queries, which carries it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ffic-bot-logs main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193; merged through feature/traffic-bot-ingest, which carries it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…affic-bot-report main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193; merged through feature/traffic-bot-connect, which carries it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ffic-broken-links main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193; merged through feature/traffic-bot-report, which carries it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ic-bot-connect main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193; merged through feature/traffic-bot-logs, which carries it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…raffic-alerts main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193; merged through feature/traffic-broken-links, which carries it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-digest main now has ansvisor#1176 (squash, identical to the stack's first commit) and ansvisor#1193; merged through feature/traffic-alerts, which carries it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ap its counters Review of ansvisor#1179: - The endpoint written into a Worker, Logpush job or drain came from the request's Host. It now comes from PUBLIC_SERVER_URL (https; http only on localhost outside production), and no connection is made without it. - ai_bot_daily grew by about a row an event past the month's cap. Hits past it now go on one '(other)' row per bot and day, and /bots/ingest has a per-connection limit (600 a minute, keyed by the secret's hash). - Also: the Worker passes requests through on its own errors and sends the page without its query string, and ingest errors go to the app logger. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…backfill Review of ansvisor#1177: - ai_traffic_google_pages spent its time on normalize_page_path, twice a row (4 s warm, 18 s cold on 110k rows). gsc_page_stats now stores page_key as a generated column and the function groups by it; only the ranked rows work out their display path. Plus an index on date for the table-wide prune. - A first page sync cut short left 28 days of history for months. The sync now reads the 190 days until one gets through them all for the property (brands.gsc_pages_backfilled_property), and drops the old property's pages when it changes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of ansvisor#1180: - gunzipSync on up to 64 MB and a synchronous parse could hold up the API. Files are now inflated asynchronously to at most 16 MB, hold at most 20,000 lines (413 otherwise), and are parsed 1,000 lines at a time; the Logpush job we suggest sends at most 10,000 records a file. - A file retried after a timeout was counted twice. Each connection's files are claimed by the SHA-256 of their body (ai_bot_ingested_files, kept 7 days) and a resent one is answered without reading it; a read that fails gives its claim back. - Also: a line with an unreadable time is dropped, not the whole file. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…alert honest Review of ansvisor#1182: - Connecting from the report section lost the secret: the page's revision bump took the dialog down. It now keeps the connections it was opened with while the section reads again (with a test of the flow). - Stale bot data listed every cited page. ai_bot_report now gives the list only while a live connection sent within 2 days and no search hits went past the month's cap in the 30 days (alert_state 'on'); otherwise the section says the alert is paused. '(other)' rows aren't pages. - "All time" scanned every row: it covers the last 90 days here (labelled so), the first and last day come from the index's ends, the rows are added up once by bot and page, and the uncrawled check uses not exists. An export whose bot report fails keeps its other sheets. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ll address Review of ansvisor#1192: - Visits counted pageviews from before the page broke. They now count only 404, 410, or no status with a not-found title. - Pages that differ only by query string were merged, so a deleted /index.php?route=product&id=42 could suggest redirecting /index.php, the whole site. The status is decided per address (path plus query, utm_* left out), and a path is broken only when none of its addresses last answered 2xx or 3xx. - Also: the tab count comes with the Pages read (no broken-links pipeline on every load, and the card stays up if that list fails), and the column change gives up after 3 s instead of queueing beacon inserts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…second, let F02 run without Site Audit Review of ansvisor#1195: - analytics_days is a jsonb array of days, so Number() made it 0 and every alert said "from AI results". It's counted by length now, with fixtures of the real shape. - Midnight bounds with p_to_inclusive false put a boundary day's Analytics in both weeks. The weeks are read to their last second, inclusive. - cited_page_uncrawled couldn't become an action without Site Audit: F02 requires only tracking now; its audit tasks still need an audit and the planner drops them for a brand without one. - The uncrawled-page signal is raised only while the bot data is whole (ai_bot_report's alert_state 'on'). - Also: a new AI platform needs 3 visits and a source on the list, since the beacon is public. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… left unsent Review of ansvisor#1196: - Brands whose Daily Pulse is off got the digest. It's skipped for them (no settings row still gets it), and Settings shows it off with why. - The boundary Monday's Analytics counted in both weeks: the weeks are read to their last second, inclusive. - A week was lost to one failed Monday. The sweep runs Monday to Wednesday, retries a failing read, gives a week back when Resend refuses the e-mail, and takes over a claim older than an hour that never sent (ai_traffic_digests.sent_at). - Also: the brand list is paged past 1,000, a page or platform back after a quiet week isn't called "its first AI visit", and members get select on ai_traffic_digests. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # server/src/lib/bot-ingest.test.js # server/src/routes/bot-ingest.js # server/src/routes/bots.js
gkhngyk
left a comment
There was a problem hiding this comment.
The sections are wired right: every range-dependent part of the stack reports to the gate, the calls and auth are unchanged, and the double read on empty ranges is gone. One thing needs fixing before merge, plus a few smaller ones.
1. The page's own reads can land out of order (page.tsx loadSummary, loadLogs, and the effect that calls them).
- On main, Next ran the server actions one at a time, so their responses came back in the order they were sent. Through
/api/traffic/readthey now run in parallel, and neither loader checks that its response is still the latest. - Click 90d, then 24h within a second. The 24h reads land first and the gate settles. Then the 90d responses land and run
setSummary,setTrend,setLogs,setIsLoadingSummary(false)andsetSummaryRange. The KPIs, platform table, trend and visit list show 90d under "Last 24 Hours" until the next change. - The visit list has the same race. With the 300 ms debounce, "pri" then "pricing" sends two reads, and the broader one can land last.
- Fix: a request-id ref per loader (or a
cancelledflag in the effect, as the sections already have). Set state, including infinally, only for the latest request.
Smaller, here or as a quick follow-up:
settledKeyisn't cleared on a range change (_range-ready.tsx). The 24h/7d/30d/90d keys change every time, but All time ('|') and a repeated custom range don't. So All time → 7d → All time while 7d is loading shows the old All time state as settled at once, with 7d's data if it landed. A counter bumped on each range change avoids that.- One range change starts about 17 statements at once, and nothing aborts on a quick second click. Some are duplicates:
- SummaryLine's
getTrafficPages(..., { tab: 'citedNotClicked', limit: 0 })is the sameai_traffic_pagescall PagesCard makes, and that call returns every tab's count. - SummaryLine's untracked count repeats
_untracked-queries.tsx's call. getBotConnectionsandgetLocationQuotadon't depend on the range.- The effect reruns both loaders when either callback changes, so a visit-list page click re-reads the summary and trend too.
- Splitting the effect and dropping the duplicates keeps a big brand's
ai_traffic_pages(0.3–2 s on its own) away from the 8 s timeout under load.
- SummaryLine's
- The 20 s cap keeps every section blank while the slowest read runs. A cap near the statement timeout (8–10 s) would be enough.
- The early
return rangeSpinnerkeeps the sections unmounted until the summary returns, so the first open is still two rounds of reads. The gate already shows the spinner. - Nit: the description still says it is stacked on #1196, which is merged.
… once gkhngyk's review of ansvisor#1216: - The page's own reads run side by side now, so they could land out of order: 90d then 24h showed 90d's numbers under "Last 24 Hours", and the visit search's "pri" could land after "pricing". loadSummary and loadLogs keep only their latest request (useLatestRequest), and the effect is split so a visit-list page or filter reads only the list. - The range gate waits anew on every range change, so All time → 7d → All time no longer reads as settled at once; its cap is 10 s, about the reads' statement timeout. - No early spinner return: the gate shows the spinner and the sections, mounted behind it, read alongside the summary on the first open. - Fewer statements per range change: the summary line's Cited, not clicked and untracked-queries counts take the Pages card's and the Google section's reads (getTrafficPageCounts, getUntrackedQueryCount), and the bot connections and prompt quota are read only when they can change, not per range. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@gkhngyk Thanks. All of it is in 1. Out-of-order reads
Smaller ones
|
Resolves _bots-report.tsx against ansvisor#1224 and ansvisor#1225: the connections keep their own read, and they keep ansvisor#1225's lastInfo so a failed read after a create doesn't close the dialog and lose the new secret. ansvisor#1224's logsPausedUntil import stays. Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
gkhngyk
left a comment
There was a problem hiding this comment.
Thanks, the blocking point is fixed. loadSummary and loadLogs now set state only for their latest request, and the effect is split, so a visit-list page or filter no longer re-reads the summary. The smaller points are in too:
- the gate waits again on every range change, with a 10 s cap;
- the early spinner return is gone;
- the duplicate pages and untracked counts are shared;
- connections and quota are read only when they can change.
I pushed a merge commit that resolves _bots-report.tsx against #1224 and #1225:
- the connections keep their own read;
- they keep #1225's
lastInfo, so a failed read after a create doesn't take down the dialog and its one-time secret; - #1224's
logsPausednote stays.
Tested on top of #1224 and #1225: web 1,848 and server 1,908 tests pass, and tsc, lint and Prettier are clean.
Two small things, neither blocking:
- KPI cards still mount a round late. While
summaryis null,isEmptyis true, soTrafficKpisand itsSummaryLinemount only after the summary lands: on the first open, and when coming from a range with no visits. Their Google totals read starts then. If that is more than 5 s after the Pages card's read, the shared count has expired andai_traffic_pagesruns a second time. - Description: it still says the cap is 20 s.
Summary
The AI Traffic page is slow when the date range changes. This PR makes its reads run side by side, and shows only a spinner until the new range's data is in.
Why it was slow.
What changed.
POST /api/traffic/readruns one read by name (read,args) with the member's session, as the actions do, so RLS and the reports' org checks apply unchanged.lib/traffic-reads.tsexports the same function names with the same arguments; the sections only switch imports._range-ready.tsx).useRangeReady, whether it has its data for the current range (or has nothing to read).It covers the whole AI Traffic stack's sections (#1176–#1196, all merged); the branch sits on main.
Related issue
None. A user report ("AI Traffic is very slow when switching date ranges; show only a spinner until the data is in").
Type of change
feat— New featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
/dashboard/trafficand switch between 24h, 7d and 30d./api/traffic/readrequests start together rather than one after another.I checked this locally with timings (above), in light and dark themes, at 1440 and 1024 px. Charts draw correctly once shown.
Tests:
api/traffic/read/route.test.ts: dispatch, null → undefined arguments, unknown read, bad brand id, signed out, generic 500.lib/traffic-reads.test.ts: the POST, side-by-side requests, errors._range-ready.test.tsx: waits for all, a settled range stays shown, a new range waits again, the 20 s cap.@/lib/traffic-readsnow.Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromweb/)yarn typecheckpasses (run fromweb/)yarn format:checkpasses (run fromweb/)Also run:
yarn test(1,733 pass) andyarn build(with the CI placeholders).🤖 Generated with Claude Code