Repository navigation
fix(reports): aggregate report sections in Postgres, and let a report survive a failed one - #762
Merged
Merged
Conversation
… 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.
7 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
Six cancellations, six
500s, and they map onto three sections:visibility_rate_trend,ai_visibility_aggregatesx2competitor_aggregates,ai_visibility_aggregatesai_visibility_aggregatesauthenticatedhas an 8sstatement_timeout. Those statements went past it — but they are not slow on their own. Measured on an idle database,ai_visibility_aggregatestakes 1.7s.The report was competing with itself. Three other sections computed their figures by paging every matching
prompt_resultsrow 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.allfinished 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.
citationscolumnBoth figures are
EXPLAIN ANALYZEagainst the brand this was reported on.A fourth section, found while this was in review
getFanoutSnapshotread 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 ownsource_platformwhen 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:
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
computeAiVisibilityScorefolds — 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_evidenceIt groups on the URL with the query string removed.
citation_urlskeeps?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 DEFINERbecausecitation_urlscarries RLS with no select policy, which is whycitations_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 fixMigration
00063_report_aggregate_rpcs.sql,00064_report_query_fanout_rpc.sqland00065_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.
Verification already done
postgres_logsandedge_logsrather than inferring it: sixcanceling statement due to statement timeoutentries matching six500s, and each mapped to its call site in the code.EXPLAIN ANALYZEon all five new functions against production data — the timings above.timesSearched: 2, while the new function returns 24, 19, 18, 17 for the same window.report_citation_evidenceexercised under a real JWT: returns rows for a member of the brand's org and zero rows for a user outside it.developers.google.comrows at 413/379/370 become one at 1,227.yarn typecheck,yarn lint(0 errors),yarn format:check,yarn test(90 passing) andyarn buildall pass fromweb/.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
feature/,fix/,chore/,docs/)yarn lintpasses (run fromweb/)yarn typecheckpasses (run fromweb/)yarn format:checkpasses (run fromweb/)