: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
perf(signals): make the scout roster poll revalidate instead of refetch (#117938)
posthog[bot]6cd8a473a12e
diff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.pyindex d9e9ed5f07ee..f51afa8cedd0 100644--- a/products/signals/backend/scout_harness/tools/runs.py+++ b/products/signals/backend/scout_harness/tools/runs.py@@ -16,6 +16,8 @@ findings (and so left no `Signal` row to query against) — plus thefrom __future__ import annotations+import json+import hashlibfrom collections.abc import Iterablefrom dataclasses import asdict, dataclass, field, replacefrom datetime import datetime, timedelta@@ -82,6 +84,10 @@ STALENESS_INTERVAL_MULTIPLE = 3# monthly cron reads as ~31 days, a weekday-only one as the weekend gap.CRON_GAP_SAMPLES = 4+# Part of every `runs_version`. Bump it when `_to_summary` changes its output, so a client that+# holds a body in the old shape fetches the new one.+RUNS_VERSION_SCHEMA = 1+# Runaway guard on the fan-out of the per-scout probe. Deliberately a limit on *scouts* rather than# on rows: capping rows after the per-scout ranking would drop the slowest scouts' history, which is# the exact crowd-out this query exists to remove. A scout that makes the cut gets its full history.@@ -350,6 +356,26 @@ def recent_runs_per_scout() -> list[RunSummary]:"""Return each configured scout's most recent runs, newest first across the fleet.+ See `recent_run_ids_per_scout` for which runs those are.+ """+ run_ids = recent_run_ids_per_scout(+ team_id=team_id,+ per_scout_limit=per_scout_limit,+ max_age_days=max_age_days,+ exclude_skill_name=exclude_skill_name,+ )+ return runs_by_id(team_id=team_id, run_ids=run_ids)+++def recent_run_ids_per_scout(+ *,+ team_id: int,+ per_scout_limit: int = DEFAULT_RUNS_PER_SCOUT,+ max_age_days: int = DEFAULT_RUNS_PER_SCOUT_MAX_AGE_DAYS,+ exclude_skill_name: str | None = None,+) -> list[Any]:+ """Return the ids of each configured scout's most recent runs.+A cadence-invariant alternative to `search_recent_runs`' fixed time window. A fleet-widelookback has to serve an hourly scout and a weekly one from one budget: widen it and the busyscouts fill the result cap, leaving the sparse ones with a history that gets shorter the@@ -402,9 +428,13 @@ def recent_runs_per_scout(floor_days=floor_days,))+ return run_ids+++def runs_by_id(*, team_id: int, run_ids: list[Any]) -> list[RunSummary]:+ """Hydrate these runs into summaries, newest first."""if not run_ids:return []-rows = (SignalScoutRun.objects.filter(team_id=team_id, id__in=run_ids).select_related("task_run")@@ -414,6 +444,36 @@ def recent_runs_per_scout(return _without_deleted_reports([_to_summary(row, team_id=team_id) for row in rows], team_id=team_id)+def runs_version(*, team_id: int, run_ids: list[Any]) -> str:+ """A validator for what `runs_by_id` returns, read without hydrating the runs.++ The inbox roster polls the runs every minute, and most polls find nothing changed. Hydration+ reads wide rows, so a poll that only checks this version skips the expensive read. The read+ here takes only narrow columns. It covers every input of `_to_summary`: each write to the run+ row stamps `updated_at` (see `SignalScoutRun.save`), and the task run fields it reads move with+ the task run's status, completion stamp, or `updated_at`. A report deletion does not touch the+ run row, so the deleted ids go into the version too.+ """+ versions: list[tuple[str, ...]] = []+ touched: set[str] = set()+ for run_id, updated_at, status, task_updated_at, completed_at, emitted, edited in SignalScoutRun.objects.filter(+ team_id=team_id, id__in=run_ids+ ).values_list(+ "id",+ "updated_at",+ "task_run__status",+ "task_run__updated_at",+ "task_run__completed_at",+ "emitted_report_ids",+ "edited_report_ids",+ ):+ versions.append(tuple(str(part) for part in (run_id, updated_at, status, task_updated_at, completed_at)))+ touched.update(_touched_report_ids(emitted, edited))+ deleted = sorted(_deleted_report_ids(touched, team_id=team_id))+ seed = json.dumps([RUNS_VERSION_SCHEMA, sorted(versions), deleted])+ return hashlib.sha256(seed.encode()).hexdigest()++@dataclass(frozen=True)class FleetFindingsSummary:"""Cheap fleet-wide tally of recent scout output — what the "Scout findings" callout reads.diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 29ea7567a31b..fde1862af899 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -31,6 +31,7 @@ from django.db import transactionfrom django.db.models import Q, Valuefrom django.db.models.functions import Coalesce, Lower, NullIffrom django.utils import timezone+from django.utils.cache import get_conditional_responsefrom django.utils.dateparse import parse_datetimeimport structlog@@ -237,8 +238,10 @@ from products.signals.backend.scout_harness.tools.runs import (DEFAULT_RUNS_PER_SCOUT_MAX_AGE_DAYS,fleet_findings_summary,get_run,- recent_runs_per_scout,+ recent_run_ids_per_scout,run_id_for_sandbox_task,+ runs_by_id,+ runs_version,search_recent_runs,)from products.signals.backend.scout_harness.tools.scratchpad import (@@ -754,6 +757,10 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):response=SignalScoutRunSummarySerializer(many=True),description="Each scout's most recent runs, newest-first across the fleet.",),+ 304: OpenApiResponse(+ description="The runs match the `ETag` sent in `If-None-Match`, so the body is left out.",+ ),+ 412: OpenApiResponse(description="The runs do not match the `ETag` sent in `If-Match`."),},summary="List each scout's most recent runs",description=(@@ -785,18 +792,32 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):saved = saved_reads_for_request(request, _canonical_team_id(self))per_scout_limit = validated.get("per_scout_limit") or DEFAULT_RUNS_PER_SCOUTmax_age_days = validated.get("max_age_days") or DEFAULT_RUNS_PER_SCOUT_MAX_AGE_DAYS- rows = recent_runs_per_scout(+ run_ids = recent_run_ids_per_scout(team_id=_canonical_team_id(self),per_scout_limit=per_scout_limit,max_age_days=max_age_days,exclude_skill_name=saved.context.skill_name if saved is not None else None,)if saved is not None:+ rows = runs_by_id(team_id=_canonical_team_id(self), run_ids=run_ids)rows.extend(saved.recent_runs([], limit=per_scout_limit, date_from=timezone.now() - timedelta(days=max_age_days)))rows.sort(key=lambda row: row.created_at, reverse=True)- return Response(SignalScoutRunSummarySerializer([row.as_dict() for row in rows], many=True).data)+ return Response(SignalScoutRunSummarySerializer([row.as_dict() for row in rows], many=True).data)+ # The inbox polls this every minute. A browser revalidates a `no-cache` body with+ # If-None-Match by itself, so an unchanged fleet costs the narrow version read, not hydration.+ etag = f'"{runs_version(team_id=_canonical_team_id(self), run_ids=run_ids)}"'+ conditional = get_conditional_response(request._request, etag=etag)+ if conditional is not None:+ # 304 for a matching If-None-Match, 412 for a failed If-Match.+ response = Response(status=conditional.status_code)+ else:+ rows = runs_by_id(team_id=_canonical_team_id(self), run_ids=run_ids)+ response = Response(SignalScoutRunSummarySerializer([row.as_dict() for row in rows], many=True).data)+ response["ETag"] = etag+ response["Cache-Control"] = "private, no-cache"+ return response@validated_request(query_serializer=FleetFindingsSummaryQuerySerializer,diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 8dac03b2c6e0..a48f7eb85896 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -767,6 +767,42 @@ class TestScoutHarnessRecentPerScoutAPI(APIBaseTest):response = self.client.get(self._url(), data={"per_scout_limit": 5000})assert response.status_code == status.HTTP_400_BAD_REQUEST+ def test_an_unchanged_fleet_revalidates_without_hydrating_the_runs(self) -> None:+ _make_run(self.team)+ first = self.client.get(self._url())+ assert first.status_code == status.HTTP_200_OK+ with patch("products.signals.backend.scout_harness.views.runs_by_id") as runs_by_id:+ second = self.client.get(self._url(), HTTP_IF_NONE_MATCH=first["ETag"])+ assert second.status_code == status.HTTP_304_NOT_MODIFIED+ runs_by_id.assert_not_called()++ def test_a_failed_if_match_is_a_failed_precondition_not_a_cache_hit(self) -> None:+ _make_run(self.team)+ response = self.client.get(self._url(), HTTP_IF_MATCH='"stale"')+ assert response.status_code == status.HTTP_412_PRECONDITION_FAILED++ @parameterized.expand(["emit_tally", "task_run_settles", "report_deleted", "new_run"])+ def test_a_change_the_summary_shows_moves_the_etag(self, change: str) -> None:+ report = SignalReport.objects.create(team=self.team, status=SignalReport.Status.READY)+ run = _make_run(self.team, emitted_report_ids=[str(report.id)])+ first = self.client.get(self._url())++ if change == "emit_tally":+ run.emitted_finding_ids = ["finding-1"]+ run.emitted_count = 1+ run.save(update_fields=["emitted_finding_ids", "emitted_count"])+ elif change == "task_run_settles":+ run.task_run.status = run.task_run.Status.COMPLETED+ run.task_run.save(update_fields=["status"])+ elif change == "report_deleted":+ SignalReport.objects.filter(id=report.id).update(status=SignalReport.Status.DELETED)+ else:+ _make_run(self.team)++ second = self.client.get(self._url(), HTTP_IF_NONE_MATCH=first["ETag"])+ assert second.status_code == status.HTTP_200_OK+ assert second["ETag"] != first["ETag"]+class TestScoutHarnessFindingsSummaryAPI(APIBaseTest):def _url(self) -> str:diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.tsindex 1e178e1f6cd2..988cf0718a20 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.test.ts@@ -1050,9 +1050,15 @@ describe('scoutFleetLogic', () => {// eagerly is the worse failure though: the roster would show a frozen cost forever.// 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.+ // Both runs are live, so each poll asks for their costs again.mockSignalsScoutRunsRecentPerScout.mockResolvedValue([- makeRun({ run_id: 'run-priced' }),- makeRun({ run_id: 'run-other', skill_name: 'signals-scout-other' }),+ makeRun({ run_id: 'run-priced', status: 'in_progress', completed_at: null }),+ makeRun({+ run_id: 'run-other',+ skill_name: 'signals-scout-other',+ status: 'in_progress',+ completed_at: null,+ }),])mockSignalsScoutRunsTokenCosts.mockResolvedValue({costs: [@@ -1090,6 +1096,35 @@ describe('scoutFleetLogic', () => {expect(slices.get('signals-scout-other')).toBe(firstSlices.get('signals-scout-other'))})+ it('asks for a settled run once, and keeps asking for a live or newly settled one', async () => {+ const recentlySettled = new Date(Date.now() - 60_000).toISOString()+ mockSignalsScoutRunsRecentPerScout.mockResolvedValue([+ makeRun({ run_id: 'run-settled' }),+ makeRun({ run_id: 'run-just-settled', completed_at: recentlySettled }),+ makeRun({ run_id: 'run-live', status: 'in_progress', completed_at: null }),+ ])+ mockSignalsScoutRunsTokenCosts.mockResolvedValue({+ costs: [+ { run_id: 'run-settled', token_cost_usd: 4.03 },+ { run_id: 'run-just-settled', token_cost_usd: 1 },+ { run_id: 'run-live', token_cost_usd: 2 },+ ],+ available: true,+ })+ await mountAsStaff(true)++ logic.actions.loadScoutRuns()+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])+ logic.actions.loadScoutRuns()+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])++ expect(mockSignalsScoutRunsTokenCosts.mock.calls.map(([, body]) => body.run_ids)).toEqual([+ ['run-settled', 'run-just-settled', 'run-live'],+ ['run-just-settled', 'run-live'],+ ])+ expect(logic.values.scoutRunCosts.get('run-settled')).toBe(4.03)+ })+it('sends no further batches once the deployment reports it cannot price runs', async () => {// `available: false` is the same answer for every batch, and each one costs the backend// a run-row read and a traceback, so asking again buys nothing.@@ -1163,6 +1198,32 @@ describe('scoutFleetLogic', () => {expect(logic.values.scoutRunCosts.get('run-0')).toBe(4.03)})+ it('asks again for a batch whose costs never reached the store because a sibling failed', async () => {+ const runIds = Array.from({ length: 401 }, (_, index) => `run-${index}`)+ mockSignalsScoutRunsRecentPerScout.mockResolvedValue(runIds.map((run_id) => makeRun({ run_id })))+ mockSignalsScoutRunsTokenCosts.mockImplementation(async (_projectId, body) => {+ if (body.run_ids.includes('run-200')) {+ throw new ApiError('nope', 500)+ }+ if (body.run_ids.includes('run-400')) {+ await new Promise((resolve) => setTimeout(resolve, 5))+ }+ return { costs: body.run_ids.map((run_id) => ({ run_id, token_cost_usd: 1 })), available: true }+ })+ await mountAsStaff(true)++ logic.actions.loadScoutRuns()+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])+ await new Promise((resolve) => setTimeout(resolve, 20))+ mockSignalsScoutRunsTokenCosts.mockClear().mockResolvedValue({ costs: [], available: true })+ logic.actions.loadScoutRuns()+ await expectLogic(logic).toDispatchActions(['loadScoutRunsSuccess', 'loadScoutRunCostsSuccess'])++ const askedAgain = mockSignalsScoutRunsTokenCosts.mock.calls.flatMap(([, body]) => body.run_ids)+ expect(askedAgain).toContain('run-400')+ expect(askedAgain).not.toContain('run-0')+ })+// Recovering in the loader skips the gate `initKea` applies to loader failures, so the// loader reapplies it. A backend fault must still leave a client-side exception behind, and// a gateway blip must not, since filing those buries the crashes worth seeing.diff --git a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts b/products/signals/frontend/inbox/logics/scoutFleetLogic.tsindex 68ea210db55c..c66219b1b8e6 100644--- a/products/signals/frontend/inbox/logics/scoutFleetLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutFleetLogic.ts@@ -157,6 +157,10 @@ const RUN_COST_BATCH_LIMIT = 200// How many batches are in flight together. Enough to hide the round trips of a materialized fleet,// few enough that one poll cannot queue every other roster request behind its own burst.const RUN_COST_BATCH_CONCURRENCY = 4+// The cost endpoint keeps a settled run's total open for 5 minutes after it settles, while its last+// generations cross ingestion, and it caches a total read in that grace for 60 seconds more. A run+// that settled before this answers with its final total. The rest covers clock skew.+const RUN_COST_FINAL_AFTER_MS = 10 * 60_000// Roster filter state also lives in the URL so a filtered view survives a refresh and is shareable.// The search param is written on this debounce, so typing does not rewrite the URL per keystroke.@@ -243,6 +247,14 @@ function sameTags(a: string[], b: string[]): boolean {// Keep the cost map reference-stable when a poll re-derives the same numbers, the way// `reconcileById` does for the polled lists. A settled run's total is cached for an hour, so an// unchanged poll is the normal case, and every roster card subscribes to this map.+function runCostIsFinal(run: SignalScoutRunSummary, now: number): boolean {+ if (!isSettledRun(run)) {+ return false+ }+ // The backend treats a settled run with no completion stamp as final too.+ return !run.completed_at || now - new Date(run.completed_at).getTime() > RUN_COST_FINAL_AFTER_MS+}+function reuseCostsIfUnchanged(previous: Map<string, number>, next: Map<string, number>): Map<string, number> {if (previous.size !== next.size) {return next@@ -785,7 +797,7 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([mergeScoutRunCosts: (costs: Map<string, number>) => ({ costs }),}),- loaders(({ actions, values }) => ({+ loaders(({ actions, values, cache }) => ({scoutConfigs: [null as SignalScoutConfig[] | null,{@@ -909,11 +921,11 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([},},],- // Per-run model spend, staff only. The roster's own runs are the batch: one request per- // `RUN_COST_BATCH_LIMIT` ids, and the endpoint caches a settled run's total, so a poll over- // an unchanged fleet costs cache reads rather than a query per run. Runs with nothing- // attributed are dropped rather than stored as 0 — the tooltip then says nothing about- // cost, instead of claiming the run was free.+ // Per-run model spend, staff only. The roster's runs are the batch: one request per+ // `RUN_COST_BATCH_LIMIT` ids. A run whose answer is final is asked once, so a poll over+ // an unchanged fleet asks only for the live runs. Runs with nothing attributed are dropped+ // rather than stored as 0 — the tooltip then says nothing about cost, instead of claiming+ // the run was free.scoutRunCosts: [new Map<string, number>(),{@@ -922,11 +934,23 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([if (!teamId || !values.isStaff || values.scoutRuns.length === 0) {return values.scoutRunCosts}+ const finalRunIds: Set<string> = (cache.finalRunCostIds ??= new Set<string>())+ const now = Date.now()+ const pending = values.scoutRuns.filter((run) => !finalRunIds.has(run.run_id))+ const finalOnAnswer = new Set(+ pending.filter((run) => runCostIsFinal(run, now)).map((run) => run.run_id)+ )const batches = chunk(- values.scoutRuns.map((run) => run.run_id),+ pending.map((run) => run.run_id),RUN_COST_BATCH_LIMIT)const costs = new Map<string, number>()+ for (const run of values.scoutRuns) {+ const known = values.scoutRunCosts.get(run.run_id)+ if (finalRunIds.has(run.run_id) && known !== undefined) {+ costs.set(run.run_id, known)+ }+ }const priceBatch = async (batch: string[]): Promise<Map<string, number> | null> => {const response = await signalsScoutRunsTokenCosts(String(teamId), { run_ids: batch })breakpoint()@@ -947,21 +971,32 @@ export const scoutFleetLogic = kea<scoutFleetLogicType>([}return priced}+ // Only after the batch's costs reach the store, so a failed sibling cannot leave a+ // run final with no cost on screen.+ const markFinal = (batch: string[]): void => {+ for (const runId of batch) {+ if (finalOnAnswer.has(runId)) {+ finalRunIds.add(runId)+ }+ }+ }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. Each wave lands as one merge,// because every merge is a store update that the whole roster processes.- const first = await priceBatch(batches[0])+ const first = batches.length > 0 ? await priceBatch(batches[0]) : nullif (first) {actions.mergeScoutRunCosts(first)+ markFinal(batches[0])for (let start = 1; start < batches.length; start += RUN_COST_BATCH_CONCURRENCY) {const wave = batches.slice(start, start + RUN_COST_BATCH_CONCURRENCY)const priced = await Promise.all(wave.map(priceBatch))actions.mergeScoutRunCosts(new Map(priced.flatMap((batch) => (batch ? [...batch] : []))))+ wave.forEach((batch, index) => priced[index] && markFinal(batch))if (priced.includes(null)) {break}