: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): stop re-rendering the whole scout roster per cost batch (#115224)
posthog[bot]813401d19468
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsxindex 349e4de5337d..7346e7c201ff 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutHealthStrip.tsx@@ -19,7 +19,7 @@ import {import { ScoutStatusTag } from './ScoutBadges'import { ScoutCadenceLabel } from './ScoutCadenceLabel'import { ScoutNextRunLabel } from './ScoutNextRunLabel'-import { ScoutRunBoxes } from './ScoutRunBoxes'+import { ScoutRosterRunBoxes } from './ScoutRosterRunBoxes'import { ScoutStatusDot } from './ScoutStatusDot'/**@@ -59,8 +59,7 @@ export function ScoutHealthStrip({noteCount: numberlearnedCount: number}): JSX.Element {- const { scoutRunCosts, scoutCostRollups, expensiveRunCostThreshold, scoutRunsLoadedOnce, scoutRunsCoverFleet } =- useValues(scoutFleetLogic)+ const { scoutCostRollups, scoutRunsLoadedOnce, scoutRunsCoverFleet } = useValues(scoutFleetLogic)const { currentTeam } = useValues(teamLogic)const now = new Date()@@ -103,7 +102,7 @@ export function ScoutHealthStrip({<Segment tooltip={`Runs this scout made in the ${SCOUT_RUNS_PER_SCOUT_LABEL}, quiet ones included.`}>{runs.length > 0 ? (<>- <ScoutRunBoxes runs={runs} costs={scoutRunCosts} costThreshold={expensiveRunCostThreshold} />+ <ScoutRosterRunBoxes skillName={config.skill_name} runs={runs} /><span className="whitespace-nowrap tabular-nums">{pluralize(runs.length, 'run')}</span>{/* The counts here and below change while the page is open, so each numbergets its own element — see "Rule 7" in frontend/src/AGENTS.md for what adiff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsxindex 4938d0a5a1d5..2edb032c8cde 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterCard.tsx@@ -16,7 +16,7 @@ import { ScoutCadenceLabel } from './ScoutCadenceLabel'import { ScoutEnabledSwitch } from './ScoutConfigControls'import { ScoutCostLine } from './ScoutCostLine'import { ScoutNextRunLabel } from './ScoutNextRunLabel'-import { ScoutRunBoxes } from './ScoutRunBoxes'+import { ScoutRosterRunBoxes } from './ScoutRosterRunBoxes'import { ScoutStatusDot } from './ScoutStatusDot'import { ScoutWriteAccessTag } from './ScoutWriteAccessTag'@@ -41,15 +41,8 @@ function MetaSeparator(): JSX.Element {*/export const ScoutRosterCard = memo(function ScoutRosterCard({ row }: { row: ScoutRosterRow }): JSX.Element {const { config, group } = row- const {- rollups,- updatingScoutIds,- scoutRunsLoadedOnce,- scoutRunsCoverFleet,- scoutRunCosts,- scoutCostRollups,- expensiveRunCostThreshold,- } = useValues(scoutFleetLogic)+ const { rollups, updatingScoutIds, scoutRunsLoadedOnce, scoutRunsCoverFleet, scoutCostRollups } =+ useValues(scoutFleetLogic)const { updateScoutConfig } = useActions(scoutFleetLogic)const { currentTeam } = useValues(teamLogic)const now = new Date()@@ -111,7 +104,7 @@ export const ScoutRosterCard = memo(function ScoutRosterCard({ row }: { row: Sco{/* A fixed strip width on wide rows keeps every row's newest run on one vertical line. */}<div className="flex min-w-0 justify-end @lg:w-52">{runs.length > 0 ? (- <ScoutRunBoxes runs={runs} costs={scoutRunCosts} costThreshold={expensiveRunCostThreshold} />+ <ScoutRosterRunBoxes skillName={config.skill_name} runs={runs} />) : (// Until the runs request has landed once, an empty rollup means "not// loaded", not "never ran"; the poll retries a failed load on its own. Pastdiff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRosterRunBoxes.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterRunBoxes.tsxnew file mode 100644index 000000000000..4c17661f6883--- /dev/null+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRosterRunBoxes.tsx@@ -0,0 +1,28 @@+import { useValues } from 'kea'+import { memo } from 'react'++import { scoutFleetLogic } from '../../../logics/scoutFleetLogic'+import { SignalScoutRunSummary } from '../../../types'+import { ScoutRunBoxes } from './ScoutRunBoxes'++/**+ * A scout's run strip with that scout's costs. The cost subscription lives here, not in the card or+ * table that holds the strip, so a cost batch re-renders this small component and not the whole row.+ * `ScoutRunBoxes` then skips its render when the scout's cost slice kept its reference.+ */+export const ScoutRosterRunBoxes = memo(function ScoutRosterRunBoxes({+ skillName,+ runs,+}: {+ skillName: string+ runs: SignalScoutRunSummary[]+}): JSX.Element | null {+ const { scoutRunCostsByScout, expensiveRunCostThreshold } = useValues(scoutFleetLogic)+ return (+ <ScoutRunBoxes+ runs={runs}+ costs={scoutRunCostsByScout.get(skillName)}+ costThreshold={expensiveRunCostThreshold}+ />+ )+})diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsxindex ec5a847a4f76..1b21c22a1f03 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutRunBoxes.tsx@@ -1,4 +1,4 @@-import { useMemo } from 'react'+import { memo, useMemo } from 'react'import { Link, Tooltip } from '@posthog/lemon-ui'@@ -73,7 +73,7 @@ function runTooltip(run: SignalScoutRunSummary, now: Date, costUsd: number | und* vertical line. Left-aligning instead scatters the newest run across the column by run count,* which is the one box a reader is scanning for.*/-export function ScoutRunBoxes({+export const ScoutRunBoxes = memo(function ScoutRunBoxes({runs,costs,costThreshold,@@ -139,4 +139,4 @@ export function ScoutRunBoxes({{hidden > 0 ? <span className="shrink-0 text-[10px] text-muted">+{hidden}</span> : null}</div>)-}+})diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterTable.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterTable.tsxindex 5c6da4bdedb4..2d649ffd9dbe 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterTable.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterTable.tsx@@ -16,7 +16,7 @@ import { scoutCostColumns } from './ScoutCostCell'import { ScoutNameCell } from './ScoutNameCell'import { ScoutNextRunLabel } from './ScoutNextRunLabel'import { ScoutOwnersCell } from './ScoutOwnersCell'-import { ScoutRunBoxes } from './ScoutRunBoxes'+import { ScoutRosterRunBoxes } from './ScoutRosterRunBoxes'import { ScoutStatusDot } from './ScoutStatusDot'/**@@ -32,16 +32,8 @@ import { ScoutStatusDot } from './ScoutStatusDot'* nothing to say about a canonical one.*/export function ScoutsRosterTable({ compact }: { compact: boolean }): JSX.Element {- const {- rosterScouts,- rollups,- updatingScoutIds,- scoutRunsLoadedOnce,- scoutRunsCoverFleet,- scoutRunCosts,- scoutCostRollups,- expensiveRunCostThreshold,- } = useValues(scoutFleetLogic)+ const { rosterScouts, rollups, updatingScoutIds, scoutRunsLoadedOnce, scoutRunsCoverFleet, scoutCostRollups } =+ useValues(scoutFleetLogic)const { updateScoutConfig } = useActions(scoutFleetLogic)if (rosterScouts.length === 0) {@@ -157,13 +149,7 @@ export function ScoutsRosterTable({ compact }: { compact: boolean }): JSX.Elemenrender: (_, row: ScoutRosterRow) => {const runs = rollups.get(row.config.skill_name)?.runs ?? []if (runs.length) {- return (- <ScoutRunBoxes- runs={runs}- costs={scoutRunCosts}- costThreshold={expensiveRunCostThreshold}- />- )+ return <ScoutRosterRunBoxes skillName={row.config.skill_name} runs={runs} />}// Until the runs request has landed once, an empty rollup means "not// loaded", not "never ran"; the poll retries a failed load on its own. Pastdiff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.tsindex 6975928eedad..1e178e1f6cd2 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts@@ -1048,9 +1048,17 @@ describe('scoutFleetLogic', () => {// Every roster card subscribes to this map and ScoutRunBoxes keys its tooltip memo on it,// so a fresh map each poll re-renders the whole roster for nothing. Reusing it too// eagerly is the worse failure though: the roster would show a frozen cost forever.- mockSignalsScoutRunsRecentPerScout.mockResolvedValue([makeRun({ run_id: 'run-priced' })])+ // Each strip reads its own scout's slice, so a moved cost must replace only that+ // scout's slice and leave every other strip's slice, and its render, alone.+ mockSignalsScoutRunsRecentPerScout.mockResolvedValue([+ makeRun({ run_id: 'run-priced' }),+ makeRun({ run_id: 'run-other', skill_name: 'signals-scout-other' }),+ ])mockSignalsScoutRunsTokenCosts.mockResolvedValue({- costs: [{ run_id: 'run-priced', token_cost_usd: 4.03 }],+ costs: [+ { run_id: 'run-priced', token_cost_usd: 4.03 },+ { run_id: 'run-other', token_cost_usd: 0.5 },+ ],available: true,})await mountAsStaff(true)@@ -1058,6 +1066,7 @@ describe('scoutFleetLogic', () => {logic.actions.loadScoutRuns()await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])const first = logic.values.scoutRunCosts+ const firstSlices = logic.values.scoutRunCostsByScoutexpect(first.get('run-priced')).toBe(4.03)logic.actions.loadScoutRuns()@@ -1065,13 +1074,20 @@ describe('scoutFleetLogic', () => {expect(logic.values.scoutRunCosts).toBe(first)mockSignalsScoutRunsTokenCosts.mockResolvedValue({- costs: [{ run_id: 'run-priced', token_cost_usd: 5.11 }],+ costs: [+ { run_id: 'run-priced', token_cost_usd: 5.11 },+ { run_id: 'run-other', token_cost_usd: 0.5 },+ ],available: true,})logic.actions.loadScoutRuns()await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])expect(logic.values.scoutRunCosts).not.toBe(first)expect(logic.values.scoutRunCosts.get('run-priced')).toBe(5.11)+ const slices = logic.values.scoutRunCostsByScout+ expect(slices.get(BASE_CONFIG.skill_name)).not.toBe(firstSlices.get(BASE_CONFIG.skill_name))+ expect(slices.get(BASE_CONFIG.skill_name)?.get('run-priced')).toBe(5.11)+ expect(slices.get('signals-scout-other')).toBe(firstSlices.get('signals-scout-other'))})it('sends no further batches once the deployment reports it cannot price runs', async () => {@@ -1095,8 +1111,12 @@ describe('scoutFleetLogic', () => {const runIds = Array.from({ length: 401 }, (_, index) => `run-${index}`)mockSignalsScoutRunsRecentPerScout.mockResolvedValue(runIds.map((run_id) => makeRun({ run_id })))const held: Array<() => void> = []+ // A tenth of each batch costs more, so the fleet has a top decile to mark.mockSignalsScoutRunsTokenCosts.mockImplementation(async (_projectId, body) => {- const costs = [{ run_id: body.run_ids[0], token_cost_usd: 1 }]+ const costs = body.run_ids.map((run_id, index) => ({+ run_id,+ token_cost_usd: index % 10 === 0 ? 5 : 1,+ }))if (!body.run_ids.includes('run-0')) {await new Promise<void>((resolve) => held.push(resolve))}@@ -1108,15 +1128,19 @@ describe('scoutFleetLogic', () => {await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'mergeScoutRunCosts'])await new Promise((resolve) => setTimeout(resolve, 0))- expect(logic.values.scoutRunCosts.get('run-0')).toBe(1)+ expect(logic.values.scoutRunCosts.get('run-0')).toBe(5)expect(logic.values.scoutRunCostsLoading).toBe(true)expect(held).toHaveLength(2)+ // The threshold ranks the whole fleet, so it waits for the load to finish rather than+ // moving with each batch and re-rendering every strip on the roster.+ expect(logic.values.expensiveRunCostThreshold).toBeNull()held.forEach((resolve) => resolve())await expectLogic(logic).toDispatchActions(['loadScoutRunCostsSuccess'])- expect(logic.values.scoutRunCosts.get('run-200')).toBe(1)- expect(logic.values.scoutRunCosts.get('run-400')).toBe(1)+ expect(logic.values.scoutRunCosts.get('run-200')).toBe(5)+ expect(logic.values.scoutRunCosts.get('run-400')).toBe(5)+ expect(logic.values.expensiveRunCostThreshold).toBe(5)})it('keeps the batches that answered when a later batch fails', async () => {diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.tsindex ce1338486eee..68ea210db55c 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts@@ -76,6 +76,7 @@ import {isSettledRun,rosterRunCosts,runResponseCoversFleet,+ scoutRunCostSlices,scoutDisplayName,SCOUT_ROSTER_WINDOW_DAYS,SCOUT_ROSTER_WINDOW_HOURS,@@ -325,6 +326,7 @@ export interface ScoutChatRequest {templateId: string | null}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scoutFleetLogicValues {dataProcessingAccepted: boolean // aiConsentLogicdataProcessingApprovalDisabledReason: string | null // aiConsentLogic@@ -382,6 +384,7 @@ export interface scoutFleetLogicValues {scoutOwnerOptions: ScoutOwnerOption[]scoutRosterSort: ScoutRosterSortscoutRunCosts: Map<string, number>+ scoutRunCostsByScout: Map<string, Map<string, number>>scoutRunCostsLoading: booleanscoutRuns: SignalScoutRunSummary[]scoutRunsCoverFleet: boolean@@ -391,6 +394,7 @@ export interface scoutFleetLogicValues {scoutTagOptions: ScoutTagOption[]selectedScoutOwner: string | nullselectedScoutTags: string[]+ settledScoutRunCosts: Map<string, number>updatingScoutIds: string[]}@@ -645,6 +649,10 @@ export interface scoutFleetLogicMeta {) => void | Promise<void>}__keaTypeGenInternalSelectorTypes: {+ scoutRunCostsByScout: (+ scoutRuns: SignalScoutRunSummary[],+ scoutRunCosts: Map<string, number>+ ) => Map<string, Map<string, number>>aiConsentDisabledReason: (dataProcessingAccepted: boolean,dataProcessingApprovalDisabledReason: string | null@@ -653,7 +661,7 @@ export interface scoutFleetLogicMeta {scoutRunsCoverFleet: (scoutConfigs: SignalScoutConfigApi[] | null) => booleanexpensiveRunCostThreshold: (scoutRuns: SignalScoutRunSummary[],- scoutRunCosts: Map<string, number>+ settledScoutRunCosts: Map<string, number>) => number | nullscoutCostRollups: (scoutCosts: ScoutCostsApi | null) => Map<string, ScoutCostRollup>isStaff: (user: null | import('~/types').UserType) => boolean@@ -919,14 +927,14 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([RUN_COST_BATCH_LIMIT)const costs = new Map<string, number>()- const priceBatch = async (batch: string[]): Promise<boolean> => {+ const priceBatch = async (batch: string[]): Promise<Map<string, number> | null> => {const response = await signalsScoutRunsTokenCosts(String(teamId), { run_ids: batch })breakpoint()// This deployment has no internal project to price runs against, so every// batch answers the same way and each one costs the backend a run-row read// and a traceback. Every cost stays unknown.if (!response.available) {- return false+ return null}const priced = new Map<string, number>()for (const cost of response.costs) {@@ -937,18 +945,24 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([for (const [runId, cost] of priced) {costs.set(runId, cost)}- actions.mergeScoutRunCosts(priced)- return true+ return priced}try {// The first batch also answers whether this deployment prices runs at all,// so it goes on its own. The rest go a wave at a time: a materialized fleet// is several batches, and holding them all back leaves the whole strip- // costless until the slowest one answers.- if (await priceBatch(batches[0])) {+ // costless until the slowest one answers. Each wave lands as one merge,+ // because every merge is a store update that the whole roster processes.+ const first = await priceBatch(batches[0])+ if (first) {+ actions.mergeScoutRunCosts(first)for (let start = 1; start < batches.length; start += RUN_COST_BATCH_CONCURRENCY) {const wave = batches.slice(start, start + RUN_COST_BATCH_CONCURRENCY)- if ((await Promise.all(wave.map(priceBatch))).includes(false)) {+ const priced = await Promise.all(wave.map(priceBatch))+ actions.mergeScoutRunCosts(+ new Map(priced.flatMap((batch) => (batch ? [...batch] : [])))+ )+ if (priced.includes(null)) {break}}@@ -1082,6 +1096,18 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([mergeCosts(state, costs),},],+ // The cost map as of the last finished load. The expensive-run threshold ranks the whole+ // fleet, so a half-priced fleet gives a wrong threshold, and a threshold that moves with each+ // batch re-renders every strip on the roster.+ settledScoutRunCosts: [+ new Map<string, number>(),+ {+ loadScoutRunCostsSuccess: (+ _: Map<string, number>,+ { scoutRunCosts }: { scoutRunCosts: Map<string, number> }+ ) => scoutRunCosts,+ },+ ],// Tracks which CTA's chat-task kickoff is mid-flight, keyed by its chat type, so only the// pressed chip spins (the others merely disable). A shared boolean spun all three at once.runningChatType: [@@ -1238,6 +1264,24 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([],}),+ selectors(() => {+ // Each logic instance keeps its last slices, so a scout whose costs did not move keeps its+ // slice reference across cost batches and polls.+ let previousCostSlices = new Map<string, Map<string, number>>()+ return {+ scoutRunCostsByScout: [+ (s) => [s.scoutRuns, s.scoutRunCosts],+ (+ scoutRuns: SignalScoutRunSummary[],+ scoutRunCosts: Map<string, number>+ ): Map<string, Map<string, number>> => {+ previousCostSlices = scoutRunCostSlices(scoutRuns, scoutRunCosts, previousCostSlices)+ return previousCostSlices+ },+ ],+ }+ }),+selectors({aiConsentDisabledReason: [(s) => [s.dataProcessingAccepted, s.dataProcessingApprovalDisabledReason],@@ -1256,9 +1300,9 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([(scoutConfigs: SignalScoutConfig[] | null): boolean => runResponseCoversFleet(scoutConfigs?.length ?? 0),],expensiveRunCostThreshold: [- (s) => [s.scoutRuns, s.scoutRunCosts],- (scoutRuns: SignalScoutRunSummary[], scoutRunCosts: Map<string, number>): number | null =>- expensiveRunCostThreshold(rosterRunCosts(scoutRuns, scoutRunCosts)),+ (s) => [s.scoutRuns, s.settledScoutRunCosts],+ (scoutRuns: SignalScoutRunSummary[], settledScoutRunCosts: Map<string, number>): number | null =>+ expensiveRunCostThreshold(rosterRunCosts(scoutRuns, settledScoutRunCosts)),],scoutCostRollups: [(s) => [s.scoutCosts],diff --git a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts b/products/signals/frontend/inbox/utils/scoutRunsWindow.tsindex cee5d0ea6e4a..3fe9f157674a 100644--- a/products/signals/frontend/inbox/utils/scoutRunsWindow.ts+++ b/products/signals/frontend/inbox/utils/scoutRunsWindow.ts@@ -215,6 +215,51 @@ export function rosterRunCosts(runs: SignalScoutRunSummary[], costs: Map<string,return onRoster}+function sameCosts(a: Map<string, number>, b: Map<string, number>): boolean {+ if (a.size !== b.size) {+ return false+ }+ for (const [runId, cost] of b) {+ if (a.get(runId) !== cost) {+ return false+ }+ }+ return true+}++/**+ * The roster's run costs split by scout, so each strip reads only its own runs. A scout whose+ * costs did not change keeps its slice from `previous`. A cost batch prices runs of a few scouts,+ * and a fresh slice for every scout would re-render every strip on the roster for each batch.+ * A scout with no priced run has no slice.+ */+export function scoutRunCostSlices(+ runs: SignalScoutRunSummary[],+ costs: Map<string, number>,+ previous: Map<string, Map<string, number>>+): Map<string, Map<string, number>> {+ const slices = new Map<string, Map<string, number>>()+ for (const run of runs) {+ const cost = costs.get(run.run_id)+ if (cost === undefined) {+ continue+ }+ let slice = slices.get(run.skill_name)+ if (!slice) {+ slice = new Map()+ slices.set(run.skill_name, slice)+ }+ slice.set(run.run_id, cost)+ }+ for (const [skillName, slice] of slices) {+ const prior = previous.get(skillName)+ if (prior && sameCosts(prior, slice)) {+ slices.set(skillName, prior)+ }+ }+ return slices+}+// Below this many priced runs the top decile moves with every run that lands, so the marker would// point at a different box each poll and mean nothing.const MIN_PRICED_RUNS_FOR_COST_MARKER = 20