: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(signals): bound the scout notes and memory panel reads (#102448)
posthog[bot]b4d99b716bac
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.test.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.test.tsxindex 18a48f3f9164..f4d394cdd588 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.test.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutNotesPanel.test.tsx@@ -1,8 +1,9 @@-import { cleanup, fireEvent, render } from '@testing-library/react'+import { act, cleanup, fireEvent, render } from '@testing-library/react'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { PANEL_LOAD_TIMEOUT_MS } from '../../../utils/panelLoadTimeout'import { ScoutNotesPanel } from './ScoutNotesPanel'const SKILL_NAME = 'signals-scout-daily-digest'@@ -30,7 +31,10 @@ describe('ScoutNotesPanel', () => {initKeaTests()})- afterEach(cleanup)+ afterEach(() => {+ cleanup()+ jest.useRealTimers()+ })it('shows the opening of a long note until it is expanded', async () => {const { findByText, getByText, queryByText } = render(<ScoutNotesPanel skillName={SKILL_NAME} />)@@ -44,4 +48,19 @@ describe('ScoutNotesPanel', () => {expect(getByText(new RegExp(TAIL))).toBeTruthy()})++ it('offers a retry once a load that never settles times out', async () => {+ useMocks({ get: { '/api/projects/:team/signals/scout/notes/': () => new Promise(() => {}) } })+ jest.useFakeTimers()++ const { findByText, getByText } = render(<ScoutNotesPanel skillName={SKILL_NAME} />)++ expect(getByText('Loading notes…')).toBeTruthy()++ await act(async () => {+ jest.advanceTimersByTime(PANEL_LOAD_TIMEOUT_MS)+ })++ expect(await findByText('Try again')).toBeTruthy()+ })})diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.tsindex 83463eccc3f2..43976802dbc7 100644--- a/products/signals/frontend/inbox/inboxAnalytics.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.ts@@ -29,6 +29,7 @@ export const INBOX_EVENTS = {WELCOME_MANUAL_SETUP_CLICKED: 'Inbox welcome manual setup clicked',INTRO_MODAL_VIEWED: 'Inbox intro modal viewed',PANEL_VIEWED: 'Inbox panel viewed',+ PANEL_LOAD_TIMED_OUT: 'Inbox panel load timed out',QUERY_CHANGED: 'Inbox query changed',REPORTS_IMPRESSED: 'Inbox reports impressed',REPORT_OPENED: 'Inbox report opened',@@ -153,6 +154,9 @@ export type InboxReportActionOutcome = 'success' | 'failure' | 'blocked' | 'limi*/export type InboxPanelName = 'runs' | 'config' | 'scratchpad' | 'findings' | 'triage'+/** A panel read that carries its own timeout, named so each one's stall rate reads separately. */+export type InboxPanelLoad = 'scout_notes' | 'scout_memory'+/** Which control moved the report list to a new query. `url` is a shared/deep link being applied. */export type InboxQueryChange =| 'scope'@@ -620,6 +624,18 @@ export function captureInboxPanelViewed(params: { panel: InboxPanelName; itemCou})}+/**+ * A panel read was aborted for taking too long. A request that never settles is invisible to+ * `client_request_failure`, which only records a response, so this is the one place a stalled pane+ * can be counted.+ */+export function capturePanelLoadTimedOut(params: { load: InboxPanelLoad; timeoutMs: number }): void {+ captureInboxEvent(INBOX_EVENTS.PANEL_LOAD_TIMED_OUT, {+ load: params.load,+ timeout_ms: params.timeoutMs,+ })+}+/*** The list moved to a new query — a filter, sort, search, or scope change. `Inbox viewed` fires once* per tab mount, so re-querying an already-open inbox left no trace at all: a user working a filtereddiff --git a/products/signals/frontend/inbox/logics/scoutNotesLogic.test.ts b/products/signals/frontend/inbox/logics/scoutNotesLogic.test.tsnew file mode 100644index 000000000000..3cd9064ecd6a--- /dev/null+++ b/products/signals/frontend/inbox/logics/scoutNotesLogic.test.ts@@ -0,0 +1,51 @@+/* oxlint-disable react-hooks/rules-of-hooks -- useMocks is a test helper, not a React hook */+import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { PANEL_LOAD_TIMEOUT_MS } from '../utils/panelLoadTimeout'+import { scoutNotesLogic } from './scoutNotesLogic'++const NOTES_URL = '/api/projects/:team_id/signals/scout/notes/'+const SKILL_NAME = 'signals-scout-daily-digest'++describe('scoutNotesLogic', () => {+ let logic: ReturnType<typeof scoutNotesLogic.build>+ let reads: number++ beforeEach(() => {+ reads = 0+ // Neither read settles. What the test is about is which one owns the pane when the first+ // read's bound expires.+ useMocks({+ get: {+ [NOTES_URL]: () => {+ reads += 1+ return new Promise(() => {})+ },+ },+ })+ initKeaTests()+ jest.useFakeTimers()+ logic = scoutNotesLogic({ skillName: SKILL_NAME })+ })++ afterEach(() => {+ logic.unmount()+ jest.useRealTimers()+ })++ it('keeps an older read that times out from failing the pane under a newer one', async () => {+ logic.mount()++ // Saving a note reloads the list, so a second read can start part-way through the first.+ await jest.advanceTimersByTimeAsync(PANEL_LOAD_TIMEOUT_MS / 2)+ logic.actions.loadNotes()+ await jest.advanceTimersByTimeAsync(PANEL_LOAD_TIMEOUT_MS / 2)++ expect(reads).toEqual(2)+ // The first read's bound has expired and the second is still in flight, so the pane stays+ // on its spinner rather than offering a retry for a read that was already superseded.+ expect(logic.values.notesLoadFailed).toBe(false)+ expect(logic.values.notesLoading).toBe(true)+ })+})diff --git a/products/signals/frontend/inbox/logics/scoutNotesLogic.ts b/products/signals/frontend/inbox/logics/scoutNotesLogic.tsindex eee9b6a03813..d5f8f3db9b38 100644--- a/products/signals/frontend/inbox/logics/scoutNotesLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutNotesLogic.ts@@ -13,6 +13,7 @@ import {import type { ScoutNoteApi } from 'products/signals/frontend/generated/api.schemas'import { captureScoutAction } from '../inboxAnalytics'+import { withPanelLoadTimeout } from '../utils/panelLoadTimeout'export interface ScoutNotesLogicProps {/** The scout these notes steer, or '' for the fleet-wide view. */@@ -81,7 +82,7 @@ export interface scoutNotesLogicActions {deleteNoteFailed: (noteId: string) => {noteId: string}- loadNotes: () => any+ loadNotes: (_payload: void) => voidloadNotesFailure: (error: string,errorObject?: any@@ -91,10 +92,10 @@ export interface scoutNotesLogicActions {}loadNotesSuccess: (notes: ScoutNoteApi[],- payload?: any+ payload?: void) => {notes: ScoutNoteApi[]- payload?: any+ payload?: void}}@@ -144,15 +145,29 @@ export const scoutNotesLogic = kea<scoutNotesLogicType>([notes: [[] as ScoutNoteApi[],{- loadNotes: async () => {+ loadNotes: async (_payload: void, breakpoint) => {const teamId = teamLogic.values.currentTeamIdif (!teamId) {return []}- return await signalsScoutNotesList(String(teamId), {- limit: NOTES_FETCH_LIMIT,- ...(props.skillName ? { skill_name: props.skillName } : {}),+ // A save reloads the notes, so a second read can start while the first is still+ // in flight. The breakpoint on both paths stops the older read answering for+ // the newer one — including when what it has to say is its own timeout.+ const notes = await withPanelLoadTimeout('scout_notes', (options) =>+ signalsScoutNotesList(+ String(teamId),+ {+ limit: NOTES_FETCH_LIMIT,+ ...(props.skillName ? { skill_name: props.skillName } : {}),+ },+ options+ )+ ).catch((error: unknown) => {+ breakpoint()+ throw error})+ breakpoint()+ return notes},},],diff --git a/products/signals/frontend/inbox/logics/scratchpadLogic.test.ts b/products/signals/frontend/inbox/logics/scratchpadLogic.test.tsindex be8bbe60ed87..b228752e41ef 100644--- a/products/signals/frontend/inbox/logics/scratchpadLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scratchpadLogic.test.ts@@ -10,6 +10,7 @@ import { initKeaTests } from '~/test/init'import type { ScratchpadEntryApi } from 'products/signals/frontend/generated/api.schemas'+import { PANEL_LOAD_TIMEOUT_MS } from '../utils/panelLoadTimeout'import {SCRATCHPAD_FETCH_LIMIT,SCRATCHPAD_PREVIEW_CHARS,@@ -63,6 +64,7 @@ describe('scratchpadLogic', () => {afterEach(() => {logic.unmount()+ jest.useRealTimers()})it('asks for previews rather than full bodies on the list read', async () => {@@ -545,6 +547,45 @@ describe('scratchpadLogic', () => {expect(describeLoadedSpan(entries)).toEqual(expected)})+ it('fails the window read when it never settles', async () => {+ useMocks({ get: { [SCRATCHPAD_URL]: () => new Promise(() => {}) } })+ jest.useFakeTimers()++ logic.actions.loadEntries()+ expect(logic.values.entriesLoading).toBe(true)++ jest.advanceTimersByTime(PANEL_LOAD_TIMEOUT_MS)+ await expectLogic(logic).toDispatchActions(['loadEntriesFailure'])++ expect(logic.values.entriesLoading).toBe(false)+ expect(logic.values.loadFailed).toBe(true)+ })++ // The span controls stay live through the first read, so a reader can change the span while+ // that read hangs. Nothing clears the flag on its own, so a superseded read that fails late+ // would leave the banner warning about rows that do answer the controls above.+ it('keeps a read that times out late from failing the window that superseded it', async () => {+ let reads = 0+ useMocks({+ get: {+ [SCRATCHPAD_URL]: () => {+ reads += 1+ return reads === 1 ? new Promise(() => {}) : [200, [WHOLE]]+ },+ },+ })+ jest.useFakeTimers()++ logic.actions.loadEntries()+ await jest.advanceTimersByTimeAsync(PANEL_LOAD_TIMEOUT_MS / 2)+ logic.actions.setTimeFilter('1h')+ await jest.advanceTimersByTimeAsync(PANEL_LOAD_TIMEOUT_MS / 2)++ expect(reads).toEqual(2)+ expect(logic.values.entries).toEqual([WHOLE])+ expect(logic.values.loadFailed).toBe(false)+ })+it('keeps the card usable when the body lookup fails', async () => {useMocks({ get: { [SCRATCHPAD_URL]: () => [500, {}] } })diff --git a/products/signals/frontend/inbox/logics/scratchpadLogic.ts b/products/signals/frontend/inbox/logics/scratchpadLogic.tsindex be4d56172e47..1b73bc3dc615 100644--- a/products/signals/frontend/inbox/logics/scratchpadLogic.ts+++ b/products/signals/frontend/inbox/logics/scratchpadLogic.ts@@ -8,6 +8,7 @@ import { teamLogic } from 'scenes/teamLogic'import { signalsReportsRetrieve, signalsScoutScratchpadSearch } from 'products/signals/frontend/generated/api'import type { ScratchpadEntryApi } from 'products/signals/frontend/generated/api.schemas'+import { withPanelLoadTimeout } from '../utils/panelLoadTimeout'import { SCOUT_ROSTER_WINDOW_HOURS, isPipelineWriter } from '../utils/scoutRunsWindow'import { BOOKKEEPING_KINDS, isReportUuid, scratchpadKindOf, scratchpadTopicOf } from '../utils/scratchpadKeys'@@ -368,10 +369,21 @@ export const scratchpadLogic = kea<scratchpadLogicType>([if (!teamId) {return []}- const page = await signalsScoutScratchpadSearch(String(teamId), {- limit: SCRATCHPAD_FETCH_LIMIT,- content_max_chars: SCRATCHPAD_PREVIEW_CHARS,- ...dateFromParam(values.timeFilter),+ const page = await withPanelLoadTimeout('scout_memory', (options) =>+ signalsScoutScratchpadSearch(+ String(teamId),+ {+ limit: SCRATCHPAD_FETCH_LIMIT,+ content_max_chars: SCRATCHPAD_PREVIEW_CHARS,+ ...dateFromParam(values.timeFilter),+ },+ options+ )+ ).catch((error: unknown) => {+ // A superseded read's own timeout is a stale answer too. Without this the+ // throw jumps the breakpoint below and fails a window that already landed.+ breakpoint()+ throw error})// Drop a stale response if the span moved on while this request was in flight.// A wider span is the slower read, so narrowing right after widening is thediff --git a/products/signals/frontend/inbox/utils/panelLoadTimeout.test.ts b/products/signals/frontend/inbox/utils/panelLoadTimeout.test.tsnew file mode 100644index 000000000000..1475b105a55a--- /dev/null+++ b/products/signals/frontend/inbox/utils/panelLoadTimeout.test.ts@@ -0,0 +1,46 @@+import posthog from 'posthog-js'++import { PromiseTimeoutError } from 'lib/utils/async'++import { INBOX_CLIENT, INBOX_EVENTS } from '../inboxAnalytics'+import { PANEL_LOAD_TIMEOUT_MS, withPanelLoadTimeout } from './panelLoadTimeout'++jest.mock('posthog-js')++function timeoutCaptures(): Record<string, any>[] {+ return (posthog.capture as jest.Mock).mock.calls+ .filter(([event]) => event === INBOX_EVENTS.PANEL_LOAD_TIMED_OUT)+ .map(([, properties]) => properties)+}++describe('withPanelLoadTimeout', () => {+ beforeEach(() => {+ jest.useFakeTimers()+ ;(posthog.capture as jest.Mock).mockClear()+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ it('records which read stalled when the bound expires', async () => {+ const outcome = withPanelLoadTimeout('scout_notes', () => new Promise<string[]>(() => {})).catch(+ (error) => error+ )++ jest.advanceTimersByTime(PANEL_LOAD_TIMEOUT_MS)++ expect(await outcome).toBeInstanceOf(PromiseTimeoutError)+ expect(timeoutCaptures()).toEqual([+ { inbox_client: INBOX_CLIENT, load: 'scout_notes', timeout_ms: PANEL_LOAD_TIMEOUT_MS },+ ])+ })++ it('records nothing for a read that settles in time', async () => {+ await expect(withPanelLoadTimeout('scout_memory', async () => ['entry'])).resolves.toEqual(['entry'])++ jest.advanceTimersByTime(PANEL_LOAD_TIMEOUT_MS)++ expect(timeoutCaptures()).toEqual([])+ })+})diff --git a/products/signals/frontend/inbox/utils/panelLoadTimeout.ts b/products/signals/frontend/inbox/utils/panelLoadTimeout.tsnew file mode 100644index 000000000000..4595bed9ccda--- /dev/null+++ b/products/signals/frontend/inbox/utils/panelLoadTimeout.ts@@ -0,0 +1,30 @@+import { PromiseTimeoutError, withTimeout } from 'lib/utils/async'++import { capturePanelLoadTimedOut } from '../inboxAnalytics'+import type { InboxPanelLoad } from '../inboxAnalytics'++/**+ * How long a side-panel read may stay in flight. A panel shows its spinner while the loader flag is+ * true and reaches its retry branch only once the read settles, so a read that never settles leaves+ * the pane with no way out. Well above a healthy read, so a slow but live one still lands.+ */+export const PANEL_LOAD_TIMEOUT_MS = 20_000++/**+ * Bound a panel's read, so one that never settles fails the loader and reaches whatever the panel+ * renders for a failed load. A read that never settles writes no `client_request_failure` row, so+ * the expiry is the only place it can be counted.+ */+export async function withPanelLoadTimeout<T>(+ load: InboxPanelLoad,+ request: (options: RequestInit) => Promise<T>+): Promise<T> {+ try {+ return await withTimeout((signal) => request({ signal }), PANEL_LOAD_TIMEOUT_MS, `${load} load timed out`)+ } catch (error) {+ if (error instanceof PromiseTimeoutError) {+ capturePanelLoadTimedOut({ load, timeoutMs: PANEL_LOAD_TIMEOUT_MS })+ }+ throw error+ }+}