Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(mentions): refresh the Mentions rollups one at a time, and rebuild Insights days of a deleted prompt (#1227)
Cihan1306b45d17aa
diff --git a/server/src/lib/insights-rollups.js b/server/src/lib/insights-rollups.jsindex 49ca8a0bc..4f2fab8d5 100644--- a/server/src/lib/insights-rollups.js+++ b/server/src/lib/insights-rollups.js@@ -11,6 +11,8 @@* as a backstop: runs that never stamped (partial, crashed, ghost tasks)* and out-of-run writes (a prompt analyzed the moment it was added, #754)* all get their day picked up the next morning+ * - the rebuild queue, which refreshes the days of a deleted prompt+ * (00192): its answers are gone, but the rows keep them until then** Every entry point is best-effort. The rollups are derived state, always* recomputable from prompt_results; a refresh failure costs freshness until@@ -63,10 +65,89 @@ export async function refreshForCompletedRun(brandId, runStartedAtIso) {return ok;}+/** Days refreshed per call when a queued range is rebuilt, as the backfill chunks them. */+export const REBUILD_CHUNK_DAYS = 31;++function addDays(day, n) {+ const d = new Date(`${day}T00:00:00Z`);+ d.setUTCDate(d.getUTCDate() + n);+ return utcDay(d.toISOString());+}++/** The drain in progress, if any. */+let rebuildInFlight = null;++/**+ * Refresh the days queued by a prompt delete (the trigger on prompts in+ * 00192). The prompt's answers cascade away, but insights_brand_daily keeps+ * them until those days are refreshed, and the sweep covers only the last+ * SWEEP_DAYS; the Mentions page, which reads existing prompts only, already+ * leaves them out. A queue entry is cleared only if nothing re-queued the+ * brand while it was refreshed.+ *+ * Called on the citation rebuilds' schedule and at the end of the nightly+ * sweep. Runs never overlap: a call made while one is in progress returns at+ * once with `skipped: true`.+ */+export async function rebuildQueuedInsightsRollups() {+ if (rebuildInFlight) return { rebuilt: 0, failed: 0, skipped: true };+ rebuildInFlight = drainRebuildQueue();+ try {+ return await rebuildInFlight;+ } finally {+ rebuildInFlight = null;+ }+}++async function drainRebuildQueue() {+ const { data: queued, error } = await supabaseAdmin+ .from('insights_rollup_rebuilds')+ .select('brand_id, day_from, day_to, requested_at');+ if (error) {+ logger.error({ err: error }, '[insights-rollups] could not read the rebuild queue');+ return { rebuilt: 0, failed: 0 };+ }++ let rebuilt = 0;+ let failed = 0;+ for (const entry of queued ?? []) {+ const {+ brand_id: brandId,+ day_from: dayFrom,+ day_to: dayTo,+ requested_at: requestedAt,+ } = entry;+ let ok = true;+ for (let from = dayFrom; ok && from <= dayTo; from = addDays(from, REBUILD_CHUNK_DAYS)) {+ const end = addDays(from, REBUILD_CHUNK_DAYS - 1);+ ok = await refreshInsightsDaily(brandId, from, end < dayTo ? end : dayTo);+ }+ // A failed refresh logged itself; the entry stays for the next drain.+ if (!ok) {+ failed++;+ continue;+ }+ const { error: clearError } = await supabaseAdmin+ .from('insights_rollup_rebuilds')+ .delete()+ .eq('brand_id', brandId)+ .lte('requested_at', requestedAt);+ if (clearError) {+ logger.warn({ err: clearError, brandId }, '[insights-rollups] could not clear a rebuild');+ }+ rebuilt++;+ }++ if (rebuilt + failed > 0) {+ logger.info({ rebuilt, failed }, '[insights-rollups] deleted-prompt rebuilds complete');+ }+ return { rebuilt, failed };+}+/*** Daily backstop: refresh the trailing SWEEP_DAYS for every brand, Insights,* Citations and Mentions rollups alike, then rebuild the brands queued by- * topic moves.+ * topic moves and prompt deletes.** Deliberately every brand rather than "brands with recent results" — a* refresh over days with no rows deletes nothing and inserts nothing, so the@@ -99,7 +180,9 @@ export async function sweepInsightsRollups({ days = SWEEP_DAYS } = {}) {logger.info({ refreshed, failed, dayFrom, dayTo }, '[insights-rollups] sweep complete');- // Brands whose prompts changed topic get their citation history rebuilt.+ // Brands whose prompts changed topic get their citation history rebuilt,+ // and the days of deleted prompts their Insights rows.await rebuildQueuedCitationRollups();+ await rebuildQueuedInsightsRollups();return { refreshed, failed };}diff --git a/server/src/lib/insights-rollups.test.js b/server/src/lib/insights-rollups.test.jsindex bba4c6724..84688d5c1 100644--- a/server/src/lib/insights-rollups.test.js+++ b/server/src/lib/insights-rollups.test.js@@ -24,16 +24,52 @@ vi.mock('./mentions-rollups.js', () => ({}));import {+ rebuildQueuedInsightsRollups,refreshInsightsDaily,refreshForCompletedRun,sweepInsightsRollups,utcDay,+ REBUILD_CHUNK_DAYS,SWEEP_DAYS,} from './insights-rollups.js';+/**+ * The admin client's from(): the brands list, and the rebuild queue (00192)+ * with the deletes made on it.+ */+let brandRows = [];+let brandsError = null;+let queueRows = [];+const queueDeletes = [];+function tables() {+ from.mockImplementation((table) => {+ if (table === 'brands') {+ return { select: () => Promise.resolve({ data: brandRows, error: brandsError }) };+ }+ const filters = [];+ const chain = {+ eq: (...a) => (filters.push(['eq', ...a]), chain),+ lte: (...a) => {+ filters.push(['lte', ...a]);+ queueDeletes.push(filters);+ return Promise.resolve({ error: null });+ },+ };+ return {+ select: () => Promise.resolve({ data: queueRows, error: null }),+ delete: () => chain,+ };+ });+}+beforeEach(() => {rpc.mockReset();from.mockReset();+ brandRows = [];+ brandsError = null;+ queueRows = [];+ queueDeletes.length = 0;+ tables();refreshCitationsDaily.mockReset().mockResolvedValue(true);refreshMentionsDaily.mockReset().mockResolvedValue(true);rebuildQueuedCitationRollups.mockReset().mockResolvedValue({ rebuilt: 0, failed: 0 });@@ -116,7 +152,8 @@ describe('refreshForCompletedRun', () => {describe('sweepInsightsRollups', () => {function brandsList(rows, error = null) {- from.mockReturnValue({ select: () => Promise.resolve({ data: rows, error }) });+ brandRows = rows;+ brandsError = error;}it('refreshes the trailing window for every brand, today included', async () => {@@ -178,3 +215,71 @@ describe('sweepInsightsRollups', () => {expect(rpc).not.toHaveBeenCalled();});});++describe('rebuildQueuedInsightsRollups (00192)', () => {+ const entry = {+ brand_id: 'b1',+ day_from: '2026-06-01',+ day_to: '2026-08-10',+ requested_at: '2026-08-21T05:00:00.123456+00:00',+ };++ it("refreshes a deleted prompt's days in chunks, then clears the entry", async () => {+ queueRows = [entry];+ rpc.mockResolvedValue({ error: null });++ expect(await rebuildQueuedInsightsRollups()).toEqual({ rebuilt: 1, failed: 0 });++ expect(REBUILD_CHUNK_DAYS).toBe(31);+ expect(rpc.mock.calls.map(([, args]) => [args.p_day_from, args.p_day_to])).toEqual([+ ['2026-06-01', '2026-07-01'],+ ['2026-07-02', '2026-08-01'],+ ['2026-08-02', '2026-08-10'],+ ]);+ // Only if nothing re-queued the brand meanwhile.+ expect(queueDeletes).toEqual([+ [+ ['eq', 'brand_id', 'b1'],+ ['lte', 'requested_at', entry.requested_at],+ ],+ ]);+ });++ it('keeps the entry for the next drain when a refresh fails', async () => {+ queueRows = [entry, { ...entry, brand_id: 'b2', day_from: '2026-08-01' }];+ rpc.mockResolvedValueOnce({ error: { message: 'timeout' } }).mockResolvedValue({ error: null });++ expect(await rebuildQueuedInsightsRollups()).toEqual({ rebuilt: 1, failed: 1 });+ // b1 stopped at its first chunk; b2 was refreshed and cleared.+ expect(rpc.mock.calls[0][1].p_brand_id).toBe('b1');+ expect(rpc.mock.calls.slice(1).every(([, args]) => args.p_brand_id === 'b2')).toBe(true);+ expect(queueDeletes).toHaveLength(1);+ expect(queueDeletes[0][0]).toEqual(['eq', 'brand_id', 'b2']);+ });++ it('never runs twice at once', async () => {+ queueRows = [entry];+ let release;+ rpc.mockReturnValueOnce(new Promise((resolve) => (release = resolve)));+ rpc.mockResolvedValue({ error: null });++ const first = rebuildQueuedInsightsRollups();+ expect(await rebuildQueuedInsightsRollups()).toEqual({ rebuilt: 0, failed: 0, skipped: true });+ release({ error: null });+ expect(await first).toEqual({ rebuilt: 1, failed: 0 });+ });++ it('runs at the end of the nightly sweep', async () => {+ brandRows = [];+ queueRows = [entry];+ rpc.mockResolvedValue({ error: null });++ await sweepInsightsRollups();++ expect(rpc).toHaveBeenCalledWith('refresh_insights_daily', {+ p_brand_id: 'b1',+ p_day_from: '2026-06-01',+ p_day_to: '2026-07-01',+ });+ });+});diff --git a/server/src/server.js b/server/src/server.jsindex 7db0943cd..be98ac017 100644--- a/server/src/server.js+++ b/server/src/server.js@@ -22,7 +22,7 @@ import {cleanupStalePendingTasks,} from './lib/job-manager.js';import { runTrackingJob, recoverWaitingJobs } from './lib/job-runner.js';-import { sweepInsightsRollups } from './lib/insights-rollups.js';+import { rebuildQueuedInsightsRollups, sweepInsightsRollups } from './lib/insights-rollups.js';import { rebuildQueuedCitationRollups, REBUILD_QUEUE_SCHEDULE } from './lib/citations-rollups.js';import { sweepActionValidation } from './lib/action-center/validate.js';import { sweepImproveOutcomes } from './lib/action-center/improve-outcome.js';@@ -759,14 +759,17 @@ server.listen(PORT, async () => {setInterval(recover, 60_000);// Rebuild the citation rollups of brands whose prompts changed topic- // (00118) within minutes, not at the nightly sweep, so the Citations topic- // filter catches up soon after a move. An empty queue costs one select, and- // the function itself refuses to overlap with a run still in progress.- cron.schedule(REBUILD_QUEUE_SCHEDULE, () =>+ // (00118), and the Insights days of deleted prompts (00192), within+ // minutes, not at the nightly sweep. An empty queue costs one select, and+ // each function refuses to overlap with a run of its own still in progress.+ cron.schedule(REBUILD_QUEUE_SCHEDULE, () => {rebuildQueuedCitationRollups().catch((err) =>logger.error({ err }, '[citations-rollups] scheduled rebuild crashed'),- ),- );+ );+ rebuildQueuedInsightsRollups().catch((err) =>+ logger.error({ err }, '[insights-rollups] scheduled rebuild crashed'),+ );+ });if (!isCloud()) {const schedule = process.env.DAILY_CRON_SCHEDULE || '0 6 * * *';diff --git a/supabase/migrations/00192_rollup_integrity.sql b/supabase/migrations/00192_rollup_integrity.sqlnew file mode 100644index 000000000..fe0c96286--- /dev/null+++ b/supabase/migrations/00192_rollup_integrity.sql@@ -0,0 +1,196 @@+-- ============================================================================+-- 00192: the Mentions rollups refresh one at a time, and a deleted prompt+-- leaves the Insights rollups+-- ============================================================================+-- Two ways the Insights and Mentions pages could still show different numbers+-- for the same days once they count the same things (00191).+--+-- 1. refresh_mentions_daily (00157) deletes a day range and inserts it again+-- with no lock. A run's refresh and the nightly sweep (or a backfill) for+-- the same brand could overlap: both delete, both insert, and the days+-- they share are counted twice. refresh_insights_daily had the same gap+-- until 00164 (#1020). It now takes the same per-brand advisory lock, rows+-- written twice before are dropped (the copy with the latest answer is+-- kept; the next refresh of those days rewrites them anyway), and unique+-- keys make a second copy impossible.+--+-- 2. Deleting a prompt cascades its prompt_results. The Mentions page drops+-- its rows at read time (it reads existing prompts only), but+-- insights_brand_daily keeps them until something refreshes those days,+-- and the nightly sweep only covers the last 3. A trigger now queues the+-- brand with the deleted prompt's day range (read from+-- insights_prompt_daily before the delete), and the server refreshes that+-- range, as the citation rollups' queue does (00118).++-- ─── One refresh per brand at a time ────────────────────────────────────────++create or replace function public.refresh_mentions_daily(+ p_brand_id uuid,+ p_day_from date,+ p_day_to date+) returns void+language plpgsql+set search_path to 'public'+as $$+declare+ -- The range's bounds as instants, so the answers are found by range.+ v_from timestamptz := p_day_from::timestamp at time zone 'utc';+ v_to timestamptz := (p_day_to + 1)::timestamp at time zone 'utc';+begin+ -- One refresh per brand at a time, as refresh_insights_daily (00164); the+ -- lock releases at commit.+ perform pg_advisory_xact_lock(+ hashtextextended('refresh_mentions_daily:' || p_brand_id::text, 0));++ delete from public.mentions_prompt_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.mentions_competitor_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;++ insert into public.mentions_prompt_daily (+ brand_id, day, prompt_id, platform, region,+ answer_count, mention_answers, mention_occurrences,+ positive_answers, negative_answers, position_sum, position_count, last_answer_at)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ pr.prompt_id, pr.platform, pr.region,+ count(*),+ count(*) filter (where pr.mention_count > 0),+ coalesce(sum(pr.mention_count), 0),+ count(*) filter (where pr.mention_count > 0 and pr.sentiment = 'positive'),+ count(*) filter (where pr.mention_count > 0 and pr.sentiment = 'negative'),+ coalesce(sum(pr.mention_position)+ filter (where pr.mention_count > 0 and pr.mention_position is not null), 0),+ count(*) filter (where pr.mention_count > 0 and pr.mention_position is not null),+ max(pr.created_at)+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and pr.created_at >= v_from+ and pr.created_at < v_to+ group by 2, pr.prompt_id, pr.platform, pr.region;++ insert into public.mentions_competitor_daily (+ brand_id, day, prompt_id, platform, region, competitor_id,+ mention_answers, co_mention_answers)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ pr.prompt_id, pr.platform, pr.region,+ cm.value->>'competitor_id',+ count(*),+ count(*) filter (where pr.mention_count > 0)+ from public.prompt_results pr+ cross join lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and pr.created_at >= v_from+ and pr.created_at < v_to+ and cm.value ? 'competitor_id'+ and coalesce((cm.value->>'mention_count')::int, 0) > 0+ group by 2, pr.prompt_id, pr.platform, pr.region, cm.value->>'competitor_id';+end;+$$;++revoke execute on function public.refresh_mentions_daily(uuid, date, date)+ from public, anon, authenticated;++-- ─── Rows written twice ─────────────────────────────────────────────────────++delete from public.mentions_prompt_daily d+using (+ select ctid,+ row_number() over (+ partition by brand_id, day, prompt_id, platform, region+ order by last_answer_at desc, answer_count desc) as n+ from public.mentions_prompt_daily+) x+where d.ctid = x.ctid and x.n > 1;++delete from public.mentions_competitor_daily d+using (+ select ctid,+ row_number() over (+ partition by brand_id, day, prompt_id, platform, region, competitor_id+ order by mention_answers desc) as n+ from public.mentions_competitor_daily+) x+where d.ctid = x.ctid and x.n > 1;++-- On large tables, build these by hand first with `create unique index+-- concurrently`, which doesn't hold back the refreshes; these statements then+-- find them in place. A null platform or region is one key, not many.+create unique index if not exists mentions_prompt_daily_key+ on public.mentions_prompt_daily (brand_id, day, prompt_id, platform, region)+ nulls not distinct;++create unique index if not exists mentions_competitor_daily_key+ on public.mentions_competitor_daily (brand_id, day, prompt_id, platform, region, competitor_id)+ nulls not distinct;++-- ─── A deleted prompt queues its days ───────────────────────────────────────++-- No foreign key on purpose, as citation_rollup_rebuilds: a brand delete must+-- never fail on it. A brand gone by the time the server reads its entry has+-- no rows left, so the refresh is a no-op and the entry is cleared.+create table if not exists public.insights_rollup_rebuilds (+ brand_id uuid primary key,+ day_from date not null,+ day_to date not null,+ requested_at timestamptz not null default now()+);++-- Service role only: no policies.+alter table public.insights_rollup_rebuilds enable row level security;++-- Before the delete, so the prompt's rows are still there to give its days.+create or replace function public.queue_insights_rollup_rebuild()+returns trigger+language plpgsql+security definer+set search_path to 'public'+as $$+declare+ v_brand uuid;+ v_from date;+ v_to date;+begin+ -- Only for a brand that still exists: during a brand delete the cascade+ -- removes the brand first, so its prompts queue nothing.+ select ps.brand_id into v_brand+ from public.prompt_sets ps+ join public.brands b on b.id = ps.brand_id+ where ps.id = old.prompt_set_id;+ if v_brand is null then+ return old;+ end if;++ select min(d.day), max(d.day) into v_from, v_to+ from public.insights_prompt_daily d+ where d.brand_id = v_brand and d.prompt_id = old.id;+ if v_from is null then+ return old;+ end if;++ insert into public.insights_rollup_rebuilds as q (brand_id, day_from, day_to)+ values (v_brand, v_from, v_to)+ on conflict (brand_id) do update+ set day_from = least(q.day_from, excluded.day_from),+ day_to = greatest(q.day_to, excluded.day_to),+ requested_at = now();+ return old;+end;+$$;++revoke execute on function public.queue_insights_rollup_rebuild()+ from public, anon, authenticated;++drop trigger if exists prompts_queue_insights_rollup_rebuild on public.prompts;+create trigger prompts_queue_insights_rollup_rebuild+ before delete on public.prompts+ for each row execute function public.queue_insights_rollup_rebuild();++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 6f4a42787..faed8604b 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -26341,3 +26341,203 @@ comment on function public.ai_bot_prune(timestamptz, date, timestamptz, integer)notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00192_rollup_integrity.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00192: the Mentions rollups refresh one at a time, and a deleted prompt+-- leaves the Insights rollups+-- ============================================================================+-- Two ways the Insights and Mentions pages could still show different numbers+-- for the same days once they count the same things (00191).+--+-- 1. refresh_mentions_daily (00157) deletes a day range and inserts it again+-- with no lock. A run's refresh and the nightly sweep (or a backfill) for+-- the same brand could overlap: both delete, both insert, and the days+-- they share are counted twice. refresh_insights_daily had the same gap+-- until 00164 (#1020). It now takes the same per-brand advisory lock, rows+-- written twice before are dropped (the copy with the latest answer is+-- kept; the next refresh of those days rewrites them anyway), and unique+-- keys make a second copy impossible.+--+-- 2. Deleting a prompt cascades its prompt_results. The Mentions page drops+-- its rows at read time (it reads existing prompts only), but+-- insights_brand_daily keeps them until something refreshes those days,+-- and the nightly sweep only covers the last 3. A trigger now queues the+-- brand with the deleted prompt's day range (read from+-- insights_prompt_daily before the delete), and the server refreshes that+-- range, as the citation rollups' queue does (00118).++-- ─── One refresh per brand at a time ────────────────────────────────────────++create or replace function public.refresh_mentions_daily(+ p_brand_id uuid,+ p_day_from date,+ p_day_to date+) returns void+language plpgsql+set search_path to 'public'+as $$+declare+ -- The range's bounds as instants, so the answers are found by range.+ v_from timestamptz := p_day_from::timestamp at time zone 'utc';+ v_to timestamptz := (p_day_to + 1)::timestamp at time zone 'utc';+begin+ -- One refresh per brand at a time, as refresh_insights_daily (00164); the+ -- lock releases at commit.+ perform pg_advisory_xact_lock(+ hashtextextended('refresh_mentions_daily:' || p_brand_id::text, 0));++ delete from public.mentions_prompt_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.mentions_competitor_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;++ insert into public.mentions_prompt_daily (+ brand_id, day, prompt_id, platform, region,+ answer_count, mention_answers, mention_occurrences,+ positive_answers, negative_answers, position_sum, position_count, last_answer_at)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ pr.prompt_id, pr.platform, pr.region,+ count(*),+ count(*) filter (where pr.mention_count > 0),+ coalesce(sum(pr.mention_count), 0),+ count(*) filter (where pr.mention_count > 0 and pr.sentiment = 'positive'),+ count(*) filter (where pr.mention_count > 0 and pr.sentiment = 'negative'),+ coalesce(sum(pr.mention_position)+ filter (where pr.mention_count > 0 and pr.mention_position is not null), 0),+ count(*) filter (where pr.mention_count > 0 and pr.mention_position is not null),+ max(pr.created_at)+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and pr.created_at >= v_from+ and pr.created_at < v_to+ group by 2, pr.prompt_id, pr.platform, pr.region;++ insert into public.mentions_competitor_daily (+ brand_id, day, prompt_id, platform, region, competitor_id,+ mention_answers, co_mention_answers)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ pr.prompt_id, pr.platform, pr.region,+ cm.value->>'competitor_id',+ count(*),+ count(*) filter (where pr.mention_count > 0)+ from public.prompt_results pr+ cross join lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and pr.created_at >= v_from+ and pr.created_at < v_to+ and cm.value ? 'competitor_id'+ and coalesce((cm.value->>'mention_count')::int, 0) > 0+ group by 2, pr.prompt_id, pr.platform, pr.region, cm.value->>'competitor_id';+end;+$$;++revoke execute on function public.refresh_mentions_daily(uuid, date, date)+ from public, anon, authenticated;++-- ─── Rows written twice ─────────────────────────────────────────────────────++delete from public.mentions_prompt_daily d+using (+ select ctid,+ row_number() over (+ partition by brand_id, day, prompt_id, platform, region+ order by last_answer_at desc, answer_count desc) as n+ from public.mentions_prompt_daily+) x+where d.ctid = x.ctid and x.n > 1;++delete from public.mentions_competitor_daily d+using (+ select ctid,+ row_number() over (+ partition by brand_id, day, prompt_id, platform, region, competitor_id+ order by mention_answers desc) as n+ from public.mentions_competitor_daily+) x+where d.ctid = x.ctid and x.n > 1;++-- On large tables, build these by hand first with `create unique index+-- concurrently`, which doesn't hold back the refreshes; these statements then+-- find them in place. A null platform or region is one key, not many.+create unique index if not exists mentions_prompt_daily_key+ on public.mentions_prompt_daily (brand_id, day, prompt_id, platform, region)+ nulls not distinct;++create unique index if not exists mentions_competitor_daily_key+ on public.mentions_competitor_daily (brand_id, day, prompt_id, platform, region, competitor_id)+ nulls not distinct;++-- ─── A deleted prompt queues its days ───────────────────────────────────────++-- No foreign key on purpose, as citation_rollup_rebuilds: a brand delete must+-- never fail on it. A brand gone by the time the server reads its entry has+-- no rows left, so the refresh is a no-op and the entry is cleared.+create table if not exists public.insights_rollup_rebuilds (+ brand_id uuid primary key,+ day_from date not null,+ day_to date not null,+ requested_at timestamptz not null default now()+);++-- Service role only: no policies.+alter table public.insights_rollup_rebuilds enable row level security;++-- Before the delete, so the prompt's rows are still there to give its days.+create or replace function public.queue_insights_rollup_rebuild()+returns trigger+language plpgsql+security definer+set search_path to 'public'+as $$+declare+ v_brand uuid;+ v_from date;+ v_to date;+begin+ -- Only for a brand that still exists: during a brand delete the cascade+ -- removes the brand first, so its prompts queue nothing.+ select ps.brand_id into v_brand+ from public.prompt_sets ps+ join public.brands b on b.id = ps.brand_id+ where ps.id = old.prompt_set_id;+ if v_brand is null then+ return old;+ end if;++ select min(d.day), max(d.day) into v_from, v_to+ from public.insights_prompt_daily d+ where d.brand_id = v_brand and d.prompt_id = old.id;+ if v_from is null then+ return old;+ end if;++ insert into public.insights_rollup_rebuilds as q (brand_id, day_from, day_to)+ values (v_brand, v_from, v_to)+ on conflict (brand_id) do update+ set day_from = least(q.day_from, excluded.day_from),+ day_to = greatest(q.day_to, excluded.day_to),+ requested_at = now();+ return old;+end;+$$;++revoke execute on function public.queue_insights_rollup_rebuild()+ from public, anon, authenticated;++drop trigger if exists prompts_queue_insights_rollup_rebuild on public.prompts;+create trigger prompts_queue_insights_rollup_rebuild+ before delete on public.prompts+ for each row execute function public.queue_insights_rollup_rebuild();++notify pgrst, 'reload schema';+