: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 the scouts roster refetching deleted reports (#105546)
posthog[bot]8ec8f82595db
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 7e581d06e0ef..0e6d709da5bd 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -14041,7 +14041,7 @@ snapshots:scenes-app-signals-artefactloglist--replacement-lifecycle--dark:hash: v1.k794b7964.f723b2160bdf85cd5a827fa3dac4c281d75950f47555cdef7fc01f2ef689dfc6.wAOg7AG2Pf4mYO8EjKdD8lFlC1Ulv4MhkXIEMkzfCrgscenes-app-signals-artefactloglist--replacement-lifecycle--light:- hash: v1.k794b7964.9c43f6666a1a6a374d7de2874e8041d143d372b268675b7effc129b4759c676f.1ksfg48ORs-DX0VjvAFzGKg98c7Ikzp_Cr-tksdqVZ8+ hash: v1.k794b7964.bb6f3f49907d13832cfad4b4c2c5ca3793bb4b29ab9bfcdda58a3abb848996a6.IjmVg1UPLdiV6r2dZcxKXAqYdiY6qBiuRiVeIqhd_hYscenes-app-signals-artefactloglist--revision-limit--dark:hash: v1.k794b7964.d9e475caa06b8c102d144f5a714e26addf9fdfe71d0b5008a4d09448142d60d7.KrLa7tfvjyW7kx7jRx7f8a2uctJrVoOP47m2TBccgrcscenes-app-signals-artefactloglist--revision-limit--light:diff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.pyindex 1461816650d5..edc7b8e57e6d 100644--- a/products/signals/backend/scout_harness/tools/runs.py+++ b/products/signals/backend/scout_harness/tools/runs.py@@ -16,7 +16,8 @@ findings (and so left no `Signal` row to query against) — plus thefrom __future__ import annotations-from dataclasses import asdict, dataclass, field+from collections.abc import Iterable+from dataclasses import asdict, dataclass, field, replacefrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Anyfrom uuid import UUID@@ -29,7 +30,7 @@ from django.utils import timezoneimport structlogfrom croniter import CroniterError, croniter-from products.signals.backend.models import SignalScoutConfig, SignalScoutRun+from products.signals.backend.models import SignalReport, SignalScoutConfig, SignalScoutRunfrom products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAMfrom products.tasks.backend.facade import api as tasks_facade@@ -236,7 +237,7 @@ def search_recent_runs(if skill_version is not None:qs = qs.filter(skill_version=skill_version)qs = qs[:clamped_limit]- return [_to_summary(row, team_id=team_id) for row in qs]+ return _without_deleted_reports([_to_summary(row, team_id=team_id) for row in qs], team_id=team_id)def _schedule_gap_minutes(config: SignalScoutConfig) -> int:@@ -387,7 +388,7 @@ def recent_runs_per_scout(.select_related("task_run").order_by("-created_at"))- return [_to_summary(row, team_id=team_id) for row in rows]+ return _without_deleted_reports([_to_summary(row, team_id=team_id) for row in rows], team_id=team_id)@dataclass(frozen=True)@@ -469,13 +470,27 @@ def fleet_findings_summary(*, team_id: int, window_hours: int = DEFAULT_FINDINGS# Distinct touched reports, most recently touched first (rows are newest-first), capped at the# same 50 the findings page keeps (`MAX_FLEET_TOUCHED_REPORTS`) — so the callout never# advertises reports the page has sliced away. Dict preserves insertion (recency) order.+ # Deleted reports are unreachable by id, so the page can't list one however recently it was+ # touched — counting it here would advertise a row that silently never renders.+ deleted_report_ids = _deleted_report_ids(+ {+ report_id+ for _, _, _, emitted_report_ids, edited_report_ids in materialized+ for report_id in _touched_report_ids(emitted_report_ids, edited_report_ids)+ },+ team_id=team_id,+ )kept_report_ids: dict[str, None] = {}for _, _, _, emitted_report_ids, edited_report_ids in materialized:- for report_id in [*(edited_report_ids or []), *(emitted_report_ids or [])]:+ for report_id in _touched_report_ids(emitted_report_ids, edited_report_ids):+ if report_id in deleted_report_ids:+ continueif report_id not in kept_report_ids and len(kept_report_ids) < FLEET_FINDINGS_SUMMARY_REPORT_CAP:kept_report_ids[report_id] = Nonefor _, skill_name, _, emitted_report_ids, edited_report_ids in materialized:- if any(report_id in kept_report_ids for report_id in [*(emitted_report_ids or []), *(edited_report_ids or [])]):+ if any(+ report_id in kept_report_ids for report_id in _touched_report_ids(emitted_report_ids, edited_report_ids)+ ):scouts.add(skill_name)# Authoring supersedes an edit of the same report — one report, one bucket.authored_reports: set[str] = set()@@ -558,10 +573,57 @@ def _to_summary(row: SignalScoutRun, *, team_id: int) -> RunSummary:def _to_detail(row: SignalScoutRun, *, team_id: int) -> RunDetail:- summary = _to_summary(row, team_id=team_id)+ summary = _without_deleted_reports([_to_summary(row, team_id=team_id)], team_id=team_id)[0]return RunDetail(**asdict(summary))+def _without_deleted_reports(rows: list[RunSummary], *, team_id: int) -> list[RunSummary]:+ """Drop deleted reports out of the touched-report lists a run exposes.++ Deletion is terminal and the report endpoints subtract the deleted status from the statuses+ they serve, so a deleted id is unreachable by id for good. The run row keeps naming it, so a+ reader that resolves these ids — the inbox roster above all — asks for the same dead ids on+ every load and every poll. One query per rollup keeps them out of the response instead.+ """+ touched = {report_id for row in rows for report_id in (*row.emitted_report_ids, *row.edited_report_ids)}+ if not touched:+ return rows+ deleted = _deleted_report_ids(touched, team_id=team_id)+ if not deleted:+ return rows+ return [+ replace(+ row,+ emitted_report_ids=[report_id for report_id in row.emitted_report_ids if report_id not in deleted],+ edited_report_ids=[report_id for report_id in row.edited_report_ids if report_id not in deleted],+ )+ for row in rows+ ]+++def _touched_report_ids(emitted_report_ids: list[str] | None, edited_report_ids: list[str] | None) -> list[str]:+ """Every report a run touched, edits first, so the recency order of the caps stays stable."""+ return [*(edited_report_ids or []), *(emitted_report_ids or [])]+++def _deleted_report_ids(report_ids: Iterable[str], *, team_id: int) -> set[str]:+ """Which of these ids belong to a deleted report of this team. Unparseable ids are left alone."""+ candidates: list[UUID] = []+ for report_id in report_ids:+ try:+ candidates.append(UUID(str(report_id)))+ except ValueError:+ continue+ if not candidates:+ return set()+ return {+ str(report_id)+ for report_id in SignalReport.objects.filter(+ team_id=team_id, id__in=candidates, status=SignalReport.Status.DELETED+ ).values_list("id", flat=True)+ }++def _derive_failure(task_run: TaskRun | None) -> tuple[str | None, str | None]:"""Return `(error, failure_reason)` for a run — both None unless it failed/cancelled.diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex d3f84b4c3079..e2854e79e9c9 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -258,6 +258,24 @@ class TestScoutHarnessRunsAPI(APIBaseTest):assert row["emitted_report_ids"] == ["r-1"]assert row["edited_report_ids"] == ["r-2"]+ @parameterized.expand([("list",), ("detail",)])+ def test_deleted_reports_drop_out_of_the_touched_report_ids(self, surface: str) -> None:+ live = SignalReport.objects.create(team=self.team, title="Checkout 500s", status=SignalReport.Status.READY)+ deleted_author = SignalReport.objects.create(team=self.team, status=SignalReport.Status.DELETED)+ deleted_edit = SignalReport.objects.create(team=self.team, status=SignalReport.Status.DELETED)+ run = _make_run(+ self.team,+ emitted_report_ids=[str(live.id), str(deleted_author.id)],+ edited_report_ids=[str(deleted_edit.id)],+ )+ url = self._list_url() if surface == "list" else self._detail_url(str(run.id))+ response = self.client.get(url)+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ row = body[0] if surface == "list" else body+ assert row["emitted_report_ids"] == [str(live.id)]+ assert row["edited_report_ids"] == []+@parameterized.expand([("emitted_true", "true"), ("emitted_false", "false")])def test_list_emitted_filter_keeps_only_the_matching_runs(self, _name: str, emitted_param: str) -> None:emitting = _make_run(self.team, emitted_count=1, emitted_finding_ids=["f-x"])diff --git a/products/signals/frontend/inbox/logics/findingsLogic.ts b/products/signals/frontend/inbox/logics/findingsLogic.tsindex 626d73a92a2a..b626cb7ea81a 100644--- a/products/signals/frontend/inbox/logics/findingsLogic.ts+++ b/products/signals/frontend/inbox/logics/findingsLogic.ts@@ -25,6 +25,7 @@ import {prettifyScoutSkillName,runTouchedReports,} from '../utils/scoutRunsWindow'+import { isReportUnreachable, rememberUnreachableReport } from '../utils/unreachableReports'import { ScoutEmissionRow, ScoutReportAction } from './scoutDetailLogic'import { scoutFleetLogic } from './scoutFleetLogic'@@ -391,22 +392,30 @@ export const findingsLogic = kea<findingsLogicType>([}const touchedIds = new Set(touched.map(({ id }) => id))// Targeted refresh fetches only the named (still-touched) ids; a full load- // fetches the whole capped set.- const fetchIds = ids ? [...new Set(ids)].filter((id) => touchedIds.has(id)) : [...touchedIds]+ // fetches the whole capped set. Ids a previous round found unreachable are+ // dropped: a deleted report stays deleted, so re-asking only burns requests.+ const fetchIds = (+ ids ? [...new Set(ids)].filter((id) => touchedIds.has(id)) : [...touchedIds]+ ).filter((id) => !isReportUnreachable(id))if (fetchIds.length === 0) {return values.scoutReports}const settled = await Promise.allSettled(fetchIds.map((id) => api.signalReports.get(id)))const byId = new Map<string, SignalReport>()- for (const result of settled) {+ let transientFailure = false+ settled.forEach((result, index) => {if (result.status === 'fulfilled') {byId.set(result.value.id, result.value)+ return}- }- // Every fetch rejected — throw BEFORE merging cached rows, so an outage flags- // `scoutReportsLoadFailed` (warning banner over the stale set kea-loaders keeps)- // instead of laundering the cache into a "successful" refresh.- if (byId.size === 0) {+ transientFailure =+ !rememberUnreachableReport(fetchIds[index], result.reason) || transientFailure+ })+ // Every fetch rejected and at least one can recover — throw BEFORE merging cached+ // rows, so an outage flags `scoutReportsLoadFailed` (warning banner over the stale+ // set kea-loaders keeps) instead of laundering the cache into a "successful"+ // refresh. An all-404 round is not an outage: those reports are simply gone.+ if (byId.size === 0 && transientFailure) {throw new Error('Failed to load the reports scouts touched')}// Keep prior resolved reports for still-touched ids that weren't (successfully)diff --git a/products/signals/frontend/inbox/logics/scoutDetailLogic.ts b/products/signals/frontend/inbox/logics/scoutDetailLogic.tsindex 974c5bbc8aab..310b3af65a68 100644--- a/products/signals/frontend/inbox/logics/scoutDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/scoutDetailLogic.ts@@ -16,6 +16,7 @@ import {SignalScoutRunSummary,} from '../types'import type { ScoutRollup } from '../utils/scoutRunsWindow'+import { isReportUnreachable, rememberUnreachableReport } from '../utils/unreachableReports'import { scoutFleetLogic } from './scoutFleetLogic'export interface ScoutDetailLogicProps {@@ -270,11 +271,21 @@ export const scoutDetailLogic = kea<scoutDetailLogicType>([[] as SignalReport[],{loadScoutReports: async () => {- const touched = values.touchedReports.slice(0, MAX_TOUCHED_REPORTS)+ // Ids a previous round found unreachable are dropped before the cap: a deleted+ // report stays deleted, so re-asking only burns requests and a cached 404 must+ // not hold a slot a live report could take.+ const touched = values.touchedReports+ .filter(({ id }) => !isReportUnreachable(id))+ .slice(0, MAX_TOUCHED_REPORTS)if (touched.length === 0) {return []}const settled = await Promise.allSettled(touched.map(({ id }) => api.signalReports.get(id)))+ settled.forEach((result, index) => {+ if (result.status === 'rejected') {+ rememberUnreachableReport(touched[index].id, result.reason)+ }+ })const fetched = settled.filter((result): result is PromiseFulfilledResult<SignalReport> => result.status === 'fulfilled'diff --git a/products/signals/frontend/inbox/utils/unreachableReports.test.ts b/products/signals/frontend/inbox/utils/unreachableReports.test.tsnew file mode 100644index 000000000000..c850f1d36bd9--- /dev/null+++ b/products/signals/frontend/inbox/utils/unreachableReports.test.ts@@ -0,0 +1,24 @@+import { ApiError } from 'lib/api-error'++import { forgetUnreachableReports, isReportUnreachable, rememberUnreachableReport } from './unreachableReports'++describe('unreachableReports', () => {+ beforeEach(() => {+ forgetUnreachableReports()+ })++ it('remembers a report the endpoint answered 404 for', () => {+ rememberUnreachableReport('report-1', new ApiError('Not found', 404))+ expect(isReportUnreachable('report-1')).toBe(true)+ expect(isReportUnreachable('report-2')).toBe(false)+ })++ test.each([+ ['server error', new ApiError('Boom', 500)],+ ['gateway error', new ApiError('Bad gateway', 502)],+ ['no response at all', new TypeError('Failed to fetch')],+ ])('keeps a report retryable after %s', (_label, reason) => {+ rememberUnreachableReport('report-1', reason)+ expect(isReportUnreachable('report-1')).toBe(false)+ })+})diff --git a/products/signals/frontend/inbox/utils/unreachableReports.ts b/products/signals/frontend/inbox/utils/unreachableReports.tsnew file mode 100644index 000000000000..9e650446821b--- /dev/null+++ b/products/signals/frontend/inbox/utils/unreachableReports.ts@@ -0,0 +1,32 @@+import { ApiError } from 'lib/api-error'++/**+ * Report ids the report endpoint answered 404 for.+ *+ * Deletion is terminal, and a deleted report is unreachable by id, but the scout run rows keep+ * naming it. Without this the roster asks for the same dead ids on every load and every 60 second+ * poll, for the whole life of the page. Module-level so the two report readers (the fleet findings+ * feed and the per-scout detail view) share one answer across mounts.+ */+const unreachableReportIds = new Set<string>()++export function isReportUnreachable(id: string): boolean {+ return unreachableReportIds.has(id)+}++/**+ * Remember a failure, and report whether it was terminal. Only a 404 is remembered. Every other+ * failure can be transient, so the id stays retryable.+ */+export function rememberUnreachableReport(id: string, reason: unknown): boolean {+ if (!(reason instanceof ApiError) || reason.status !== 404) {+ return false+ }+ unreachableReportIds.add(id)+ return true+}++/** Test-only: the set outlives a logic mount by design. */+export function forgetUnreachableReports(): void {+ unreachableReportIds.clear()+}