Skip to content

perf(insights): drop the full-table scan on load + use SQL limit/count (closes #313) - #352

Merged
gkhngyk merged 2 commits into
mainfrom
perf/insights-load
Jul 6, 2026
Merged

gkhngyk merged 2 commits into
mainfrom
perf/insights-load

Conversation

@gkhngyk

@gkhngyk gkhngyk commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Summary

Speeds up the first load of /dashboard/insights. The page fired five server actions through one client-side Promise.all; Next.js runs server actions sequentially (each is its own queued POST), so latency was ~their sum. One of them scanned the brand's entire prompt_results history, and getPromptResults over-fetched every matching row's heavy columns (full response text + JSON) just to slice/count in JS. (#313)

Changes

  • getPromptResults (web/src/lib/actions/tracking.ts) — now issues one query: SQL .range(offset, offset + limit - 1) for the page plus count: 'exact' for an accurate total, instead of materializing every matching row and slicing/counting in Node.
    • This also fixes a latent cap: the old fetch-all was bounded by Supabase's default (~1000 rows), so both the returned list and total were silently capped at ~1000. The range + count now return the true page (up to limit) and the true N — which is exactly what "Showing 1500 of N" should show.
  • getInsightsData(brandId, opts) (new) — runs summary + results + competitor + SoV in a real server-side Promise.all (genuinely parallel, one round trip) and derives "has any data" from a cheap count: 'exact', head: true instead of the old unbounded getPromptResults(..., { limit: 1 }) scan.
  • Insights page — the five-promise block is replaced by a single getInsightsData call.

Behavior-preserving

This is a performance refactor — the displayed rows, grouped table, and every number stay identical:

Related issue

Closes #313. (The optional "narrower select" from the issue — dropping heavy columns not shown in the row list — is intentionally left as a safe follow-up so this PR stays strictly behavior-preserving; the count + .range() already remove the unbounded scan and the over-fetch of all rows.)

Type of change

  • refactor — performance

How to test

  1. Open /dashboard/insights on a brand with a large history → first paint is noticeably faster; there is no select('*') over the whole history in the load path (the has-data check is a count … head: true).
  2. Every number matches the previous page (KPI strip, competitor, SoV, trend, and the expandable table's per-topic/prompt rollups) for the same filters.
  3. "Showing N of TOTAL" shows the correct TOTAL (now accurate past ~1000).
  4. Filters (date / model / region / topic) and empty states behave exactly as before.
  5. yarn typecheck, yarn lint, yarn format:check, yarn test pass from web/.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (from web/)
  • yarn typecheck passes (from web/)
  • yarn format:check passes (from web/)
  • Changes are focused — one concern per PR

The Insights page fired five server actions through one client-side
Promise.all; Next.js runs server actions sequentially (each is its own
POST), so the wait was ~their sum. One of them scanned the brand's entire
prompt_results history, and getPromptResults over-fetched every row's heavy
columns just to slice/count in JS. (#313)

- getPromptResults now issues one query: SQL `.range(offset, offset+limit)`
  for the page + `count: 'exact'` for an accurate total, instead of
  materializing every matching row and slicing/counting in Node. This also
  fixes a latent cap: the old fetch-all was bounded by Supabase's default
  ~1000 rows, so both the returned list and `total` were silently capped;
  the range + count return the true page (up to `limit`) and true N.
- New getInsightsData(brandId, opts): runs summary + results + competitor +
  SoV in a real server-side Promise.all (one round trip) and derives
  "has any data" from a cheap `count: 'exact', head: true` instead of the
  old unbounded `limit: 1` scan.
- Insights page calls the one consolidated action.

Behavior-preserving: same rows (newest first, same cap), same numbers, same
filters/empty states. buildResultsQuery's count is opt-in so exportPromptResults
is untouched. Also speeds up the topic detail page (#312), which shares
getPromptResults.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR improves first-load performance for /dashboard/insights by eliminating client-side server action serialization and removing an unbounded prompt_results scan from the load path. It also makes getPromptResults return an accurate total by using SQL pagination + count instead of fetching all matching rows and slicing/counting in JS.

Changes:

  • Updated getPromptResults to use .range(offset, offset + limit - 1) and count: 'exact' to page in SQL and return an accurate total (fixing the prior ~1000-row silent cap).
  • Added getInsightsData(brandId, opts) to consolidate the Insights page’s data fetch into a single server action with a real server-side Promise.all.
  • Updated the Insights page to call getInsightsData instead of firing multiple server actions from the client.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
web/src/lib/actions/tracking.ts Adds opt-in count support to the results query, implements SQL paging + count in getPromptResults, and introduces consolidated getInsightsData with a cheap existence count.
web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx Replaces multiple client-initiated server actions with a single consolidated getInsightsData call to avoid serialized server action latency.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread web/src/lib/actions/tracking.ts Outdated
Comment on lines +322 to +327
const { count } = await supabase
.from('prompt_results')
.select('*', { count: 'exact', head: true })
.eq('brand_id', brandId)
.neq('platform', 'chatgpt-shopping');
return count ?? 0;
…review)

getBrandResultsTotal swallowed a Supabase error and returned 0, which would
flip hasAnyData to false and show the empty state (and hide the failure).
Throw on error like the other queries in this file, and select `id` for the
head-only count instead of `*`.

Addresses the Copilot review on #352.
@gkhngyk
gkhngyk merged commit 6d817ba into main Jul 6, 2026
3 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.

perf(insights): drop the full-table scan on load + use SQL limit/count instead of fetching all rows

2 participants