Skip to content

fix(db): split 00536 into a quick migration and a chunked backfill - #2352

Merged
gkhngyk merged 1 commit into
ansvisor:mainfrom
cihan-gyk:fix/split-00536-backfill
Nov 12, 2026
Merged

gkhngyk merged 1 commit into
ansvisor:mainfrom
cihan-gyk:fix/split-00536-backfill

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

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.

main already 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:

  1. 00536 fills nothing. It holds the tables, the refresh changes, the two reads and the backfill functions. The nightly refreshes write the new tables for every brand from the moment it applies.
    • It applies in 0.09 s on the fixture.
    • Everything in it is idempotent (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.
  2. Chunked, re-runnable backfill.
    • 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:
      • it inserts what's missing;
      • it updates what changed (on conflict do update … where … is distinct from, so a re-run writes nothing);
      • it deletes rows whose source row is gone.
    • It first takes both refreshes' advisory locks for the brand, so a nightly refresh runs before or after a chunk, never across one.
    • The driver is server/src/scripts/backfill-fast-rollups.js; the logic is in server/src/lib/fast-rollups-backfill.js, with unit tests. It goes brand by brand in day chunks:
      • --chunk-days sets the chunk size (default 14) and --pause-ms the pause between calls (default 250).
      • It prints each chunk's time and rows.
      • It resumes with --from-brand / --from-day. On a failure it prints both and exits 1.
      • --dry-run prints the number of calls, --last-days N runs the final re-run, and --brand ID runs 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 one jsonb value, so PostgREST's row cap can't truncate it.
  3. Reads never come back short.
    • A new table, fast_rollups_ready(brand_id pk, ready_at), is server-only, with RLS on.
    • topics_overview_window and mentions_perception_live read the new tables only for brands listed there. Every other brand runs the pre-00536 read path. The choice is made on each call, and force_custom_plan lets the planner drop the unused branch.
    • The script lists a brand with its last chunk, in that chunk's transaction, once every day the brand has rollups for is in.
    • The last chunk runs through today. If a refresh was mid-flight when 00536 applied, it still holds the brand's lock, so the chunk waits for its commit and its days get in too.
    • Later runs skip brands that are already ready, unless they are named with --brand.
  4. 00537 builds the mentions_terms_daily_all term index after the backfill. Without the index the reads are correct, just a little slower (see the table below).
  5. Refresh overlap. The runbook ends with --last-days 3 for every brand, ready or not. That run lists no brand as ready, and it is idempotent.

Also:

  • JIT: mentions_perception_live runs with jit = 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.
  • Demo: the demo stays on the old path.
    • fast_rollups_backfill_ranges() leaves out is_demo brands, so the demo brand is never listed as ready.
    • fast_rollups_ready gets a SKIPPED entry in server/src/lib/demo/coverage.js; no demo code changes.
    • The demo still lists the other new tables, which its refreshes rewrite.
  • Access: brand-access-policies lists fast_rollups_ready as 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).

  • Topics: 2, 7, 30, 90 and 180 days, plus two windows with an explicit end.
  • Perception: 7, 30 and 90 days, with and without an end, plus a platform filter and a country filter.
  • Each was checked with the brand not ready (new tables empty), ready without 00537, and ready with 00537.
  • The checks were repeated after re-applying the first 00536, then this 00536, then 00537.

Every comparison was identical (row sets, or jsonb equality).

Backfill on the fixture

  • Full run: 15 calls of 14 days for the 200-day brand, 0.68–0.78 s each; the last, partial chunk took 0.2 s. The total was 14.3 s, including the 250 ms pauses. Row counts match the first 00536's fill: 40,000 / 339,310 / 416,204.
  • Immediate re-run: 0 rows inserted, updated or deleted.
  • Refresh overlap: I simulated a refresh with the old definitions by deleting, changing and adding source rows in the last 3 days, which left 353 / 1,290 / 724 rows out of step. --last-days 3 brought 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.
  • Memory: one fresh 14-day chunk for the heaviest brand peaked at 14 MB of the backend's private memory (RssAnon, sampled every 20 ms), against 3 MB idle.
    • The largest hash table was 5.4 MB, in a single batch, with no temp files (work_mem 4 MB, log_temp_files = 0).
    • Each hash table holds at most one chunk's groups, so the peak depends on the chunk's days, not the table's size.
  • The fixture did not reproduce the OOM. The first 00536's one-statement fill of 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.
    • Chunking bounds each transaction's rows, WAL, after-trigger (foreign key) queue, lock time and cache churn, whatever the cause was.
    • Prod's Postgres log should say which process the OOM killer picked.

Read times on the fixture

Warm cache, best of 5, in ms:

Read pre-00536 not ready ready, before 00537 ready, with 00537
topics_overview_window 30d 225 227 n/a (doesn't use the index) 43
topics_overview_window 90d 732 782 n/a 102
mentions_perception_live 30d 153 54 (JIT off) 27 25
mentions_perception_live 90d 224 139 (JIT off) 52 44

Related issue

Follow-up to #2345 (00536): the production apply ran out of memory and was rolled back.

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

Needs 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, for psql.
  • For the script: a checkout of main after this PR merges, with server/ dependencies installed, and prod's SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY set in the environment or in server/.env.

1. Apply 00536 (estimate: under a minute). Apply it the way you applied 00536 this morning, for example with psql:

psql "$DATABASE_URL" -v ON_ERROR_STOP=1 --single-transaction \
  -c "set lock_timeout = '5s'" \
  -f supabase/migrations/00536_faster_topics_and_perception_reads.sql
  • The three new foreign keys take a brief lock on brands, blocking writes to it until the transaction commits (under a second).
  • The lock timeout makes the apply fail fast if a long transaction holds brands, instead of queueing every brands write behind it. If it fails, re-run it.
  • The release can ship once this step is done. It doesn't need the backfill: every brand reads exactly as before until step 2 lists it.

2. Backfill (estimate: 10–30 min; see below):

cd server
node src/scripts/backfill-fast-rollups.js --dry-run   # prints: N brand(s), M call(s) …
node src/scripts/backfill-fast-rollups.js             # --chunk-days 14 --pause-ms 250
  • It prints one line per chunk: [i/N] <brand> <from>..<to> <ms> ms · rows written: …. A brand's last line ends with · ready.
  • If a call fails: the script exits 1 and prints Resume with: --from-brand <id> --from-day <day>. Run it again with those flags.
  • To stop: press Ctrl-C at any time. Starting again with no flags also works: ready brands are skipped, and the interrupted brand restarts from its first day.
  • If a brand's calls take more than about 10 s: stop, then resume from the last printed brand and day with --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.sql

A 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:

psql "$DATABASE_URL" -c "create index concurrently if not exists mentions_terms_daily_all_term on public.mentions_terms_daily_all (brand_id, entity, term, day) include (answers)"
psql "$DATABASE_URL" -At -c "select indisvalid from pg_index where indexrelid = 'public.mentions_terms_daily_all_term'::regclass"   # must print t

If the check prints f, the concurrent build failed. Drop the index and build it again: if not exists would keep the invalid one.

4. Re-run the last 3 days of every brand (estimate: a few minutes at most):

node src/scripts/backfill-fast-rollups.js --last-days 3
  • It covers 3 days ago through today, for every brand with days in that range, ready or not.
  • It lists no brand as ready.
  • It picks up anything a refresh with the old definitions rewrote while step 1 applied.
  • It is safe to run again.

5. Vacuum (estimate: under a minute):

psql "$DATABASE_URL" -c "vacuum analyze public.topics_prompt_daily, public.topics_competitor_daily, public.mentions_terms_daily_all, public.fast_rollups_ready"

Check:

select count(*) from public.fast_rollups_ready;   -- brands on the new reads
select public.health_probe('<user_id>', '<brand_id>', 'topics_overview_window', 90);
select public.health_probe('<user_id>', '<brand_id>', 'mentions_perception_live', 30);

Rollback, at any point: delete from public.fast_rollups_ready; sends every brand back to the old reads at once. Add where 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.

  • Size: prod's mentions_terms_daily has about 5.5M rows, roughly 3.7× the fixture's.
  • Speed: prod is slower per row. The first 00536 ran 2 minutes on prod without finishing work that takes about 10 s here on a quarter of the data (1/3.7), so prod is at least about 3× slower. The health report's 90-day Topics read was about 18× the fixture's. I assume 3–15× slower.
  • Step 2:
    • Chunk work: 10.5 s here × 3.7 × 3–15 ≈ 2–10 min.
    • Pauses and round trips add about 0.35 s × the dry run's call count M. For example, 300 brands with about 6 months of data each make about 3,900 calls, about 23 min. For many small brands, --pause-ms 100 cuts this.
    • The heaviest brand's 14-day chunk takes 0.7 s here, so about 2–10 s on prod.
  • Step 3: 0.6 s here for 416k rows, so about 5–30 s for about 1.5M rows.
  • Step 4: one call per active brand at about 0.2 s here, so minutes at most.
  • Step 5: 0.3 s here, so under a minute.
  • Total: roughly 15–45 minutes for a few hundred brands, almost all of it step 2. Step 2's dry run gives the call count M to refine this: about M × 0.35 s, plus 2–10 min.

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

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): no web files changed
  • yarn typecheck passes (run from web/): no web files changed
  • yarn format:check passes (run from web/): no web files changed
  • Changes are focused — one concern per PR
  • Help article updated under help/ (or no user-visible change) — see help/README.md

Checks run:

  • supabase/build-schema.sh: schema.sql regenerated (424 migration files).
  • Web vitest, 17 files and 351 tests: every web test that reads the migrations or schema.sql, including brand-access-functions.test.ts.
  • Server vitest, 35 files and 469 tests:
    • every server test that reads the migrations, including brand-access-policies and demo/coverage;
    • all of lib/health and lib/demo;
    • insights-rollups and mentions-rollups;
    • the new fast-rollups-backfill.test.js.
  • Prettier and ESLint on the server files touched.
  • Local Postgres 16:
    • applied 00536 after 00535 and ran the script through a psql-backed rpc;
    • applied 00537;
    • re-applied the first 00536, this one and 00537 over the result.

Generated by Claude Code

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
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Nov 12, 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.

LGTM: 00536 now creates only, the reads stay on the old path until a brand is backfilled, and the backfill functions are server-only.

@gkhngyk
gkhngyk merged commit 1d5cb89 into ansvisor:main Nov 12, 2026
13 checks passed
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.

3 participants