Skip to content

: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.

fix(signals): stop one warehouse read from 500ing the signal sources list (#96047)

posthog[bot]3c5f9fdca769
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b48d4f205d2d..41caf1d4b9a0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7648,6 +7648,10 @@ snapshots:
hash: v1.k794b7964.f897b9dd52eae8ad29d04c46ba689c27f47602692b2144b0e75a97ef34fae702.qixI7HhZb5rWIcR5HzZB9i8SidHDxo9eBF_dsAFvSew
scenes-app-inbox-signalsourcespanel--server-side-exceptions-only--light:
hash: v1.k794b7964.13df8c7b214cfd00e7eba5fea6da33f833ac202b7d3a2ebbadd331440bb9f97a.SL1Tzb4sMCHF1TQHfGCWGJYsBO88sT0dkLTlU88JrvQ
+ scenes-app-inbox-signalsourcespanel--source-configs-unavailable--dark:
+ hash: v1.k794b7964.b0af9348cf4a495b517dd863dca45310eb45c83964c8136eec37e6e7ada42ab3.mZK2q6HoW8jDn2n8yA9u1fqH22TvClzd8UgGiwfeRfc
+ scenes-app-inbox-signalsourcespanel--source-configs-unavailable--light:
+ hash: v1.k794b7964.0a6cf287cde55b6cccce78b2603b9b736dacebd2ab6547f541df49845d6d3fdc.ry1SP43RXFgAvURyGogdG_ZZLfNuzaxCK0to6orM04A
scenes-app-inbox-signalsourcespanel--tools-on-no-recent-data--dark:
hash: v1.k794b7964.748be85b9907181d7eb082c40e4d4f93429073c22a34fd3ad19f010006856b4d.m6AmUOQ3eZ_Le5wuOhR7RCAT_xVrzvZJSHptyYmtTpM
scenes-app-inbox-signalsourcespanel--tools-on-no-recent-data--light:
diff --git a/products/signals/backend/management/commands/reset_signals_self_driving.py b/products/signals/backend/management/commands/reset_signals_self_driving.py
index 7c4877eeeb68..12faf7484045 100644
--- a/products/signals/backend/management/commands/reset_signals_self_driving.py
+++ b/products/signals/backend/management/commands/reset_signals_self_driving.py
@@ -264,14 +264,13 @@ class Command(BaseCommand):
delete_discover_schemas_schedule,
delete_external_data_schedule,
)
- from products.signals.backend.serializers import _DATA_IMPORT_SOURCE_MAP
+ from products.signals.backend.serializers import _DATA_IMPORT_EXTERNAL_SOURCE_TYPES
from products.warehouse_sources.backend.facade.models import ExternalDataSource
- dwh_source_types = {ext_source_type for (ext_source_type, _schema_name) in _DATA_IMPORT_SOURCE_MAP.values()}
sources = list(
ExternalDataSource.objects.filter(
team=team,
- source_type__in=dwh_source_types,
+ source_type__in=_DATA_IMPORT_EXTERNAL_SOURCE_TYPES,
created_via=ExternalDataSourceCreatedVia.MCP,
deleted=False,
)
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index e233fa716428..c5a7dc012123 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -3,18 +3,21 @@ from collections.abc import Mapping
from datetime import datetime
from typing import cast
-from django.db.models import Q, TextChoices
+from django.db.models import TextChoices
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field
from rest_framework import serializers
+from posthog.dataclasses import frozen
+from posthog.exceptions_capture import capture_exception
from posthog.models import User
from products.signals.backend import contracts
from products.signals.backend.billing import REFUND_INELIGIBILITY_REASONS, refund_ineligibility_reason
from products.signals.backend.contracts import DEFAULT_NOT_ACTIONABLE_KEY, STEERING_KEY, STEERING_MAX_LENGTH
from products.signals.backend.enums import SignalSourceProduct, SignalSourceType
+from products.warehouse_sources.backend.facade.models import ExternalDataSchema
from products.warehouse_sources.backend.facade.types import ExternalDataSchemaStatus
from .artefact_schemas import NON_WRITABLE_ARTEFACT_TYPES
@@ -37,14 +40,58 @@ from .report_generation.resolve_reviewers import enrich_reviewer_dicts_with_org_
DEFAULT_SESSION_ANALYSIS_SAMPLE_RATE = 0.1
-# Maps (source_product, source_type) → (ExternalDataSourceType value, schema name)
-_DATA_IMPORT_SOURCE_MAP: dict[tuple[str, str], tuple[str, str]] = {
- (SignalSourceConfig.SourceProduct.GITHUB, SignalSourceConfig.SourceType.ISSUE): ("Github", "issues"),
- (SignalSourceConfig.SourceProduct.LINEAR, SignalSourceConfig.SourceType.ISSUE): ("Linear", "issues"),
- (SignalSourceConfig.SourceProduct.ZENDESK, SignalSourceConfig.SourceType.TICKET): ("Zendesk", "tickets"),
- (SignalSourceConfig.SourceProduct.PGANALYZE, SignalSourceConfig.SourceType.ISSUE): ("PgAnalyze", "issues"),
+@frozen
+class _DataImportSchema:
+ """The warehouse source type and schema name a signal source reads its sync status from."""
+
+ source_type: str
+ schema_name: str
+
+ def matches(self, source_type: str, name: str) -> bool:
+ # A repo-qualified schema reads as `<owner>/<repo>.<endpoint>`, a legacy one as the bare
+ # endpoint name.
+ return source_type == self.source_type and (name == self.schema_name or name.endswith(f".{self.schema_name}"))
+
+
+# Maps (source_product, source_type) → the warehouse schema carrying that source's sync status
+_DATA_IMPORT_SOURCE_MAP: dict[tuple[str, str], _DataImportSchema] = {
+ (SignalSourceConfig.SourceProduct.GITHUB, SignalSourceConfig.SourceType.ISSUE): _DataImportSchema(
+ source_type="Github", schema_name="issues"
+ ),
+ (SignalSourceConfig.SourceProduct.LINEAR, SignalSourceConfig.SourceType.ISSUE): _DataImportSchema(
+ source_type="Linear", schema_name="issues"
+ ),
+ (SignalSourceConfig.SourceProduct.ZENDESK, SignalSourceConfig.SourceType.TICKET): _DataImportSchema(
+ source_type="Zendesk", schema_name="tickets"
+ ),
+ (SignalSourceConfig.SourceProduct.PGANALYZE, SignalSourceConfig.SourceType.ISSUE): _DataImportSchema(
+ source_type="PgAnalyze", schema_name="issues"
+ ),
}
+_DATA_IMPORT_EXTERNAL_SOURCE_TYPES = sorted({schema.source_type for schema in _DATA_IMPORT_SOURCE_MAP.values()})
+
+
+def _read_data_import_statuses(team_id: int) -> dict[_DataImportSchema, set[str]]:
+ """Every data-import schema on a team in one query, bucketed by `_DATA_IMPORT_SOURCE_MAP` value."""
+ rows = (
+ ExternalDataSchema.objects.filter(
+ team_id=team_id,
+ source__source_type__in=_DATA_IMPORT_EXTERNAL_SOURCE_TYPES,
+ )
+ .exclude(source__deleted=True)
+ .values_list("source__source_type", "name", "status")
+ )
+ statuses: dict[_DataImportSchema, set[str]] = {}
+ for row_source_type, row_name, row_status in rows:
+ # `status` is nullable. A row without one matches none of the ranked states below.
+ if row_status is None:
+ continue
+ for schema in _DATA_IMPORT_SOURCE_MAP.values():
+ if schema.matches(row_source_type, row_name):
+ statuses.setdefault(schema, set()).add(row_status)
+ return statuses
+
_SOURCE_CONFIG_HELP_TEXT = (
"Per-source settings as a JSON object. Keys read by the emission actionability gate on sources "
@@ -74,7 +121,13 @@ class _SourceConfigField(serializers.JSONField):
class SignalSourceConfigSerializer(serializers.ModelSerializer):
- status = serializers.SerializerMethodField()
+ status = serializers.SerializerMethodField(
+ help_text=(
+ "Sync state of the warehouse import behind this source: `running`, `failed`, or "
+ "`completed`. Null for a source that imports nothing from the warehouse, for an "
+ "import that has never synced, and when the sync state could not be read."
+ ),
+ )
config = _SourceConfigField(required=False, help_text=_SOURCE_CONFIG_HELP_TEXT)
class Meta:
@@ -91,25 +144,19 @@ class SignalSourceConfigSerializer(serializers.ModelSerializer):
]
read_only_fields = ["id", "created_at", "updated_at", "status"]
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+ # Absent key means "not read yet", a `None` value means the read failed.
+ self._data_import_statuses_by_team: dict[int, dict[_DataImportSchema, set[str]] | None] = {}
+
def get_status(self, obj: SignalSourceConfig) -> str | None:
- mapping = _DATA_IMPORT_SOURCE_MAP.get((obj.source_product, obj.source_type))
- if mapping is None:
+ schema = _DATA_IMPORT_SOURCE_MAP.get((obj.source_product, obj.source_type))
+ if schema is None:
return None
- ext_source_type, schema_name = mapping
- return self._get_data_import_status(obj.team_id, ext_source_type, schema_name)
-
- def _get_data_import_status(self, team_id: int, ext_source_type: str, schema_name: str) -> str | None:
- from products.warehouse_sources.backend.facade.models import ExternalDataSchema
-
- statuses = set(
- ExternalDataSchema.objects.filter(
- Q(name=schema_name) | Q(name__endswith=f".{schema_name}"),
- team_id=team_id,
- source__source_type=ext_source_type,
- )
- .exclude(source__deleted=True)
- .values_list("status", flat=True)
- )
+ statuses_by_schema = self._data_import_statuses(obj.team_id)
+ if statuses_by_schema is None:
+ return None
+ statuses = statuses_by_schema.get(schema, set())
if ExternalDataSchemaStatus.RUNNING in statuses:
return "running"
# One failing repo outranks its siblings' success, so a broken repo is never hidden.
@@ -123,6 +170,24 @@ class SignalSourceConfigSerializer(serializers.ModelSerializer):
return "completed"
return None
+ def _data_import_statuses(self, team_id: int) -> dict[_DataImportSchema, set[str]] | None:
+ """Sync statuses of every data-import source on a team, keyed as `_DATA_IMPORT_SOURCE_MAP` values.
+
+ The inbox reads this list on load, and DRF reuses one child serializer across a list,
+ so the first row that needs a status resolves every row's in one query. A `None` return
+ means the warehouse read raised. Those rows then report no status, which keeps the
+ response a 200 so a person can still configure their sources.
+ """
+ if team_id in self._data_import_statuses_by_team:
+ return self._data_import_statuses_by_team[team_id]
+ try:
+ statuses = _read_data_import_statuses(team_id)
+ except Exception as exc:
+ capture_exception(exc)
+ statuses = None
+ self._data_import_statuses_by_team[team_id] = statuses
+ return statuses
+
def validate(self, attrs: dict) -> dict:
source_product = attrs.get("source_product", getattr(self.instance, "source_product", None))
source_type = attrs.get("source_type", getattr(self.instance, "source_type", None))
diff --git a/products/signals/backend/test/test_source_config_status.py b/products/signals/backend/test/test_source_config_status.py
index ca8ba7fecf80..e15ef75a983c 100644
--- a/products/signals/backend/test/test_source_config_status.py
+++ b/products/signals/backend/test/test_source_config_status.py
@@ -1,4 +1,7 @@
from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.db import OperationalError
from parameterized import parameterized
@@ -13,20 +16,23 @@ FAILED = ExternalDataSchema.Status.FAILED
class TestSignalSourceConfigStatus(BaseTest):
- def _github_source_with_schemas(self, *schemas: tuple[str, str]) -> None:
+ def _source_with_schemas(self, source_type: str, *schemas: tuple[str, str]) -> None:
source = ExternalDataSource.objects.create(
- team=self.team, source_type="Github", status="Running", prefix="github_"
+ team=self.team, source_type=source_type, status="Running", prefix=f"{source_type.lower()}_"
)
for name, status in schemas:
ExternalDataSchema.objects.create(team=self.team, source=source, name=name, status=status)
- def _status(self) -> str | None:
- config = SignalSourceConfig.objects.create(
+ def _config(self, source_product: str, source_type: str) -> SignalSourceConfig:
+ return SignalSourceConfig.objects.create(
team=self.team,
- source_product=SignalSourceProduct.GITHUB,
- source_type=SignalSourceType.ISSUE,
+ source_product=source_product,
+ source_type=source_type,
enabled=True,
)
+
+ def _status(self) -> str | None:
+ config = self._config(SignalSourceProduct.GITHUB, SignalSourceType.ISSUE)
return SignalSourceConfigSerializer(config).data["status"]
@parameterized.expand(
@@ -49,7 +55,7 @@ class TestSignalSourceConfigStatus(BaseTest):
]
)
def test_status_across_repo_rows(self, _name: str, schemas: list[tuple[str, str]], expected: str | None) -> None:
- self._github_source_with_schemas(*schemas)
+ self._source_with_schemas("Github", *schemas)
assert self._status() == expected
@@ -60,3 +66,39 @@ class TestSignalSourceConfigStatus(BaseTest):
ExternalDataSchema.objects.create(team=self.team, source=source, name="posthog/posthog.issues", status=RUNNING)
assert self._status() is None
+
+ def test_reports_no_status_when_the_warehouse_read_fails(self) -> None:
+ self._source_with_schemas("Github", ("posthog/posthog.issues", RUNNING))
+ configs = [
+ self._config(SignalSourceProduct.GITHUB, SignalSourceType.ISSUE),
+ self._config(SignalSourceProduct.LINEAR, SignalSourceType.ISSUE),
+ ]
+
+ with patch.object(
+ ExternalDataSchema.objects, "filter", side_effect=OperationalError("statement timeout")
+ ) as read:
+ rows = SignalSourceConfigSerializer(configs, many=True).data
+
+ assert [row["status"] for row in rows] == [None, None]
+ # A failed read is cached, so a broken warehouse costs the list one query instead of one per row.
+ assert read.call_count == 1
+
+ def test_reads_every_source_status_in_one_query(self) -> None:
+ # Github and Linear issues share the `issues` schema name, so a status read that keys on
+ # the name alone would hand one source the other's badge.
+ self._source_with_schemas("Github", ("posthog/posthog.issues", RUNNING))
+ self._source_with_schemas("Linear", ("issues", COMPLETED))
+ configs = [
+ self._config(SignalSourceProduct.GITHUB, SignalSourceType.ISSUE),
+ self._config(SignalSourceProduct.LINEAR, SignalSourceType.ISSUE),
+ self._config(SignalSourceProduct.ZENDESK, SignalSourceType.TICKET),
+ ]
+
+ with self.assertNumQueries(1):
+ rows = SignalSourceConfigSerializer(configs, many=True).data
+
+ assert {row["source_product"]: row["status"] for row in rows} == {
+ SignalSourceProduct.GITHUB: "running",
+ SignalSourceProduct.LINEAR: "completed",
+ SignalSourceProduct.ZENDESK: None,
+ }
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index a7ab37f2ce69..f639bd5a3093 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -323,9 +323,9 @@ class SignalSourceConfigViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
@tracer.start_as_current_span("signals.source_configs.list")
def list(self, request, *args, **kwargs):
- # This list is fetched on inbox load. The default serializer resolves a per-row `status`,
- # which for session-analysis rows makes a synchronous Temporal RPC — a potential N+1. The
- # span lets us see how much of the inbox load this endpoint accounts for.
+ # This list is fetched on inbox load, so the span shows how much of that load the
+ # endpoint accounts for. The serializer resolves every row's `status` from one warehouse
+ # query per team, and reports no status rather than failing the list if that query fails.
return super().list(request, *args, **kwargs)
def _is_scout_source(self, source_product: str | None, source_type: str | None) -> bool:
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 60e377d929d6..549161305278 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -4337,7 +4337,10 @@ export interface SignalSourceConfigApi {
config?: SignalSourceConfigApiConfig
readonly created_at: string
readonly updated_at: string
- /** @nullable */
+ /**
+ * Sync state of the warehouse import behind this source: `running`, `failed`, or `completed`. Null for a source that imports nothing from the warehouse, for an import that has never synced, and when the sync state could not be read.
+ * @nullable
+ */
readonly status: string | null
}
@@ -4364,7 +4367,10 @@ export interface PatchedSignalSourceConfigApi {
config?: PatchedSignalSourceConfigApiConfig
readonly created_at?: string
readonly updated_at?: string
- /** @nullable */
+ /**
+ * Sync state of the warehouse import behind this source: `running`, `failed`, or `completed`. Null for a source that imports nothing from the warehouse, for an import that has never synced, and when the sync state could not be read.
+ * @nullable
+ */
readonly status?: string | null
}
diff --git a/products/signals/frontend/inbox/components/config/AgentsRoster.tsx b/products/signals/frontend/inbox/components/config/AgentsRoster.tsx
index 5da1070e85e9..87d8761c9bd4 100644
--- a/products/signals/frontend/inbox/components/config/AgentsRoster.tsx
+++ b/products/signals/frontend/inbox/components/config/AgentsRoster.tsx
@@ -3,6 +3,7 @@ import { memo, useCallback, useMemo, useState } from 'react'
import { IconArrowUpRight, IconChevronRight, IconGear, IconPlus } from '@posthog/icons'
import {
+ LemonBanner,
LemonButton,
LemonInput,
LemonSkeleton,
@@ -614,6 +615,8 @@ export function AgentsRoster(): JSX.Element {
isCiSignalsToggling,
toolStatusBySource,
enablingTool,
+ sourceConfigsLoadFailed,
+ sourceConfigsLoading,
} = useValues(signalSourcesLogic)
const {
toggleConversations,
@@ -627,6 +630,7 @@ export function AgentsRoster(): JSX.Element {
initiateDataWarehouseSourceToggle,
enableSourceTool,
loadToolDataEvents,
+ loadSourceConfigs,
} = useActions(signalSourcesLogic)
const { featureFlags } = useValues(featureFlagLogic)
const [expandedSource, setExpandedSource] = useState<AgentRosterSource | null>(null)
@@ -843,6 +847,22 @@ export function AgentsRoster(): JSX.Element {
return (
<div className="flex flex-col gap-3">
+ {sourceConfigsLoadFailed && (
+ // Without the configs every data-import source reads as never connected, so warn
+ // instead of letting a person act on switches that do not reflect the server.
+ <LemonBanner
+ type="warning"
+ action={{
+ children: 'Retry',
+ onClick: () => loadSourceConfigs(),
+ loading: sourceConfigsLoading,
+ 'data-attr': 'signals-retry-source-configs',
+ }}
+ >
+ Couldn't load your signal sources, so the switches below may not match what's on.
+ </LemonBanner>
+ )}
+
{!redesign && (
<div className="flex items-center gap-1.5 text-xs text-muted">
<span className={`size-2 rounded-full ${armedCount ? 'bg-success' : 'bg-border-bold'}`} />
diff --git a/products/signals/frontend/inbox/components/config/SignalSourcesPanel.stories.tsx b/products/signals/frontend/inbox/components/config/SignalSourcesPanel.stories.tsx
index 5a63f9a96246..e0a83defff49 100644
--- a/products/signals/frontend/inbox/components/config/SignalSourcesPanel.stories.tsx
+++ b/products/signals/frontend/inbox/components/config/SignalSourcesPanel.stories.tsx
@@ -33,6 +33,7 @@ interface PanelState {
hasAiEvents: boolean
hasAnalyticsEvents: boolean
eventDefinitionsUnavailable: boolean
+ sourceConfigsUnavailable: boolean
}
function sourceConfig(
@@ -112,7 +113,10 @@ function PanelHarness(state: PanelState): JSX.Element {
conversations_enabled: state.conversationsOn,
},
],
- '/api/projects/:team_id/signals/source_configs/': () => [200, { results: sourceConfigsFor(state) }],
+ '/api/projects/:team_id/signals/source_configs/': () =>
+ state.sourceConfigsUnavailable
+ ? [500, { detail: 'A server error occurred.' }]
+ : [200, { results: sourceConfigsFor(state) }],
'/api/projects/:team_id/vision/scanners/': () => {
const results = scannersFor(state)
return [200, { count: results.length, next: null, previous: null, results }]
@@ -174,6 +178,7 @@ const meta: Meta<typeof PanelHarness> = {
hasAiEvents: false,
hasAnalyticsEvents: true,
eventDefinitionsUnavailable: false,
+ sourceConfigsUnavailable: false,
},
}
export default meta
@@ -274,3 +279,10 @@ export const ServerSideExceptionsOnly: Story = {
hasExceptionEvents: true,
},
}
+
+/** The source configs endpoint failed: the roster warns that its switches may be stale, and offers a retry. */
+export const SourceConfigsUnavailable: Story = {
+ args: {
+ sourceConfigsUnavailable: true,
+ },
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2c1d800bc975..a9ea35ad2061 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -58356,7 +58356,10 @@ export namespace Schemas {
config?: SignalSourceConfigConfig;
readonly created_at: string;
readonly updated_at: string;
- /** @nullable */
+ /**
+ * Sync state of the warehouse import behind this source: `running`, `failed`, or `completed`. Null for a source that imports nothing from the warehouse, for an import that has never synced, and when the sync state could not be read.
+ * @nullable
+ */
readonly status: string | null;
}
@@ -67633,7 +67636,10 @@ export namespace Schemas {
config?: PatchedSignalSourceConfigConfig;
readonly created_at?: string;
readonly updated_at?: string;
- /** @nullable */
+ /**
+ * Sync state of the warehouse import behind this source: `running`, `failed`, or `completed`. Null for a source that imports nothing from the warehouse, for an import that has never synced, and when the sync state could not be read.
+ * @nullable
+ */
readonly status?: string | null;
}