Skip to content

perf(citations): aggregate the overview in Postgres instead of downloading it - #744

Merged
gkhngyk merged 1 commit into
mainfrom
feature/732-citations-phase2
Aug 20, 2026
Merged

gkhngyk merged 1 commit into
mainfrom
feature/732-citations-phase2

Conversation

@gkhngyk

@gkhngyk gkhngyk commented Aug 20, 2026

Copy link
Copy Markdown
Contributor

Summary

Phase 2 of #732. Phase 1 wrote every citation as a row; nothing read them until now.

The page paged raw answers out to the app tier and expanded prompt_results.citations there: 50 sequential requests carrying 65 MB of jsonb on the largest brand, with a hard 50,000-row ceiling that silently truncated that brand at its 51,679. Three functions replace the scan, called in parallel.

Measured

Largest brand, full history, warm:

Before After
Domains — 4.6s
URLs — 1.8s
Window stats — ~60ms
Wall clock (parallel) 4.6–9.9s of DB time across 50 requests ~4.6s, one round trip
Payload 65 MB ~1.5 MB
Truncation silent, at 50,000 rows none

Most brands are far below this — it is the largest by an order of magnitude.

Three functions, not one

Combining them is slower. A single function needs one CTE feeding several aggregations, and Postgres materializes a CTE referenced more than once; spilling 744,302 rows carrying domain text costs more than scanning twice. Two attempts at the combined shape both exceeded the statement timeout before this landed.

Each aggregation is two-level on purpose. count(distinct prompt_result_id) in one pass makes the planner sort 744,302 rows; grouping to (key, answer) pairs first lets it hash both levels — 1.75s against 2.36s. work_mem is raised per function because the instance default of 3.5 MB spills grouping that needs about 60 MB, which doubles the time again.

Domains uncapped, URLs capped

Domains: all 20,366. The tail cited once is exactly what the page is for.

URLs: 2,000. There are 117,316 in that window — 25 MB of payload for a table that shows a hundred at a time. Every row carries total_urls, the uncapped count, so the surface can report what it is not showing rather than implying it has everything.

What stays in JavaScript

Classification. Whether a domain belongs to this brand or to a competitor depends on the brand's own domain list, which the database has no reason to know. It now runs over ~20,000 aggregated domains instead of two million citations.

Applying the scope filters after the rollup is exact, not approximate: a category is a property of the domain, so filtering before or after the grouping gives identical counts.

Verified against the old path

Not mocked. Run against a mid-sized brand, both implementations:

RPC Old jsonb scan
Domains 717 717
Citations 118,753 118,753

Exact match.

articleTypes on the domain row is now []. It was computed on every load and rendered nowhere — the only surface that shows an article type is the URL detail page, which computes its own.

Related issue

Closes #732

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

The three functions are already applied to the hosted database — they had to be, to measure any of the above. This PR carries the migration file so the repo matches; it is create or replace, so applying it again is a no-op.

  1. Open Citations for the largest brand on all and confirm it loads in a few seconds rather than tens, in one request rather than fifty.
  2. Compare the domain table against production before this change — counts, ordering and percentages should match.
  3. Confirm the totals no longer stop at 50,000 for that brand.
  4. Exercise each filter — date preset, platform, region, topic, prompt — and confirm the numbers move as before.
  5. Exercise the three source-scope toggles and confirm they filter without changing the underlying counts.
  6. Confirm the URL tab shows the top 2,000 and reports the true total.

Checklist

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

yarn build passes. supabase/schema.sql regenerated. web/src/types/supabase.ts gains the three function signatures.

…ading it

Phase 2 of #732. Phase 1 wrote every citation as a row; nothing read them
until now.

The page paged raw answers out to the app tier and expanded
prompt_results.citations here: 50 sequential requests carrying 65 MB of jsonb
on the largest brand, with a hard 50,000-row ceiling that silently truncated
that brand at its 51,679. Three functions replace the scan, called in
parallel — domains, URLs, and the window's answer count.

Three rather than one because combining them is slower, not faster. A single
function needs one CTE feeding several aggregations, and Postgres materializes
a CTE referenced more than once: spilling 744,302 rows carrying domain text
costs more than scanning twice. Two attempts at the combined shape both
exceeded the statement timeout before this landed.

Each aggregation is two-level on purpose. count(distinct prompt_result_id) in
one pass makes the planner sort 744,302 rows; grouping to (key, answer) pairs
first lets it hash both levels — 1.75s against 2.36s on the largest brand.
work_mem is raised per function because the instance default of 3.5 MB spills
grouping that needs about 60 MB, which doubles the time again.

Domains are returned uncapped: 20,366 on that brand, and the tail cited once
is exactly what the page is for. URLs are capped at 2,000 — there are 117,316
of them, 25 MB of payload for a table that shows a hundred at a time — and
every row carries the uncapped total so the surface can say what it is not
showing rather than implying it has everything.

Classification stays in JavaScript because it is the half the database cannot
know: whether a domain belongs to this brand or a competitor depends on the
brand's own domain list. It now runs over ~20,000 aggregated domains instead
of two million citations. Applying the scope filters after the rollup is exact
rather than approximate — a category is a property of the domain, so filtering
before or after the grouping gives identical counts.

Verified against the old path on a mid-sized brand: 717 domains and 118,753
citations from both, exactly.

Closes #732
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Aug 20, 2026
@gkhngyk
gkhngyk merged commit 4a0f51c into main Aug 20, 2026
6 checks passed
@gkhngyk
gkhngyk deleted the feature/732-citations-phase2 branch August 20, 2026 06:44
gkhngyk added a commit that referenced this pull request Aug 27, 2026
…it (#791)

The URL tab under-reported whenever a source scope was selected. Two
changes that are each right on their own combined badly: #744 caps the
list at the top 2,000 by citation count, and #742 then applied the scope
on the client, over the rows that arrived. So the scope filtered within
the global top 2,000.

Measured on the largest brand, a 30-day window:

  scope          shown   actually exist
  Brand             21              395
  Competitors      125            2,794

And it was silent — the pager counts what it filtered, so the tab read
"125 of 125". A reader could not tell "this brand has 125 competitor
URLs" from "125 of them ranked in the global top two thousand".

citations_urls now takes the domains a scope resolves to and cuts the
set before the limit; total_urls counts the scoped set, so the tab
reports the scope rather than the cap. The three scopes now partition
the window exactly: 395 + 2,794 + 94,131 = 97,320.

What a brand or competitor domain *is* stays in TypeScript. The caller
already runs classifyDomain over every aggregated domain to build the
Domains tab, and the resolver reads that result, so the rule keeps one
definition instead of gaining a second one in SQL.

Two parameters rather than one, departing from the issue's sketch:
resolving every scope to an include list would send 17,532 domains for
Third-party — the whole cited set minus fourteen. Naming the fourteen to
exclude says the same thing in a request that fits in a packet.

The filter sits after the aggregate, and that placement is load-bearing.
Pushed into the citation scan the planner abandons the hash join for a
nested loop: 4.57s against a 1.67s unscoped baseline, close to the 8s
statement timeout on a warm cache. Applied to the aggregated rows it is
a hash semi-join costing 11ms, and every scope lands within noise of the
unscoped query.

Selecting a scope now refetches the overview, since the scope has to be
known before the query runs. The unscoped view every page open starts on
keeps its three queries in flight, so the default load is unchanged.

The Domains tab is untouched: domains come back uncapped, so filtering
them client-side is exact.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Citations: store each citation as a row instead of expanding jsonb on every page load

1 participant