Skip to content

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.

fix(traffic): count the report's and the MCP tool's AI traffic past 1,000 visits (#1165)

Cihanb4f12fafd6dd
diff --git a/web/src/lib/actions/reports.ts b/web/src/lib/actions/reports.ts
index e4aa9a40c..be44f2b67 100644
--- a/web/src/lib/actions/reports.ts
+++ b/web/src/lib/actions/reports.ts
@@ -21,6 +21,7 @@ import { getCitationsOverview, type CitationsSourceBreakdown } from '@/lib/actio
import { getShoppingKpis } from '@/lib/actions/shopping';
import { type SourceCategory } from '@/lib/citations/classify';
import { stripEntityMarkup } from '@/lib/entity-markup';
+import { countTrafficLogs, scanTrafficLogs } from '@/lib/traffic-scan';
import {
getReportTemplate,
ALL_REPORT_SECTIONS,
@@ -480,36 +481,28 @@ async function getTrafficSnapshot(
const prev = previousWindow(dateFrom, dateTo);
// Visits, not pageviews: a row whose visit_of is null starts one (00172),
- // as the AI Traffic page counts them.
- const [{ data: cur, error }, { data: prevRows }] = await Promise.all([
- supabase
- .from('ai_traffic_logs')
- .select('source_platform, url')
- .eq('brand_id', brandId)
- .is('visit_of', null)
- .gte('created_at', dateFrom)
- .lte('created_at', dateTo),
- supabase
- .from('ai_traffic_logs')
- .select('id')
- .eq('brand_id', brandId)
- .is('visit_of', null)
- .gte('created_at', prev.from)
- .lt('created_at', prev.to),
+ // as the AI Traffic page counts them. The totals by count, which no row
+ // cap touches, and the breakdowns by paging through the period: one plain
+ // select stopped at PostgREST's 1,000 rows.
+ const period = { from: dateFrom, to: dateTo, toInclusive: true };
+ const cur: Record<string, unknown>[] = [];
+ const [totalVisits, prevVisits] = await Promise.all([
+ countTrafficLogs(supabase, brandId, period),
+ countTrafficLogs(supabase, brandId, { from: prev.from, to: prev.to }),
+ scanTrafficLogs(supabase, brandId, { ...period, columns: 'source_platform, url' }, (row) =>
+ cur.push(row),
+ ),
]);
- if (error) throw new Error(error.message);
const byPlatform = new Map<string, number>();
const byPage = new Map<string, number>();
- for (const r of cur ?? []) {
+ for (const r of cur) {
const p = (r.source_platform as string) || 'unknown';
byPlatform.set(p, (byPlatform.get(p) ?? 0) + 1);
const u = (r.url as string) || '';
if (u) byPage.set(u, (byPage.get(u) ?? 0) + 1);
}
- const totalVisits = cur?.length ?? 0;
- const prevVisits = prevRows?.length ?? 0;
return {
totalVisits,
change: prevVisits > 0 ? round1(((totalVisits - prevVisits) / prevVisits) * 100) : null,
diff --git a/web/src/lib/actions/traffic-reads-paging.test.ts b/web/src/lib/actions/traffic-reads-paging.test.ts
new file mode 100644
index 000000000..f3bf8f01c
--- /dev/null
+++ b/web/src/lib/actions/traffic-reads-paging.test.ts
@@ -0,0 +1,161 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { McpAuthContext } from '@/lib/mcp-auth';
+
+/**
+ * PostgREST answers an un-paginated select with its first 1,000 rows and no
+ * sign that more exist. The report's AI traffic section and the MCP / API
+ * traffic tool read that way, so a brand past 1,000 visits read as 1,000.
+ * Both now count their totals and page through the breakdowns, as the AI
+ * Traffic page does (lib/traffic-scan.ts).
+ */
+
+type Call = [string, ...unknown[]];
+
+// 2,500 visits: 1,500 from ChatGPT to /menu, 1,000 from Gemini to /pricing.
+const VISITS = Array.from({ length: 2500 }, (_, i) => ({
+ id: `v${String(i).padStart(4, '0')}`,
+ url: i < 1500 ? 'https://acme.example/menu' : 'https://acme.example/pricing',
+ source_platform: i < 1500 ? 'chatgpt' : 'gemini',
+ country: i < 1500 ? 'US' : 'DE',
+ created_at: '2026-10-15T09:00:00Z',
+}));
+const PREVIOUS_VISITS = 1200;
+const POSTGREST_MAX_ROWS = 1000;
+
+const queries: { table: string; calls: Call[] }[] = [];
+const inserted: Record<string, unknown>[] = [];
+
+function answer(table: string, calls: Call[]) {
+ if (table === 'ai_traffic_logs') {
+ const select = calls.find(([m]) => m === 'select');
+ const head = (select?.[2] as { head?: boolean } | undefined)?.head;
+ // The previous period (an exclusive end) has its own, smaller total.
+ const previous = calls.some(([m]) => m === 'lt');
+ if (head) return { data: null, count: previous ? PREVIOUS_VISITS : VISITS.length, error: null };
+ const range = calls.find(([m]) => m === 'range') as [string, number, number] | undefined;
+ // Without .range(), PostgREST stops at its cap, as in production.
+ const [from, to] = range ? [range[1], range[2]] : [0, POSTGREST_MAX_ROWS - 1];
+ return {
+ data: VISITS.slice(from, Math.min(to, from + POSTGREST_MAX_ROWS - 1) + 1),
+ error: null,
+ };
+ }
+ if (table === 'brands')
+ return { data: { id: 'b1', name: 'Acme', shopping_mode_enabled: false }, error: null };
+ if (table === 'brand_domains') return { data: [{ domain: 'acme.example' }], error: null };
+ if (table === 'reports') return { data: { id: 'report-1' }, error: null };
+ return { data: [], error: null };
+}
+
+function query(table: string) {
+ const calls: Call[] = [];
+ queries.push({ table, calls });
+ const builder: Record<string, unknown> = {};
+ for (const method of [
+ 'select',
+ 'eq',
+ 'is',
+ 'in',
+ 'gte',
+ 'lte',
+ 'lt',
+ 'order',
+ 'range',
+ 'limit',
+ ]) {
+ builder[method] = (...args: unknown[]) => {
+ calls.push([method, ...args]);
+ return builder;
+ };
+ }
+ builder.insert = (row: Record<string, unknown>) => {
+ inserted.push(row);
+ return builder;
+ };
+ builder.single = async () => answer(table, calls);
+ builder.maybeSingle = async () => answer(table, calls);
+ builder.then = (resolve: (a: unknown) => unknown) => resolve(answer(table, calls));
+ return builder;
+}
+
+const client = {
+ from: (table: string) => query(table),
+ rpc: async () => ({ data: [], error: null }),
+ auth: {
+ getSession: async () => ({ data: { session: { access_token: 'tok', user: { id: 'u1' } } } }),
+ },
+};
+vi.mock('@/lib/supabase/server', () => ({ createClient: async () => client }));
+vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: client }));
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }));
+vi.mock('@/config/api', () => ({ API_BASE_URL: 'http://api.test' }));
+
+const { createReport } = await import('./reports');
+const { getAiTrafficFor } = await import('@/lib/mcp/data');
+
+/** The pages each scan asked for, as [first, last] row. */
+const scannedRanges = () =>
+ queries
+ .filter((q) => q.table === 'ai_traffic_logs')
+ .flatMap((q) => q.calls.filter(([m]) => m === 'range').map(([, from, to]) => [from, to]));
+
+beforeEach(() => {
+ queries.length = 0;
+ inserted.length = 0;
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response(JSON.stringify({ summary: '' }), { status: 200 })),
+ );
+});
+
+describe('traffic reads past 1,000 visits', () => {
+ it("the report's AI traffic section counts every visit and its change", async () => {
+ await createReport('b1', {
+ dateFrom: '2026-10-11T00:00:00.000Z',
+ dateTo: '2026-10-17T23:59:59.999Z',
+ sections: ['aiTraffic'],
+ });
+
+ const payload = inserted[0].payload as { aiTraffic: Record<string, unknown> };
+ expect(payload.aiTraffic.totalVisits).toBe(2500);
+ // 2,500 against 1,200: no longer 1,000 against 1,000.
+ expect(payload.aiTraffic.change).toBe(108.3);
+ expect(payload.aiTraffic.platformBreakdown).toEqual([
+ { platform: 'chatgpt', visits: 1500 },
+ { platform: 'gemini', visits: 1000 },
+ ]);
+ expect(payload.aiTraffic.topPages).toEqual([
+ { url: 'https://acme.example/menu', visits: 1500 },
+ { url: 'https://acme.example/pricing', visits: 1000 },
+ ]);
+ expect(scannedRanges()).toEqual([
+ [0, 999],
+ [1000, 1999],
+ [2000, 2999],
+ ]);
+ });
+
+ it('the MCP and API traffic tool counts every visit in each breakdown', async () => {
+ const auth = { organizationId: 'org-1' } as McpAuthContext;
+ const result = await getAiTrafficFor(auth, { brandId: 'b1', dateTo: '2026-10-17' });
+
+ expect(result?.total_visits).toBe(2500);
+ expect(result?.platform_breakdown).toEqual([
+ { platform: 'chatgpt', visits: 1500 },
+ { platform: 'gemini', visits: 1000 },
+ ]);
+ expect(result?.top_pages).toEqual([
+ { url: '/menu', visits: 1500 },
+ { url: '/pricing', visits: 1000 },
+ ]);
+ expect(result?.country_breakdown).toEqual([
+ { country: 'US', visits: 1500 },
+ { country: 'DE', visits: 1000 },
+ ]);
+ // A bare day still reads to its end.
+ const scan = queries.find(
+ (q) => q.table === 'ai_traffic_logs' && q.calls.some(([m]) => m === 'range'),
+ )!;
+ expect(scan.calls).toContainEqual(['lte', 'created_at', '2026-10-17T23:59:59.999Z']);
+ });
+});
diff --git a/web/src/lib/actions/traffic-visit-readers.test.ts b/web/src/lib/actions/traffic-visit-readers.test.ts
index e6fe135c5..eb832ce04 100644
--- a/web/src/lib/actions/traffic-visit-readers.test.ts
+++ b/web/src/lib/actions/traffic-visit-readers.test.ts
@@ -150,8 +150,8 @@ describe('readers of the snippet count visits, not pageviews', () => {
{ platform: 'gemini', visits: 1 },
{ platform: 'chatgpt', visits: 1 },
]);
- // This window and the one before it.
- expect(trafficQueries()).toHaveLength(2);
+ // A count for this window and the one before it, and the breakdowns' scan.
+ expect(trafficQueries()).toHaveLength(3);
for (const q of trafficQueries()) expect(visitsOnly(q.calls)).toBe(true);
});
diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.ts
index d86944663..8a09845c2 100644
--- a/web/src/lib/actions/traffic.ts
+++ b/web/src/lib/actions/traffic.ts
@@ -2,6 +2,7 @@
import { createClient } from '@/lib/supabase/server';
import { API_BASE_URL } from '@/config/api';
+import { TRAFFIC_PAGE_SIZE, countTrafficLogs, scanTrafficLogs } from '@/lib/traffic-scan';
import { expandDateToEndOfDay, utcDay } from '@/lib/dates';
import { isHourlyWindow, listUtcHours, utcHourKey } from '@/lib/traffic-buckets';
import { getSuggestionSourceStates, type SourceState } from '@/lib/actions/integrations';
@@ -144,51 +145,6 @@ function listUtcDays(from: string, to: string): string[] {
return days;
}
-/**
- * PostgREST silently caps un-paginated selects at 1000 rows, which froze the
- * visits KPI at 1000 and truncated every breakdown on busy brands (#450).
- * Totals come from exact count queries; the breakdown/trend scans page
- * through the window with deterministic ordering and a hard ceiling so a
- * pathological brand can't pin the server action.
- *
- * The scans read the rows that start a visit only, so the breakdowns and the
- * trend count visits, not pageviews (AT-003).
- */
-const TRAFFIC_PAGE_SIZE = 1000;
-const TRAFFIC_MAX_ROWS = 50_000;
-
-async function scanTrafficLogs(
- supabase: Awaited<ReturnType<typeof createClient>>,
- brandId: string,
- window: { columns: string; from?: string; to?: string; toInclusive?: boolean },
- onRow: (row: Record<string, unknown>) => void,
-): Promise<void> {
- for (let start = 0; start < TRAFFIC_MAX_ROWS; start += TRAFFIC_PAGE_SIZE) {
- let query = supabase
- .from('ai_traffic_logs')
- .select(window.columns)
- .eq('brand_id', brandId)
- .is('visit_of', null)
- // Deterministic order so .range() pages don't shuffle between requests.
- .order('created_at', { ascending: true })
- .order('id', { ascending: true })
- .range(start, start + TRAFFIC_PAGE_SIZE - 1);
- if (window.from) query = query.gte('created_at', window.from);
- if (window.to) {
- query = window.toInclusive
- ? query.lte('created_at', window.to)
- : query.lt('created_at', window.to);
- }
-
- const { data, error } = await query;
- if (error) throw new Error(error.message);
-
- const batch = (data ?? []) as unknown as Record<string, unknown>[];
- for (const row of batch) onRow(row);
- if (batch.length < TRAFFIC_PAGE_SIZE) break;
- }
-}
-
export async function getTrafficSummary(
brandId: string,
window?: TrafficDateWindow,
@@ -199,25 +155,12 @@ export async function getTrafficSummary(
const { from, to, prevFrom, prevTo } = resolveTrafficWindow(window);
// Exact totals — count queries transfer no rows and are immune to the cap.
- const countRows = async (
+ const countRows = (
fromTs?: string,
toTs?: string,
toInclusive = false,
- { visits = true } = {},
- ) => {
- let query = supabase
- .from('ai_traffic_logs')
- .select('id', { count: 'exact', head: true })
- .eq('brand_id', brandId);
- if (visits) query = query.is('visit_of', null);
- if (fromTs) query = query.gte('created_at', fromTs);
- if (toTs) {
- query = toInclusive ? query.lte('created_at', toTs) : query.lt('created_at', toTs);
- }
- const { count, error } = await query;
- if (error) throw new Error(error.message);
- return count ?? 0;
- };
+ opts?: { visits?: boolean },
+ ) => countTrafficLogs(supabase, brandId, { from: fromTs, to: toTs, toInclusive }, opts);
// Platform breakdown + top pages, aggregated per batch.
const platformMap = new Map<string, number>();
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 3a55205a5..714a3ecd6 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -10,6 +10,7 @@ import {
} from '@/lib/citations/classify';
import { classifyArticleType } from '@/lib/citations/article-type';
import { expandDateToEndOfDay } from '@/lib/dates';
+import { countTrafficLogs, scanTrafficLogs } from '@/lib/traffic-scan';
import { computeAiVisibilityScore } from '@/lib/visibility-score';
import { API_BASE_URL } from '@/config/api';
import { ORG_PLAN_COLUMNS, planFromOrgRow } from '@/lib/guards/plan-guard';
@@ -2201,26 +2202,28 @@ export async function getAiTrafficFor(
if (!brand) return null;
// Visits, not pageviews: a row whose visit_of is null starts one (00172),
- // as the AI Traffic page counts them.
- let query = supabaseAdmin
- .from('ai_traffic_logs')
- .select('source_platform, url, country')
- .eq('brand_id', params.brandId)
- .is('visit_of', null);
-
- if (params.dateFrom) query = query.gte('created_at', params.dateFrom);
- const expandedDateTo = expandDateToEndOfDay(params.dateTo);
- if (expandedDateTo) query = query.lte('created_at', expandedDateTo);
-
- const { data: rows, error } = await query;
- if (error) throw new Error(error.message);
-
- const rawRows =
- (rows as Array<{
- source_platform: string | null;
- url: string;
- country: string | null;
- }> | null) ?? [];
+ // as the AI Traffic page counts them. The total by count, which no row cap
+ // touches, and the breakdowns by paging through the range: one plain
+ // select stopped at PostgREST's 1,000 rows.
+ const range = {
+ from: params.dateFrom,
+ to: expandDateToEndOfDay(params.dateTo),
+ toInclusive: true,
+ };
+ const rawRows: Array<{
+ source_platform: string | null;
+ url: string;
+ country: string | null;
+ }> = [];
+ const [totalVisits] = await Promise.all([
+ countTrafficLogs(supabaseAdmin, params.brandId, range),
+ scanTrafficLogs(
+ supabaseAdmin,
+ params.brandId,
+ { ...range, columns: 'source_platform, url, country' },
+ (row) => rawRows.push(row as (typeof rawRows)[number]),
+ ),
+ ]);
// Platform breakdown
const platformMap = new Map<string, number>();
@@ -2259,7 +2262,7 @@ export async function getAiTrafficFor(
.sort((a, b) => b.visits - a.visits);
return {
- total_visits: rawRows.length,
+ total_visits: totalVisits,
platform_breakdown,
top_pages,
country_breakdown,
diff --git a/web/src/lib/traffic-scan.test.ts b/web/src/lib/traffic-scan.test.ts
new file mode 100644
index 000000000..4203d6fc9
--- /dev/null
+++ b/web/src/lib/traffic-scan.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest';
+import type { SupabaseClient } from '@supabase/supabase-js';
+import {
+ TRAFFIC_MAX_ROWS,
+ TRAFFIC_PAGE_SIZE,
+ countTrafficLogs,
+ scanTrafficLogs,
+} from './traffic-scan';
+
+/**
+ * Reading AI-referred visits past PostgREST's 1,000-row cap: totals by an
+ * exact count, breakdowns a page at a time in a fixed order.
+ */
+
+type Call = [string, ...unknown[]];
+
+/** A client whose ai_traffic_logs holds `total` visits, answering at most a page per request. */
+function fakeClient(total: number, count = total) {
+ const queries: Call[][] = [];
+ const client = {
+ from: () => {
+ const calls: Call[] = [];
+ queries.push(calls);
+ const builder: Record<string, unknown> = {};
+ for (const method of ['select', 'eq', 'is', 'gte', 'lte', 'lt', 'order', 'range']) {
+ builder[method] = (...args: unknown[]) => {
+ calls.push([method, ...args]);
+ return builder;
+ };
+ }
+ builder.then = (resolve: (a: unknown) => unknown) => {
+ const range = calls.find(([m]) => m === 'range') as [string, number, number] | undefined;
+ if (!range) return resolve({ data: null, count, error: null });
+ const [, from, to] = range;
+ const size = Math.max(0, Math.min(to, total - 1) - from + 1);
+ return resolve({
+ data: Array.from({ length: size }, (_, i) => ({ id: `v${from + i}` })),
+ error: null,
+ });
+ };
+ return builder;
+ },
+ };
+ return { client: client as unknown as SupabaseClient, queries };
+}
+
+describe('countTrafficLogs', () => {
+ it('counts the visits in a window without reading a row', async () => {
+ const { client, queries } = fakeClient(0, 4321);
+ await expect(
+ countTrafficLogs(client, 'b1', { from: '2026-10-01', to: '2026-10-08' }),
+ ).resolves.toBe(4321);
+
+ expect(queries[0]).toEqual([
+ ['select', 'id', { count: 'exact', head: true }],
+ ['eq', 'brand_id', 'b1'],
+ ['is', 'visit_of', null],
+ ['gte', 'created_at', '2026-10-01'],
+ // The window's end is its first moment after: exclusive.
+ ['lt', 'created_at', '2026-10-08'],
+ ]);
+ });
+
+ it('counts every pageview when asked, up to an inclusive end', async () => {
+ const { client, queries } = fakeClient(0, 9);
+ await countTrafficLogs(
+ client,
+ 'b1',
+ { to: '2026-10-08T23:59:59.999Z', toInclusive: true },
+ { visits: false },
+ );
+ expect(queries[0]).not.toContainEqual(['is', 'visit_of', null]);
+ expect(queries[0]).toContainEqual(['lte', 'created_at', '2026-10-08T23:59:59.999Z']);
+ });
+});
+
+describe('scanTrafficLogs', () => {
+ it('reads every visit a page at a time, in a fixed order', async () => {
+ const { client, queries } = fakeClient(2500);
+ const seen: unknown[] = [];
+ await scanTrafficLogs(client, 'b1', { columns: 'id', from: '2026-10-01' }, (r) =>
+ seen.push(r.id),
+ );
+
+ expect(seen).toHaveLength(2500);
+ expect(new Set(seen).size).toBe(2500);
+ expect(queries.map((q) => q.find(([m]) => m === 'range')?.slice(1))).toEqual([
+ [0, TRAFFIC_PAGE_SIZE - 1],
+ [1000, 1999],
+ [2000, 2999],
+ ]);
+ // Created time, then id: pages never overlap or skip a row.
+ expect(queries[0]).toContainEqual(['order', 'created_at', { ascending: true }]);
+ expect(queries[0]).toContainEqual(['order', 'id', { ascending: true }]);
+ expect(queries[0]).toContainEqual(['is', 'visit_of', null]);
+ });
+
+ it('stops at its ceiling', async () => {
+ const { client, queries } = fakeClient(TRAFFIC_MAX_ROWS + 5000);
+ let rows = 0;
+ await scanTrafficLogs(client, 'b1', { columns: 'id' }, () => rows++);
+ expect(rows).toBe(TRAFFIC_MAX_ROWS);
+ expect(queries).toHaveLength(TRAFFIC_MAX_ROWS / TRAFFIC_PAGE_SIZE);
+ });
+});
diff --git a/web/src/lib/traffic-scan.ts b/web/src/lib/traffic-scan.ts
new file mode 100644
index 000000000..6fa46fc56
--- /dev/null
+++ b/web/src/lib/traffic-scan.ts
@@ -0,0 +1,84 @@
+/**
+ * Reading AI-referred visits past PostgREST's row cap: the AI Traffic page,
+ * the report and the MCP traffic tool all read through here.
+ *
+ * PostgREST silently caps an un-paginated select at 1,000 rows, which froze
+ * the page's visits KPI at 1,000 and truncated every breakdown on busy brands
+ * (#450). Totals come from exact count queries, which transfer no rows; the
+ * breakdowns page through the window in a fixed order, up to a hard ceiling
+ * so a pathological brand can't pin the server.
+ *
+ * Both read the rows that start a visit (visit_of is null, 00172), so they
+ * count visits, not pageviews (AT-003) — unless a count asks for pageviews.
+ *
+ * Server-only: callers pass their own client — the member's session, or the
+ * service role after checking the brand belongs to the caller.
+ */
+
+import type { SupabaseClient } from '@supabase/supabase-js';
+
+export const TRAFFIC_PAGE_SIZE = 1000;
+export const TRAFFIC_MAX_ROWS = 50_000;
+
+export interface TrafficScanWindow {
+ from?: string;
+ to?: string;
+ /** Whether `to` is the window's last moment (lte) rather than its end (lt). */
+ toInclusive?: boolean;
+}
+
+/** Visits in the window — or, with `visits: false`, every pageview. */
+export async function countTrafficLogs(
+ supabase: SupabaseClient,
+ brandId: string,
+ window: TrafficScanWindow,
+ { visits = true }: { visits?: boolean } = {},
+): Promise<number> {
+ let query = supabase
+ .from('ai_traffic_logs')
+ .select('id', { count: 'exact', head: true })
+ .eq('brand_id', brandId);
+ if (visits) query = query.is('visit_of', null);
+ if (window.from) query = query.gte('created_at', window.from);
+ if (window.to) {
+ query = window.toInclusive
+ ? query.lte('created_at', window.to)
+ : query.lt('created_at', window.to);
+ }
+ const { count, error } = await query;
+ if (error) throw new Error(error.message);
+ return count ?? 0;
+}
+
+/** Every visit in the window, up to TRAFFIC_MAX_ROWS, one page at a time. */
+export async function scanTrafficLogs(
+ supabase: SupabaseClient,
+ brandId: string,
+ window: TrafficScanWindow & { columns: string },
+ onRow: (row: Record<string, unknown>) => void,
+): Promise<void> {
+ for (let start = 0; start < TRAFFIC_MAX_ROWS; start += TRAFFIC_PAGE_SIZE) {
+ let query = supabase
+ .from('ai_traffic_logs')
+ .select(window.columns)
+ .eq('brand_id', brandId)
+ .is('visit_of', null)
+ // Deterministic order so .range() pages don't shuffle between requests.
+ .order('created_at', { ascending: true })
+ .order('id', { ascending: true })
+ .range(start, start + TRAFFIC_PAGE_SIZE - 1);
+ if (window.from) query = query.gte('created_at', window.from);
+ if (window.to) {
+ query = window.toInclusive
+ ? query.lte('created_at', window.to)
+ : query.lt('created_at', window.to);
+ }
+
+ const { data, error } = await query;
+ if (error) throw new Error(error.message);
+
+ const batch = (data ?? []) as unknown as Record<string, unknown>[];
+ for (const row of batch) onRow(row);
+ if (batch.length < TRAFFIC_PAGE_SIZE) break;
+ }
+}