Skip to content

fix(reports): aggregate report sections in Postgres, and let a report survive a failed one - #762

Merged
gkhngyk merged 1 commit into
mainfrom
fix/report-generation-scale
Aug 21, 2026
Merged

gkhngyk merged 1 commit into
mainfrom
fix/report-generation-scale

Conversation

@gkhngyk

@gkhngyk gkhngyk commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Generating a report with most sections selected produced nothing at all — no report row, just a generic failure toast.

The database logs name the cause exactly. Nine seconds into a run, six statements were cancelled at once:

10:39:49  generation starts
10:39:58  canceling statement due to statement timeout  (x6)

Six cancellations, six 500s, and they map onto three sections:

Section Statement
Trend visibility_rate_trend, ai_visibility_aggregates x2
Competitors competitor_aggregates, ai_visibility_aggregates
KPIs ai_visibility_aggregates

authenticated has an 8s statement_timeout. Those statements went past it — but they are not slow on their own. Measured on an idle database, ai_visibility_aggregates takes 1.7s.

The report was competing with itself. Three other sections computed their figures by paging every matching prompt_results row into Node: dozens of sequential round trips each, running at the same time as the aggregates, against the same tables. The aggregate statements were the victims; the row scans were most of the cause.

Promise.all finished the job: one rejection discarded the sections that had succeeded.

What changed

The three scans aggregate in SQL

They now return one row per prompt, per topic and per cited URL instead of one per answer.

Section Before After
Prompt performance 12,370 rows downloaded 308 rows, 53 ms
Topic performance ~51,000 rows over a 60-day span 17 rows, 501 ms
Citation evidence every row's citations column 10 rows

Both figures are EXPLAIN ANALYZE against the brand this was reported on.

A fourth section, found while this was in review

getFanoutSnapshot read its window the same way, and worse: no .range(), no pagination, and no .order() either, so the 1000 rows PostgREST returns were not even a defined slice.

The effect was visible in a real report. Every one of its ten fan-out entries came out at timesSearched: 2, listed alphabetically because the counts were all tied — the signature of ranking inside an arbitrary twelfth of the data. The genuine top query had been searched 24 times and was absent from the list entirely.

Now aggregated in SQL like the other three (00064), 220ms for that window, with the same counting rules: a sub-query counts once per answer however often that answer repeats it, and an engine is the item's own source_platform when it has one, otherwise the answer's platform.

Fixing the rows did not change which engines appear, and that turned out to matter more than the truncation. Ranking by how many answers ran the identical string favours engines that reuse their phrasing:

Engine Distinct sub-queries Answers Top repeat
ChatGPT 3,341 1,286 9
Perplexity 952 1,857 16
Copilot 782 2,038 18

ChatGPT fans out the most and reaches the top ten least, because it rephrases every time. Read on its own the table says ChatGPT does not fan out; it fans out more than the other two combined.

So each engine now carries its distinct sub-query count and the answers those came from, above the table (00065). Variety and volume point in opposite directions here — Copilot fans out on more answers, ChatGPT with more different queries — which one number could not have shown.

The ranking itself is untouched. Whether the top ten should be picked per engine is a larger question about what the section is for, and is deliberately left open.

A ceiling that was quietly truncating monthly reports

The scans stopped at 50,000 rows. Topic performance reads twice the report window to compute its delta, so a 30-day report already spans 60 days — past the ceiling on this brand, and growing daily. Its figures were computed from a truncated window with nothing saying so. Aggregating in SQL removes the ceiling rather than raising it.

The scoring stays in TypeScript

The functions return the raw counts and sums that computeAiVisibilityScore folds — not finished scores. The blend is shared with the Prompts and Topics pages; a second copy in SQL would be a second thing to keep in step, and the first divergence would show up as a report disagreeing with the page it came from.

One failed section no longer costs the whole report

Gathering runs in two waves, aggregates first, and a section that throws is recorded instead of propagating. The page names what is missing, so an absent section cannot be read as a brand with no data.

The AI summary degrades the same way. Prose is the one part of a report a reader can do without; losing the figures with it was never the right trade.

On report_citation_evidence

It groups on the URL with the query string removed. citation_urls keeps ?utm_source= and friends as separate rows, so grouping on it directly listed the same article three times — the section's own normalization, now in SQL.

It is SECURITY DEFINER because citation_urls carries RLS with no select policy, which is why citations_urls (00061) is defined that way too. Unlike those, this one checks that the caller belongs to the brand's org rather than trusting the brand id it was handed.

Related issue

None — reported directly from testing.

Type of change

  • fix — Bug fix

Migration

00063_report_aggregate_rpcs.sql, 00064_report_query_fanout_rpc.sql and 00065_report_query_fanout_engines.sql. All three already applied to the hosted database. Unlike a policy change, this one is additive — three new functions nothing referenced yet — so applying it before the code that calls it is the safe order, not the risky one.

How to test

Needs a brand with enough data to have failed before — several thousand answers in the window.

  1. Generate a report with every section selected over 7 days. Expected: it generates. Previously nothing was saved.
  2. Same with 30 days, and with 90 days. Expected: all generate, and the topic figures now cover the whole window rather than the first 50,000 rows of it.
  3. Compare a generated report's Prompts and Topics sections against the Prompts and Topics pages for the same range. Expected: the same scores — the blend did not move.
  4. Check the Citation Evidence list. Expected: one entry per page, not one per tracking-parameter variant.
  5. Check the Query Fan-out section. Expected: counts well above 2 and a list that is not alphabetical, and a per-engine coverage line above the table naming every engine that fanned out — including ones absent from the table itself.
  6. Generate with only the Weekly Visibility defaults. Expected: unchanged.

Verification already done

  • Read the failure out of postgres_logs and edge_logs rather than inferring it: six canceling statement due to statement timeout entries matching six 500s, and each mapped to its call site in the code.
  • EXPLAIN ANALYZE on all five new functions against production data — the timings above.
  • Fan-out checked against the report that surfaced it: the stored payload's ten entries all read timesSearched: 2, while the new function returns 24, 19, 18, 17 for the same window.
  • report_citation_evidence exercised under a real JWT: returns rows for a member of the brand's org and zero rows for a user outside it.
  • Confirmed the URL grouping merges variants: three developers.google.com rows at 413/379/370 become one at 1,227.
  • yarn typecheck, yarn lint (0 errors), yarn format:check, yarn test (90 passing) and yarn build all pass from web/.

Not covered by tests. This repo has no test harness that can reach a server action or a Postgres function, so the checks above are manual. The section-failure path in particular has no automated proof — steps 1 and 2 are what confirm it.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/)
  • 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

… survive a failed one

Generating a report with most sections selected produced nothing at all. Three
sections computed their figures by paging every matching prompt_results row
into Node -- on a brand with ~12k answers a week that is dozens of sequential
round trips each, issued while every other section queries the same tables.
The aggregate RPCs behind KPIs, Trend and Competitors then ran past the 8s
statement_timeout of the authenticated role and returned 500. Six statements
cancelled, six sections gone, and Promise.all turned that into no report.

Those three scans now aggregate in SQL and return one row per prompt, per
topic and per cited URL instead of one per answer. On the brand this was
reported against, prompt performance drops from 12,370 rows downloaded to 308
rows in 53ms, and topic performance from a 60-day span of roughly 51,000 rows
to 17 rows in half a second.

That span mattered for more than speed. The scans stopped at 50,000 rows, so a
30-day report -- which reads 60 days for the topic delta -- was already past
the ceiling and computed its figures from a truncated window without saying so.

The scoring blend stays in TypeScript. The functions return the raw counts and
sums the existing computeAiVisibilityScore folds, so a prompt or topic still
reads the same in a report as it does on its own page, and there is no second
copy of the formula to keep in step.

Gathering is now in two waves, aggregates first, and a section that fails is
recorded rather than thrown. Losing one module is a gap the reader can see;
losing all fourteen because the last one timed out is a report that never
existed. The page names what is missing so an absent section cannot be
mistaken for a brand with no data. The AI summary degrades the same way: prose
is the one part a reader can do without.

report_citation_evidence groups on the URL with its query string removed. The
shared citation_urls table keeps ?utm_source= and friends as separate rows, so
grouping on it directly listed the same article three times. It also checks
that the caller belongs to the brand's org, which the citations functions it
borrows its SECURITY DEFINER from do not.
@gkhngyk gkhngyk added bug Something isn't working needs-migration Adds or edits a migration — apply it to the hosted database labels Aug 21, 2026
@gkhngyk
gkhngyk merged commit b2068a1 into main Aug 21, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working 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.

1 participant