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.

feat(signals): honor source steering for error tracking and health checks (#90594)

posthog[bot]2c77bfca48ba
diff --git a/posthog/temporal/health_checks/signal_emitter.py b/posthog/temporal/health_checks/signal_emitter.py
index 32251a1dc700..48aff5d4c4dd 100644
--- a/posthog/temporal/health_checks/signal_emitter.py
+++ b/posthog/temporal/health_checks/signal_emitter.py
@@ -16,6 +16,8 @@ logger = structlog.get_logger(__name__)
SOURCE_PRODUCT = "health_checks"
SOURCE_TYPE = "health_issue"
+# Concurrent emissions per batch. Matches the signals pipeline's own emit fan-out.
+EMIT_CONCURRENCY_LIMIT = 50
@dataclass(frozen=True)
@@ -72,9 +74,9 @@ def emit_health_check_signals(issues: list[HealthIssue]) -> int:
"""Emit Signals-inbox signals for a batch of newly-firing health issues.
Returns the number of signals queued. Resolves every issue up front, fetches all
- teams in one query, then fires the emissions concurrently rather than blocking the
- processing thread on each one's serial IO. Never raises — a single bad issue must
- not break the orchestrator batch.
+ teams in one query, then fires the emissions concurrently (bounded) rather than
+ blocking the processing thread on each one's serial IO. Never raises — a single bad
+ issue must not break the orchestrator batch.
"""
# Deferred import: keeps the signals product off the core import path and
# avoids the facade's circular import back into the temporal stack.
@@ -108,7 +110,16 @@ def emit_health_check_signals(issues: list[HealthIssue]) -> int:
return True
async def _emit_all() -> list[bool | BaseException]:
- return await asyncio.gather(*(_emit_one(signal) for signal in prepared), return_exceptions=True)
+ # A batch spans every team a check swept, and a team that steers this source has `emit_signal`
+ # run an LLM gate before queueing. Unbounded, one sweep could put hundreds of concurrent calls
+ # on the AI gateway. The semaphore is built here so it binds to the loop `async_to_sync` made.
+ semaphore = asyncio.Semaphore(EMIT_CONCURRENCY_LIMIT)
+
+ async def _bounded_emit(signal: _PreparedSignal) -> bool:
+ async with semaphore:
+ return await _emit_one(signal)
+
+ return await asyncio.gather(*(_bounded_emit(signal) for signal in prepared), return_exceptions=True)
queued = 0
for signal, result in zip(prepared, async_to_sync(_emit_all)()):
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index c9f8bd6647b3..fff2a08a0a45 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -537,7 +537,9 @@ Per-team configuration for which signal sources are enabled.
- `llm_analytics` signals go through the standard enabled-row check like every other source. `evaluation_report` is the only type AI observability emits, gated by its own `(llm_analytics, evaluation_report)` row (the inbox "AI observability" toggle). The per-result workflow and activity remain registered only so existing Temporal histories can finish replaying.
- For session replay configs, serializer validation enforces that `config.recording_filters` is a JSON object when present.
-- Two `config` keys steer the emission actionability gate per source: `config.steering` (free text, the team's preferences about the source's records — injected into the canonical actionability prompt, never replacing it) and `config.default_not_actionable` (boolean — flips the gate's "when in doubt" posture from keep to filter). Serializer validation enforces `steering` is a string capped at `STEERING_MAX_LENGTH` (2000 chars) and `default_not_actionable` is a boolean; injection escapes braces so the text can never break the gate's one-word output contract (see `backend/emission/steering.py`). The keys apply to sources that run `run_signal_pipeline` (data warehouse imports and Conversations); other sources persist them unread today, and future consumers (report research, the autostart gate) are expected to read the same text.
+- Two `config` keys steer the emission actionability gate per source: `config.steering` (free text, the team's preferences about the source's records — injected into the canonical actionability prompt, never replacing it) and `config.default_not_actionable` (boolean — flips the gate's "when in doubt" posture from keep to filter). Serializer validation enforces `steering` is a string capped at `STEERING_MAX_LENGTH` (2000 chars) and `default_not_actionable` is a boolean; injection escapes braces so the text can never break the gate's one-word output contract (see `backend/emission/steering.py`). The keys apply to sources that run `run_signal_pipeline` (data warehouse imports and Conversations), and to the direct-emitting sources listed in `DIRECT_STEERABLE_SOURCES` (error tracking and health checks), which `emit_signal` runs through the gate in `backend/emission/direct_gate.py` before queueing the signal.
+ A direct source is judged only when the team has written steering, and only against that text: the canonical prompt there states no criteria of its own, so a first rule filters what it describes and nothing else.
+ Sources outside both sets persist the keys unread, and future consumers (report research, the autostart gate) are expected to read the same text.
- The serializer exposes a computed `status` field:
- data-import-backed sources (`github`, `linear`, `zendesk`) derive status from `ExternalDataSchema`
- The `signals_scout` source variant pairs with `source_type=cross_source_issue` and is the emission channel used by the headless Signals agent's `emit_signal_*` tools. It is the only `(source_product, source_type)` pair the agent emits today.
diff --git a/products/signals/backend/contracts.py b/products/signals/backend/contracts.py
index 7cb1d0360064..5a6d6017568b 100644
--- a/products/signals/backend/contracts.py
+++ b/products/signals/backend/contracts.py
@@ -22,6 +22,19 @@ DEFAULT_NOT_ACTIONABLE_KEY = "default_not_actionable"
# defensively so a row written by another path cannot bloat every gate prompt.
STEERING_MAX_LENGTH = 2000
+# The sources that emit straight through `emit_signal` and still honor steering, via the gate in
+# `emission/direct_gate.py`. Every other direct source skips the gate, so writing steering onto its
+# row would store text nothing reads. The roster's `steerable` flags in `agentRosterMeta.ts` mirror
+# this set, and only these pairs may be offered the steering form.
+DIRECT_STEERABLE_SOURCES: frozenset[tuple[str, str]] = frozenset(
+ {
+ (SignalSourceProduct.ERROR_TRACKING, SignalSourceType.ISSUE_CREATED),
+ (SignalSourceProduct.ERROR_TRACKING, SignalSourceType.ISSUE_REOPENED),
+ (SignalSourceProduct.ERROR_TRACKING, SignalSourceType.ISSUE_SPIKING),
+ (SignalSourceProduct.HEALTH_CHECKS, SignalSourceType.HEALTH_ISSUE),
+ }
+)
+
class ContractModel(BaseModel):
# Emitted payloads are validated against these models at the emit boundary; unknown fields are
diff --git a/products/signals/backend/emission/AGENTS.md b/products/signals/backend/emission/AGENTS.md
index f18555f48991..95b24b35a98c 100644
--- a/products/signals/backend/emission/AGENTS.md
+++ b/products/signals/backend/emission/AGENTS.md
@@ -28,6 +28,18 @@ The core signal pipeline (`products/signals/backend/emission/pipeline.py`) is so
A steered gate gets all of `extra` in that block instead; a source declaring nothing keeps a byte-identical prompt.
5. **Emission** — emits surviving outputs as Signals via `products/signals/backend/api/emit_signal`
+### Direct sources
+
+Error tracking and health checks never enter the shared pipeline: they build a description themselves and call `emit_signal` directly.
+They still honor steering, through the gate in `direct_gate.py` that `emit_signal` applies to the `(source_product, source_type)` pairs in `contracts.DIRECT_STEERABLE_SOURCES`.
+Two rules keep that gate predictable.
+A team that wrote no steering gets no LLM call and no change in behavior.
+A team that wrote steering is filtered by that text alone, because the prompt there carries no actionability criteria of its own, unlike the record-shaped prompts in `_prompts.py`.
+The gate fails open, and reports a dropped signal as `signal_data_source_filtered` with `steering_applied`, the same stage event the pipeline fires.
+
+A pair listed in `DIRECT_STEERABLE_SOURCES` that the registry also serves would have every record judged twice, so the two sets must stay disjoint (`tests/test_direct_gate.py` holds that).
+The roster's `steerable` flags in `products/signals/frontend/inbox/components/config/agentRosterMeta.ts` mirror the same set: a source that offers the steering form without a gate behind it stores text nothing reads.
+
### Registry
`products/signals/backend/emission/registry.py` maps `(source_type, schema_name)` pairs to their config.
diff --git a/products/signals/backend/emission/direct_gate.py b/products/signals/backend/emission/direct_gate.py
new file mode 100644
index 000000000000..41d3ba8710f0
--- /dev/null
+++ b/products/signals/backend/emission/direct_gate.py
@@ -0,0 +1,136 @@
+"""Steering for the sources that emit straight through ``emit_signal``.
+
+Error tracking and health checks never enter the batch pipeline in ``pipeline.py``, so until now
+nothing read the ``steering`` text a team wrote for them and the only way to stop a class of report
+was to turn the source off. This gate closes that gap: ``emit_signal`` asks it about every signal
+from a pair in ``DIRECT_STEERABLE_SOURCES``, and drops the signal when the team's own rules say to
+skip it.
+
+Two properties keep the gate cheap and predictable:
+
+- **No steering, no gate.** Written ``steering`` text is the only thing that turns the gate on, so a
+ team that wrote nothing gets no LLM call, no added latency, and the behavior it has today. The
+ retired ``default_not_actionable`` posture is deliberately ignored here: it tells the model to keep
+ only records that clearly match the prompt's ACTIONABLE criteria, and this prompt states none, so
+ honoring it would drop nearly everything.
+- **The team's rules are the only criteria.** The canonical prompt here states no opinion of its own
+ about what deserves a report, unlike the record-shaped prompts in ``_prompts.py`` that the batch
+ pipeline applies whether or not a team has steered. So writing a first rule filters what that rule
+ describes, and nothing else.
+
+The gate fails open. A steering rule that never runs costs a team one noisy report; a gate that
+drops signals when the LLM is unreachable loses real ones.
+"""
+
+import asyncio
+from typing import Any
+
+import structlog
+
+from posthog.llm.gateway_client import build_async_anthropic_client, resolve_ai_gateway_config
+from posthog.models import Organization, Team
+
+from products.signals.backend.emission.pipeline import EMISSION_AI_PRODUCT, capture_pipeline_stage, check_actionability
+from products.signals.backend.emission.registry import SignalEmitterOutput
+from products.signals.backend.emission.steering import (
+ SourceSteering,
+ afetch_source_config,
+ apply_steering,
+ steering_from_config,
+)
+
+logger = structlog.get_logger(__name__)
+
+# The whole verdict, retries included, has to fit inside the budget its caller already has, and some
+# callers emit many signals in one activity. `check_actionability` alone can spend three attempts of
+# up to 120 seconds, which overruns the tightest of those budgets (the 2-minute activity in
+# `temporal/backfill_error_tracking.py`) on a single signal. A verdict is not worth holding an emit
+# for once it is this late, so the gate gives up and fails open well before its caller has to.
+GATE_TIMEOUT_SECONDS = 20
+
+# Keeps the `When in doubt, classify as ACTIONABLE` line `apply_steering` anchors on, and the
+# one-word output contract `check_actionability` parses.
+DIRECT_SOURCE_ACTIONABILITY_PROMPT = """You are triaging one record a PostHog product raised for the team that owns it, to decide whether the team should see it.
+
+The team's own preferences are the only thing that filters here. Classify the record NOT_ACTIONABLE when those preferences say to skip it. There are no other criteria: a record that no preference excludes is ACTIONABLE.
+
+When in doubt, classify as ACTIONABLE.
+
+<record>
+{description}
+</record>
+
+Respond with exactly one word: ACTIONABLE or NOT_ACTIONABLE"""
+
+
+async def steering_filters_signal(
+ *,
+ team: Team,
+ organization: Organization,
+ source_product: str,
+ source_type: str,
+ source_id: str,
+ description: str,
+ weight: float,
+ extra: dict[str, Any],
+) -> bool:
+ """Whether this team's steering says to drop the signal.
+
+ Returns False without an LLM call when the team has written no steering for the source. A dropped
+ signal reports itself as ``signal_data_source_filtered`` with ``steering_applied``, the same stage
+ event the batch pipeline fires, so a filtered signal is distinguishable from one lost to a failure.
+ """
+ # Text only, dropping any `default_not_actionable` the row carries. See the module docstring.
+ steering = SourceSteering(
+ text=steering_from_config(await afetch_source_config(team.id, source_product, source_type)).text
+ )
+ if not steering.text:
+ return False
+
+ output = SignalEmitterOutput(
+ source_product=source_product,
+ source_type=source_type,
+ source_id=source_id,
+ description=description,
+ weight=weight,
+ extra=extra,
+ )
+ try:
+ # Closed on the way out: unlike the batch pipeline, which builds one client for a whole run,
+ # this path builds one per signal, and each carries its own httpx connection pool.
+ async with build_async_anthropic_client(
+ product="signals", ai_product=EMISSION_AI_PRODUCT, team_id=team.id
+ ) as client:
+ actionable = await asyncio.wait_for(
+ check_actionability(
+ client,
+ team.id,
+ output,
+ apply_steering(DIRECT_SOURCE_ACTIONABILITY_PROMPT, steering),
+ gateway_mode=resolve_ai_gateway_config() is not None,
+ # Steering rules reference facts the description does not always carry (a host, a
+ # check kind), so the steered gate sees all of `extra`, as in the batch pipeline.
+ include_record_metadata=True,
+ ),
+ timeout=GATE_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ logger.exception(
+ "Source steering gate failed, keeping signal",
+ signal_source_product=source_product,
+ signal_source_type=source_type,
+ signal_source_id=source_id,
+ )
+ return False
+
+ if actionable:
+ return False
+
+ logger.info(
+ "Filtered signal by source steering",
+ signal_source_product=source_product,
+ signal_source_type=source_type,
+ signal_source_id=source_id,
+ )
+ capture_pipeline_stage("signal_data_source_filtered", team, organization, output, {"steering_applied": True})
+ return True
diff --git a/products/signals/backend/emission/pipeline.py b/products/signals/backend/emission/pipeline.py
index b964f13c4ecb..710972ef0ab1 100644
--- a/products/signals/backend/emission/pipeline.py
+++ b/products/signals/backend/emission/pipeline.py
@@ -92,7 +92,7 @@ def _extract_text(response: Any) -> str:
return "".join(block.text for block in response.content if getattr(block, "type", None) == "text")
-def _capture_pipeline_stage(
+def capture_pipeline_stage(
event: str,
team: Team,
organization: Organization,
@@ -285,7 +285,7 @@ def _declared_context(extra: dict[str, Any], context_fields: tuple[str, ...]) ->
return {key: extra[key] for key in context_fields if extra.get(key) is not None}
-async def _check_actionability(
+async def check_actionability(
client: AsyncAnthropic,
team_id: int,
output: SignalEmitterOutput,
@@ -294,6 +294,11 @@ async def _check_actionability(
include_record_metadata: bool = False,
context_fields: tuple[str, ...] = (),
) -> bool:
+ """One record's actionability verdict, fail-open: every retry exhausted returns actionable.
+
+ Shared with the direct-source gate in `direct_gate.py`, which judges a single signal that never
+ entered this batch pipeline.
+ """
description = output.description
# Steering rules often reference metadata (labels, state, priority) that emitters keep in `extra`
# rather than in the description, so the steered gate sees all of it. An unsteered gate sees only
@@ -359,7 +364,7 @@ async def filter_actionable(
nonlocal checked_count
async with semaphore:
try:
- result = await _check_actionability(
+ result = await check_actionability(
client,
team.id,
output,
@@ -475,7 +480,7 @@ async def _emit_signals(
signal_source_id=output.source_id,
**extra,
)
- _capture_pipeline_stage(
+ capture_pipeline_stage(
"signal_data_source_emit_failed", team, organization, output, {"error_type": error_type}
)
metrics.increment_dropped(stage=EMIT_DROP_STAGE, reason=error_type)
@@ -531,7 +536,7 @@ async def run_signal_pipeline(
organization = await database_sync_to_async(lambda: team.organization)()
for output in outputs:
- _capture_pipeline_stage("signal_data_source_entered", team, organization, output)
+ capture_pipeline_stage("signal_data_source_entered", team, organization, output)
if config.summarization_prompt is not None and config.description_summarization_threshold_chars is not None:
threshold = config.description_summarization_threshold_chars
@@ -546,7 +551,7 @@ async def run_signal_pipeline(
for output in outputs:
pre = pre_summary_by_id.get(output.source_id)
if pre is not None and len(pre.description) > threshold:
- _capture_pipeline_stage("signal_data_source_summarized", team, organization, output)
+ capture_pipeline_stage("signal_data_source_summarized", team, organization, output)
if config.actionability_prompt:
steering = steering_from_config(source_config)
@@ -564,7 +569,7 @@ async def run_signal_pipeline(
post_filter_ids = {o.source_id for o in outputs}
for source_id, output in pre_filter_by_id.items():
if source_id not in post_filter_ids:
- _capture_pipeline_stage(
+ capture_pipeline_stage(
"signal_data_source_filtered", team, organization, output, {"steering_applied": steering.active}
)
diff --git a/products/signals/backend/emission/tests/test_direct_gate.py b/products/signals/backend/emission/tests/test_direct_gate.py
new file mode 100644
index 000000000000..b5871c8009d7
--- /dev/null
+++ b/products/signals/backend/emission/tests/test_direct_gate.py
@@ -0,0 +1,187 @@
+import uuid
+import asyncio
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from products.signals.backend.contracts import DIRECT_STEERABLE_SOURCES
+from products.signals.backend.emission.direct_gate import steering_filters_signal
+from products.signals.backend.emission.registry import _SIGNAL_TABLE_CONFIGS
+from products.signals.backend.facade.api import emit_signal
+
+GATE_MODULE_PATH = "products.signals.backend.emission.direct_gate"
+FACADE_MODULE_PATH = "products.signals.backend.facade.api"
+
+
+def _make_llm_response(verdict: str) -> MagicMock:
+ block = MagicMock()
+ block.type = "text"
+ block.text = verdict
+ response = MagicMock()
+ response.content = [block]
+ response.stop_reason = "end_turn"
+ return response
+
+
+def _make_team() -> MagicMock:
+ return MagicMock(id=1, uuid=uuid.uuid4())
+
+
+async def _run_gate(source_config: dict, *, verdict: str = "NOT_ACTIONABLE", extra: dict | None = None):
+ """Run the gate against a stubbed source config and LLM, returning (dropped, anthropic client)."""
+ client = MagicMock()
+ client.messages.create = AsyncMock(return_value=_make_llm_response(verdict))
+ client.__aenter__.return_value = client
+ with (
+ patch(f"{GATE_MODULE_PATH}.afetch_source_config", AsyncMock(return_value=source_config)),
+ patch(f"{GATE_MODULE_PATH}.build_async_anthropic_client", return_value=client),
+ patch(f"{GATE_MODULE_PATH}.resolve_ai_gateway_config", return_value=None),
+ patch(f"{GATE_MODULE_PATH}.capture_pipeline_stage") as capture,
+ ):
+ dropped = await steering_filters_signal(
+ team=_make_team(),
+ organization=MagicMock(),
+ source_product="error_tracking",
+ source_type="issue_created",
+ source_id="issue-1",
+ description="TypeError: undefined is not a function",
+ weight=1.0,
+ extra=extra or {"fingerprint": "abc123"},
+ )
+ return dropped, client, capture
+
+
+class TestSteeringFiltersSignal:
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "source_config",
+ [{}, {"steering": " "}, {"steering": None}, {"other_key": "value"}, {"default_not_actionable": True}],
+ ids=["no_config", "blank_steering", "null_steering", "unrelated_keys", "retired_posture_flag_only"],
+ )
+ async def test_a_source_with_no_steering_keeps_every_signal_and_never_calls_the_llm(self, source_config):
+ # Direct sources emitted straight through before this gate existed. A team that wrote no
+ # rules must keep that behavior exactly, and must not start paying for an LLM call per signal.
+ dropped, client, _ = await _run_gate(source_config)
+
+ assert dropped is False
+ client.messages.create.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_steering_drops_the_signal_and_reports_it_as_filtered(self):
+ dropped, client, capture = await _run_gate({"steering": "Ignore errors from localhost."})
+
+ assert dropped is True
+ prompt = client.messages.create.call_args.kwargs["messages"][0]["content"]
+ assert "Ignore errors from localhost." in prompt
+ # `extra` reaches the gate too, so a rule can name a fact the description does not carry.
+ assert '"fingerprint": "abc123"' in prompt
+ event, _team, _organization, output, properties = capture.call_args.args
+ assert event == "signal_data_source_filtered"
+ assert properties == {"steering_applied": True}
+ assert output.source_id == "issue-1"
+
+ @pytest.mark.asyncio
+ async def test_a_row_carrying_the_retired_posture_flag_still_keeps_the_lenient_posture(self):
+ # The flag tells the model to keep only records that clearly match the prompt's ACTIONABLE
+ # criteria. This prompt states none, so honoring it here would drop nearly everything.
+ _dropped, client, _capture = await _run_gate(
+ {"steering": "Ignore errors from localhost.", "default_not_actionable": True}
+ )
+
+ prompt = client.messages.create.call_args.kwargs["messages"][0]["content"]
+ assert "When in doubt, classify as ACTIONABLE." in prompt
+ assert "err on the side of filtering" not in prompt
+
+ @pytest.mark.asyncio
+ async def test_a_steered_signal_the_rules_do_not_exclude_still_emits(self):
+ dropped, _client, capture = await _run_gate({"steering": "Ignore errors from localhost."}, verdict="ACTIONABLE")
+
+ assert dropped is False
+ capture.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_a_stalled_gateway_gives_up_on_the_gate_rather_than_holding_the_emit(self):
+ # The caller emits inside its own activity timeout. Waiting out every retry would blow that
+ # budget, fail the activity, and have Temporal replay the emit instead of sending it.
+ async def never_answers(**_kwargs):
+ await asyncio.sleep(60)
+
+ client = MagicMock()
+ client.messages.create = AsyncMock(side_effect=never_answers)
+ client.__aenter__.return_value = client
+ with (
+ patch(f"{GATE_MODULE_PATH}.afetch_source_config", AsyncMock(return_value={"steering": "Skip noise."})),
+ patch(f"{GATE_MODULE_PATH}.build_async_anthropic_client", return_value=client),
+ patch(f"{GATE_MODULE_PATH}.resolve_ai_gateway_config", return_value=None),
+ patch(f"{GATE_MODULE_PATH}.GATE_TIMEOUT_SECONDS", 0.01),
+ ):
+ dropped = await steering_filters_signal(
+ team=_make_team(),
+ organization=MagicMock(),
+ source_product="error_tracking",
+ source_type="issue_created",
+ source_id="issue-1",
+ description="TypeError: undefined is not a function",
+ weight=1.0,
+ extra={},
+ )
+
+ assert dropped is False
+
+ @pytest.mark.asyncio
+ async def test_the_gate_fails_open_when_the_llm_client_cannot_be_built(self):
+ # Dropping signals whenever the gateway is unreachable would lose real problems silently,
+ # which is worse than letting a noisy one through.
+ with (
+ patch(f"{GATE_MODULE_PATH}.afetch_source_config", AsyncMock(return_value={"steering": "Skip noise."})),
+ patch(f"{GATE_MODULE_PATH}.build_async_anthropic_client", side_effect=RuntimeError("no gateway")),
+ ):
+ dropped = await steering_filters_signal(
+ team=_make_team(),
+ organization=MagicMock(),
+ source_product="error_tracking",
+ source_type="issue_created",
+ source_id="issue-1",
+ description="TypeError: undefined is not a function",
+ weight=1.0,
+ extra={},
+ )
+
+ assert dropped is False
+
+
+class TestEmitSignalWiring:
+ @pytest.mark.asyncio
+ async def test_emit_signal_consults_the_gate_and_drops_a_filtered_signal_before_queueing(self):
+ # The gate reaches production only through the membership check in `emit_signal`, whose
+ # `(source_product, source_type)` tuple has to match the enum values the set is built from.
+ team = _make_team()
+ team.organization.is_ai_data_processing_approved = True
+ connect = AsyncMock()
+ with (
+ patch(f"{FACADE_MODULE_PATH}.SignalSourceConfig") as source_config,
+ patch(f"{FACADE_MODULE_PATH}.posthoganalytics"),
+ patch(f"{FACADE_MODULE_PATH}.async_connect", connect),
+ patch(f"{GATE_MODULE_PATH}.steering_filters_signal", AsyncMock(return_value=True)) as gate,
+ ):
+ source_config.is_source_enabled.return_value = True
+ await emit_signal(
+ team=team,
+ source_product="error_tracking",
+ source_type="issue_created",
+ source_id="record-1",
+ description="Something happened",
+ extra={"fingerprint": "abc123"},
+ )
+
+ assert gate.called
+ # A signal the gate drops never reaches Temporal, so it cannot become a report.
+ assert not connect.called
+
+
+def test_no_pipeline_source_is_listed_as_directly_steerable():
+ # A source registered for the batch pipeline already runs its own steered actionability gate.
+ # Listing it here too would judge every one of its records twice, at twice the LLM cost.
+ pipeline_sources = {(config.source_product, config.source_type) for config in _SIGNAL_TABLE_CONFIGS.values()}
+
+ assert DIRECT_STEERABLE_SOURCES.isdisjoint(pipeline_sources)
diff --git a/products/signals/backend/emission/tests/test_emit_signals.py b/products/signals/backend/emission/tests/test_emit_signals.py
index cd41129e4ac7..04204d462913 100644
--- a/products/signals/backend/emission/tests/test_emit_signals.py
+++ b/products/signals/backend/emission/tests/test_emit_signals.py
@@ -26,10 +26,10 @@ from products.signals.backend.emission.fetchers.data_warehouse import data_wareh
from products.signals.backend.emission.pipeline import (
LLM_MAX_ATTEMPTS,
TEMPORAL_PAYLOAD_MAX_BYTES,
- _check_actionability,
_emit_signals,
_summarize_description,
build_emitter_outputs,
+ check_actionability,
filter_actionable,
run_signal_pipeline,
summarize_long_descriptions,
@@ -273,7 +273,7 @@ class TestCheckActionability:
mock_client.messages.create = AsyncMock(return_value=_make_llm_response(llm_response))
output = _make_output(description="test ticket")
- is_actionable = await _check_actionability(mock_client, 1, output, "Is this actionable? {description}")
+ is_actionable = await check_actionability(mock_client, 1, output, "Is this actionable? {description}")
assert is_actionable is expected
@@ -286,7 +286,7 @@ class TestCheckActionability:
mock_client.messages.create = AsyncMock(return_value=_make_llm_response("ACTIONABLE"))
output = _make_output(extra={"author_login": "dependabot[bot]", "state": "open"})
- await _check_actionability(mock_client, 1, output, "prompt {description}", context_fields=("author_login",))
+ await check_actionability(mock_client, 1, output, "prompt {description}", context_fields=("author_login",))
prompt = mock_client.messages.create.call_args.kwargs["messages"][0]["content"]
assert '"author_login": "dependabot[bot]"' in prompt
@@ -301,7 +301,7 @@ class TestCheckActionability:
mock_client.messages.create = AsyncMock(return_value=_make_llm_response("ACTIONABLE"))
output = _make_output(extra={"author_login": None, "author_association": None})
- await _check_actionability(
+ await check_actionability(
mock_client, 1, output, "prompt {description}", context_fields=("author_login", "author_association")
)
@@ -316,7 +316,7 @@ class TestCheckActionability:
mock_client.messages.create = AsyncMock(return_value=_make_llm_response("ACTIONABLE"))
output = _make_output(extra={"labels": ["x" * 100] * 40, "author_login": "octocat"})
- await _check_actionability(
+ await check_actionability(
mock_client,
1,
output,
@@ -334,7 +334,7 @@ class TestCheckActionability:
mock_client.messages.create = AsyncMock(side_effect=Exception("API error"))
with patch(f"{PIPELINE_MODULE_PATH}.posthoganalytics"):
- is_actionable = await _check_actionability(mock_client, 1, _make_output(), "prompt {description}")
+ is_actionable = await check_actionability(mock_client, 1, _make_output(), "prompt {description}")
assert is_actionable is True
assert mock_client.messages.create.call_count == LLM_MAX_ATTEMPTS
@@ -344,7 +344,7 @@ class TestCheckActionability:
mock_client = MagicMock()
mock_client.messages.create = AsyncMock(return_value=_make_llm_response(None))
- is_actionable = await _check_actionability(mock_client, 1, _make_output(), "prompt {description}")
+ is_actionable = await check_actionability(mock_client, 1, _make_output(), "prompt {description}")
assert is_actionable is True
@@ -354,7 +354,7 @@ class TestCheckActionability:
mock_client.messages.create = AsyncMock(return_value=_make_llm_response("ACTIONABLE"))
output = _make_output(source_id="42")
- await _check_actionability(mock_client, 7, output, "Is this actionable? {description}")
+ await check_actionability(mock_client, 7, output, "Is this actionable? {description}")
call_kwargs = mock_client.messages.create.call_args.kwargs
assert call_kwargs["metadata"]["user_id"] == "team-7"
@@ -373,7 +373,7 @@ class TestCheckActionability:
mock_client.messages.create = AsyncMock(return_value=_make_llm_response("ACTIONABLE"))
output = _make_output(source_id="42")
- await _check_actionability(mock_client, 7, output, "Is this actionable? {description}")
+ await check_actionability(mock_client, 7, output, "Is this actionable? {description}")
headers = mock_client.messages.create.call_args.kwargs["extra_headers"]
# The Go gateway reads labels only from X-PostHog-Properties; the per-key headers are gone.
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index db4d07eb3a2e..2506d8a17b05 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -20,7 +20,7 @@ from posthog.models import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.client import async_connect
-from products.signals.backend.contracts import SIGNAL_VARIANT_LOOKUP, SignalRemediation
+from products.signals.backend.contracts import DIRECT_STEERABLE_SOURCES, SIGNAL_VARIANT_LOOKUP, SignalRemediation
from products.signals.backend.enums import SIGNAL_SOURCE_PRODUCT_LABELS, SignalSourceProduct
from products.signals.backend.models import SignalReport, SignalScoutConfig, SignalScoutRun, SignalSourceConfig
from products.signals.backend.signal_metadata import fetch_signal_stats_for_source_slice
@@ -511,6 +511,11 @@ async def emit_signal(
Active path:
emit_signal() -> SignalEmitterWorkflow -> BufferSignalsWorkflow -> TeamSignalGroupingV2Workflow
+ A source in `DIRECT_STEERABLE_SOURCES` is checked against the team's steering first and dropped
+ when the team's rules say to skip it (see `emission/direct_gate.py`). A team that wrote no
+ steering is unaffected. Sources that reach here through the batch pipeline already ran their own
+ steered gate, so they stay out of that set and are never judged twice.
+
Args:
team: The team object
source_product: Product emitting the signal (e.g., "experiments", "web_analytics")
@@ -589,8 +594,9 @@ async def emit_signal(
)
# Fire a "started" marker so direct callers (error tracking, AI observability evals, etc.)
- # that don't go through the data-source pipeline still have a top-of-funnel event. The
- # gap to `signal_emitted` surfaces Temporal/dispatch failures.
+ # that don't go through the data-source pipeline still have a top-of-funnel event. The gap to
+ # `signal_emitted` surfaces Temporal/dispatch failures, once the steering gate below is
+ # subtracted: started - signal_data_source_filtered - emitted = failures.
try:
posthoganalytics.capture(
event="signal_emission_started",
@@ -612,6 +618,25 @@ async def emit_signal(
source_id=source_id,
)
+ # Below the started event on purpose: a filtered signal then has a top-of-funnel event to be
+ # counted against, so a steering drop reads apart from a dispatch failure rather than as one.
+ if (source_product, source_type) in DIRECT_STEERABLE_SOURCES:
+ # Deferred: the emission package imports this facade back, and its __init__ registers every
+ # emitter, which must stay off the import path of Celery workers and management commands.
+ from products.signals.backend.emission.direct_gate import steering_filters_signal # noqa: PLC0415
+
+ if await steering_filters_signal(
+ team=team,
+ organization=organization,
+ source_product=source_product,
+ source_type=source_type,
+ source_id=source_id,
+ description=description,
+ weight=weight,
+ extra=extra or {},
+ ):
+ return
+
client = await async_connect()
signal_input = EmitSignalInputs(
diff --git a/products/signals/eval/conftest.py b/products/signals/eval/conftest.py
index 96ebd77f077c..0056aa08f314 100644
--- a/products/signals/eval/conftest.py
+++ b/products/signals/eval/conftest.py
@@ -98,7 +98,7 @@ def gateway_client():
"""Async Anthropic client pointed at the internal LLM gateway's native Messages endpoint.
Used by eval_grouping_e2e to drive the production signals pre-emit pipeline
- (`_check_actionability` etc.) through the gateway, attributing cost to EVAL_TEAM_ID.
+ (`check_actionability` etc.) through the gateway, attributing cost to EVAL_TEAM_ID.
"""
return get_async_anthropic_gateway_client(product="signals", team_id=EVAL_TEAM_ID)
diff --git a/products/signals/eval/eval_grouping_e2e.py b/products/signals/eval/eval_grouping_e2e.py
index 5d138c4d0b59..c956d187991b 100644
--- a/products/signals/eval/eval_grouping_e2e.py
+++ b/products/signals/eval/eval_grouping_e2e.py
@@ -39,7 +39,7 @@ from sklearn.metrics import adjusted_rand_score, homogeneity_completeness_v_meas
from tqdm import tqdm
from products.signals.backend.emission.pipeline import (
- _check_actionability,
+ check_actionability,
summarize_long_descriptions as _summarize_long_descriptions,
)
from products.signals.backend.temporal.grouping import (
@@ -301,7 +301,7 @@ class EvalGroupingPipeline:
output = outputs[0]
if config.actionability_prompt:
- is_actionable = await _check_actionability(
+ is_actionable = await check_actionability(
self.gateway_client,
EVAL_TEAM_ID,
output,
diff --git a/products/signals/frontend/inbox/components/config/AgentsRoster.tsx b/products/signals/frontend/inbox/components/config/AgentsRoster.tsx
index 653a6b59e8f9..5da1070e85e9 100644
--- a/products/signals/frontend/inbox/components/config/AgentsRoster.tsx
+++ b/products/signals/frontend/inbox/components/config/AgentsRoster.tsx
@@ -95,8 +95,11 @@ interface AgentSourceState {
entities: RosterEntity[]
/** The entity list is still loading, so the count would read as a wrong zero. */
entitiesLoading: boolean
- /** The source's `SignalSourceConfig` row, for sources that persist one. Steering writes to it. */
- sourceConfig: SignalSourceConfig | null
+ /**
+ * The source's `SignalSourceConfig` rows, for sources that persist them. Guidance writes to all
+ * of them, so a source with a row per signal type is steered from its one card.
+ */
+ steeringConfigs: SignalSourceConfig[]
}
function AgentIcon({ source }: { source: AgentRosterDefinition }): JSX.Element | null {
@@ -335,7 +338,7 @@ function Expansion({
{onSteer && (
<div className="flex items-center gap-2">
<span className="text-xs text-secondary">
- {state.sourceConfig && sourceSteeringIsSet(state.sourceConfig)
+ {state.steeringConfigs.some(sourceSteeringIsSet)
? 'Guidance is set for this source.'
: 'Tell the agent what matters and what to skip.'}
</span>
@@ -346,9 +349,7 @@ function Expansion({
onClick={onSteer}
data-attr="signal-source-steering-open"
>
- {state.sourceConfig && sourceSteeringIsSet(state.sourceConfig)
- ? 'Edit guidance'
- : 'Add guidance'}
+ {state.steeringConfigs.some(sourceSteeringIsSet) ? 'Edit guidance' : 'Add guidance'}
</LemonButton>
</div>
)}
@@ -597,6 +598,7 @@ export function AgentsRoster(): JSX.Element {
ciSignalsConfig,
ciSignalsConfigLoading,
ciSignalsIsFullyEnabled,
+ errorTrackingConfigs,
errorTrackingTypeStates,
visionScanners,
visionScannersLoading,
@@ -629,7 +631,7 @@ export function AgentsRoster(): JSX.Element {
const { featureFlags } = useValues(featureFlagLogic)
const [expandedSource, setExpandedSource] = useState<AgentRosterSource | null>(null)
// Which modal is open is a view concern; the form and save live in sourceSteeringModalLogic.
- const [steeringTarget, setSteeringTarget] = useState<{ config: SignalSourceConfig; label: string } | null>(null)
+ const [steeringTarget, setSteeringTarget] = useState<{ configs: SignalSourceConfig[]; label: string } | null>(null)
const scannerEntities = useMemo(
(): RosterEntity[] =>
@@ -659,7 +661,7 @@ export function AgentsRoster(): JSX.Element {
const base = {
entities: [] as RosterEntity[],
entitiesLoading: false,
- sourceConfig: null as SignalSourceConfig | null,
+ steeringConfigs: [] as SignalSourceConfig[],
}
const dwState = (config: SignalSourceConfig | null, loading: boolean): AgentSourceState => ({
...base,
@@ -668,7 +670,7 @@ export function AgentsRoster(): JSX.Element {
// No config row yet → the source has never been connected; surface a Connect button.
requiresSetup: config === null,
syncStatus: config?.status,
- sourceConfig: config,
+ steeringConfigs: config ? [config] : [],
})
switch (source) {
case 'error_tracking':
@@ -681,6 +683,7 @@ export function AgentsRoster(): JSX.Element {
requiresSetup: false,
syncStatus: null,
entities: errorTrackingEntities,
+ steeringConfigs: errorTrackingConfigs,
}
case 'conversations':
return {
@@ -689,7 +692,7 @@ export function AgentsRoster(): JSX.Element {
loading: isConversationsToggling,
requiresSetup: false,
syncStatus: conversationsConfig?.status,
- sourceConfig: conversationsConfig,
+ steeringConfigs: conversationsConfig ? [conversationsConfig] : [],
}
case 'replay_vision':
return {
@@ -724,6 +727,7 @@ export function AgentsRoster(): JSX.Element {
loading: isHealthChecksToggling,
requiresSetup: false,
syncStatus: healthChecksConfig?.status,
+ steeringConfigs: healthChecksConfig ? [healthChecksConfig] : [],
}
case 'github':
return dwState(githubIssuesConfig, isGithubIssuesToggling)
@@ -746,6 +750,7 @@ export function AgentsRoster(): JSX.Element {
},
[
errorTrackingEntities,
+ errorTrackingConfigs,
errorTrackingTypeStates,
isErrorTrackingToggling,
conversationsConfig,
@@ -857,9 +862,11 @@ export function AgentsRoster(): JSX.Element {
// placeholder rows wait until the reload lands. Disabled sources keep
// the control: enabling starts a sync immediately, so rules must be
// settable before the first sync runs.
- const steeringConfig =
- agent.steerable && state.sourceConfig && !state.sourceConfig.id.startsWith('new_')
- ? state.sourceConfig
+ const steeringConfigs =
+ agent.steerable &&
+ state.steeringConfigs.length > 0 &&
+ state.steeringConfigs.every((config) => !config.id.startsWith('new_'))
+ ? state.steeringConfigs
: null
return (
<AgentRow
@@ -879,8 +886,8 @@ export function AgentsRoster(): JSX.Element {
onEnableTool={(tool) => tool.enablement && enableSourceTool(tool.enablement)}
onConfigureFilters={undefined}
onSteer={
- steeringConfig
- ? () => setSteeringTarget({ config: steeringConfig, label: agent.label })
+ steeringConfigs
+ ? () => setSteeringTarget({ configs: steeringConfigs, label: agent.label })
: undefined
}
onRetryData={loadToolDataEvents}
@@ -894,8 +901,8 @@ export function AgentsRoster(): JSX.Element {
{/* Remounts per target (the key), so the form defaults re-derive from that source's config. */}
{steeringTarget && (
<SourceSteeringModal
- key={steeringTarget.config.id}
- sourceConfig={steeringTarget.config}
+ key={steeringTarget.configs.map((config) => config.id).join(',')}
+ sourceConfigs={steeringTarget.configs}
sourceLabel={steeringTarget.label}
onClose={() => setSteeringTarget(null)}
/>
diff --git a/products/signals/frontend/inbox/components/config/SourceSteeringModal.stories.tsx b/products/signals/frontend/inbox/components/config/SourceSteeringModal.stories.tsx
index 14c573181ca2..e7fd13e19b02 100644
--- a/products/signals/frontend/inbox/components/config/SourceSteeringModal.stories.tsx
+++ b/products/signals/frontend/inbox/components/config/SourceSteeringModal.stories.tsx
@@ -21,7 +21,7 @@ interface HarnessProps {
}
function ModalHarness({ config }: HarnessProps): JSX.Element {
- return <SourceSteeringModal sourceConfig={sourceConfig(config)} sourceLabel="GitHub issues" onClose={() => {}} />
+ return <SourceSteeringModal sourceConfigs={[sourceConfig(config)]} sourceLabel="GitHub issues" onClose={() => {}} />
}
const meta: Meta<typeof ModalHarness> = {
diff --git a/products/signals/frontend/inbox/components/config/SourceSteeringModal.tsx b/products/signals/frontend/inbox/components/config/SourceSteeringModal.tsx
index 091e55afec2e..e054799b1bf7 100644
--- a/products/signals/frontend/inbox/components/config/SourceSteeringModal.tsx
+++ b/products/signals/frontend/inbox/components/config/SourceSteeringModal.tsx
@@ -14,15 +14,16 @@ import {
import { SOURCE_STEERING_MAX_LENGTH, SignalSourceConfig } from '../../types'
export interface SourceSteeringModalProps {
- sourceConfig: SignalSourceConfig
+ /** Every config row this source's guidance is saved to. See `SourceSteeringModalLogicProps`. */
+ sourceConfigs: SignalSourceConfig[]
/** The roster label of the source being steered, for the modal title. */
sourceLabel: string
onClose: () => void
}
-export function SourceSteeringModal({ sourceConfig, sourceLabel, onClose }: SourceSteeringModalProps): JSX.Element {
+export function SourceSteeringModal({ sourceConfigs, sourceLabel, onClose }: SourceSteeringModalProps): JSX.Element {
const formId = useId()
- const logicProps: SourceSteeringModalLogicProps = { sourceConfig, onClose }
+ const logicProps: SourceSteeringModalLogicProps = { sourceConfigs, onClose }
const logic = sourceSteeringModalLogic(logicProps)
const { isSourceSteeringSubmitting, sourceSteeringChanged, sourceSteeringValidationErrors, steeringExamples } =
useValues(logic)
@@ -78,7 +79,7 @@ export function SourceSteeringModal({ sourceConfig, sourceLabel, onClose }: Sour
enableFormOnSubmit
>
<div className="flex flex-col gap-3">
- {sourceHasLegacyPosture(sourceConfig) && (
+ {sourceConfigs.some(sourceHasLegacyPosture) && (
<LemonBanner type="info">
This source only reports records that clearly qualify. Saving here replaces that with what
you write below.
diff --git a/products/signals/frontend/inbox/components/config/agentRosterMeta.ts b/products/signals/frontend/inbox/components/config/agentRosterMeta.ts
index 11c38c11828f..838a1d51e7ec 100644
--- a/products/signals/frontend/inbox/components/config/agentRosterMeta.ts
+++ b/products/signals/frontend/inbox/components/config/agentRosterMeta.ts
@@ -54,10 +54,11 @@ export interface AgentRosterDefinition {
*/
manageUrl?: string
/**
- * The emission pipeline runs an actionability gate on this source's records, and that gate
- * reads the steering keys on `SignalSourceConfig.config` (see `sourceSteeringModalLogic`).
- * Sources without a gate must not offer the steering form: the keys would be stored but
- * nothing would read them.
+ * An actionability gate runs on this source's records and reads the steering keys on
+ * `SignalSourceConfig.config` (see `sourceSteeringModalLogic`). Either the emission pipeline's
+ * gate, or, for a source that emits directly, the one listing it in the backend's
+ * `DIRECT_STEERABLE_SOURCES`. Sources without a gate must not offer the steering form: the keys
+ * would be stored but nothing would read them.
*/
steerable?: boolean
/** Show this entry only while the given feature flag is enabled (alpha rollouts). */
@@ -81,6 +82,7 @@ export const AGENT_ROSTER_GROUPS: AgentRosterGroup[] = [
detail: 'Each type below is a separate trigger, so turning one off leaves the others watching.',
entityNoun: 'signal types',
entityNounSingular: 'signal type',
+ steerable: true,
docsUrl: 'https://posthog.com/docs/error-tracking',
docsLabel: 'Error tracking',
},
@@ -132,6 +134,7 @@ export const AGENT_ROSTER_GROUPS: AgentRosterGroup[] = [
label: 'Health checks',
watches: 'Missing events, proxy gaps, and outdated SDKs',
detail: 'Checks your setup for missing events, an outdated SDK, proxy problems, failed warehouse syncs, and missing source maps.',
+ steerable: true,
docsUrl: urls.health(),
docsLabel: 'Health checks',
},
diff --git a/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.test.ts b/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.test.ts
index f3efe702bef3..06fedb122ad2 100644
--- a/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.test.ts
@@ -22,12 +22,16 @@ const sourceConfig: SignalSourceConfig = {
describe('sourceSteeringModalLogic', () => {
let logic: ReturnType<typeof sourceSteeringModalLogic.build>
let patchBodies: Record<string, any>[]
+ let patchedIds: string[]
let onClose: jest.Mock
let reloadFails: boolean
+ let failingConfigId: string | null
beforeEach(() => {
patchBodies = []
+ patchedIds = []
reloadFails = false
+ failingConfigId = null
useMocks({
get: {
'/api/projects/:team_id/signals/source_configs/': () =>
@@ -36,9 +40,13 @@ describe('sourceSteeringModalLogic', () => {
: [200, { results: [sourceConfig], count: 1, next: null, previous: null }],
},
patch: {
- '/api/projects/:team_id/signals/source_configs/:id/': async ({ request }) => {
+ '/api/projects/:team_id/signals/source_configs/:id/': async ({ request, params }) => {
+ if (String(params.id) === failingConfigId) {
+ return [500, { detail: 'Internal server error' }]
+ }
const body = (await request.json()) as Record<string, any>
patchBodies.push(body)
+ patchedIds.push(String(params.id))
// The serializer recomputes the sync status on every response.
return [200, { ...sourceConfig, ...body, status: 'completed' }]
},
@@ -46,7 +54,7 @@ describe('sourceSteeringModalLogic', () => {
})
initKeaTests()
onClose = jest.fn()
- logic = sourceSteeringModalLogic({ sourceConfig, onClose })
+ logic = sourceSteeringModalLogic({ sourceConfigs: [sourceConfig], onClose })
logic.mount()
})
@@ -73,6 +81,65 @@ describe('sourceSteeringModalLogic', () => {
expect(onClose).toHaveBeenCalled()
})
+ it('saves one card of guidance to every row behind it', async () => {
+ // Error tracking is one card over three config rows. Writing only the first would leave
+ // reopened and spiking issues unfiltered, so the rules would look ignored half the time.
+ logic.unmount()
+ const rows: SignalSourceConfig[] = [
+ SignalSourceType.IssueCreated,
+ SignalSourceType.IssueReopened,
+ SignalSourceType.IssueSpiking,
+ ].map((sourceType) => ({
+ ...sourceConfig,
+ id: sourceType,
+ source_product: SignalSourceProduct.ErrorTracking,
+ source_type: sourceType,
+ config: {},
+ }))
+ logic = sourceSteeringModalLogic({ sourceConfigs: rows, onClose })
+ logic.mount()
+
+ logic.actions.setSourceSteeringValue('steering', 'Ignore errors from localhost.')
+ await expectLogic(logic, () => {
+ logic.actions.submitSourceSteering()
+ }).toDispatchActions(['submitSourceSteeringSuccess'])
+
+ expect(patchedIds).toEqual([
+ SignalSourceType.IssueCreated,
+ SignalSourceType.IssueReopened,
+ SignalSourceType.IssueSpiking,
+ ])
+ expect(patchBodies).toEqual(rows.map(() => ({ config: { steering: 'Ignore errors from localhost.' } })))
+ })
+
+ it('keeps writing the remaining rows when one fails, and stays open to be retried', async () => {
+ // Stopping at the failure would leave more triggers unfiltered than it has to, and closing
+ // the modal would report a save the source did not get.
+ logic.unmount()
+ failingConfigId = String(SignalSourceType.IssueReopened)
+ const rows: SignalSourceConfig[] = [
+ SignalSourceType.IssueCreated,
+ SignalSourceType.IssueReopened,
+ SignalSourceType.IssueSpiking,
+ ].map((sourceType) => ({
+ ...sourceConfig,
+ id: sourceType,
+ source_product: SignalSourceProduct.ErrorTracking,
+ source_type: sourceType,
+ config: {},
+ }))
+ logic = sourceSteeringModalLogic({ sourceConfigs: rows, onClose })
+ logic.mount()
+
+ logic.actions.setSourceSteeringValue('steering', 'Ignore errors from localhost.')
+ await expectLogic(logic, () => {
+ logic.actions.submitSourceSteering()
+ }).toDispatchActions(['submitSourceSteeringFailure'])
+
+ expect(patchedIds).toEqual([SignalSourceType.IssueCreated, SignalSourceType.IssueSpiking])
+ expect(onClose).not.toHaveBeenCalled()
+ })
+
it('merges onto the freshest cached config, not the open-time snapshot', async () => {
// A reload landed while the modal was open and changed a key steering does not own.
signalSourcesLogic.actions.loadSourceConfigsSuccess([
@@ -111,7 +178,7 @@ describe('sourceSteeringModalLogic', () => {
config: { ...sourceConfig.config, steering: 'saved rules' },
updated_at: '2026-08-02T00:00:00Z',
}
- logic = sourceSteeringModalLogic({ sourceConfig: reloaded, onClose })
+ logic = sourceSteeringModalLogic({ sourceConfigs: [reloaded], onClose })
logic.mount()
expect(logic.values.sourceSteering).toEqual({ steering: 'saved rules' })
diff --git a/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.ts b/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.ts
index 978f685de591..3b572c7da5db 100644
--- a/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.ts
+++ b/products/signals/frontend/inbox/logics/sourceSteeringModalLogic.ts
@@ -40,7 +40,11 @@ export interface SteeringExample {
}
export interface SourceSteeringModalLogicProps {
- sourceConfig: SignalSourceConfig
+ /**
+ * Every config row the card's guidance applies to. Most sources have one; error tracking has a
+ * row per signal type, and the card steers the source as a whole, so a save writes all of them.
+ */
+ sourceConfigs: SignalSourceConfig[]
onClose: () => void
}
@@ -64,9 +68,17 @@ export function sourceHasLegacyPosture(config: SignalSourceConfig): boolean {
// Type-checked reads: the config blob is an open object, so a non-string steering value
// (possible via the raw API before the serializer validation landed) must degrade to the
// defaults rather than break the form.
-function steeringFormDefaults(sourceConfig: SignalSourceConfig): SourceSteeringFormValues {
- const steering = sourceConfig.config[SOURCE_STEERING_KEY]
- return { steering: typeof steering === 'string' ? steering : '' }
+// Saves write every row, so the rows normally agree. They can disagree when one was written
+// through the API on its own, and then showing the text that is filtering beats showing a blank
+// field that reads as "nothing is set".
+function steeringFormDefaults(sourceConfigs: SignalSourceConfig[]): SourceSteeringFormValues {
+ for (const config of sourceConfigs) {
+ const steering = config.config[SOURCE_STEERING_KEY]
+ if (typeof steering === 'string' && steering.trim()) {
+ return { steering }
+ }
+ }
+ return { steering: '' }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -149,14 +161,14 @@ export type sourceSteeringModalLogicType = MakeLogicType<
export const sourceSteeringModalLogic: LogicWrapper<sourceSteeringModalLogicType> = kea<sourceSteeringModalLogicType>([
path(['scenes', 'inbox', 'logics', 'sourceSteeringModalLogic']),
props({} as SourceSteeringModalLogicProps),
- key((logicProps) => logicProps.sourceConfig.id),
+ key((logicProps) => logicProps.sourceConfigs.map((config) => config.id).join(',')),
connect(() => ({
values: [teamLogic, ['currentTeamId'], signalSourcesLogic, ['sourceConfigs']],
actions: [signalSourcesLogic, ['loadSourceConfigs', 'replaceSourceConfig']],
})),
forms(({ props: logicProps, actions, values }) => ({
sourceSteering: {
- defaults: steeringFormDefaults(logicProps.sourceConfig),
+ defaults: steeringFormDefaults(logicProps.sourceConfigs),
errors: ({ steering }: SourceSteeringFormValues) => ({
steering:
steering.length > SOURCE_STEERING_MAX_LENGTH
@@ -168,51 +180,66 @@ export const sourceSteeringModalLogic: LogicWrapper<sourceSteeringModalLogicType
lemonToast.error('Select a project before saving')
throw new Error('No project selected')
}
- const { sourceConfig } = logicProps
const steering = formValues.steering.trim()
- // The endpoint replaces the config object wholesale, so the whole blob goes back
- // with the steering keys merged in; a partial object would clobber source-specific
- // keys like recording_filters. The merge base is the freshest cached row rather
- // than the open-time prop snapshot, so a config change that landed while the
- // modal was open (another card's toggle, an earlier save) survives. A concurrent
- // write from another client can still be lost until the endpoint merges
- // server-side.
- const baseConfig =
- values.sourceConfigs?.find((c: SignalSourceConfig) => c.id === sourceConfig.id)?.config ??
- sourceConfig.config
- // The posture flag has no UI any more; dropping it on save keeps the free text the
- // only thing steering the gate, so what a user sees here is all that applies.
- const { [SOURCE_DEFAULT_NOT_ACTIONABLE_KEY]: _droppedPosture, ...restConfig } = baseConfig
- const config = { ...restConfig, [SOURCE_STEERING_KEY]: steering }
const analyticsParams = {
- sourceProduct: sourceConfig.source_product,
- sourceType: sourceConfig.source_type,
+ sourceProduct: logicProps.sourceConfigs[0].source_product,
+ // One card, so one event: the types it wrote, rather than one event per row.
+ sourceType: logicProps.sourceConfigs
+ .map((c: SignalSourceConfig) => c.source_type)
+ .sort()
+ .join(','),
steeringLength: steering.length,
}
- let updated: SignalSourceConfigApi
- try {
- updated = await signalsSourceConfigsPartialUpdate(String(values.currentTeamId), sourceConfig.id, {
- config,
+ // Every row gets its turn even after one fails, so a failure leaves the fewest rows
+ // behind. Retrying writes the same text to all of them, so a partial save heals.
+ let firstError: unknown = null
+ for (const sourceConfig of logicProps.sourceConfigs) {
+ // The endpoint replaces the config object wholesale, so the whole blob goes back
+ // with the steering keys merged in; a partial object would clobber source-specific
+ // keys like recording_filters. The merge base is the freshest cached row rather
+ // than the open-time prop snapshot, so a config change that landed while the
+ // modal was open (another card's toggle, an earlier save) survives. A concurrent
+ // write from another client can still be lost until the endpoint merges
+ // server-side.
+ const baseConfig =
+ values.sourceConfigs?.find((c: SignalSourceConfig) => c.id === sourceConfig.id)?.config ??
+ sourceConfig.config
+ // The posture flag has no UI any more; dropping it on save keeps the free text the
+ // only thing steering the gate, so what a user sees here is all that applies.
+ const { [SOURCE_DEFAULT_NOT_ACTIONABLE_KEY]: _droppedPosture, ...restConfig } = baseConfig
+ const config = { ...restConfig, [SOURCE_STEERING_KEY]: steering }
+ let updated: SignalSourceConfigApi
+ try {
+ updated = await signalsSourceConfigsPartialUpdate(
+ String(values.currentTeamId),
+ sourceConfig.id,
+ { config }
+ )
+ } catch (error) {
+ firstError = firstError ?? error
+ continue
+ }
+ // Overlay the saved row onto the cached list before the reload: if the reload is
+ // slow or fails, a reopened modal would otherwise derive its form from the stale
+ // config and a second save could restore the obsolete rules.
+ actions.replaceSourceConfig({
+ ...sourceConfig,
+ enabled: updated.enabled ?? sourceConfig.enabled,
+ config: updated.config ?? config,
+ updated_at: updated.updated_at,
+ // The generated type widens the serializer's sync status to string | null.
+ status: (updated.status ?? null) as SignalSourceConfig['status'],
})
- } catch (error) {
+ }
+ if (firstError !== null) {
captureSignalSourceSteeringChanged({ ...analyticsParams, success: false })
- const apiError = error instanceof ApiError ? error : null
+ const apiError = firstError instanceof ApiError ? firstError : null
lemonToast.error(apiError?.detail ?? "Couldn't save your guidance. Please try again.")
- throw error
+ actions.loadSourceConfigs()
+ throw firstError
}
captureSignalSourceSteeringChanged({ ...analyticsParams, success: true })
lemonToast.success('Guidance saved. It applies from the next sync.')
- // Overlay the saved row onto the cached list before the reload: if the reload is
- // slow or fails, a reopened modal would otherwise derive its form from the stale
- // config and a second save could restore the obsolete rules.
- actions.replaceSourceConfig({
- ...sourceConfig,
- enabled: updated.enabled ?? sourceConfig.enabled,
- config: updated.config ?? config,
- updated_at: updated.updated_at,
- // The generated type widens the serializer's sync status to string | null.
- status: (updated.status ?? null) as SignalSourceConfig['status'],
- })
actions.loadSourceConfigs()
logicProps.onClose()
},
diff --git a/products/signals/frontend/inbox/signalSourcesLogic.test.ts b/products/signals/frontend/inbox/signalSourcesLogic.test.ts
index 2387ebfac7f5..6b22e25787ed 100644
--- a/products/signals/frontend/inbox/signalSourcesLogic.test.ts
+++ b/products/signals/frontend/inbox/signalSourcesLogic.test.ts
@@ -129,6 +129,36 @@ describe('signalSourcesLogic', () => {
expect(logic.values.dataSourceSetupSource).toBe(setup)
})
+ it('carries the card guidance onto an error tracking signal type turned on later', async () => {
+ // Error tracking is one guidance box over three rows. A row created after the guidance was
+ // written would otherwise start empty, so that one trigger would report everything while the
+ // card still reads as steered.
+ const steeredRow = (sourceType: SignalSourceType): any => ({
+ ...githubIssuesConfig,
+ id: `config-${sourceType}`,
+ source_product: SignalSourceProduct.ErrorTracking,
+ source_type: sourceType,
+ config: { steering: 'Ignore errors from localhost.' },
+ })
+ const create = jest.spyOn(api.signalSourceConfigs, 'create').mockResolvedValue(githubIssuesConfig as any)
+ logic.actions.loadSourceConfigsSuccess([
+ steeredRow(SignalSourceType.IssueCreated),
+ steeredRow(SignalSourceType.IssueReopened),
+ ])
+
+ await expectLogic(logic, () => {
+ logic.actions.toggleErrorTrackingType(SignalSourceType.IssueSpiking)
+ }).toDispatchActions(['loadSourceConfigs'])
+
+ expect(create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ source_type: SignalSourceType.IssueSpiking,
+ config: { steering: 'Ignore errors from localhost.' },
+ })
+ )
+ create.mockRestore()
+ })
+
it('keeps an enabled source enabled when its config loads during the source lookup', async () => {
let resolveSources!: (sources: Awaited<ReturnType<typeof api.externalDataSources.list>>) => void
const sourcesPromise = new Promise<Awaited<ReturnType<typeof api.externalDataSources.list>>>((resolve) => {
diff --git a/products/signals/frontend/inbox/signalSourcesLogic.ts b/products/signals/frontend/inbox/signalSourcesLogic.ts
index 290378cca08b..40d922e4b50e 100644
--- a/products/signals/frontend/inbox/signalSourcesLogic.ts
+++ b/products/signals/frontend/inbox/signalSourcesLogic.ts
@@ -29,7 +29,7 @@ import { SignalSourceProduct, SignalSourceType } from 'products/signals/frontend
import type { SignalSourceTypeApi } from '../generated/api.schemas'
import type { AgentRosterSource } from './components/config/agentRosterMeta'
import { captureSignalSourceConnected, captureSignalSourceDisabled } from './inboxAnalytics'
-import { SignalSourceConfig, ToggleSignalSourceParams } from './types'
+import { SOURCE_STEERING_KEY, SignalSourceConfig, ToggleSignalSourceParams } from './types'
/** product_enablement recipe names for tools that back a signal source. */
export type SourceToolEnablement = 'session_replay' | 'error_tracking' | 'conversations'
@@ -59,6 +59,18 @@ export const ERROR_TRACKING_SIGNAL_SOURCE_TYPES: SignalSourceType[] = [
SignalSourceType.IssueSpiking,
]
+/**
+ * The guidance written on the Error tracking card is stored on each of its signal-type rows, so a
+ * row created later starts from what its siblings already carry. Without this, turning a type on
+ * after writing guidance leaves that one trigger emitting unsteered while the card reads as set.
+ */
+function inheritedErrorTrackingConfig(configs: SignalSourceConfig[]): Record<string, any> {
+ const steering = configs
+ .map((config) => config.config[SOURCE_STEERING_KEY])
+ .find((value) => typeof value === 'string' && value.trim())
+ return steering ? { [SOURCE_STEERING_KEY]: steering } : {}
+}
+
/** Warehouse-backed signal sources, keyed by roster source id. */
export type WarehouseBackedSource = 'github' | 'linear' | 'zendesk' | 'pganalyze' | 'engineering_analytics'
@@ -212,6 +224,7 @@ export interface signalSourcesLogicValues {
dataSourceSetupSource: WarehouseBackedSource | null
enabledSourcesCount: number
enablingTool: SourceToolEnablement | null
+ errorTrackingConfigs: SignalSourceConfig[]
errorTrackingIsFullyEnabled: boolean
errorTrackingTypeStates: {
enabled: boolean
@@ -461,6 +474,7 @@ export interface signalSourcesLogicMeta {
ciSignalsIsFullyEnabled: (ciSignalsConfig: CISignalsConfigApi | null) => boolean
isCiSignalsToggling: (togglingSourceKeys: Set<string>) => boolean
hasEmittingScanner: (visionScanners: ReplayScannerApi[] | null) => boolean | null
+ errorTrackingConfigs: (sourceConfigs: SignalSourceConfig[] | null) => SignalSourceConfig[]
errorTrackingTypeStates: (sourceConfigs: SignalSourceConfig[] | null) => {
enabled: boolean
sourceType: SignalSourceType
@@ -921,6 +935,18 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
(visionScanners: ReplayScannerApi[] | null): boolean | null =>
visionScanners === null ? null : visionScanners.some((scanner) => scanner.emits_signals),
],
+ // The rows behind the one Error tracking card. Guidance written on the card is saved to all
+ // of them, since a reader steering "error tracking" means the source, not one trigger.
+ errorTrackingConfigs: [
+ (s) => [s.sourceConfigs],
+ (sourceConfigs: SignalSourceConfig[] | null): SignalSourceConfig[] =>
+ ERROR_TRACKING_SIGNAL_SOURCE_TYPES.map((sourceType) =>
+ sourceConfigs?.find(
+ (row) =>
+ row.source_product === SignalSourceProduct.ErrorTracking && row.source_type === sourceType
+ )
+ ).filter((row): row is SignalSourceConfig => !!row),
+ ],
// Each error tracking signal type is its own config row, so each can be armed on its own.
errorTrackingTypeStates: [
(s) => [s.sourceConfigs],
@@ -1137,6 +1163,7 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
// stand every type down rather than arm the remaining ones.
const desiredEnabled = !values.errorTrackingTypeStates.some(({ enabled }) => enabled)
const configs = values.sourceConfigs ?? []
+ const inheritedConfig = inheritedErrorTrackingConfig(values.errorTrackingConfigs)
// First connection when no persisted error-tracking config existed before this enable.
const wasConnected = configs.some(
(c) => c.source_product === SignalSourceProduct.ErrorTracking && !c.id.startsWith('new_')
@@ -1154,7 +1181,7 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
source_product: SignalSourceProduct.ErrorTracking,
source_type: sourceType,
enabled: true,
- config: {},
+ config: inheritedConfig,
})
}
}
@@ -1184,6 +1211,7 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
},
toggleErrorTrackingType: async ({ sourceType }, breakpoint) => {
const configs = values.sourceConfigs ?? []
+ const inheritedConfig = inheritedErrorTrackingConfig(values.errorTrackingConfigs)
const existing = configs.find(
(c) => c.source_product === SignalSourceProduct.ErrorTracking && c.source_type === sourceType
)
@@ -1196,7 +1224,7 @@ export const signalSourcesLogic = kea<signalSourcesLogicType>([
source_product: SignalSourceProduct.ErrorTracking,
source_type: sourceType,
enabled: true,
- config: {},
+ config: inheritedConfig,
})
}
breakpoint()