Skip to content

fix(rollups): serialize concurrent refreshes of a brand's citation rollups - #1131

Merged
gkhngyk merged 2 commits into
ansvisor:mainfrom
shahzainshafique:fix/rollups-serialize-concurrent-refresh
Oct 20, 2026
Merged

gkhngyk merged 2 commits into
ansvisor:mainfrom
shahzainshafique:fix/rollups-serialize-concurrent-refresh

Conversation

@shahzainshafique

Copy link
Copy Markdown
Contributor

Summary

refresh_insights_daily and refresh_citations_daily delete a brand's rollup rows for a day range and reinsert them, on tables with no unique key. When two refreshes of the same brand and days overlap (a completed run, the nightly sweep and the topic-move rebuild can all fire together), the second one's DELETE waits for the first to commit, but its snapshot predates the first one's INSERT. It skips those rows and adds its own, so every overlapping row ends up twice.

New migration 00156_serialize_rollup_refreshes.sql takes a transaction-scoped advisory lock per brand at the start of both functions, before the deletes, as proposed in the issue:

perform pg_advisory_xact_lock(hashtextextended('refresh_citations_daily:' || p_brand_id::text, 0));

Each function has its own key, since they write different tables. A second refresh of the same brand now waits, then deletes the first one's rows. Refreshes of different brands still run in parallel. The function bodies are 00131's and 00118's unchanged apart from the lock; I generated them by copying the originals and diffed them to confirm. schema.sql is regenerated (+240, purely additive).

Statement timeout: the lock lasts one call. refreshCitationHistory rebuilds a brand in HISTORY_CHUNK_DAYS (14-day) calls, each its own transaction, so a refresh queued behind a rebuild waits for one chunk, not the whole history, and stays inside the service role's 120 s statement_timeout (00100).

Verification (local Supabase, demo seed brand)

Two sessions refresh the same brand and days at once. Session A refreshes and then holds its transaction open for 4 s; session B starts 1 s in.

Session B Rows Duplicated groups
Before refresh_citations_daily 3242 ms 284 142 (every row twice)
Before refresh_insights_daily 3338 ms 266 133
After refresh_citations_daily 3269 ms 142 0
After refresh_insights_daily 3317 ms 133 0
  • The issue's acceptance query (… group by brand_id, day, model_used, platform, region, topic_id having count(*) > 1) returns nothing after the migration.
  • Different brands don't serialize: with A holding brand X's lock, B's refresh of another brand finished in 373 ms, without waiting.

Related issue

Closes #1020

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

Checklist

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

Note: 00156 is the next free number on main as of this branch. If another open PR lands a migration first, I'm happy to renumber.

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 17, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks, the lock and the two-session check are what the issue asked for. Main has moved since this branch, so three changes before it can land:

  1. Migration number. 00156–00163 are taken on main now. Please rename the file to 00164_serialize_rollup_refreshes.sql and regenerate schema.sql with supabase/build-schema.sh.
  2. refresh_insights_daily body. 00162 redefined it. Its inserts now find the answers by pr.created_at >= v_from and pr.created_at < v_to instead of (pr.created_at at time zone 'utc')::date between ..., so they read the range through (brand_id, created_at) (12 s → 0.66 s for one day of the largest brand). As written, this migration copies 00131's body and would undo that. Please start from 00162's body (with its declare block) and add the lock there.
  3. refresh_mentions_daily. 00157 added a third function with the same pattern: it deletes and reinserts mentions_prompt_daily and mentions_competitor_daily, which have no unique key, from the same callers (a completed run and the nightly sweep). Please give it its own lock key in the same migration.

refresh_citations_daily matches 00118, which is still current.

@gkhngyk

gkhngyk commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Update to my review: #867 just landed as 00164_insights_topic_rollups.sql, and it already gives refresh_insights_daily a per-brand lock (hashtextextended('refresh_insights_daily:' || p_brand_id::text, 0), on 00162's body). That makes this one smaller:

  1. Use 00165 for the migration.
  2. Leave refresh_insights_daily out; it's covered.
  3. Keep refresh_citations_daily (00118's body plus the lock, as you have it) and add the same lock to refresh_mentions_daily (00157's body).

@gkhngyk

gkhngyk commented Oct 18, 2026

Copy link
Copy Markdown
Contributor

Correction on the migration number: 00165–00169 have landed since my last note, so please take the next free number when you rebase (00170 as of now). The rest stands: leave refresh_insights_daily out, lock refresh_citations_daily and refresh_mentions_daily.

@gkhngyk

gkhngyk commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

@shahzainshafique Before this can merge, the migration needs to shrink. Main has moved on under it:

  • refresh_insights_daily would go back to an old body. It is the 00131 version, which filters by (created_at at time zone 'utc')::date between …. Applied today, it would undo two later migrations:
    • 00162, which replaced that filter with an indexed range lookup (the old one took 12 s cold on our largest brand);
    • 00164, which fills new rollup columns.
  • That function is already serialized. 00164 takes the same advisory lock, with the same key.
  • The number is taken. 00156_topics_overview_window.sql exists, and open PRs claim 00188–00197.

What's still new here is the lock on refresh_citations_daily. Please cut the migration down to that function alone, starting from its current definition on main (00118's body plus the lock), and rename it 00198_serialize_citation_refreshes.sql. Then rebuild supabase/schema.sql with bash supabase/build-schema.sh.

#1227 does the same for the Mentions rollups and adds a dedup with unique keys. Copying that pattern for citation_*_daily would close #1020's acceptance query for citations too.

…llups

refresh_citations_daily (00118) deletes a brand's citation_*_daily rows for
a day range and inserts them again, with no lock and no unique key. A run's
refresh, the nightly sweep and the topic-move rebuild can overlap on the
same brand: the second refresh's delete waits for the first to commit, but
its snapshot predates the first one's insert, so the days they share end up
counted twice.

As 00164 did for refresh_insights_daily and 00192 for
refresh_mentions_daily: take a per-brand advisory lock before the deletes,
drop rows written twice, and add nulls-not-distinct unique keys on
citation_result_daily, citation_domain_daily and citation_url_daily so a
second copy is impossible. The body is 00118's unchanged apart from the
lock; schema.sql rebuilt.

Closes ansvisor#1020
@shahzainshafique
shahzainshafique force-pushed the fix/rollups-serialize-concurrent-refresh branch from 7e7609c to c5a5a32 Compare October 20, 2026 10:06
@shahzainshafique shahzainshafique changed the title fix(rollups): serialize concurrent refreshes of a brand's daily rollups fix(rollups): serialize concurrent refreshes of a brand's citation rollups Oct 20, 2026
@shahzainshafique

Copy link
Copy Markdown
Contributor Author

Hi @gkhngyk,

Thanks for the follow-ups. I have rebased onto current main and cut it down as you described. 00198_serialize_citation_refreshes.sql now only touches refresh_citations_daily (00118’s body plus the per-brand lock); insights and mentions are left to 00164/00192. I also followed 00192’s pattern for the citation tables: rows written twice are dropped and nulls not distinct unique keys on all three citation_*_daily tables make a second copy impossible. schema.sql rebuilt.

Re-ran the two-session check locally: with 00118, overlapping refreshes left 142 duplicated groups in citation_result_daily; with 00198, zero, and the issue’s acceptance query returns nothing. Duplicate domain/URL rows with null keys are removed (highest copy kept) and a new null-key duplicate is rejected by the unique key. A refresh of a different brand doesn’t wait on the lock.

00198 went to the webhook event subscriptions (ansvisor#1239), so this
migration moves to 00199. schema.sql is rebuilt with build-schema.sh.

Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks, this is the right size now. The function body is 00118's plus the lock, and the dedup and unique keys follow 00192.

00198 went to #1239 a few minutes before this, so I pushed a merge commit that renames the migration to 00199_serialize_citation_refreshes.sql and rebuilds schema.sql. Before applying it to production I checked three things:

  • the three citation tables had no duplicate groups;
  • no citation row has a different day than its answer, so the delete and insert ranges always match;
  • each statement fits the timeout.

00199 is applied: the lock is in place, all three unique keys are valid, and the row counts are unchanged. Tested with #1239–#1242: server 1,897 and web 1,796 tests pass.

@gkhngyk
gkhngyk merged commit 8ee1044 into ansvisor:main Oct 20, 2026
5 checks passed
cihan-gyk added a commit to cihan-gyk/ansvisor that referenced this pull request Oct 20, 2026
… to 00200

main now has 00198 (ansvisor#1239) and 00199 (ansvisor#1131), so the soft-404 migration
moves from 00198 to 00200, with the comments that name it, and
schema.sql is rebuilt from the migrations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

fix(rollups): serialize concurrent refreshes of a brand's daily rollups

2 participants