Repository navigation
Description
Problem
The daily rollup tables behind Insights and Citations are written by two SQL functions:
refresh_insights_dailywrites theinsights_*_dailytables (00098).refresh_citations_dailywrites thecitation_*_dailytables (00118).
Each one deletes a brand's rows for a day range, then recomputes and inserts them. The tables have no unique key, and nothing stops two refreshes of the same brand and days from running at once. Several callers can overlap:
- a completed run refreshes the run's days (
refreshForCompletedRun); - the nightly sweep refreshes the trailing days of every brand (
sweepInsightsRollups), while that night's runs are completing; - a topic move rebuilds the brand's whole citation history (
rebuildQueuedCitationRollups), which perf(citations): rebuild citation rollups shortly after a topic move #1006 schedules every 5 minutes.
When two refreshes of the same brand overlap, the second one's DELETE waits for the first to commit. Its snapshot was taken before the first one's INSERT, though, so it skips the rows the first one just wrote. It then inserts its own rows. The overlapping days end up with two copies of every row, and the pages show doubled counts for those days until the next refresh of that range.
No duplicates exist in production today, and the next refresh repairs them, so this is a narrow race rather than an observed failure.
Proposal
Take a transaction-scoped advisory lock per brand at the start of both functions, before the deletes. For example:
perform pg_advisory_xact_lock(hashtextextended('refresh_citations_daily:' || p_brand_id::text, 0));A second refresh of the same brand then waits until the first one commits. Its DELETE sees the first one's rows and removes them. Refreshes of different brands still run in parallel. Each function gets its own key, since they write different tables.
Acceptance criteria
- Both refresh functions take a per-brand lock before deleting, in a new migration, with
supabase/schema.sqlregenerated. - Two concurrent refreshes of the same brand and days leave one copy of each row. For example, run the function from two sessions at once, then check that this returns nothing:
select brand_id, day, count(*) from citation_result_daily group by brand_id, day, model_used, platform, region, topic_id having count(*) > 1;
- A refresh that waits behind a full-history chunk stays within the service role's statement timeout.
Activity
perf(insights): serve topic-filtered reads from prompt-grain rollups
perf(insights): serve topic-filtered reads from prompt-grain rollups (#…
fix(mentions): refresh the Mentions rollups one at a time, and rebuil…
fix(rollups): serialize concurrent refreshes of a brand's citation ro…
fix(rollups): serialize concurrent refreshes of a brand's citation ro…