Repository navigation
fix(db): split 00536 into a quick migration and a chunked backfill - #2352
Merged
Merged
Conversation
The first 00536 filled the new rollups from every brand's history in one statement each; on production it ran out of memory part-way and the database restarted. It was rolled back whole, so 00536 is rewritten: - 00536 creates the tables, the refresh changes and the reads, and fills nothing; it applies in well under a second. It is idempotent, so it also applies over the first version. - backfill_fast_rollups(brand, from, to) makes one brand's days match their sources (upsert, and stale rows deleted) under the refreshes' locks; server/src/scripts/backfill-fast-rollups.js calls it in chunks (--chunk-days, default 14), brand by brand, with a pause, resumable with --from-brand/--from-day, and --last-days for the final re-run. - topics_overview_window and mentions_perception_live read the new tables only for brands in fast_rollups_ready, which the backfill fills once a brand's whole history is in; every other brand reads as before. - 00537 builds the Perception term index after the backfill. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01SvzkMf5TZg7yqwaSeMFba9
gkhngyk
approved these changes
Nov 12, 2026
gkhngyk
left a comment
Contributor
There was a problem hiding this comment.
LGTM: 00536 now creates only, the reads stay on the old path until a brand is backfilled, and the backfill functions are server-only.
This was referenced Nov 13, 2026
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
#2345's migration 00536 also filled its three new rollups from every brand's history, with one statement per table. On production that ran for about 2 minutes. Then Postgres ran out of memory and restarted, refusing connections from 16:19 to 16:23 UTC. The migration rolled back whole.
mainalready lists the 00536 tables in the demo's table list, so the release is blocked until 00536 applies. 00536 never stayed on prod, so this PR rewrites it, as Gökhan asked:create table if not exists,create or replace). Applying the first 00536, then this one, then 00537 over the same database works, and the reads come out right afterwards.backfill_fast_rollups(p_brand_id, p_day_from, p_day_to, p_mark_ready default false)makes one brand's days in all three tables match their sources:on conflict do update … where … is distinct from, so a re-run writes nothing);server/src/scripts/backfill-fast-rollups.js; the logic is inserver/src/lib/fast-rollups-backfill.js, with unit tests. It goes brand by brand in day chunks:--chunk-dayssets the chunk size (default 14) and--pause-msthe pause between calls (default 250).--from-brand/--from-day. On a failure it prints both and exits 1.--dry-runprints the number of calls,--last-days Nruns the final re-run, and--brand IDruns one brand.fast_rollups_backfill_ranges()gives the brand list: each non-demo brand's first and last rollup day, found through(brand_id, day)indexes. It returns onejsonbvalue, so PostgREST's row cap can't truncate it.fast_rollups_ready(brand_id pk, ready_at), is server-only, with RLS on.topics_overview_windowandmentions_perception_liveread the new tables only for brands listed there. Every other brand runs the pre-00536 read path. The choice is made on each call, andforce_custom_planlets the planner drop the unused branch.--brand.mentions_terms_daily_allterm index after the backfill. Without the index the reads are correct, just a little slower (see the table below).--last-days 3for every brand, ready or not. That run lists no brand as ready, and it is idempotent.Also:
mentions_perception_liveruns withjit = off, as in fix(db): faster topics_overview_window and mentions_perception_live (00536) #2345. This changes speed only, not results, and helps brands that aren't ready too.fast_rollups_backfill_ranges()leaves outis_demobrands, so the demo brand is never listed as ready.fast_rollups_readygets aSKIPPEDentry inserver/src/lib/demo/coverage.js; no demo code changes.brand-access-policieslistsfast_rollups_readyas server-only.Results stay identical
I kept copies of the pre-00536 read functions beside the new ones and compared them on the fixture: local Postgres 16 with migrations up to 00535, one brand with 200 prompts, 6 engines, 10 competitors and 200 days of data (216k / 647k / 1.5M source rows).
Every comparison was identical (row sets, or
jsonbequality).Backfill on the fixture
--last-days 3brought all three tables back to 0 mismatches against a fresh aggregate of their sources. Nightly refreshes with the new definitions over the last 3 days: 0 mismatches.work_mem4 MB,log_temp_files = 0).mentions_terms_daily_all(1.5M source rows) peaked at 15 MB here, also with no temp files, so I can't confirm the grouping as the cause.Read times on the fixture
Warm cache, best of 5, in ms:
topics_overview_window30dtopics_overview_window90dmentions_perception_live30dmentions_perception_live90dRelated issue
Follow-up to #2345 (00536): the production apply ran out of memory and was rolled back.
Type of change
feat— New featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsNeeds migration on prod: 00536, then 00537 — runbook
When to run it: outside the nightly refresh window. Each backfill chunk takes the brand's refresh locks, so a refresh and a chunk for the same brand wait for each other. Both stay correct; they just run slower.
What you need:
$DATABASE_URL: the prod connection string, forpsql.mainafter this PR merges, withserver/dependencies installed, and prod'sSUPABASE_URLandSUPABASE_SERVICE_ROLE_KEYset in the environment or inserver/.env.1. Apply 00536 (estimate: under a minute). Apply it the way you applied 00536 this morning, for example with psql:
brands, blocking writes to it until the transaction commits (under a second).brands, instead of queueing everybrandswrite behind it. If it fails, re-run it.2. Backfill (estimate: 10–30 min; see below):
[i/N] <brand> <from>..<to> <ms> ms · rows written: …. A brand's last line ends with· ready.Resume with: --from-brand <id> --from-day <day>. Run it again with those flags.--chunk-days 7.3. Apply 00537 (estimate: under a minute):
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f supabase/migrations/00537_perception_term_index.sqlA plain index build blocks writes to
mentions_terms_daily_all(the Perception refresh) while it runs. You may prefer to build the index concurrently by hand first, in which case 00537 then does nothing:If the check prints
f, the concurrent build failed. Drop the index and build it again:if not existswould keep the invalid one.4. Re-run the last 3 days of every brand (estimate: a few minutes at most):
5. Vacuum (estimate: under a minute):
Check:
Rollback, at any point:
delete from public.fast_rollups_ready;sends every brand back to the old reads at once. Addwhere brand_id = '…'to do it for one brand. Nothing else depends on the list, and the refreshes keep the new tables current either way.How long, on prod-sized data. These are estimates, extrapolated from the fixture, not measured on prod.
mentions_terms_dailyhas about 5.5M rows, roughly 3.7× the fixture's.--pause-ms 100cuts this.Environments that applied the first 00536 (staging or dev databases, if any): their migration history already records 00536, so tooling won't run the new file. Apply it once by hand, as in step 1, then run steps 2–5. Their tables are already full, so step 2 only checks each day and lists the brands as ready.
Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromweb/): no web files changedyarn typecheckpasses (run fromweb/): no web files changedyarn format:checkpasses (run fromweb/): no web files changedhelp/(or no user-visible change) — see help/README.mdChecks run:
supabase/build-schema.sh:schema.sqlregenerated (424 migration files).schema.sql, includingbrand-access-functions.test.ts.brand-access-policiesanddemo/coverage;lib/healthandlib/demo;insights-rollupsandmentions-rollups;fast-rollups-backfill.test.js.rpc;Generated by Claude Code