: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): batch scout findings lookups to speed up inbox load (#66823)
Andrew Maguire5d7b3e9ad479
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d02e799ff110..4fc303c51128 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4845,9 +4845,9 @@ snapshots:scenes-app-customer-analytics-accounts--row-expanded-empty--light:hash: v1.k794b7964.904bd5b939f99d43408ae3a8a814a3c299bd57bf13a0fd1d98ff6033fd66e343.K1Z16ICEF6-O9kIej8kGnYyarloq2oZH5rdtmx-8Hu0scenes-app-customer-analytics-accounts--row-expanded-links-disabled--dark:- hash: v1.k794b7964.520e6455cfdd404a1af3d98f6c138a0b5ce57f94e66263f26b968418daebaa64.ACJbyDSyqXK4dZKV4TUemg4cKPIjpXZB008wOEI5D20+ hash: v1.k794b7964.dbe806f797399ea2451bdf08b2a0bc1a413ea4d65e1a244e859a6f17a330005d.i8IfnQ9ONhYyodW5HPR_2GSN7q1dcVA3cPUtXyNi_roscenes-app-customer-analytics-accounts--row-expanded-links-disabled--light:- hash: v1.k794b7964.b6d4fa4f4fe7f87fe5fea5c702fc4db8558f8b9f0904cb9659ae9aece845b3ac.QfMAWNJmI8DCp90AGyh4Ena5eXJqEtCc3OFG2onVXnI+ hash: v1.k794b7964.f82e5d3d3f153d31ba1ef5b668ebb5ab8aab000fe4acb42252f89e9f56a838bc.GkNSIp0tMmvNDlRasel6bRQBgice_VcLKHISDWHGnnUscenes-app-customer-analytics-accounts--row-expanded-usage-not-found--dark:hash: v1.k794b7964.53af994a2a4dfb2f883e27ed73be8d55e1177b97f5c8b622708dfcdbe5f33d2a.A7AJRK9hY-yytJMNPghuLYtOJIoj0VBJidseMubwZWsscenes-app-customer-analytics-accounts--row-expanded-usage-not-found--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 2a6a22d8a5ec..31854d084acf 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -5228,6 +5228,22 @@ const api = {async emissionReports(runId: string): Promise<SignalScoutEmissionReportLink[]> {return await new ApiRequest().signalScoutRun(runId).withAction('emissions/reports').get()},+ // Batched form of `emissions`: every run's findings in one request, flat newest-first+ // (each row carries its `run_id`). POST since the run-id set can be large.+ async emissionsBatch(runIds: string[]): Promise<SignalScoutEmission[]> {+ return await new ApiRequest()+ .signalScoutRuns()+ .withAction('emissions/batch')+ .create({ data: { run_ids: runIds } })+ },+ // Batched form of `emissionReports`: resolves every run's findings to their inbox report+ // in a single ClickHouse round-trip, instead of one query per run.+ async emissionReportsBatch(runIds: string[]): Promise<SignalScoutEmissionReportLink[]> {+ return await new ApiRequest()+ .signalScoutRuns()+ .withAction('emissions/reports/batch')+ .create({ data: { run_ids: runIds } })+ },},configs: {// Newest-first raw array, ordered by skill_name.diff --git a/frontend/src/scenes/inbox/components/findings/FindingsPanel.tsx b/frontend/src/scenes/inbox/components/findings/FindingsPanel.tsxindex c72412d5d50c..8ef014432f68 100644--- a/frontend/src/scenes/inbox/components/findings/FindingsPanel.tsx+++ b/frontend/src/scenes/inbox/components/findings/FindingsPanel.tsx@@ -43,7 +43,6 @@ export function FindingsPanel(): JSX.Element {hasLoadedOnce,emissionsLoadFailed,emissionsLoading,- emissionsPartialFailedRuns,} = useValues(findingsLogic)const { setSearchText, setScoutFilter, setSeverityFilter, setSortKey, loadEmissions } = useActions(findingsLogic)@@ -97,10 +96,10 @@ export function FindingsPanel(): JSX.Element {/></div>- {hasLoadedOnce && (emissionsPartialFailedRuns > 0 || (emissionsLoadFailed && totalCount > 0)) && (- // Incomplete fetch: either some runs' findings loaded and others failed (partial), or a- // later poll/retry failed outright while a prior set is still on screen (stale). Either- // way the list a user triages against may be incomplete — warn rather than show it silently.+ {hasLoadedOnce && emissionsLoadFailed && totalCount > 0 && (+ // A later poll/retry of the batched fetch failed while a prior set is still on screen+ // (stale). The list a user triages against may be incomplete — warn rather than show it+ // silently.<LemonBannertype="warning"action={{ children: 'Retry', onClick: () => loadEmissions(), loading: emissionsLoading }}diff --git a/frontend/src/scenes/inbox/logics/findingsLogic.ts b/frontend/src/scenes/inbox/logics/findingsLogic.tsindex ae0e1c31ede1..f1c0e66e71d0 100644--- a/frontend/src/scenes/inbox/logics/findingsLogic.ts+++ b/frontend/src/scenes/inbox/logics/findingsLogic.ts@@ -36,10 +36,10 @@ function severityRank(severity: SignalReportPriority | null): number {/*** Fleet-wide findings logic — the cross-troop counterpart of the per-scout `scoutDetailLogic`. Reuses- * `scoutFleetLogic`'s polled runs window to find every scout's recent emitted runs, fetches each run's- * emissions + report links, and flattens them into one searchable/filterable/sortable list. Singleton,- * mounted only by the findings page, so the per-run fan-out stays lazy (the callout reads the cheap- * `scoutFleetLogic.emittedFindingsSummary` instead).+ * `scoutFleetLogic`'s polled runs window to find every scout's recent emitted runs, fetches their+ * emissions + report links in two batched requests, and flattens them into one+ * searchable/filterable/sortable list. Singleton, mounted only by the findings page, so the fetch stays+ * lazy (the callout reads the cheap `scoutFleetLogic.emittedFindingsSummary` instead).*/export const findingsLogic = kea<findingsLogicType>([path(['scenes', 'inbox', 'logics', 'findingsLogic']),@@ -53,12 +53,9 @@ export const findingsLogic = kea<findingsLogicType>([setScoutFilter: (scoutFilter: string) => ({ scoutFilter }),setSeverityFilter: (severityFilter: string) => ({ severityFilter }),setSortKey: (sortKey: FindingsSortKey) => ({ sortKey }),- // Some (but not all) per-run emission fetches failed — the list is incomplete. Carries the- // failed-run count so the page can warn that findings are missing rather than hiding it.- setEmissionsPartialFailure: (failedRuns: number) => ({ failedRuns }),}),- loaders(({ values, actions }) => ({+ loaders(({ values }) => ({emissions: [[] as SignalScoutEmission[],{@@ -67,24 +64,10 @@ export const findingsLogic = kea<findingsLogicType>([if (runs.length === 0) {return []}- // allSettled, not all: one failed run's fetch shouldn't discard every other run's- // findings — surface the partial set.- const settled = await Promise.allSettled(- runs.map((run) => api.signalScout.runs.emissions(run.run_id))- )- const fulfilled = settled.filter(- (result): result is PromiseFulfilledResult<SignalScoutEmission[]> =>- result.status === 'fulfilled'- )- // All fetches failed while the runs say these emitted — throw so the page shows an- // error, not a false "no findings".- if (fulfilled.length === 0) {- throw new Error('Failed to load scout findings')- }- // A partial failure returns the findings that loaded, but flag the gap so the page- // can warn — silently dropping a scout's findings would mislead a triage decision.- actions.setEmissionsPartialFailure(settled.length - fulfilled.length)- return fulfilled.flatMap((result) => result.value)+ // One batched request for the whole window: the backend flattens every run's+ // findings newest-first (each row carries its run_id). A throw surfaces as the+ // page's error/retry state — far cheaper than the old per-run fan-out.+ return await api.signalScout.runs.emissionsBatch(runs.map((run) => run.run_id))},},],@@ -96,20 +79,18 @@ export const findingsLogic = kea<findingsLogicType>([if (runs.length === 0) {return []}- // Retain the prior round's links for a failed run (this re-runs on the poll); its- // links are the ones whose source_id is prefixed `run:<run_id>:`.- const previous = values.emissionReports- const settled = await Promise.allSettled(- runs.map((run) => api.signalScout.runs.emissionReports(run.run_id))- )- return runs.flatMap((run, index) => {- const result = settled[index]- if (result.status === 'fulfilled') {- return result.value- }- const prefix = `run:${run.run_id}:`- return previous.filter((link) => link.source_id.startsWith(prefix))- })+ // One batched request → one ClickHouse round-trip for every run's report links,+ // replacing the per-run fan-out. Report chips are optional enrichment over findings+ // that already loaded via `emissions`, and the retry listener re-polls this while any+ // recent finding is unlinked — so swallow failures and keep the prior links rather than+ // letting the throw hit the global loaders error handler (a token with `signal_scout:read`+ // but not `task:read` 403s this endpoint on every poll). The `emissions` loader keeps+ // throwing: that one is the page's actual content and should surface an error/retry state.+ try {+ return await api.signalScout.runs.emissionReportsBatch(runs.map((run) => run.run_id))+ } catch {+ return values.emissionReports+ }},},],@@ -123,7 +104,7 @@ export const findingsLogic = kea<findingsLogicType>([{ setSeverityFilter: (_, { severityFilter }) => severityFilter },],sortKey: ['newest' as FindingsSortKey, { setSortKey: (_, { sortKey }) => sortKey }],- // True only when the most recent emissions load failed outright (all per-run fetches rejected).+ // True only when the most recent emissions load failed outright (the batched fetch rejected).emissionsLoadFailed: [false,{@@ -132,16 +113,6 @@ export const findingsLogic = kea<findingsLogicType>([loadEmissionsFailure: () => true,},],- // Count of runs whose emission fetch failed while others succeeded — the list is incomplete.- // Reset when a fresh load starts; a clean success sets it to 0 via the partial-failure action.- emissionsPartialFailedRuns: [- 0,- {- loadEmissions: () => 0,- loadEmissionsFailure: () => 0,- setEmissionsPartialFailure: (_, { failedRuns }) => failedRuns,- },- ],}),selectors({diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex c95508d9ce64..c66aa2f95368 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -220,6 +220,29 @@ class ScoutEmissionReportLinkSerializer(serializers.Serializer):)+# Upper bound on run ids accepted by the batched emissions / emission-reports endpoints. The findings+# UI caps its window at 120 emitted runs (`MAX_FLEET_EMITTED_RUNS`); this sits above that with headroom+# and bounds a pathological request rather than coupling tightly to the client cap.+SCOUT_RUNS_BATCH_LIMIT = 200+++class ScoutRunIdsBatchRequestSerializer(serializers.Serializer):+ """Request body for the batched emissions / emission-reports lookups: the set of run UUIDs to+ resolve in one call. Collapses the findings UI's old per-run fan-out (one request — and for the+ reports lookup, one ClickHouse round-trip — per emitted run) into a single request."""++ run_ids = serializers.ListField(+ child=serializers.UUIDField(),+ allow_empty=False,+ max_length=SCOUT_RUNS_BATCH_LIMIT,+ help_text=(+ "UUIDs of the `SignalScoutRun` rows to resolve in one batch. Run ids belonging to another "+ "team are silently ignored (they contribute no rows) rather than failing the whole request. "+ f"Capped at {SCOUT_RUNS_BATCH_LIMIT} ids per call."+ ),+ )++class SearchRecentRunsQuerySerializer(serializers.Serializer):"""Query parameters for `search-recent-runs`."""diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 39bac982be4c..d7843a52e6a3 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -76,6 +76,7 @@ from products.signals.backend.scout_harness.serializers import (RememberRequestSerializer,ScoutEmissionReportLinkSerializer,ScoutMetadataSerializer,+ ScoutRunIdsBatchRequestSerializer,ScratchpadEntrySerializer,SearchMemoryQuerySerializer,SearchRecentRunsQuerySerializer,@@ -112,6 +113,11 @@ logger = structlog.get_logger(__name__)# retry-heavy run rather than leaving the payload unbounded.MAX_EMISSIONS_PER_RUN = 1000+# Upper bound on rows returned by the batched emissions endpoints. A scout emits a handful of findings+# per run, so even the 120-run findings window stays in the low hundreds; this only bounds a pathological+# payload, mirroring `MAX_EMISSIONS_PER_RUN` for the single-run path.+MAX_EMISSIONS_PER_BATCH = 5000+# `SignalScoutRunViewSet.lookup_field` is `run_id`, but the model's PK field is `id`, so# drf-spectacular can't derive the path-param type from the model and warns (fatal under# `--fail-on-warn`). Declare the param explicitly on every detail action instead.@@ -182,6 +188,53 @@ def _canonical_team_id(view: TeamAndOrgViewSetMixin) -> int:return view.team.parent_team_id or view.team_id+def _resolve_emission_report_links(+ team_id: int, canonical_team: Team, emissions: list[SignalScoutEmission], *, log_context: dict+) -> list[dict]:+ """Map each emitted finding to the inbox report (if any) its signal grouped into.++ One ClickHouse round-trip for the whole set: resolve every finding's `source_id` to the+ `report_id` its signal grouped into (best effort — unmatched/deleted findings drop out). Query+ with the canonical team so the injected `document_embeddings.team_id` guard matches where signals+ persist (child-environment requests would otherwise find none). CH/HogQL failures degrade to "no+ links" rather than 500-ing the whole page.++ Hydrate the resolved report ids into minimal projections. Exclude DELETED and SUPPRESSED reports —+ ClickHouse soft-delete and Postgres status can drift, and `SignalReportViewSet` hides both from its+ default retrieve/list flow, so a chip linking to either would deep-link to a page that can't load+ it. Treat that as "no link" rather than a dangling chip.++ Shared by the per-run and batched report endpoints so the link shape stays identical.+ """+ source_ids = [e.source_id for e in emissions if e.source_id]+ source_id_to_report_id: dict[str, str] = {}+ if source_ids:+ try:+ source_id_to_report_id = fetch_report_ids_for_source_ids(canonical_team, source_ids)+ except Exception:+ logger.exception("scout_emission_reports_lookup_failed", team_id=team_id, **log_context)++ report_ids = {rid for rid in source_id_to_report_id.values() if rid}+ reports_by_id = {+ str(row["id"]): row+ for row in SignalReport.objects.filter(team_id=team_id, id__in=report_ids)+ .exclude(status__in=[SignalReport.Status.DELETED, SignalReport.Status.SUPPRESSED])+ .values("id", "title", "status")+ }++ links = []+ for emission in emissions:+ report_id = source_id_to_report_id.get(emission.source_id)+ links.append(+ {+ "finding_id": emission.finding_id,+ "source_id": emission.source_id,+ "report": reports_by_id.get(report_id) if report_id else None,+ }+ )+ return links++class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"""Run history + finding emission for the headless agent."""@@ -349,42 +402,86 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)::MAX_EMISSIONS_PER_RUN])- # One ClickHouse round-trip for the whole run: map every finding's source_id to the- # report_id its signal grouped into (best effort — unmatched/deleted findings drop out).- # Query with the canonical team so the injected `document_embeddings.team_id` guard- # matches where signals persist (child-environment requests would otherwise find none).- # CH/HogQL failures degrade to "no links" rather than 500-ing the whole page.canonical_team = self.team.parent_team or self.team- source_ids = [e.source_id for e in emissions if e.source_id]- source_id_to_report_id: dict[str, str] = {}- if source_ids:- try:- source_id_to_report_id = fetch_report_ids_for_source_ids(canonical_team, source_ids)- except Exception:- logger.exception("scout_emission_reports_lookup_failed", run_id=str(run_id), team_id=team_id)-- # Hydrate the resolved report ids into minimal projections. Exclude DELETED and SUPPRESSED- # reports — ClickHouse soft-delete and Postgres status can drift, and `SignalReportViewSet`- # hides both from its default retrieve/list flow, so a chip linking to either would deep-link- # to a page that can't load it. Treat that as "no link" rather than a dangling chip.- report_ids = {rid for rid in source_id_to_report_id.values() if rid}- reports_by_id = {- str(row["id"]): row- for row in SignalReport.objects.filter(team_id=team_id, id__in=report_ids)- .exclude(status__in=[SignalReport.Status.DELETED, SignalReport.Status.SUPPRESSED])- .values("id", "title", "status")- }-- links = []- for emission in emissions:- report_id = source_id_to_report_id.get(emission.source_id)- links.append(- {- "finding_id": emission.finding_id,- "source_id": emission.source_id,- "report": reports_by_id.get(report_id) if report_id else None,- }- )+ links = _resolve_emission_report_links(team_id, canonical_team, emissions, log_context={"run_id": str(run_id)})+ return Response(ScoutEmissionReportLinkSerializer(links, many=True).data)++ @validated_request(+ request_serializer=ScoutRunIdsBatchRequestSerializer,+ responses={+ 200: OpenApiResponse(+ response=SignalScoutEmissionSerializer(many=True),+ description="Findings emitted across all requested runs, newest first.",+ ),+ },+ summary="List emitted findings for many runs at once",+ description=(+ "Batched form of the per-run emissions endpoint: return the findings every requested "+ "`SignalScoutRun` emitted, flattened newest-first, in a single request. Each row carries its "+ "`run_id`, so the caller can regroup by run. The findings UI uses this to load the whole "+ "recent window in one round-trip instead of one request per run. Strictly team-scoped — run "+ "ids belonging to another team contribute no rows (no per-run 404; one stale id never fails "+ "the batch)."+ ),+ operation_id="signals_scout_runs_emissions_batch",+ )+ @action(+ detail=False,+ methods=["post"],+ url_path="emissions/batch",+ required_scopes=["signal_scout:read"],+ pagination_class=None,+ )+ def emissions_batch(self, request: Request, **kwargs) -> Response:+ run_ids = request.validated_data["run_ids"]+ team_id = _canonical_team_id(self)+ # `team_id` is the tenant guard, so a foreign run id simply matches no rows — no per-run+ # existence check. One global cap bounds the payload (realistic fleets stay well under it).+ emissions = SignalScoutEmission.objects.filter(scout_run_id__in=run_ids, team_id=team_id).order_by(+ "-emitted_at", "-id"+ )[:MAX_EMISSIONS_PER_BATCH]+ return Response(SignalScoutEmissionSerializer(emissions, many=True).data)++ @validated_request(+ request_serializer=ScoutRunIdsBatchRequestSerializer,+ responses={+ 200: OpenApiResponse(+ response=ScoutEmissionReportLinkSerializer(many=True),+ description="Per-finding inbox report links across all requested runs, newest finding first.",+ ),+ },+ summary="List the inbox reports many runs' findings linked to",+ description=(+ "Batched form of the per-run emission-reports endpoint. For every finding the requested runs "+ "emitted, resolve the inbox `SignalReport` (if any) its signal grouped into — all in a single "+ "ClickHouse round-trip rather than one query per run, which is what made the findings page "+ "slow to open. `report` is null when a finding hasn't grouped yet, was de-duplicated, or its "+ "signal was deleted. Strictly team-scoped — run ids belonging to another team contribute no "+ "rows."+ ),+ operation_id="signals_scout_runs_emission_reports_batch",+ )+ @action(+ detail=False,+ methods=["post"],+ url_path="emissions/reports/batch",+ # Returns report titles, so it requires `task:read` on top of `signal_scout:read` — same as the+ # per-run `emission_reports` action; a scout-only token must not read titles it can't reach.+ required_scopes=["signal_scout:read", "task:read"],+ pagination_class=None,+ )+ def emission_reports_batch(self, request: Request, **kwargs) -> Response:+ run_ids = request.validated_data["run_ids"]+ team_id = _canonical_team_id(self)+ emissions = list(+ SignalScoutEmission.objects.filter(scout_run_id__in=run_ids, team_id=team_id).order_by(+ "-emitted_at", "-id"+ )[:MAX_EMISSIONS_PER_BATCH]+ )+ canonical_team = self.team.parent_team or self.team+ links = _resolve_emission_report_links(+ team_id, canonical_team, emissions, log_context={"run_count": len(run_ids)}+ )return Response(ScoutEmissionReportLinkSerializer(links, many=True).data)@validated_request(diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 672c119af7e4..4fa675cf3a69 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -384,6 +384,81 @@ class TestScoutHarnessEmissionReportsAPI(APIBaseTest):assert response.status_code == status.HTTP_404_NOT_FOUND+class TestScoutHarnessEmissionsBatchAPI(APIBaseTest):+ def _url(self) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/runs/emissions/batch/"++ def test_batches_emissions_across_runs_newest_first(self) -> None:+ # The findings page opens one batched request instead of one per run; the response flattens+ # every run's findings newest-first, each row tagged with its own run_id so the UI can regroup.+ run_a = _make_run(self.team)+ run_b = _make_run(self.team)+ _make_emission(self.team, run_a, finding_id="a-old")+ _make_emission(self.team, run_b, finding_id="b-mid")+ _make_emission(self.team, run_a, finding_id="a-new")+ response = self.client.post(self._url(), data={"run_ids": [str(run_a.id), str(run_b.id)]}, format="json")+ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ assert [row["finding_id"] for row in body] == ["a-new", "b-mid", "a-old"]+ run_by_finding = {row["finding_id"]: row["run_id"] for row in body}+ assert run_by_finding["a-new"] == str(run_a.id)+ assert run_by_finding["b-mid"] == str(run_b.id)++ def test_foreign_team_run_ids_contribute_no_rows(self) -> None:+ # A stale or cross-team run id must not 404 the whole batch (one bad id would blank the page) —+ # team scoping just drops its rows.+ run = _make_run(self.team)+ _make_emission(self.team, run, finding_id="mine")+ other = Team.objects.create(organization=self.organization, name="Other")+ other_run = _make_run(other)+ _make_emission(other, other_run, finding_id="theirs")+ response = self.client.post(self._url(), data={"run_ids": [str(run.id), str(other_run.id)]}, format="json")+ assert response.status_code == status.HTTP_200_OK+ assert [row["finding_id"] for row in response.json()] == ["mine"]++ def test_empty_run_ids_rejected(self) -> None:+ response = self.client.post(self._url(), data={"run_ids": []}, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST+++class TestScoutHarnessEmissionReportsBatchAPI(APIBaseTest):+ def _url(self) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/runs/emissions/reports/batch/"++ def test_resolves_every_runs_links_in_one_clickhouse_call(self) -> None:+ # The whole point of the batch endpoint: the per-run page fired one ClickHouse query per run,+ # which made Findings slow to open. The batched form resolves every run's findings in a single+ # `fetch_report_ids_for_source_ids` round-trip — assert it's called exactly once with the source+ # ids from both runs, and that links map back correctly across runs.+ run_a = _make_run(self.team)+ run_b = _make_run(self.team)+ linked_a = _make_emission(self.team, run_a, finding_id="f-a")+ linked_b = _make_emission(self.team, run_b, finding_id="f-b")+ report = SignalReport.objects.create(team=self.team, title="Checkout 500s", status=SignalReport.Status.READY)+ with patch(+ _FETCH_REPORT_IDS,+ return_value={linked_a.source_id: str(report.id), linked_b.source_id: str(report.id)},+ ) as mock_fetch:+ response = self.client.post(self._url(), data={"run_ids": [str(run_a.id), str(run_b.id)]}, format="json")+ assert response.status_code == status.HTTP_200_OK+ mock_fetch.assert_called_once()+ assert sorted(mock_fetch.call_args.args[1]) == sorted([linked_a.source_id, linked_b.source_id])+ body = {row["finding_id"]: row for row in response.json()}+ assert body["f-a"]["report"]["id"] == str(report.id)+ assert body["f-b"]["report"]["id"] == str(report.id)++ def test_foreign_team_run_ids_contribute_no_rows(self) -> None:+ run = _make_run(self.team)+ _make_emission(self.team, run, finding_id="mine")+ other = Team.objects.create(organization=self.organization, name="Other")+ other_run = _make_run(other)+ _make_emission(other, other_run, finding_id="theirs")+ with patch(_FETCH_REPORT_IDS, return_value={}):+ response = self.client.post(self._url(), data={"run_ids": [str(run.id), str(other_run.id)]}, format="json")+ assert response.status_code == status.HTTP_200_OK+ assert [row["finding_id"] for row in response.json()] == ["mine"]++class TestScoutHarnessEmitFindingAPI(APIBaseTest):def setUp(self) -> None:super().setUp()diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex e677b88ac930..8cf09dab3cb8 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -1487,6 +1487,19 @@ export interface EmitFindingResponseApi {skipped_reason: string | null}+/**+ * Request body for the batched emissions / emission-reports lookups: the set of run UUIDs to+ * resolve in one call. Collapses the findings UI's old per-run fan-out (one request — and for the+ * reports lookup, one ClickHouse round-trip — per emitted run) into a single request.+ */+export interface ScoutRunIdsBatchRequestApi {+ /**+ * UUIDs of the `SignalScoutRun` rows to resolve in one batch. Run ids belonging to another team are silently ignored (they contribute no rows) rather than failing the whole request. Capped at 200 ids per call.+ * @maxItems 200+ */+ run_ids: string[]+}+/*** `SignalScratchpad` projection used by `search-memory` and `remember`.*/diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 73d4d2498403..f260f48c51ad 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -31,6 +31,7 @@ import type {RememberRequestApi,ScoutEmissionReportLinkApi,ScoutMetadataApi,+ ScoutRunIdsBatchRequestApi,ScratchpadEntryApi,SignalReportApi,SignalReportArtefactApi,@@ -671,6 +672,48 @@ export const signalsScoutEmitSignal = async (})}+export const getSignalsScoutRunsEmissionsBatchUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/scout/runs/emissions/batch/`+}++/**+ * Batched form of the per-run emissions endpoint: return the findings every requested `SignalScoutRun` emitted, flattened newest-first, in a single request. Each row carries its `run_id`, so the caller can regroup by run. The findings UI uses this to load the whole recent window in one round-trip instead of one request per run. Strictly team-scoped — run ids belonging to another team contribute no rows (no per-run 404; one stale id never fails the batch).+ * @summary List emitted findings for many runs at once+ */+export const signalsScoutRunsEmissionsBatch = async (+ projectId: string,+ scoutRunIdsBatchRequestApi: ScoutRunIdsBatchRequestApi,+ options?: RequestInit+): Promise<SignalScoutEmissionApi[]> => {+ return apiMutator<SignalScoutEmissionApi[]>(getSignalsScoutRunsEmissionsBatchUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(scoutRunIdsBatchRequestApi),+ })+}++export const getSignalsScoutRunsEmissionReportsBatchUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/scout/runs/emissions/reports/batch/`+}++/**+ * Batched form of the per-run emission-reports endpoint. For every finding the requested runs emitted, resolve the inbox `SignalReport` (if any) its signal grouped into — all in a single ClickHouse round-trip rather than one query per run, which is what made the findings page slow to open. `report` is null when a finding hasn't grouped yet, was de-duplicated, or its signal was deleted. Strictly team-scoped — run ids belonging to another team contribute no rows.+ * @summary List the inbox reports many runs' findings linked to+ */+export const signalsScoutRunsEmissionReportsBatch = async (+ projectId: string,+ scoutRunIdsBatchRequestApi: ScoutRunIdsBatchRequestApi,+ options?: RequestInit+): Promise<ScoutEmissionReportLinkApi[]> => {+ return apiMutator<ScoutEmissionReportLinkApi[]>(getSignalsScoutRunsEmissionReportsBatchUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(scoutRunIdsBatchRequestApi),+ })+}+export const getSignalsScoutScratchpadSearchUrl = (projectId: string, params?: SignalsScoutScratchpadSearchParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 245e5a6546d5..359d361ba3cd 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -455,6 +455,44 @@ export const SignalsScoutEmitSignalBody = /* @__PURE__ */ zod}).describe('Request body for `emit-finding`. Run attribution is taken from the URL path.')+/**+ * Batched form of the per-run emissions endpoint: return the findings every requested `SignalScoutRun` emitted, flattened newest-first, in a single request. Each row carries its `run_id`, so the caller can regroup by run. The findings UI uses this to load the whole recent window in one round-trip instead of one request per run. Strictly team-scoped — run ids belonging to another team contribute no rows (no per-run 404; one stale id never fails the batch).+ * @summary List emitted findings for many runs at once+ */+export const signalsScoutRunsEmissionsBatchBodyRunIdsMax = 200++export const SignalsScoutRunsEmissionsBatchBody = /* @__PURE__ */ zod+ .object({+ run_ids: zod+ .array(zod.uuid())+ .max(signalsScoutRunsEmissionsBatchBodyRunIdsMax)+ .describe(+ 'UUIDs of the `SignalScoutRun` rows to resolve in one batch. Run ids belonging to another team are silently ignored (they contribute no rows) rather than failing the whole request. Capped at 200 ids per call.'+ ),+ })+ .describe(+ "Request body for the batched emissions \/ emission-reports lookups: the set of run UUIDs to\nresolve in one call. Collapses the findings UI's old per-run fan-out (one request — and for the\nreports lookup, one ClickHouse round-trip — per emitted run) into a single request."+ )++/**+ * Batched form of the per-run emission-reports endpoint. For every finding the requested runs emitted, resolve the inbox `SignalReport` (if any) its signal grouped into — all in a single ClickHouse round-trip rather than one query per run, which is what made the findings page slow to open. `report` is null when a finding hasn't grouped yet, was de-duplicated, or its signal was deleted. Strictly team-scoped — run ids belonging to another team contribute no rows.+ * @summary List the inbox reports many runs' findings linked to+ */+export const signalsScoutRunsEmissionReportsBatchBodyRunIdsMax = 200++export const SignalsScoutRunsEmissionReportsBatchBody = /* @__PURE__ */ zod+ .object({+ run_ids: zod+ .array(zod.uuid())+ .max(signalsScoutRunsEmissionReportsBatchBodyRunIdsMax)+ .describe(+ 'UUIDs of the `SignalScoutRun` rows to resolve in one batch. Run ids belonging to another team are silently ignored (they contribute no rows) rather than failing the whole request. Capped at 200 ids per call.'+ ),+ })+ .describe(+ "Request body for the batched emissions \/ emission-reports lookups: the set of run UUIDs to\nresolve in one call. Collapses the findings UI's old per-run fan-out (one request — and for the\nreports lookup, one ClickHouse round-trip — per emitted run) into a single request."+ )+/*** Upsert a memory keyed on `(team, key)`. Re-using a key updates the existing entry in place.* @summary Remember a scratchpad entrydiff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex 8e15ca801c79..ec7760ea3dbf 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -485,6 +485,12 @@ tools:deleted/suppressed). Use this to see *which* findings turned into actionable reports, not just what a runsurfaced (`signals-scout-runs-emissions-list`). Requires `task:read` on top of `signal_scout:read` becauseit exposes report titles. Strictly team-scoped — a run UUID belonging to another team returns 404.+ signals-scout-runs-emission-reports-batch:+ operation: signals_scout_runs_emission_reports_batch+ enabled: false+ signals-scout-runs-emissions-batch:+ operation: signals_scout_runs_emissions_batch+ enabled: falsesignals-scout-runs-emissions-list:operation: signals_scout_runs_emissionsenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b6660f240c16..762f414d7691 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -47615,6 +47615,19 @@ export namespace Schemas {limits: ScoutLimits;}+ /**+ * Request body for the batched emissions / emission-reports lookups: the set of run UUIDs to+ * resolve in one call. Collapses the findings UI's old per-run fan-out (one request — and for the+ * reports lookup, one ClickHouse round-trip — per emitted run) into a single request.+ */+ export interface ScoutRunIdsBatchRequest {+ /**+ * UUIDs of the `SignalScoutRun` rows to resolve in one batch. Run ids belonging to another team are silently ignored (they contribute no rows) rather than failing the whole request. Capped at 200 ids per call.+ * @maxItems 200+ */+ run_ids: string[];+ }+/*** `SignalScratchpad` projection used by `search-memory` and `remember`.*/