:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay-vision): chunk on-demand bulk scans to the API's per-request cap (#101289)
posthog[bot]59e908f9d5f3
diff --git a/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.test.tsindex 12cfd6828ca6..6339e54c3b1e 100644--- a/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.test.ts@@ -1,8 +1,12 @@import { expectLogic } from 'kea-test-utils'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { visionQuotaLogic } from '../logics/visionQuotaLogic'+import { makeQuota } from '../utils/quotaTestUtils'import { scannerRunTabLogic } from './scannerRunTabLogic'describe('scannerRunTabLogic', () => {@@ -109,4 +113,180 @@ describe('scannerRunTabLogic', () => {expect(postedBody).toEqual({ session_ids: ['a', 'b', 'c'] })expect(logic.values.bulkScanning).toBe(false)})++ it('splits a selection above the per-request cap into cap-sized batches', async () => {+ const postedBatches: string[][] = []+ useMocks({+ post: {+ '/api/projects/:team/vision/scanners/:id/bulk_observe/': async ({ request }: { request: Request }) => {+ const body = await request.json()+ postedBatches.push(body.session_ids)+ return [+ 202,+ {+ started: body.session_ids.length,+ results: body.session_ids.map((session_id: string) => ({+ session_id,+ scan_outcome: 'started',+ })),+ },+ ]+ },+ },+ })+ const sessionIds = Array.from({ length: 250 }, (_, i) => `s${i}`)++ await expectLogic(logic, () => logic.actions.startBulkScan(sessionIds)).toFinishAllListeners()++ // One request of 250 is rejected whole by the API, so every session has to go in a batch it accepts.+ expect(postedBatches.map((batch) => batch.length)).toEqual([200, 50])+ expect(postedBatches.flat()).toEqual(sessionIds)+ })++ it('stops batching once a batch reports a skip', async () => {+ const postedBatches: string[][] = []+ useMocks({+ post: {+ '/api/projects/:team/vision/scanners/:id/bulk_observe/': async ({ request }: { request: Request }) => {+ const body = await request.json()+ postedBatches.push(body.session_ids)+ return [+ 202,+ {+ started: 0,+ results: body.session_ids.map((session_id: string) => ({+ session_id,+ scan_outcome: 'skipped_quota',+ })),+ },+ ]+ },+ },+ })++ await expectLogic(logic, () =>+ logic.actions.startBulkScan(Array.from({ length: 250 }, (_, i) => `s${i}`))+ ).toFinishAllListeners()++ // The quota that bound on the first batch binds on every later one, so asking again only burns requests.+ expect(postedBatches).toHaveLength(1)+ })++ // A zero-start run has to name every outcome it produced. Dropping one tells the user to retry+ // a selection that is already answered, or hides the failures behind a skip message.+ test.each([+ ['every session resolved', ['already_scanned', 'already_running'], 'info', ['Nothing new to scan']],+ [+ 'resolved alongside a failure',+ ['already_scanned', 'failed'],+ 'warning',+ ['1 already scanned', '1 failed to start'],+ ],+ [+ 'resolved alongside a skip',+ ['already_scanned', 'skipped_quota'],+ 'warning',+ ['credit limit', '1 already scanned'],+ ],+ ])('names every outcome when nothing started: %s', async (_name, outcomes, level, fragments) => {+ const errorToast = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')+ const toast = jest.spyOn(lemonToast, level as 'info' | 'warning').mockImplementation(() => 'toast-id')+ useMocks({+ post: {+ '/api/projects/:team/vision/scanners/:id/bulk_observe/': () => [+ 202,+ {+ started: 0,+ results: outcomes.map((scan_outcome, i) => ({ session_id: `s${i}`, scan_outcome })),+ },+ ],+ },+ })++ await expectLogic(logic, () =>+ logic.actions.startBulkScan(outcomes.map((_, i) => `s${i}`))+ ).toFinishAllListeners()++ // The scanner load in the mounted logic toasts its own error here, so match the message+ // rather than the call count.+ expect(errorToast).not.toHaveBeenCalledWith(expect.stringContaining('Please try again'))+ const message = toast.mock.calls[0][0]+ for (const fragment of fragments) {+ expect(message).toContain(fragment)+ }+ errorToast.mockRestore()+ toast.mockRestore()+ })++ // `already_running` waits on a row the same way a start does: the backend reports it while the+ // running workflow is still enqueued, so nothing has been written for the session yet.+ test.each([+ ['started', { started: 1, results: [{ session_id: 's9', scan_outcome: 'started' }] }],+ ['already running', { started: 0, results: [{ session_id: 's9', scan_outcome: 'already_running' }] }],+ ])('keeps polling after a bulk scan whose refetch beats the new observation rows: %s', async (_name, response) => {+ // toFinishAllListeners hangs under fake timers (msw resolves responses on the clock),+ // so the whole test advances fake time instead, which also flushes microtasks.+ jest.useFakeTimers()+ try {+ let lookups = 0+ useMocks({+ get: {+ '/api/projects/:team/vision/scanners/:id/observations/': ({ request }: { request: Request }) => {+ if (request.url.includes('session_id=')) {+ lookups += 1+ }+ // A bulk trigger only starts the workflows; the rows are written by their+ // first activity, so the refetch right after it can still see nothing.+ return [200, { results: [], count: 0 }]+ },+ },+ post: {+ '/api/projects/:team/vision/scanners/:id/bulk_observe/': () => [202, response],+ },+ })++ logic.actions.setVisibleSessionIds(['s9'])+ logic.actions.startBulkScan(['s9'])+ await jest.advanceTimersByTimeAsync(1_000)+ const afterScan = lookups+ expect(afterScan).toBeGreaterThan(0)++ await jest.advanceTimersByTimeAsync(3_000)+ // Nothing is in progress and no row landed, so without a grace window the timer is+ // disposed here and the scanning rows read "Not scanned" until the scene reloads.+ expect(lookups).toBeGreaterThan(afterScan)+ } finally {+ jest.useRealTimers()+ }+ })++ it('refreshes the credit total after a bulk run starts scans', async () => {+ let quotaLoads = 0+ useMocks({+ get: {+ '/api/projects/:team/vision/quota/': () => {+ quotaLoads += 1+ return [200, makeQuota()]+ },+ },+ post: {+ '/api/projects/:team/vision/scanners/:id/bulk_observe/': () => [+ 202,+ { started: 1, results: [{ session_id: 's1', scan_outcome: 'started' }] },+ ],+ },+ })+ const quotaLogic = visionQuotaLogic()+ quotaLogic.mount()+ await expectLogic(quotaLogic).toFinishAllListeners()+ const loadsOnMount = quotaLoads++ await expectLogic(logic, () => logic.actions.startBulkScan(['s1'])).toFinishAllListeners()+ await expectLogic(quotaLogic).toFinishAllListeners()++ // Every started scan reserves credits at once, so without this the credit banner on the scanner+ // page keeps showing pre-scan usage until the scene remounts.+ expect(quotaLoads).toBe(loadsOnMount + 1)+ quotaLogic.unmount()+ })})diff --git a/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.tsindex 93b65ed5a0da..ae2513e8bc62 100644--- a/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.ts@@ -11,13 +11,16 @@ import {reducers,selectors,} from 'kea'+import posthog from 'posthog-js'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { teamLogic } from 'scenes/teamLogic'import { visionScannersBulkObserveCreate, visionScannersObservationsList } from '../generated/api'import type { ReplayObservationApi } from '../generated/api.schemas'-import { scheduleObservationPoll } from '../logics/observationPolling'+import { visionScannersBulkObserveCreateBodySessionIdsMax } from '../generated/api.zod'+import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from '../logics/observationPolling'+import { refreshVisionQuota } from '../logics/visionQuotaLogic'import { replayScannerLogic } from './replayScannerLogic'export interface RowObservation {@@ -38,9 +41,63 @@ const BULK_SKIP_MESSAGES: Record<BulkSkipOutcome, string> = {skipped_scanner_limit: 'No scans started. This scanner reached its credit limit for this billing period.',}+// The same reasons as a fragment, for the toast that also has scans to report.+const BULK_SKIP_REASONS: Record<BulkSkipOutcome, string> = {+ skipped_limit: 'too many scans already running',+ skipped_quota: "your organization's credit limit is used up",+ skipped_scanner_limit: "this scanner's credit limit is used up",+}+// Headroom per visible session for the observations a retry stacks on top of the original scan.const OBSERVATIONS_PER_SESSION_ALLOWANCE = 4+// The API rejects a whole batch over its per-request cap, so a select-all would start nothing at all.+const MAX_SESSIONS_PER_REQUEST = visionScannersBulkObserveCreateBodySessionIdsMax++type BulkSkipCounts = Record<BulkSkipOutcome, number>++interface BulkTally {+ started: number+ failed: number+ alreadyScanned: number+ alreadyRunning: number+ skips: BulkSkipCounts+}++function emptyTally(): BulkTally {+ return {+ started: 0,+ failed: 0,+ alreadyScanned: 0,+ alreadyRunning: 0,+ skips: { skipped_limit: 0, skipped_quota: 0, skipped_scanner_limit: 0 },+ }+}++function tallyBatch(tally: BulkTally, results: { scan_outcome?: string | null }[]): number {+ let capped = 0+ for (const { scan_outcome } of results) {+ if (scan_outcome && scan_outcome in tally.skips) {+ tally.skips[scan_outcome as BulkSkipOutcome] += 1+ capped += 1+ } else if (scan_outcome === 'failed') {+ tally.failed += 1+ } else if (scan_outcome === 'already_scanned') {+ tally.alreadyScanned += 1+ } else if (scan_outcome === 'already_running') {+ tally.alreadyRunning += 1+ }+ }+ return capped+}++/** Ties break toward the most specific reason, matching the backend's headroom tie-break. */+function dominantSkip(skipCounts: BulkSkipCounts): BulkSkipOutcome {+ return (['skipped_scanner_limit', 'skipped_quota', 'skipped_limit'] as BulkSkipOutcome[]).reduce((a, b) =>+ skipCounts[b] > skipCounts[a] ? b : a+ )+}+export interface ScannerRunTabLogicProps {scannerId: string}@@ -51,6 +108,7 @@ export interface scannerRunTabLogicValues {bulkScanning: booleanobservationBySession: Record<string, RowObservation>pendingId: string | null+ pollUntil: numberrefreshingObservations: booleanshouldPoll: booleanvisibleSessionIds: string[]@@ -71,8 +129,12 @@ export interface scannerRunTabLogicActions {triggerOnDemandObservationSuccess: () => {value: true} // replayScannerLogic- bulkScanDone: () => {- value: true+ bulkScanDone: (+ started: number,+ alreadyRunning: number+ ) => {+ alreadyRunning: number+ started: number}loadObservations: (background?: any) => {background: any@@ -134,7 +196,7 @@ export const scannerRunTabLogic = kea<scannerRunTabLogicType>([setVisibleSessionIds: (sessionIds: string[]) => ({ sessionIds }),startScan: (sessionId: string) => ({ sessionId }),startBulkScan: (sessionIds: string[]) => ({ sessionIds }),- bulkScanDone: true,+ bulkScanDone: (started: number, alreadyRunning: number) => ({ started, alreadyRunning }),setPendingId: (sessionId: string) => ({ sessionId }),loadObservations: (background = false) => ({ background }),loadObservationsSuccess: (bySession: Record<string, RowObservation>) => ({ bySession }),@@ -181,6 +243,19 @@ export const scannerRunTabLogic = kea<scannerRunTabLogicType>([bulkScanDone: () => false,},],+ // A bulk trigger only starts the workflows; each row is inserted moments later. Nothing else+ // holds the poll open for them — unlike a single scan, which keeps `pendingId` until its row lands.+ // An `already_running` session waits on a row the same way, because the backend reports it while+ // the running workflow is still enqueued and has written nothing yet.+ pollUntil: [+ 0,+ {+ bulkScanDone: (+ state: number,+ { started, alreadyRunning }: { started: number; alreadyRunning: number }+ ) => (started + alreadyRunning > 0 ? Date.now() + OBSERVE_POLL_GRACE_MS : state),+ },+ ],}),selectors({@@ -202,7 +277,11 @@ export const scannerRunTabLogic = kea<scannerRunTabLogicType>([listeners(({ actions, props, values, cache }) => {// Rescheduled on failure too — a transient API hiccup shouldn't permanently kill the polling cycle.const reschedulePoll = (): void =>- scheduleObservationPoll(cache.disposables, values.shouldPoll, () => actions.loadObservations(true))+ scheduleObservationPoll(+ cache.disposables,+ shouldPollObservations(values.shouldPoll, values.pollUntil),+ () => actions.loadObservations(true)+ )return {setVisibleSessionIds: ({ sessionIds }) => {if (sessionIds.length > 0) {@@ -221,55 +300,76 @@ export const scannerRunTabLogic = kea<scannerRunTabLogicType>([startBulkScan: async ({ sessionIds }) => {const teamId = teamLogic.values.currentTeamIdif (!teamId || sessionIds.length === 0) {- actions.bulkScanDone()+ actions.bulkScanDone(0, 0)return}+ const tally = emptyTally()try {- const response = await visionScannersBulkObserveCreate(String(teamId), props.scannerId, {- session_ids: sessionIds,- })- const results = response.results ?? []- const started = response.started- // The backend scans what fits and reports the rest — surface the split so the user- // knows a partial run happened rather than assuming everything started.- const skipCounts: Record<BulkSkipOutcome, number> = {- skipped_limit: 0,- skipped_quota: 0,- skipped_scanner_limit: 0,- }- for (const r of results) {- if (r.scan_outcome && r.scan_outcome in skipCounts) {- skipCounts[r.scan_outcome as BulkSkipOutcome] += 1+ for (let sent = 0; sent < sessionIds.length; sent += MAX_SESSIONS_PER_REQUEST) {+ const batch = sessionIds.slice(sent, sent + MAX_SESSIONS_PER_REQUEST)+ const response = await visionScannersBulkObserveCreate(String(teamId), props.scannerId, {+ session_ids: batch,+ })+ tally.started += response.started+ if (tallyBatch(tally, response.results ?? []) > 0) {+ // The same cap binds every later batch, so count the remainder under it instead.+ tally.skips[dominantSkip(tally.skips)] += sessionIds.length - sent - batch.length+ break}}- const limited =- skipCounts.skipped_limit + skipCounts.skipped_quota + skipCounts.skipped_scanner_limit- const failed = results.filter((r) => r.scan_outcome === 'failed').length- const extras = [- limited ? `${limited} skipped (limit reached)` : null,+ const { started, failed, alreadyScanned, alreadyRunning, skips } = tally+ const limited = skips.skipped_limit + skips.skipped_quota + skips.skipped_scanner_limit+ // Every outcome the run produced, so no branch below has to drop one silently.+ const rest = [+ alreadyScanned ? `${alreadyScanned} already scanned` : null,+ alreadyRunning ? `${alreadyRunning} already scanning` : null,failed ? `${failed} failed to start` : null,].filter(Boolean).join(', ')+ const skipped = limited ? `${limited} skipped (${BULK_SKIP_REASONS[dominantSkip(skips)]})` : ''if (started > 0) {+ const extras = [skipped, rest].filter(Boolean).join(', ')lemonToast.success(`Started ${started} scan${started === 1 ? '' : 's'}${extras ? ` — ${extras}` : ''}`)} else if (limited > 0) {- // Ties break toward the most specific reason, matching the backend's headroom tie-break.- const dominant = (- ['skipped_scanner_limit', 'skipped_quota', 'skipped_limit'] as BulkSkipOutcome[]- ).reduce((a, b) => (skipCounts[b] > skipCounts[a] ? b : a))- lemonToast.warning(BULK_SKIP_MESSAGES[dominant])+ lemonToast.warning(`${BULK_SKIP_MESSAGES[dominantSkip(skips)]}${rest ? ` Also ${rest}.` : ''}`)+ } else if (alreadyScanned + alreadyRunning > 0) {+ if (failed > 0) {+ lemonToast.warning(`No scans started. ${rest}.`)+ } else {+ lemonToast.info('Nothing new to scan. These recordings are already scanned or in progress.')+ }} else {lemonToast.error('No scans started. Please try again.')}- // Started scans create pending observations server-side — refetch to reflect them.- actions.loadObservations()} catch (error: any) {- lemonToast.error(`Bulk scan failed${error?.detail ? `: ${error.detail}` : ''}`)+ // The backend reports a trigger only once it accepts the batch, so a rejected selection would otherwise leave no trace.+ posthog.capture('replay_vision_bulk_scan_rejected', {+ scanner_id: props.scannerId,+ requested: sessionIds.length,+ started: tally.started,+ status: error?.status,+ })+ // A later batch can fail after an earlier one started scans, so say how many survived.+ const detail = error?.detail ? `: ${error.detail}` : ''+ lemonToast.error(+ tally.started > 0+ ? `Bulk scan failed after starting ${tally.started} scan${+ tally.started === 1 ? '' : 's'+ }${detail}`+ : `Bulk scan failed${detail}`+ )} finally {- actions.bulkScanDone()+ // Arm the poll window before the refetch, which can beat the row inserts.+ actions.bulkScanDone(tally.started, tally.alreadyRunning)+ // An earlier batch can have started scans before a later one failed, so refetch either way.+ actions.loadObservations()+ if (tally.started > 0 || tally.skips.skipped_quota > 0) {+ // A started scan reserves credits at once, so the cached banner number is stale.+ refreshVisionQuota()+ }}},