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.

chore(error-tracking): remove embedding result consumer (#74224)

Hugues Pouillot943e3f977e60
diff --git a/bin/start-rust-service b/bin/start-rust-service
index 9361ea21083a..c9e9a0209cb8 100755
--- a/bin/start-rust-service
+++ b/bin/start-rust-service
@@ -189,20 +189,17 @@ case "$RS_SVC" in
;;
cymbal-notifications)
- # The cymbal binary in notifications mode consumes the notifications topic
- # produced by processing mode and runs issue side effects.
+ # The notifications mode starts Temporal lifecycle workflows for notifications from processing mode.
export CYMBAL_MODE=notifications
export DEV_RUST_SVC_OVERRIDE=cymbal
export RUST_LOG=debug,rdkafka=warn
export RUST_BACKTRACE=1
export KAFKA_HOSTS="$DEFAULT_KAFKA"
- export DATABASE_URL="${DATABASE_URL:-$DEFAULT_PG}"
export KAFKA_CONSUMER_OFFSET_RESET="${KAFKA_CONSUMER_OFFSET_RESET:-earliest}"
export METRICS_PORT="${METRICS_PORT:-9107}"
export POSTHOG_API_KEY="${CYMBAL_NOTIFICATIONS_POSTHOG_API_KEY:-phc_localposthogprojecttoken}"
export POSTHOG_ENDPOINT="${CYMBAL_NOTIFICATIONS_POSTHOG_ENDPOINT:-http://localhost:3307}"
- export SIGNALS_API_BASE_URL="${SIGNALS_API_BASE_URL:-http://localhost:8000}"
- export INTERNAL_API_SECRET="${INTERNAL_API_SECRET:-posthog123}"
+ export TEMPORAL_HOST="${TEMPORAL_HOST:-temporal}"
;;
embedding-worker)
diff --git a/products/error_tracking/backend/management/commands/et_consume_embeddings.py b/products/error_tracking/backend/management/commands/et_consume_embeddings.py
deleted file mode 100644
index 8246c0181cf1..000000000000
--- a/products/error_tracking/backend/management/commands/et_consume_embeddings.py
+++ /dev/null
@@ -1,365 +0,0 @@
-import json
-import signal
-import asyncio
-from collections.abc import Callable, Mapping
-from enum import StrEnum
-from typing import TypeVar
-
-from django.conf import settings
-from django.core.management.base import BaseCommand, CommandParser
-
-import structlog
-from confluent_kafka import (
- Consumer as ConfluentConsumer,
- KafkaError,
- KafkaException,
- Message,
-)
-from temporalio.client import Client
-from temporalio.common import WorkflowIDReusePolicy
-from temporalio.exceptions import WorkflowAlreadyStartedError
-
-from posthog.kafka_client.client import _KafkaSecurityProtocol
-from posthog.kafka_client.routing import get_profile_settings, resolve_profile_name
-from posthog.kafka_client.topics import KAFKA_DOCUMENT_EMBEDDING_RESULTS_TOPIC
-from posthog.temporal.common.client import async_connect
-
-from products.error_tracking.backend.temporal.fingerprint_embedding_result.types import FingerprintEmbeddingResultInputs
-from products.error_tracking.backend.temporal.fingerprint_embedding_result.workflow import (
- ErrorTrackingFingerprintEmbeddingResultWorkflow,
-)
-from products.warehouse_sources.backend.facade.pipelines import HealthState, start_health_server
-
-logger = structlog.get_logger(__name__)
-
-PREFERRED_EMBEDDING_MODEL = "text-embedding-3-large-3072"
-
-DEFAULT_CONSUMER_GROUP = "error-tracking-fingerprint-embedding-results"
-T = TypeVar("T")
-
-# Commit failures caused by a group rebalance: the partition was reassigned, so the
-# message will be redelivered to its new owner. Workflow starts are deduplicated by
-# workflow id, so redelivery is safe and these must not crash the consumer.
-_REBALANCE_COMMIT_ERROR_CODES = (
- KafkaError.ILLEGAL_GENERATION, # type: ignore[attr-defined]
- KafkaError.UNKNOWN_MEMBER_ID, # type: ignore[attr-defined]
- KafkaError.REBALANCE_IN_PROGRESS, # type: ignore[attr-defined]
-)
-
-
-async def _run_blocking_call(callback: Callable[[], T]) -> T:
- loop = asyncio.get_running_loop()
- return await loop.run_in_executor(None, callback)
-
-
-async def _commit_message(consumer: ConfluentConsumer, message: Message) -> None:
- try:
- await _run_blocking_call(lambda: consumer.commit(message=message, asynchronous=False))
- except KafkaException as err:
- error = err.args[0] if err.args and isinstance(err.args[0], KafkaError) else None
- if error is None or error.code() not in _REBALANCE_COMMIT_ERROR_CODES:
- raise
- logger.warning(
- "error_tracking.embedding_results_consumer.commit_failed_rebalance",
- error=str(error),
- )
-
-
-class FingerprintEmbeddingResultOutcome(StrEnum):
- STARTED = "started"
- SKIPPED = "skipped"
- ALREADY_STARTED = "already_started"
-
-
-def _string_value(data: Mapping[str, object], key: str) -> str | None:
- value = data.get(key)
- if isinstance(value, str) and value:
- return value
- return None
-
-
-def _float_option(options: Mapping[str, object], key: str) -> float:
- value = options[key]
- if isinstance(value, str | int | float):
- return float(value)
- raise TypeError(f"{key} must be a number")
-
-
-def _int_option(options: Mapping[str, object], key: str) -> int:
- value = options[key]
- if isinstance(value, str | int):
- return int(value)
- raise TypeError(f"{key} must be an integer")
-
-
-def _selected_model_name(results: object) -> str | None:
- if not isinstance(results, list):
- return None
-
- selected_model_name: str | None = None
- for result in results:
- if not isinstance(result, dict):
- continue
- if result.get("outcome") != "success":
- continue
- model = result.get("model")
- if isinstance(model, str):
- if model == PREFERRED_EMBEDDING_MODEL:
- return model
- selected_model_name = selected_model_name or model
- return selected_model_name
-
-
-def _float_list(value: object) -> list[float] | None:
- if not isinstance(value, list) or not value:
- return None
- try:
- return [float(item) for item in value]
- except (TypeError, ValueError):
- return None
-
-
-def _success_embedding(results: object, model_name: str) -> list[float] | None:
- if not isinstance(results, list):
- return None
-
- for result in results:
- if not isinstance(result, dict) or result.get("outcome") != "success":
- continue
- model = result.get("model")
- if model == model_name:
- return _float_list(result.get("embedding"))
- return None
-
-
-def fingerprint_embedding_result_inputs_from_message(value: bytes) -> FingerprintEmbeddingResultInputs | None:
- loaded_data = json.loads(value)
- if not isinstance(loaded_data, dict):
- return None
- data: Mapping[str, object] = loaded_data
- if data.get("product") != "error_tracking" or data.get("document_type") != "fingerprint":
- return None
-
- team_id = data.get("team_id")
- fingerprint = _string_value(data, "document_id")
- rendering = _string_value(data, "rendering")
- timestamp = _string_value(data, "timestamp")
- results = data.get("results")
- model_name = _selected_model_name(results)
- embedding = _success_embedding(results, model_name) if model_name is not None else None
-
- invalid_fields: list[str] = []
- if not isinstance(team_id, int):
- invalid_fields.append("team_id")
- if fingerprint is None:
- invalid_fields.append("document_id")
- if rendering is None:
- invalid_fields.append("rendering")
- if timestamp is None:
- invalid_fields.append("timestamp")
- if model_name is None:
- invalid_fields.append("results")
- if embedding is None:
- invalid_fields.append("embedding")
- if invalid_fields:
- raise ValueError(f"Invalid error tracking fingerprint embedding result message: {', '.join(invalid_fields)}")
-
- if (
- not isinstance(team_id, int)
- or fingerprint is None
- or rendering is None
- or timestamp is None
- or model_name is None
- or embedding is None
- ):
- raise AssertionError("validated embedding result fields were unexpectedly invalid")
-
- return FingerprintEmbeddingResultInputs(
- team_id=team_id,
- fingerprint=fingerprint,
- rendering=rendering,
- timestamp=timestamp,
- model_name=model_name,
- embedding=embedding,
- )
-
-
-async def start_fingerprint_embedding_result_workflow(
- client: Client,
- inputs: FingerprintEmbeddingResultInputs,
-) -> FingerprintEmbeddingResultOutcome:
- workflow_id = ErrorTrackingFingerprintEmbeddingResultWorkflow.workflow_id_for(
- team_id=inputs.team_id,
- fingerprint=inputs.fingerprint,
- rendering=inputs.rendering,
- timestamp=inputs.timestamp,
- )
-
- try:
- await client.start_workflow(
- ErrorTrackingFingerprintEmbeddingResultWorkflow.run,
- inputs,
- id=workflow_id,
- task_queue=settings.ERROR_TRACKING_TASK_QUEUE,
- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
- )
- except WorkflowAlreadyStartedError:
- return FingerprintEmbeddingResultOutcome.ALREADY_STARTED
-
- return FingerprintEmbeddingResultOutcome.STARTED
-
-
-async def handle_embedding_result_message(
- client: Client,
- value: bytes,
-) -> FingerprintEmbeddingResultOutcome:
- inputs = fingerprint_embedding_result_inputs_from_message(value)
- if inputs is None:
- return FingerprintEmbeddingResultOutcome.SKIPPED
-
- return await start_fingerprint_embedding_result_workflow(client, inputs)
-
-
-class Command(BaseCommand):
- help = "Consume document embedding results and start error tracking fingerprint workflows."
-
- def add_arguments(self, parser: CommandParser) -> None:
- parser.add_argument("--topic", default=KAFKA_DOCUMENT_EMBEDDING_RESULTS_TOPIC)
- parser.add_argument("--consumer-group", default=DEFAULT_CONSUMER_GROUP)
- parser.add_argument("--poll-timeout", type=float, default=1.0)
- parser.add_argument("--max-messages", type=int, default=None)
- parser.add_argument(
- "--health-port",
- type=int,
- default=8080,
- help="Port for the health check HTTP server (default: 8080)",
- )
- parser.add_argument(
- "--health-timeout",
- type=float,
- default=60.0,
- help="Health check timeout in seconds (default: 60.0)",
- )
-
- def handle(self, *args: object, **options: object) -> None:
- topic = str(options["topic"])
- consumer_group = str(options["consumer_group"])
- poll_timeout = _float_option(options, "poll_timeout")
- max_messages = options["max_messages"]
- if max_messages is not None and not isinstance(max_messages, int):
- raise TypeError("max_messages must be an integer")
- health_port = _int_option(options, "health_port")
- health_timeout = _float_option(options, "health_timeout")
-
- health_state = HealthState(timeout_seconds=health_timeout)
- start_health_server(port=health_port, health_state=health_state)
-
- asyncio.run(
- self._run_consumer(
- topic=topic,
- consumer_group=consumer_group,
- poll_timeout=poll_timeout,
- max_messages=max_messages,
- health_reporter=health_state.report_healthy,
- )
- )
-
- async def _run_consumer(
- self,
- topic: str,
- consumer_group: str,
- poll_timeout: float,
- max_messages: int | None,
- health_reporter: Callable[[], None] | None = None,
- ) -> None:
- consumer = self._create_consumer(topic=topic, consumer_group=consumer_group)
- temporal_client = await async_connect()
- shutdown_requested = False
-
- def handle_signal(signum: int, frame: object) -> None:
- nonlocal shutdown_requested
- shutdown_requested = True
- logger.info("error_tracking.embedding_results_consumer.shutdown_signal", signal=signal.Signals(signum).name)
-
- for sig in (signal.SIGTERM, signal.SIGINT):
- signal.signal(sig, handle_signal)
-
- processed_messages = 0
- self.stdout.write("consumer_started")
- logger.info(
- "error_tracking.embedding_results_consumer.started",
- topic=topic,
- consumer_group=consumer_group,
- )
-
- try:
- while not shutdown_requested:
- if health_reporter is not None:
- health_reporter()
- message = await _run_blocking_call(lambda: consumer.poll(poll_timeout))
- if message is None:
- continue
- await self._handle_kafka_message(consumer, temporal_client, message)
- if health_reporter is not None:
- health_reporter()
- processed_messages += 1
- if max_messages is not None and processed_messages >= max_messages:
- break
- finally:
- await _run_blocking_call(consumer.close)
- logger.info(
- "error_tracking.embedding_results_consumer.stopped",
- processed_messages=processed_messages,
- )
-
- def _create_consumer(self, topic: str, consumer_group: str) -> ConfluentConsumer:
- profile = get_profile_settings(profile=resolve_profile_name(topic=topic))
- hosts = profile.hosts
- config: dict[str, str | int | float | bool | None] = {
- "bootstrap.servers": ",".join(hosts) if isinstance(hosts, list) else hosts,
- "security.protocol": profile.security_protocol or _KafkaSecurityProtocol.PLAINTEXT,
- "group.id": consumer_group,
- "auto.offset.reset": "latest",
- "enable.auto.commit": False,
- "partition.assignment.strategy": "cooperative-sticky",
- }
- if profile.security_protocol in (
- _KafkaSecurityProtocol.SASL_PLAINTEXT,
- _KafkaSecurityProtocol.SASL_SSL,
- ):
- config["sasl.mechanism"] = profile.sasl_mechanism
- config["sasl.username"] = profile.sasl_user
- config["sasl.password"] = profile.sasl_password
-
- consumer = ConfluentConsumer(config)
- consumer.subscribe([topic])
- return consumer
-
- async def _handle_kafka_message(
- self, consumer: ConfluentConsumer, temporal_client: Client, message: Message
- ) -> None:
- error = message.error()
- if error is not None:
- partition_eof_code = getattr(KafkaError, "_PARTITION_EOF", None)
- if partition_eof_code is not None and error.code() == partition_eof_code:
- return
- raise KafkaException(error)
-
- value = message.value()
- if value is None:
- logger.warning("error_tracking.embedding_results_consumer.empty_message")
- await _commit_message(consumer, message)
- return
-
- try:
- outcome = await handle_embedding_result_message(temporal_client, value)
- except (json.JSONDecodeError, UnicodeDecodeError, ValueError) as err:
- logger.warning("error_tracking.embedding_results_consumer.invalid_message", error=str(err))
- await _commit_message(consumer, message)
- return
-
- logger.info(
- "error_tracking.embedding_results_consumer.message_processed",
- outcome=outcome,
- )
- await _commit_message(consumer, message)
diff --git a/products/error_tracking/backend/temporal/__init__.py b/products/error_tracking/backend/temporal/__init__.py
index ab620da4d16a..656d81e25076 100644
--- a/products/error_tracking/backend/temporal/__init__.py
+++ b/products/error_tracking/backend/temporal/__init__.py
@@ -1,9 +1,3 @@
-from products.error_tracking.backend.temporal.fingerprint_embedding_result import (
- ACTIVITIES as FINGERPRINT_EMBEDDING_RESULT_ACTIVITIES,
- WORKFLOWS as FINGERPRINT_EMBEDDING_RESULT_WORKFLOWS,
- ErrorTrackingFingerprintEmbeddingResultWorkflow,
- merge_similar_fingerprints_activity,
-)
from products.error_tracking.backend.temporal.lifecycle import (
ACTIVITIES as LIFECYCLE_ACTIVITIES,
WORKFLOWS as LIFECYCLE_WORKFLOWS,
@@ -38,19 +32,9 @@ from products.error_tracking.backend.temporal.weekly_digest import (
send_org_digest_activity,
)
-WORKFLOWS = (
- SYMBOL_SET_WORKFLOWS
- + SPIKE_EVENT_WORKFLOWS
- + RECOMMENDATIONS_REFRESH_WORKFLOWS
- + FINGERPRINT_EMBEDDING_RESULT_WORKFLOWS
- + WEEKLY_DIGEST_WORKFLOWS
-)
+WORKFLOWS = SYMBOL_SET_WORKFLOWS + SPIKE_EVENT_WORKFLOWS + RECOMMENDATIONS_REFRESH_WORKFLOWS + WEEKLY_DIGEST_WORKFLOWS
ACTIVITIES = (
- SYMBOL_SET_ACTIVITIES
- + SPIKE_EVENT_ACTIVITIES
- + RECOMMENDATIONS_REFRESH_ACTIVITIES
- + FINGERPRINT_EMBEDDING_RESULT_ACTIVITIES
- + WEEKLY_DIGEST_ACTIVITIES
+ SYMBOL_SET_ACTIVITIES + SPIKE_EVENT_ACTIVITIES + RECOMMENDATIONS_REFRESH_ACTIVITIES + WEEKLY_DIGEST_ACTIVITIES
)
__all__ = [
@@ -58,7 +42,6 @@ __all__ = [
"LIFECYCLE_ACTIVITIES",
"LIFECYCLE_WORKFLOWS",
"WORKFLOWS",
- "ErrorTrackingFingerprintEmbeddingResultWorkflow",
"ErrorTrackingIssueCreatedWorkflow",
"ErrorTrackingIssueReopenedWorkflow",
"ErrorTrackingIssueSpikingWorkflow",
@@ -70,7 +53,6 @@ __all__ = [
"cleanup_symbol_sets_activity",
"get_digest_orgs_activity",
"get_team_batches_activity",
- "merge_similar_fingerprints_activity",
"refresh_recommendations_batch_activity",
"send_org_digest_activity",
]
diff --git a/products/error_tracking/backend/temporal/fingerprint_embedding_result/__init__.py b/products/error_tracking/backend/temporal/fingerprint_embedding_result/__init__.py
deleted file mode 100644
index 459352bee70c..000000000000
--- a/products/error_tracking/backend/temporal/fingerprint_embedding_result/__init__.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from products.error_tracking.backend.temporal.fingerprint_embedding_result.activities import (
- merge_similar_fingerprints_activity,
-)
-from products.error_tracking.backend.temporal.fingerprint_embedding_result.workflow import (
- ErrorTrackingFingerprintEmbeddingResultWorkflow,
-)
-
-WORKFLOWS = [ErrorTrackingFingerprintEmbeddingResultWorkflow]
-ACTIVITIES = [merge_similar_fingerprints_activity]
-
-__all__ = [
- "ACTIVITIES",
- "WORKFLOWS",
- "ErrorTrackingFingerprintEmbeddingResultWorkflow",
- "merge_similar_fingerprints_activity",
-]
diff --git a/products/error_tracking/backend/temporal/fingerprint_embedding_result/activities.py b/products/error_tracking/backend/temporal/fingerprint_embedding_result/activities.py
index cc10ae033323..0dde1daeec5b 100644
--- a/products/error_tracking/backend/temporal/fingerprint_embedding_result/activities.py
+++ b/products/error_tracking/backend/temporal/fingerprint_embedding_result/activities.py
@@ -4,9 +4,6 @@ from datetime import datetime, timedelta
from django.conf import settings
from django.utils.dateparse import parse_datetime
-import posthoganalytics
-from temporalio import activity
-
from posthog.hogql import ast
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
@@ -16,7 +13,6 @@ from posthog.event_usage import groups
from posthog.exceptions_capture import capture_exception
from posthog.models import Team
from posthog.ph_client import ph_scoped_capture
-from posthog.temporal.common.utils import close_db_connections
from products.error_tracking.backend.indexed_embedding import EMBEDDING_TABLES
from products.error_tracking.backend.models import (
@@ -310,16 +306,3 @@ def merge_similar_fingerprints(
workflow_name=workflow_name,
)
raise
-
-
-@close_db_connections
-def merge_similar_fingerprints_activity(
- inputs: FingerprintEmbeddingResultInputs,
-) -> FingerprintEmbeddingMergeResult:
- return merge_similar_fingerprints(
- inputs,
- activity_name="merge_similar_fingerprints_activity",
- workflow_name="error-tracking-fingerprint-embedding-result",
- )
diff --git a/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_consumer.py b/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_consumer.py
deleted file mode 100644
index 27812723bff9..000000000000
--- a/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_consumer.py
+++ /dev/null
@@ -1,194 +0,0 @@
-import json
-
-import pytest
-from unittest.mock import AsyncMock, MagicMock
-
-from django.test import override_settings
-
-from confluent_kafka import KafkaError, KafkaException
-from temporalio.common import WorkflowIDReusePolicy
-from temporalio.exceptions import WorkflowAlreadyStartedError
-
-from products.error_tracking.backend.management.commands.et_consume_embeddings import (
- Command,
- FingerprintEmbeddingResultOutcome,
- _commit_message,
- fingerprint_embedding_result_inputs_from_message,
- handle_embedding_result_message,
- start_fingerprint_embedding_result_workflow,
-)
-from products.error_tracking.backend.temporal.fingerprint_embedding_result.types import FingerprintEmbeddingResultInputs
-from products.error_tracking.backend.temporal.fingerprint_embedding_result.workflow import (
- ErrorTrackingFingerprintEmbeddingResultWorkflow,
-)
-
-
-def _embedding_result_message(**overrides: object) -> bytes:
- message: dict[str, object] = {
- "team_id": 1,
- "product": "error_tracking",
- "document_type": "fingerprint",
- "rendering": "type_message_and_stack",
- "document_id": "fingerprint-1",
- "timestamp": "2026-06-08T00:00:00Z",
- "content": "TypeError: failed",
- "models": ["text-embedding-3-large-3072"],
- "results": [
- {
- "model": "text-embedding-3-large-3072",
- "outcome": "success",
- "embedding": [0.1, 0.2, 0.3],
- },
- {
- "model": "text-embedding-3-small-1536",
- "outcome": "failure",
- "error": "rate limited",
- },
- ],
- }
- message.update(overrides)
- return json.dumps(message).encode("utf-8")
-
-
-class TestFingerprintEmbeddingResultConsumer:
- def test_extracts_minimal_workflow_inputs(self) -> None:
- inputs = fingerprint_embedding_result_inputs_from_message(_embedding_result_message())
-
- assert inputs == FingerprintEmbeddingResultInputs(
- team_id=1,
- fingerprint="fingerprint-1",
- rendering="type_message_and_stack",
- timestamp="2026-06-08T00:00:00Z",
- model_name="text-embedding-3-large-3072",
- embedding=[0.1, 0.2, 0.3],
- )
-
- def test_extracts_only_selected_model_embedding(self) -> None:
- inputs = fingerprint_embedding_result_inputs_from_message(
- _embedding_result_message(
- results=[
- {"model": "text-embedding-3-small-1536", "outcome": "success", "embedding": [0.4, 0.5]},
- {"model": "text-embedding-3-large-3072", "outcome": "success", "embedding": [0.1, 0.2, 0.3]},
- ]
- )
- )
-
- assert inputs is not None
- assert inputs.model_name == "text-embedding-3-large-3072"
- assert inputs.embedding == [0.1, 0.2, 0.3]
-
- @pytest.mark.parametrize(
- "overrides",
- [
- {"product": "llm_analytics"},
- {"document_type": "trace"},
- ],
- )
- def test_skips_unrelated_messages(self, overrides: dict[str, object]) -> None:
- assert fingerprint_embedding_result_inputs_from_message(_embedding_result_message(**overrides)) is None
-
- @pytest.mark.parametrize(
- "overrides",
- [
- {"team_id": "1"},
- {"document_id": None},
- {"rendering": None},
- {"timestamp": None},
- {"results": [{"model": "text-embedding-3-large-3072", "outcome": "failure", "error": "failed"}]},
- {"results": [{"model": "text-embedding-3-large-3072", "outcome": "success"}]},
- ],
- )
- def test_raises_for_malformed_fingerprint_messages(self, overrides: dict[str, object]) -> None:
- with pytest.raises(ValueError, match="Invalid error tracking fingerprint embedding result message"):
- fingerprint_embedding_result_inputs_from_message(_embedding_result_message(**overrides))
-
- @override_settings(ERROR_TRACKING_TASK_QUEUE="error-tracking-task-queue")
- @pytest.mark.asyncio
- async def test_start_workflow(self) -> None:
- client = AsyncMock()
- inputs = FingerprintEmbeddingResultInputs(
- team_id=1,
- fingerprint="fingerprint-1",
- rendering="type_message_and_stack",
- timestamp="2026-06-08T00:00:00Z",
- model_name="text-embedding-3-large-3072",
- embedding=[0.1, 0.2, 0.3],
- )
-
- outcome = await start_fingerprint_embedding_result_workflow(client, inputs)
-
- assert outcome == FingerprintEmbeddingResultOutcome.STARTED
- client.start_workflow.assert_awaited_once_with(
- ErrorTrackingFingerprintEmbeddingResultWorkflow.run,
- inputs,
- id=ErrorTrackingFingerprintEmbeddingResultWorkflow.workflow_id_for(
- team_id=1,
- fingerprint="fingerprint-1",
- rendering="type_message_and_stack",
- timestamp="2026-06-08T00:00:00Z",
- ),
- task_queue="error-tracking-task-queue",
- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
- )
-
- @pytest.mark.asyncio
- async def test_start_workflow_handles_duplicates(self) -> None:
- client = AsyncMock()
- client.start_workflow.side_effect = WorkflowAlreadyStartedError("already started", "workflow-id")
- inputs = FingerprintEmbeddingResultInputs(
- team_id=1,
- fingerprint="fingerprint-1",
- rendering="type_message_and_stack",
- timestamp="2026-06-08T00:00:00Z",
- model_name="text-embedding-3-large-3072",
- embedding=[0.1, 0.2, 0.3],
- )
-
- outcome = await start_fingerprint_embedding_result_workflow(client, inputs)
-
- assert outcome == FingerprintEmbeddingResultOutcome.ALREADY_STARTED
-
- @pytest.mark.asyncio
- async def test_handle_embedding_result_message_skips_unrelated_messages(self) -> None:
- client = AsyncMock()
-
- outcome = await handle_embedding_result_message(client, _embedding_result_message(product="llm_analytics"))
-
- assert outcome == FingerprintEmbeddingResultOutcome.SKIPPED
- client.start_workflow.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_handle_kafka_message_commits_malformed_fingerprint_messages(self) -> None:
- consumer = MagicMock()
- message = MagicMock()
- message.error.return_value = None
- message.value.return_value = _embedding_result_message(team_id="1")
-
- await Command()._handle_kafka_message(consumer, AsyncMock(), message)
-
- consumer.commit.assert_called_once_with(message=message, asynchronous=False)
-
- @pytest.mark.parametrize(
- "error_code",
- [
- KafkaError.ILLEGAL_GENERATION, # type: ignore[attr-defined]
- KafkaError.UNKNOWN_MEMBER_ID, # type: ignore[attr-defined]
- KafkaError.REBALANCE_IN_PROGRESS, # type: ignore[attr-defined]
- ],
- )
- @pytest.mark.asyncio
- async def test_commit_tolerates_rebalance_errors(self, error_code: int) -> None:
- consumer = MagicMock()
- consumer.commit.side_effect = KafkaException(KafkaError(error_code))
-
- await _commit_message(consumer, MagicMock())
-
- consumer.commit.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_commit_reraises_non_rebalance_errors(self) -> None:
- consumer = MagicMock()
- consumer.commit.side_effect = KafkaException(KafkaError(KafkaError.OFFSET_METADATA_TOO_LARGE)) # type: ignore[attr-defined]
-
- with pytest.raises(KafkaException):
- await _commit_message(consumer, MagicMock())
diff --git a/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_fingerprint_embedding_result.py b/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_fingerprint_embedding_result.py
index af8288349f59..5c5905e811f1 100644
--- a/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_fingerprint_embedding_result.py
+++ b/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_fingerprint_embedding_result.py
@@ -1,4 +1,3 @@
-import json
import uuid
from datetime import UTC, datetime
from typing import cast
@@ -9,10 +8,6 @@ from unittest.mock import MagicMock, patch
from django.test import override_settings
-from temporalio import activity
-from temporalio.testing import WorkflowEnvironment
-from temporalio.worker import UnsandboxedWorkflowRunner, Worker
-
from posthog.clickhouse.client.connection import ClickHouseUser, Workload
from posthog.models import Team
@@ -31,15 +26,14 @@ from products.error_tracking.backend.temporal.fingerprint_embedding_result.activ
_query_closest_fingerprints,
_report_closest_fingerprint_metrics,
_target_embedding_from_inputs,
- merge_similar_fingerprints_activity,
)
from products.error_tracking.backend.temporal.fingerprint_embedding_result.types import (
FingerprintEmbeddingMergeResult,
FingerprintEmbeddingResultInputs,
SimilarFingerprintDistance,
)
-from products.error_tracking.backend.temporal.fingerprint_embedding_result.workflow import (
- ErrorTrackingFingerprintEmbeddingResultWorkflow,
+from products.error_tracking.backend.temporal.lifecycle.issue_created.activities import (
+ merge_issue_created_fingerprint_activity,
)
@@ -54,36 +48,6 @@ def _inputs() -> FingerprintEmbeddingResultInputs:
)
-async def _run_workflow_with_mock_activity(
- inputs: FingerprintEmbeddingResultInputs,
- activity_result: FingerprintEmbeddingMergeResult,
-) -> tuple[FingerprintEmbeddingMergeResult, FingerprintEmbeddingResultInputs]:
- captured: dict[str, FingerprintEmbeddingResultInputs] = {}
-
- @activity.defn(name="merge_similar_fingerprints_activity")
- async def mock_activity(activity_inputs: FingerprintEmbeddingResultInputs) -> FingerprintEmbeddingMergeResult:
- captured["inputs"] = activity_inputs
- return activity_result
-
- task_queue = str(uuid.uuid4())
- async with await WorkflowEnvironment.start_time_skipping() as env:
- async with Worker(
- env.client,
- task_queue=task_queue,
- workflows=[ErrorTrackingFingerprintEmbeddingResultWorkflow],
- activities=[mock_activity],
- workflow_runner=UnsandboxedWorkflowRunner(),
- ):
- result = await env.client.execute_workflow(
- ErrorTrackingFingerprintEmbeddingResultWorkflow.run,
- inputs,
- id=str(uuid.uuid4()),
- task_queue=task_queue,
- )
-
- return result, captured["inputs"]
-
-
class TestFingerprintEmbeddingResultActivity:
def test_closest_fingerprints_query_uses_model_specific_table(self) -> None:
with patch(
@@ -201,7 +165,7 @@ class TestFingerprintEmbeddingResultActivity:
"products.error_tracking.backend.temporal.fingerprint_embedding_result.activities._report_closest_fingerprint_metrics"
),
):
- result = merge_similar_fingerprints_activity(_inputs())
+ result = merge_issue_created_fingerprint_activity(_inputs())
assert result.merged_count == 0
assert result.query_duration_ms is not None
@@ -217,7 +181,7 @@ class TestFingerprintEmbeddingResultActivity:
"products.error_tracking.backend.temporal.fingerprint_embedding_result.activities._capture_activity_exception"
) as capture_exception,
):
- result = merge_similar_fingerprints_activity(_inputs())
+ result = merge_issue_created_fingerprint_activity(_inputs())
assert result == FingerprintEmbeddingMergeResult()
capture_exception.assert_not_called()
@@ -500,58 +464,3 @@ class TestMergeFingerprintCrossTeamIsolation(BaseTest):
other_fingerprint = ErrorTrackingIssueFingerprintV2.objects.get(team=other_team, fingerprint="fp-source")
assert other_fingerprint.issue_id == other_source_issue.id
assert other_fingerprint.version == 0
-
-
-class TestFingerprintEmbeddingResultWorkflow:
- def test_parse_inputs_requires_payload(self) -> None:
- with pytest.raises(ValueError, match="requires exactly one input"):
- ErrorTrackingFingerprintEmbeddingResultWorkflow.parse_inputs([])
-
- def test_parse_inputs_rejects_multiple_payloads(self) -> None:
- with pytest.raises(ValueError, match="requires exactly one input"):
- ErrorTrackingFingerprintEmbeddingResultWorkflow.parse_inputs(["{}", "{}"])
-
- def test_parse_inputs(self) -> None:
- inputs = ErrorTrackingFingerprintEmbeddingResultWorkflow.parse_inputs(
- [
- json.dumps(
- {
- "team_id": 1,
- "fingerprint": "test-fingerprint",
- "rendering": "type_message_and_stack",
- "timestamp": "2026-06-08T00:00:00Z",
- "embedding": [0.1, 0.2, 0.3],
- "model_name": "text-embedding-3-large-3072",
- }
- )
- ]
- )
-
- assert inputs == _inputs()
-
- def test_workflow_id_for_is_stable_and_bounded(self) -> None:
- workflow_id = ErrorTrackingFingerprintEmbeddingResultWorkflow.workflow_id_for(
- team_id=1,
- fingerprint="test-fingerprint",
- rendering="type_message_and_stack",
- timestamp="2026-06-08T00:00:00Z",
- )
-
- assert workflow_id == ErrorTrackingFingerprintEmbeddingResultWorkflow.workflow_id_for(
- team_id=1,
- fingerprint="test-fingerprint",
- rendering="type_message_and_stack",
- timestamp="2026-06-08T00:00:00Z",
- )
- assert workflow_id.startswith("error-tracking-fingerprint-embedding-result-1-")
- assert len(workflow_id) < 100
-
- @pytest.mark.asyncio
- async def test_workflow_calls_merge_activity(self) -> None:
- inputs = _inputs()
- expected = FingerprintEmbeddingMergeResult(merged_count=2)
-
- result, activity_inputs = await _run_workflow_with_mock_activity(inputs, expected)
-
- assert result == expected
- assert activity_inputs == inputs
diff --git a/products/error_tracking/backend/temporal/fingerprint_embedding_result/workflow.py b/products/error_tracking/backend/temporal/fingerprint_embedding_result/workflow.py
deleted file mode 100644
index 07b560973db7..000000000000
--- a/products/error_tracking/backend/temporal/fingerprint_embedding_result/workflow.py
+++ /dev/null
@@ -1,46 +0,0 @@
-import json
-import hashlib
-from datetime import timedelta
-
-from temporalio import common, workflow
-
-from posthog.temporal.common.base import PostHogWorkflow
-
-with workflow.unsafe.imports_passed_through():
- from products.error_tracking.backend.temporal.fingerprint_embedding_result.activities import (
- merge_similar_fingerprints_activity,
- )
- from products.error_tracking.backend.temporal.fingerprint_embedding_result.types import (
- FingerprintEmbeddingMergeResult,
- FingerprintEmbeddingResultInputs,
- )
-
-WORKFLOW_NAME = "error-tracking-fingerprint-embedding-result"
-
-ACTIVITY_RETRY_POLICY = common.RetryPolicy(maximum_attempts=4)
-ACTIVITY_START_TO_CLOSE_TIMEOUT = timedelta(minutes=5)
-
-
[email protected](name=WORKFLOW_NAME)
-class ErrorTrackingFingerprintEmbeddingResultWorkflow(PostHogWorkflow):
- @staticmethod
- def workflow_id_for(team_id: int, fingerprint: str, rendering: str, timestamp: str) -> str:
- key = f"{fingerprint}:{rendering}:{timestamp}"
- digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]
- return f"error-tracking-fingerprint-embedding-result-{team_id}-{digest}"
-
- @staticmethod
- def parse_inputs(inputs: list[str]) -> FingerprintEmbeddingResultInputs:
- if len(inputs) != 1:
- raise ValueError("Fingerprint embedding result workflow requires exactly one input")
- data = json.loads(inputs[0])
- return FingerprintEmbeddingResultInputs(**data)
-
- @workflow.run
- async def run(self, inputs: FingerprintEmbeddingResultInputs) -> FingerprintEmbeddingMergeResult:
- return await workflow.execute_activity(
- merge_similar_fingerprints_activity,
- inputs,
- start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,
- retry_policy=ACTIVITY_RETRY_POLICY,
- )
diff --git a/rust/cymbal/README.md b/rust/cymbal/README.md
index dfc3d5fa618f..1eb40c0b24fa 100644
--- a/rust/cymbal/README.md
+++ b/rust/cymbal/README.md
@@ -3,15 +3,20 @@
You throw 'em, we catch 'em.
Cymbal owns the HTTP ingress and full processing pipeline (fingerprinting,
-suppression, Kafka producers, issue linking). The binary runs in one of two
+suppression, Kafka producers, issue linking). The binary runs in one of three
modes selected by `CYMBAL_MODE` (default `processing`): the processing
-pipeline, or the `cymbal.resolution.v1` gRPC symbol-resolution service
-(`CYMBAL_MODE=resolution`). Symbol resolution can run either inline inside the
-processing binary (default) or be offloaded to resolution-mode pods via the
-`cymbal.resolution.v1` contract. The remote path is opt-in via
-`CYMBAL_REMOTE_RESOLUTION_ENABLED=true` and has **no silent local fallback**
-— see the [resolution mode README](src/modes/resolution/README.md) for
-rollout, configuration, and operator guidance.
+pipeline, the `cymbal.resolution.v1` gRPC symbol-resolution service
+(`CYMBAL_MODE=resolution`), or the Kafka notification consumer
+(`CYMBAL_MODE=notifications`). The notification consumer starts the matching
+Temporal lifecycle workflow for every issue-created, issue-reopened, or
+issue-spiking notification.
+
+Symbol resolution can run either inline inside the processing binary (default)
+or be offloaded to resolution-mode pods via the `cymbal.resolution.v1`
+contract. The remote path is opt-in via
+`CYMBAL_REMOTE_RESOLUTION_ENABLED=true` and has **no silent local fallback**.
+See the [resolution mode README](src/modes/resolution/README.md) for rollout,
+configuration, and operator guidance.
## Remote resolution behavior
diff --git a/rust/cymbal/src/core/metric_consts.rs b/rust/cymbal/src/core/metric_consts.rs
index 13c147effd4e..09ac7bf1a386 100644
--- a/rust/cymbal/src/core/metric_consts.rs
+++ b/rust/cymbal/src/core/metric_consts.rs
@@ -111,14 +111,6 @@ pub const SPIKE_ISSUES_CHECKED: &str = "cymbal_spike_issues_checked";
pub const SPIKE_ISSUES_SPIKING: &str = "cymbal_spike_issues_spiking";
pub const SPIKE_ISSUES_BLOCKED_BY_COOLDOWN: &str = "cymbal_spike_issues_blocked_by_cooldown";
-// Signal metrics
-pub const SIGNAL_EMITTED: &str = "cymbal_signal_emitted";
-pub const SIGNAL_EMIT_FAILED: &str = "cymbal_signal_emit_failed";
-pub const SIGNAL_EMIT_RESPONSE: &str = "cymbal_signal_emit_response";
-
-// Fingerprint embedding metrics
-pub const FINGERPRINT_EMBEDDING_SKIPPED: &str = "cymbal_fingerprint_embedding_skipped";
-
// Stages Name.
// We want to keep previous value for comparison, can be changed later on
pub const HTTP_EXCEPTION_PIPELINE: &str = "cymbal_http_exception_pipeline";
diff --git a/rust/cymbal/src/modes/notifications/config.rs b/rust/cymbal/src/modes/notifications/config.rs
index e44e7b1dfa6c..01f5a5201524 100644
--- a/rust/cymbal/src/modes/notifications/config.rs
+++ b/rust/cymbal/src/modes/notifications/config.rs
@@ -10,8 +10,7 @@ pub const DEFAULT_CONSUMER_TOPIC: &str = "error_tracking_ingestion_notifications
/// `KAFKA_CONSUMER_GROUP`.
pub const DEFAULT_CONSUMER_GROUP: &str = "error_tracking_ingestion_notifications";
-/// Top-level config for notifications mode. Includes the downstream clients
-/// needed for legacy side effects and opt-in Temporal workflow starts.
+/// Top-level config for notifications mode.
#[derive(Envconfig, Clone)]
pub struct NotificationsConfig {
#[envconfig(nested = true)]
@@ -23,74 +22,15 @@ pub struct NotificationsConfig {
#[envconfig(nested = true)]
pub consumer: ConsumerConfig,
- #[envconfig(default = "postgres://posthog:posthog@localhost:5432/posthog")]
- pub database_url: String,
-
- // Keep this low: each Cymbal pod owns its own sqlx pool, regardless of DATABASE_URL routing.
- #[envconfig(default = "4")]
- pub max_pg_connections: u32,
-
- #[envconfig(default = "")]
- pub internal_api_secret: String,
-
/// HTTP bind port for liveness, readiness, and Prometheus metrics.
#[envconfig(from = "METRICS_PORT", default = "9102")]
pub metrics_port: u16,
- // Internal API for signal emission.
- #[envconfig(default = "")]
- pub signals_api_base_url: String,
-
- #[envconfig(default = "document_embeddings_input")]
- pub embedding_worker_topic: String,
-
- #[envconfig(default = "cdp_internal_events")]
- pub internal_events_topic: String,
-
- // Optional override for the brokers used to produce `cdp_internal_events`.
- #[envconfig(from = "CYMBAL_CYCLOTRON_KAFKA_HOSTS")]
- pub cyclotron_kafka_hosts: Option<String>,
-
- // Optional TLS override for the cyclotron producer.
- #[envconfig(from = "CYMBAL_CYCLOTRON_KAFKA_TLS")]
- pub cyclotron_kafka_tls: Option<bool>,
-
pub posthog_api_key: Option<String>,
#[envconfig(default = "https://us.i.posthog.com/capture")]
pub posthog_endpoint: String,
- /// Direct Temporal starts are disabled by default. When enabled with an empty
- /// allowlist, every team is routed to the issue-created workflow.
- #[envconfig(
- from = "ERROR_TRACKING_ISSUE_CREATED_WORKFLOW_ENABLED",
- default = "false"
- )]
- pub issue_created_workflow_enabled: bool,
-
- /// Comma-separated rollout allowlist. An empty value means all teams when
- /// `ERROR_TRACKING_ISSUE_CREATED_WORKFLOW_ENABLED` is true.
- #[envconfig(from = "ERROR_TRACKING_ISSUE_CREATED_WORKFLOW_TEAM_IDS", default = "")]
- pub issue_created_workflow_team_ids: String,
-
- #[envconfig(
- from = "ERROR_TRACKING_ISSUE_REOPENED_WORKFLOW_ENABLED",
- default = "false"
- )]
- pub issue_reopened_workflow_enabled: bool,
-
- #[envconfig(from = "ERROR_TRACKING_ISSUE_REOPENED_WORKFLOW_TEAM_IDS", default = "")]
- pub issue_reopened_workflow_team_ids: String,
-
- #[envconfig(
- from = "ERROR_TRACKING_ISSUE_SPIKING_WORKFLOW_ENABLED",
- default = "false"
- )]
- pub issue_spiking_workflow_enabled: bool,
-
- #[envconfig(from = "ERROR_TRACKING_ISSUE_SPIKING_WORKFLOW_TEAM_IDS", default = "")]
- pub issue_spiking_workflow_team_ids: String,
-
#[envconfig(from = "TEMPORAL_HOST", default = "")]
pub temporal_host: String,
diff --git a/rust/cymbal/src/modes/notifications/context.rs b/rust/cymbal/src/modes/notifications/context.rs
index 5f78bbbab5dc..73351506b640 100644
--- a/rust/cymbal/src/modes/notifications/context.rs
+++ b/rust/cymbal/src/modes/notifications/context.rs
@@ -1,98 +1,17 @@
-use std::time::Duration;
-
-use common_kafka::kafka_producer::{create_kafka_producer, KafkaContext};
-use health::HealthRegistry;
-use rdkafka::producer::FutureProducer;
-use sqlx::PgPool;
-
-use crate::core::config::build_pg_pool;
use crate::core::error::UnhandledError;
use crate::modes::notifications::config::NotificationsConfig;
-use crate::modes::notifications::signals::{MaybeSignalClient, SignalClient};
-use crate::modes::notifications::temporal::{
- build_issue_lifecycle_temporal_client, IssueLifecycleWorkflowStarters,
-};
+use crate::modes::notifications::temporal::IssueLifecycleWorkflowStarters;
#[derive(Clone)]
pub struct NotificationsContext {
- pub posthog_pool: PgPool,
- pub immediate_producer: FutureProducer<KafkaContext>,
- pub cyclotron_producer: FutureProducer<KafkaContext>,
- pub signal_client: MaybeSignalClient,
- pub embedding_worker_topic: String,
- pub internal_events_topic: String,
pub issue_lifecycle_workflow_starters: IssueLifecycleWorkflowStarters,
}
impl NotificationsContext {
pub async fn from_config(config: &NotificationsConfig) -> Result<Self, UnhandledError> {
- let posthog_pool = build_pg_pool(
- &config.database_url,
- config.max_pg_connections,
- "cymbal_notifications",
- )?;
- let immediate_producer = build_immediate_producer(config).await?;
- let lifecycle_temporal_client = build_issue_lifecycle_temporal_client(config).await?;
-
Ok(Self {
- posthog_pool,
- cyclotron_producer: build_cyclotron_producer(config, &immediate_producer).await?,
- immediate_producer,
- signal_client: build_signal_client(config),
- embedding_worker_topic: config.embedding_worker_topic.clone(),
- internal_events_topic: config.internal_events_topic.clone(),
- issue_lifecycle_workflow_starters: IssueLifecycleWorkflowStarters::from_config(
- config,
- lifecycle_temporal_client.as_ref(),
- )?,
+ issue_lifecycle_workflow_starters: IssueLifecycleWorkflowStarters::from_config(config)
+ .await?,
})
}
}
-
-async fn build_immediate_producer(
- config: &NotificationsConfig,
-) -> Result<FutureProducer<KafkaContext>, UnhandledError> {
- create_kafka_producer(&config.kafka, kafka_liveness("immediate_kafka").await)
- .await
- .map_err(Into::into)
-}
-
-async fn build_cyclotron_producer(
- config: &NotificationsConfig,
- immediate_producer: &FutureProducer<KafkaContext>,
-) -> Result<FutureProducer<KafkaContext>, UnhandledError> {
- let Some(hosts) = config
- .cyclotron_kafka_hosts
- .as_deref()
- .filter(|hosts| !hosts.is_empty())
- else {
- return Ok(immediate_producer.clone());
- };
-
- let mut cyclotron_config = config.kafka.clone();
- cyclotron_config.kafka_hosts = hosts.to_string();
- if let Some(tls) = config.cyclotron_kafka_tls {
- cyclotron_config.kafka_tls = tls;
- }
-
- create_kafka_producer(&cyclotron_config, kafka_liveness("cyclotron_kafka").await)
- .await
- .map_err(Into::into)
-}
-
-fn build_signal_client(config: &NotificationsConfig) -> MaybeSignalClient {
- if config.signals_api_base_url.is_empty() {
- return MaybeSignalClient::disabled();
- }
-
- MaybeSignalClient::enabled(SignalClient::new_with_parts(
- config.signals_api_base_url.clone(),
- config.internal_api_secret.clone(),
- ))
-}
-
-async fn kafka_liveness(component: &str) -> health::HealthHandle {
- HealthRegistry::new("notifications_liveness")
- .register(component.to_string(), Duration::from_secs(30))
- .await
-}
diff --git a/rust/cymbal/src/modes/notifications/issue_handler.rs b/rust/cymbal/src/modes/notifications/issue_handler.rs
index 8290a14dc1e9..203ebdf6fc0b 100644
--- a/rust/cymbal/src/modes/notifications/issue_handler.rs
+++ b/rust/cymbal/src/modes/notifications/issue_handler.rs
@@ -1,86 +1,29 @@
-use chrono::{DateTime, Utc};
-use tracing::{debug, warn};
-use uuid::Uuid;
-
use crate::core::{
error::UnhandledError,
- types::notification::{
- IssueCreated, IssueNotificationContext, IssueReopened, IssueSnapshot, IssueSpiking,
- },
+ types::notification::{IssueCreated, IssueReopened, IssueSpiking},
};
use crate::modes::notifications::analytics::{capture_issue_created, capture_issue_reopened};
use crate::modes::notifications::context::NotificationsContext;
-use crate::modes::notifications::side_effects::{
- send_issue_created_internal_event, send_issue_reopened_internal_event,
- send_issue_spiking_internal_event, send_new_fingerprint_event,
-};
-use crate::modes::notifications::types::IssueNotificationData;
pub async fn handle_issue_created(
context: &NotificationsContext,
notification: IssueCreated,
) -> Result<(), UnhandledError> {
- if context
+ context
.issue_lifecycle_workflow_starters
- .start_created_if_enabled(&notification)
- .await?
- {
- let sentry_integration = notification
- .issue
- .event_properties
- .properties()
- .contains_key("$sentry_event_id");
- capture_issue_created(
- notification.meta.team_id,
- notification.issue.issue_id,
- sentry_integration,
- );
- return Ok(());
- }
+ .start_created(&notification)
+ .await?;
- let IssueCreated {
- meta,
- issue,
- event_uuid,
- event_timestamp,
- assignee,
- ..
- } = notification;
- let IssueNotificationContext {
- issue_id,
- issue: issue_snapshot,
- event_properties,
- } = issue;
- let issue = issue_from_notification(meta.team_id, issue_id, issue_snapshot);
-
- send_new_fingerprint_event(
- &context.immediate_producer,
- &context.embedding_worker_topic,
- &issue,
- &event_properties,
- )
- .await?;
- let sentry_integration = event_properties
+ let sentry_integration = notification
+ .issue
+ .event_properties
.properties()
.contains_key("$sentry_event_id");
-
- send_issue_created_internal_event(
- &context.cyclotron_producer,
- &context.internal_events_topic,
- meta.notification_id,
- &issue,
- assignee,
- &event_properties,
- &parse_notification_timestamp(&event_timestamp, event_uuid),
- )
- .await?;
-
- context
- .signal_client
- .emit_issue_created(&issue, &event_properties);
-
- capture_issue_created(meta.team_id, issue_id, sentry_integration);
-
+ capture_issue_created(
+ notification.meta.team_id,
+ notification.issue.issue_id,
+ sentry_integration,
+ );
Ok(())
}
@@ -88,45 +31,12 @@ pub async fn handle_issue_reopened(
context: &NotificationsContext,
notification: IssueReopened,
) -> Result<(), UnhandledError> {
- if context
- .issue_lifecycle_workflow_starters
- .start_reopened_if_enabled(&notification)
- .await?
- {
- capture_issue_reopened(notification.meta.team_id, notification.issue.issue_id);
- return Ok(());
- }
-
- let IssueReopened {
- meta,
- issue,
- event_timestamp,
- assignee,
- ..
- } = notification;
- let IssueNotificationContext {
- issue_id,
- issue: issue_snapshot,
- event_properties,
- } = issue;
- let issue = issue_from_notification(meta.team_id, issue_id, issue_snapshot);
-
- send_issue_reopened_internal_event(
- &context.cyclotron_producer,
- &context.internal_events_topic,
- meta.notification_id,
- &issue,
- assignee,
- &event_properties,
- &parse_notification_timestamp(&event_timestamp, Uuid::nil()),
- )
- .await?;
-
context
- .signal_client
- .emit_issue_reopened(&issue, &event_properties);
- capture_issue_reopened(meta.team_id, issue_id);
+ .issue_lifecycle_workflow_starters
+ .start_reopened(&notification)
+ .await?;
+ capture_issue_reopened(notification.meta.team_id, notification.issue.issue_id);
Ok(())
}
@@ -134,203 +44,8 @@ pub async fn handle_issue_spiking(
context: &NotificationsContext,
notification: IssueSpiking,
) -> Result<(), UnhandledError> {
- if context
+ context
.issue_lifecycle_workflow_starters
- .start_spiking_if_enabled(&notification)
- .await?
- {
- return Ok(());
- }
-
- let IssueSpiking {
- meta,
- issue,
- computed_baseline,
- current_bucket_value,
- assignee,
- ..
- } = notification;
- let IssueNotificationContext {
- issue_id,
- issue: issue_snapshot,
- event_properties,
- } = issue;
-
- let detected_at = spike_detection_time(meta.notification_id);
-
- match persist_spike_event(
- context,
- meta.notification_id,
- meta.team_id,
- issue_id,
- detected_at,
- computed_baseline,
- current_bucket_value,
- )
- .await?
- {
- PersistSpikeEventResult::Inserted => {}
- PersistSpikeEventResult::AlreadyPersisted => {
- debug!(
- notification_id = %meta.notification_id,
- team_id = meta.team_id,
- issue_id = %issue_id,
- "dropping duplicate spike notification"
- );
- return Ok(());
- }
- PersistSpikeEventResult::MissingIssue => {
- warn!(
- notification_id = %meta.notification_id,
- team_id = meta.team_id,
- issue_id = %issue_id,
- "dropping spike notification for missing issue"
- );
- return Ok(());
- }
- }
-
- let issue = issue_from_notification(meta.team_id, issue_id, issue_snapshot);
-
- send_issue_spiking_internal_event(
- &context.cyclotron_producer,
- &context.internal_events_topic,
- meta.notification_id,
- &issue,
- assignee,
- &event_properties,
- detected_at,
- computed_baseline,
- current_bucket_value,
- )
- .await?;
-
- context.signal_client.emit_issue_spiking(
- &issue,
- &event_properties,
- computed_baseline,
- current_bucket_value,
- );
-
- Ok(())
-}
-
-enum PersistSpikeEventResult {
- Inserted,
- AlreadyPersisted,
- MissingIssue,
-}
-
-fn issue_from_notification(
- team_id: i32,
- issue_id: Uuid,
- issue: IssueSnapshot,
-) -> IssueNotificationData {
- IssueNotificationData {
- id: issue_id,
- team_id,
- status: issue.status,
- name: issue.name,
- description: issue.description,
- created_at: issue.created_at,
- }
-}
-
-// When the spike was detected, not when this consumer processed the notification. The
-// notification_id is a UUIDv7 minted in notification_meta() on the processing side, in the same
-// call stack as spike detection, so its embedded timestamp survives any consumer lag. Falls back
-// to now() for legacy payloads where serde defaulted the id at consume time.
-fn spike_detection_time(notification_id: Uuid) -> DateTime<Utc> {
- notification_id
- .get_timestamp()
- .and_then(|ts| {
- let (secs, nanos) = ts.to_unix();
- DateTime::from_timestamp(secs as i64, nanos)
- })
- .unwrap_or_else(Utc::now)
-}
-
-async fn persist_spike_event(
- context: &NotificationsContext,
- notification_id: Uuid,
- team_id: i32,
- issue_id: Uuid,
- detected_at: DateTime<Utc>,
- computed_baseline: f64,
- current_bucket_value: f64,
-) -> Result<PersistSpikeEventResult, UnhandledError> {
- let result = sqlx::query(
- r#"WITH existing_issue AS (
- SELECT 1 FROM posthog_errortrackingissue
- WHERE team_id = $2 AND id = $3
- FOR KEY SHARE
- )
- INSERT INTO posthog_errortrackingspikeevent
- (id, team_id, issue_id, detected_at, computed_baseline, current_bucket_value)
- SELECT $1, $2, $3, $4, $5, $6 FROM existing_issue
- ON CONFLICT (id) DO NOTHING"#,
- )
- .bind(notification_id)
- .bind(team_id)
- .bind(issue_id)
- .bind(detected_at)
- .bind(computed_baseline)
- .bind(current_bucket_value as i32)
- .execute(&context.posthog_pool)
- .await?;
-
- if result.rows_affected() > 0 {
- return Ok(PersistSpikeEventResult::Inserted);
- }
-
- let issue_exists: bool = sqlx::query_scalar(
- r#"SELECT EXISTS(
- SELECT 1 FROM posthog_errortrackingissue WHERE team_id = $1 AND id = $2
- )"#,
- )
- .bind(team_id)
- .bind(issue_id)
- .fetch_one(&context.posthog_pool)
- .await?;
-
- if issue_exists {
- return Ok(PersistSpikeEventResult::AlreadyPersisted);
- }
-
- Ok(PersistSpikeEventResult::MissingIssue)
-}
-
-fn parse_notification_timestamp(event_timestamp: &str, event_uuid: Uuid) -> DateTime<Utc> {
- common_types::format::parse_datetime_assuming_utc(event_timestamp).unwrap_or_else(|e| {
- warn!(
- event = event_uuid.to_string(),
- "Failed to get event timestamp, using current time, error: {:?}", e
- );
- Utc::now()
- })
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use uuid::{NoContext, Timestamp};
-
- #[test]
- fn spike_detection_time_recovers_the_v7_mint_instant() {
- let minted = DateTime::parse_from_rfc3339("2026-07-16T10:30:00.123Z")
- .unwrap()
- .with_timezone(&Utc);
- let ts = Timestamp::from_unix(
- NoContext,
- minted.timestamp() as u64,
- minted.timestamp_subsec_nanos(),
- );
- let notification_id = Uuid::new_v7(ts);
-
- // UUIDv7 stores millisecond precision, so compare at that granularity.
- assert_eq!(
- spike_detection_time(notification_id).timestamp_millis(),
- minted.timestamp_millis()
- );
- }
+ .start_spiking(&notification)
+ .await
}
diff --git a/rust/cymbal/src/modes/notifications/mod.rs b/rust/cymbal/src/modes/notifications/mod.rs
index e2de9ad1c112..2c15503abc46 100644
--- a/rust/cymbal/src/modes/notifications/mod.rs
+++ b/rust/cymbal/src/modes/notifications/mod.rs
@@ -1,5 +1,5 @@
//! Notifications mode: consumes the `error_tracking_ingestion_notifications`
-//! Kafka topic and fans ingestion notifications out to downstream side effects.
+//! Kafka topic and starts the matching Temporal lifecycle workflow.
use std::sync::{
atomic::{AtomicBool, Ordering},
@@ -22,11 +22,7 @@ mod consumer_loop;
mod context;
mod handler;
mod issue_handler;
-pub mod side_effects;
-pub mod signals;
-pub mod stacktrace;
pub mod temporal;
-pub mod types;
pub use config::NotificationsConfig;
diff --git a/rust/cymbal/src/modes/notifications/side_effects.rs b/rust/cymbal/src/modes/notifications/side_effects.rs
deleted file mode 100644
index 381915edf118..000000000000
--- a/rust/cymbal/src/modes/notifications/side_effects.rs
+++ /dev/null
@@ -1,400 +0,0 @@
-use chrono::{DateTime, Utc};
-use common_kafka::kafka_messages::internal_events::{InternalEvent, InternalEventEvent};
-use common_kafka::kafka_producer::{send_iter_to_kafka, KafkaContext, KafkaProduceError};
-use common_types::embedding::{EmbeddingModel, EmbeddingRequest};
-use rdkafka::producer::FutureProducer;
-use rdkafka::types::RDKafkaErrorCode;
-use serde_json::Value;
-use tracing::debug;
-use uuid::Uuid;
-
-use crate::core::error::UnhandledError;
-use crate::metric_consts::FINGERPRINT_EMBEDDING_SKIPPED;
-use crate::modes::notifications::stacktrace::print_stacktrace;
-use crate::modes::notifications::types::NotificationIssue;
-use crate::modes::processing::fingerprinting::FingerprintRecordPart;
-use crate::types::ProcessedExceptionProperties;
-
-/// SDKs whose fingerprint embeddings we don't generate — they emit too many
-/// distinct issues, so embedding every fingerprint isn't worth the cost.
-const EMBEDDING_DISABLED_LIBS: &[&str] = &["posthog-elixir"];
-
-struct IssueLifecycleInternalEvent<'a, I: NotificationIssue> {
- event: &'static str,
- notification_id: Uuid,
- issue: &'a I,
- assignee: Option<String>,
- processed_properties: &'a ProcessedExceptionProperties,
- event_timestamp: &'a DateTime<Utc>,
-}
-
-pub async fn send_new_fingerprint_event<I: NotificationIssue>(
- producer: &FutureProducer<KafkaContext>,
- embedding_worker_topic: &str,
- issue: &I,
- processed_properties: &ProcessedExceptionProperties,
-) -> Result<(), UnhandledError> {
- if let Some(reason) = skip_fingerprint_embedding_reason(processed_properties) {
- metrics::counter!(FINGERPRINT_EMBEDDING_SKIPPED, "reason" => reason).increment(1);
- debug!(
- team_id = issue.team_id(),
- fingerprint = %processed_properties.fingerprint(),
- reason,
- "skipping fingerprint embedding request"
- );
- return Ok(());
- }
-
- let request = fingerprint_embedding_request(issue, processed_properties);
-
- let res = send_iter_to_kafka(producer, embedding_worker_topic, &[request])
- .await
- .into_iter()
- .collect::<Result<Vec<_>, _>>();
- if let Err(err) = res {
- return Err(UnhandledError::KafkaProduceError(err));
- }
- Ok(())
-}
-
-/// Returns the reason a fingerprint embedding request should be skipped, or
-/// `None` if it should be sent. We don't embed issues grouped by a fingerprint
-/// the user controls — manual fingerprints and custom grouping rules — since
-/// embedding-based similarity grouping doesn't apply to them, nor events from
-/// SDKs in `EMBEDDING_DISABLED_LIBS` (they emit too many issues).
-fn skip_fingerprint_embedding_reason(
- processed_properties: &ProcessedExceptionProperties,
-) -> Option<&'static str> {
- if processed_properties
- .fingerprint_record()
- .iter()
- .any(|part| matches!(part, FingerprintRecordPart::Manual))
- {
- return Some("manual_fingerprint");
- }
-
- if processed_properties
- .fingerprint_record()
- .iter()
- .any(|part| matches!(part, FingerprintRecordPart::Custom { .. }))
- {
- return Some("custom_grouping_rule");
- }
-
- let lib = processed_properties
- .properties()
- .get("$lib")
- .and_then(Value::as_str);
- if lib.is_some_and(|lib| EMBEDDING_DISABLED_LIBS.contains(&lib)) {
- return Some("disabled_sdk");
- }
-
- None
-}
-
-fn fingerprint_embedding_request<I: NotificationIssue>(
- issue: &I,
- processed_properties: &ProcessedExceptionProperties,
-) -> EmbeddingRequest {
- EmbeddingRequest {
- team_id: issue.team_id(),
- product: "error_tracking".to_string(),
- document_type: "fingerprint".to_string(),
- rendering: "type_message_and_stack".to_string(),
- document_id: processed_properties.fingerprint().to_string(),
- timestamp: issue.created_at(),
- content: print_stacktrace(processed_properties, Some(7000)),
- models: vec![EmbeddingModel::OpenAITextEmbeddingLarge],
- metadata: Default::default(),
- }
-}
-
-pub async fn send_issue_created_internal_event<I: NotificationIssue>(
- producer: &FutureProducer<KafkaContext>,
- internal_events_topic: &str,
- notification_id: Uuid,
- issue: &I,
- assignee: Option<String>,
- processed_properties: &ProcessedExceptionProperties,
- event_timestamp: &DateTime<Utc>,
-) -> Result<(), UnhandledError> {
- send_internal_event_with_producer(
- producer,
- internal_events_topic,
- IssueLifecycleInternalEvent {
- event: "$error_tracking_issue_created",
- notification_id,
- issue,
- assignee,
- processed_properties,
- event_timestamp,
- },
- )
- .await
-}
-
-pub async fn send_issue_reopened_internal_event<I: NotificationIssue>(
- producer: &FutureProducer<KafkaContext>,
- internal_events_topic: &str,
- notification_id: Uuid,
- issue: &I,
- assignee: Option<String>,
- processed_properties: &ProcessedExceptionProperties,
- event_timestamp: &DateTime<Utc>,
-) -> Result<(), UnhandledError> {
- send_internal_event_with_producer(
- producer,
- internal_events_topic,
- IssueLifecycleInternalEvent {
- event: "$error_tracking_issue_reopened",
- notification_id,
- issue,
- assignee,
- processed_properties,
- event_timestamp,
- },
- )
- .await
-}
-
-#[allow(clippy::too_many_arguments)]
-pub async fn send_issue_spiking_internal_event<I: NotificationIssue>(
- producer: &FutureProducer<KafkaContext>,
- internal_events_topic: &str,
- notification_id: Uuid,
- issue: &I,
- assignee: Option<String>,
- processed_properties: &ProcessedExceptionProperties,
- detected_at: DateTime<Utc>,
- computed_baseline: f64,
- current_bucket_value: f64,
-) -> Result<(), UnhandledError> {
- let mut event = InternalEventEvent::new(
- "$error_tracking_issue_spiking",
- issue.id(),
- Utc::now(),
- None,
- );
- event.uuid = notification_id.to_string();
- event
- .insert_prop("name", issue.name())
- .expect("insert_prop for name should never fail");
- event
- .insert_prop("description", issue.description())
- .expect("insert_prop for description should never fail");
- event
- .insert_prop("issue_description", issue.description())
- .expect("insert_prop for issue_description should never fail");
- event
- .insert_prop("first_seen", issue.created_at())
- .expect("insert_prop for first_seen should never fail");
- if let Some(assignee) = assignee {
- event
- .insert_prop("assignee", assignee)
- .expect("insert_prop for assignee should never fail");
- }
- event
- .insert_prop("computed_baseline", computed_baseline)
- .expect("insert_prop for computed_baseline should never fail");
- event
- .insert_prop("current_bucket_value", current_bucket_value)
- .expect("insert_prop for current_bucket_value should never fail");
- event
- .insert_prop("fingerprint", processed_properties.fingerprint())
- .expect("insert_prop for fingerprint should never fail");
- // Spikes are detected on live traffic, so detection time is a good anchor for finding
- // example events.
- event
- .insert_prop("exception_timestamp", detected_at)
- .expect("insert_prop for exception_timestamp should never fail");
- event.insert_prop("exception_props", processed_properties)?;
-
- send_internal_event_with_fallback(producer, internal_events_topic, issue.team_id(), event).await
-}
-
-async fn send_internal_event_with_producer<I: NotificationIssue>(
- producer: &FutureProducer<KafkaContext>,
- internal_events_topic: &str,
- request: IssueLifecycleInternalEvent<'_, I>,
-) -> Result<(), UnhandledError> {
- let IssueLifecycleInternalEvent {
- event,
- notification_id,
- issue,
- assignee,
- processed_properties,
- event_timestamp,
- } = request;
-
- let mut event = InternalEventEvent::new(event, issue.id(), Utc::now(), None);
- event.uuid = notification_id.to_string();
- event
- .insert_prop("name", issue.name())
- .expect("Strings are serializable");
- event
- .insert_prop("description", issue.description())
- .expect("Strings are serializable");
- event.insert_prop("issue_description", issue.description())?;
- event.insert_prop("first_seen", issue.created_at())?;
- event.insert_prop("status", issue.status())?;
- event.insert_prop("fingerprint", processed_properties.fingerprint())?;
- event.insert_prop("exception_timestamp", event_timestamp)?;
- event.insert_prop("exception_props", processed_properties)?;
-
- if let Some(assignee) = assignee {
- event
- .insert_prop("assignee", assignee)
- .expect("Strings are serializable");
- }
-
- send_internal_event_with_fallback(producer, internal_events_topic, issue.team_id(), event).await
-}
-
-async fn send_internal_event_with_fallback(
- producer: &FutureProducer<KafkaContext>,
- internal_events_topic: &str,
- team_id: i32,
- event: InternalEventEvent,
-) -> Result<(), UnhandledError> {
- let mut events = [InternalEvent {
- team_id,
- event,
- person: None,
- }];
-
- let res = send_iter_to_kafka(producer, internal_events_topic, &events)
- .await
- .into_iter()
- .collect::<Result<Vec<_>, _>>();
-
- match res {
- Ok(_) => Ok(()),
- Err(KafkaProduceError::KafkaProduceError { error })
- if matches!(
- error.rdkafka_error_code(),
- Some(RDKafkaErrorCode::MessageSizeTooLarge)
- ) =>
- {
- remove_oversized_exception_props(&mut events[0].event)?;
- send_iter_to_kafka(producer, internal_events_topic, &events)
- .await
- .into_iter()
- .collect::<Result<Vec<_>, _>>()?;
- Ok(())
- }
- Err(e) => Err(e.into()),
- }
-}
-
-fn remove_oversized_exception_props(event: &mut InternalEventEvent) -> Result<(), UnhandledError> {
- event.properties.remove("exception_props");
- event.insert_prop("message_was_too_large", true)?;
- Ok(())
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn props_with(
- record: Vec<FingerprintRecordPart>,
- lib: Option<&str>,
- ) -> ProcessedExceptionProperties {
- let mut value = serde_json::json!({
- "$exception_list": [{"type": "Error", "value": "boom"}],
- "$exception_fingerprint": "test-fingerprint",
- "$exception_fingerprint_record": record,
- "$exception_issue_id": Uuid::nil(),
- "$exception_handled": false,
- "$exception_types": ["Error"],
- "$exception_values": ["boom"],
- "$exception_sources": [],
- "$exception_functions": [],
- });
- if let Some(lib) = lib {
- value
- .as_object_mut()
- .unwrap()
- .insert("$lib".to_string(), Value::String(lib.to_string()));
- }
- serde_json::from_value(value).unwrap()
- }
-
- #[test]
- fn sends_embedding_for_automatic_fingerprint() {
- let props = props_with(
- vec![FingerprintRecordPart::Exception {
- id: None,
- pieces: vec!["boom".to_string()],
- }],
- Some("posthog-python"),
- );
- assert_eq!(skip_fingerprint_embedding_reason(&props), None);
- }
-
- #[test]
- fn skips_embedding_for_manual_fingerprint() {
- let props = props_with(vec![FingerprintRecordPart::Manual], Some("posthog-python"));
- assert_eq!(
- skip_fingerprint_embedding_reason(&props),
- Some("manual_fingerprint")
- );
- }
-
- #[test]
- fn skips_embedding_for_custom_grouping_rule() {
- let props = props_with(
- vec![FingerprintRecordPart::Custom {
- rule_id: Uuid::nil(),
- }],
- Some("posthog-python"),
- );
- assert_eq!(
- skip_fingerprint_embedding_reason(&props),
- Some("custom_grouping_rule")
- );
- }
-
- #[test]
- fn skips_embedding_for_elixir_sdk() {
- let props = props_with(
- vec![FingerprintRecordPart::Exception {
- id: None,
- pieces: vec!["boom".to_string()],
- }],
- Some("posthog-elixir"),
- );
- assert_eq!(
- skip_fingerprint_embedding_reason(&props),
- Some("disabled_sdk")
- );
- }
-
- #[test]
- fn oversized_internal_event_fallback_removes_only_exception_properties() {
- let mut event = InternalEventEvent::new(
- "$error_tracking_issue_spiking",
- Uuid::nil(),
- Utc::now(),
- None,
- );
- event
- .insert_prop("fingerprint", "server-fingerprint")
- .unwrap();
- event
- .insert_prop("exception_props", serde_json::json!({"large": "payload"}))
- .unwrap();
-
- remove_oversized_exception_props(&mut event).unwrap();
-
- assert!(!event.properties.contains_key("exception_props"));
- assert_eq!(
- event.properties.get("fingerprint"),
- Some(&Value::String("server-fingerprint".to_string()))
- );
- assert_eq!(
- event.properties.get("message_was_too_large"),
- Some(&Value::Bool(true))
- );
- }
-}
diff --git a/rust/cymbal/src/modes/notifications/signals.rs b/rust/cymbal/src/modes/notifications/signals.rs
deleted file mode 100644
index 78f28c392535..000000000000
--- a/rust/cymbal/src/modes/notifications/signals.rs
+++ /dev/null
@@ -1,231 +0,0 @@
-use std::sync::Arc;
-
-use serde::Serialize;
-use tracing::warn;
-
-use crate::metric_consts::{SIGNAL_EMITTED, SIGNAL_EMIT_FAILED, SIGNAL_EMIT_RESPONSE};
-use crate::modes::notifications::stacktrace::print_stacktrace;
-use crate::modes::notifications::types::NotificationIssue;
-use crate::types::ProcessedExceptionProperties;
-
-/// Signal payload matching the Django internal API contract.
-#[derive(Serialize)]
-pub struct EmitSignalRequest {
- pub source_product: &'static str,
- pub source_type: &'static str,
- pub source_id: String,
- pub description: String,
- pub weight: f64,
- pub extra: serde_json::Value,
-}
-
-/// Context for building a signal from an issue + its error properties.
-pub struct IssueSignalContext<'a, I: NotificationIssue> {
- pub issue: &'a I,
- pub props: &'a ProcessedExceptionProperties,
- pub source_type: &'static str,
- /// Brief LLM-facing explanation of what this signal means, e.g. "New issue" or "Issue reopened".
- pub preamble: String,
- pub weight: f64,
- pub extra: serde_json::Value,
-}
-
-impl<I: NotificationIssue> From<IssueSignalContext<'_, I>> for EmitSignalRequest {
- fn from(ctx: IssueSignalContext<'_, I>) -> Self {
- let header = format!(
- "{}:\n{}: {}\n",
- ctx.preamble,
- ctx.issue.name().unwrap_or("Unknown"),
- ctx.issue.description().unwrap_or("")
- );
- let header_tokens = crate::tokenizer::CL100K_BPE
- .encode_with_special_tokens(&header)
- .len();
- let stacktrace = print_stacktrace(ctx.props, Some(8000 - header_tokens));
- let description = format!("{header}\n```\n{stacktrace}\n```");
-
- EmitSignalRequest {
- source_product: "error_tracking",
- source_type: ctx.source_type,
- source_id: ctx.issue.id().to_string(),
- description,
- weight: ctx.weight,
- extra: ctx.extra,
- }
- }
-}
-
-/// Thin HTTP client that emits signals via the internal Django API.
-#[derive(Clone)]
-pub struct SignalClient {
- // Notably, this client needs to allow hitting internal APIs, so is unsafe to use elsewhere.
- http: reqwest::Client,
- /// e.g. "http://posthog-web:8000"
- base_url: String,
- secret: String,
-}
-
-impl SignalClient {
- pub fn new_with_parts(base_url: String, secret: String) -> Self {
- Self {
- http: reqwest::Client::builder()
- .no_proxy()
- .build()
- .expect("Failed to build SignalClient HTTP client"),
- base_url,
- secret,
- }
- }
-
- pub async fn emit_issue_created<I: NotificationIssue>(
- &self,
- issue: &I,
- props: &ProcessedExceptionProperties,
- ) {
- let request = EmitSignalRequest::from(IssueSignalContext {
- issue,
- props,
- source_type: "issue_created",
- preamble: "New error tracking issue created - this particular exception was observed for the first time".to_string(),
- weight: 1.0,
- extra: serde_json::json!({
- "fingerprint": props.fingerprint(),
- }),
- });
- self.send(issue.team_id(), request).await;
- }
-
- pub async fn emit_issue_reopened<I: NotificationIssue>(
- &self,
- issue: &I,
- props: &ProcessedExceptionProperties,
- ) {
- let request = EmitSignalRequest::from(IssueSignalContext {
- issue,
- props,
- source_type: "issue_reopened",
- preamble: "Previously resolved error tracking issue has reappeared - this particular exception was observed previously, and thought to be resolved, but has reappeared".to_string(),
- weight: 1.0,
- extra: serde_json::json!({
- "fingerprint": props.fingerprint(),
- }),
- });
- self.send(issue.team_id(), request).await;
- }
-
- pub async fn emit_issue_spiking<I: NotificationIssue>(
- &self,
- issue: &I,
- props: &ProcessedExceptionProperties,
- computed_baseline: f64,
- current_bucket_value: f64,
- ) {
- let multiplier = current_bucket_value / computed_baseline;
- let preamble = format!(
- "This error tracking issue is experiencing a spike in occurrences
- (baseline: {computed_baseline:.1}, current: {current_bucket_value:.1}) ({multiplier:.1} over baseline)"
- );
- let request = EmitSignalRequest::from(IssueSignalContext {
- issue,
- props,
- source_type: "issue_spiking",
- preamble,
- weight: 1.0,
- extra: serde_json::json!({
- "fingerprint": props.fingerprint(),
- }),
- });
- self.send(issue.team_id(), request).await;
- }
-
- async fn send(&self, team_id: i32, body: EmitSignalRequest) {
- let source_type = body.source_type;
- let url = format!(
- "{}/api/projects/{}/internal/signals/emit",
- self.base_url, team_id
- );
-
- metrics::counter!(SIGNAL_EMITTED, "source_type" => source_type).increment(1);
-
- match self
- .http
- .post(&url)
- .header("X-Internal-Api-Secret", &self.secret)
- .json(&body)
- .send()
- .await
- {
- Ok(resp) => {
- let status = resp.status().as_u16().to_string();
- metrics::counter!(SIGNAL_EMIT_RESPONSE, "source_type" => source_type, "status" => status).increment(1);
- if !resp.status().is_success() {
- warn!("Signal emit returned status {}", resp.status());
- }
- }
- Err(e) => {
- metrics::counter!(SIGNAL_EMIT_FAILED, "source_type" => source_type).increment(1);
- warn!("Failed to emit signal: {e}");
- }
- }
- }
-}
-
-/// Wraps an optional SignalClient. Signals are best-effort: callers should emit
-/// them after durable side effects, and failures only affect signal metrics/logs.
-#[derive(Clone)]
-pub struct MaybeSignalClient(Option<Arc<SignalClient>>);
-
-impl MaybeSignalClient {
- pub fn disabled() -> Self {
- Self(None)
- }
-
- pub fn enabled(client: SignalClient) -> Self {
- Self(Some(Arc::new(client)))
- }
-
- pub fn emit_issue_created<I>(&self, issue: &I, props: &ProcessedExceptionProperties)
- where
- I: NotificationIssue + Clone + Send + Sync + 'static,
- {
- if let Some(c) = self.0.clone() {
- let issue = issue.clone();
- let props = props.clone();
- tokio::spawn(async move {
- c.emit_issue_created(&issue, &props).await;
- });
- }
- }
-
- pub fn emit_issue_reopened<I>(&self, issue: &I, props: &ProcessedExceptionProperties)
- where
- I: NotificationIssue + Clone + Send + Sync + 'static,
- {
- if let Some(c) = self.0.clone() {
- let issue = issue.clone();
- let props = props.clone();
- tokio::spawn(async move {
- c.emit_issue_reopened(&issue, &props).await;
- });
- }
- }
-
- pub fn emit_issue_spiking<I>(
- &self,
- issue: &I,
- props: &ProcessedExceptionProperties,
- computed_baseline: f64,
- current_bucket_value: f64,
- ) where
- I: NotificationIssue + Clone + Send + Sync + 'static,
- {
- if let Some(c) = self.0.clone() {
- let issue = issue.clone();
- let props = props.clone();
- tokio::spawn(async move {
- c.emit_issue_spiking(&issue, &props, computed_baseline, current_bucket_value)
- .await;
- });
- }
- }
-}
diff --git a/rust/cymbal/src/modes/notifications/stacktrace.rs b/rust/cymbal/src/modes/notifications/stacktrace.rs
deleted file mode 100644
index 7a7d72a4a609..000000000000
--- a/rust/cymbal/src/modes/notifications/stacktrace.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-use crate::frames::Frame;
-use crate::tokenizer::CL100K_BPE;
-use crate::types::ProcessedExceptionProperties;
-
-/// Render exception types, messages, and stack frames as a human-readable string.
-///
-/// If `max_tokens` is `Some(limit)`, the output is measured against `limit`
-/// tokens (using the cl100k_base tiktoken encoding). When the full output
-/// would exceed the limit, only the first and last frame of each exception
-/// are kept with a `...` marker between them. If the truncated output is
-/// still over the limit, the string is hard-truncated to exactly `limit`
-/// tokens.
-pub fn print_stacktrace(props: &ProcessedExceptionProperties, max_tokens: Option<usize>) -> String {
- let full = render_stacktrace(props, false);
-
- let Some(limit) = max_tokens else {
- return full;
- };
-
- let bpe = &*CL100K_BPE;
- let tokens = bpe.encode_with_special_tokens(&full);
-
- if tokens.len() <= limit {
- return full;
- }
-
- let truncated = render_stacktrace(props, true);
- let tokens = bpe.encode_with_special_tokens(&truncated);
-
- if tokens.len() <= limit {
- return truncated;
- }
-
- let mut tokens: Vec<_> = tokens.into_iter().take(limit).collect();
- loop {
- match bpe.decode(tokens.clone()) {
- Ok(text) => break text,
- Err(_) => {
- tokens.pop();
- }
- }
- }
-}
-
-fn render_stacktrace(props: &ProcessedExceptionProperties, truncate: bool) -> String {
- let mut content = String::with_capacity(2048);
-
- for exception in &props.exception_list().0 {
- let type_and_value = format!(
- "{}: {}\n",
- exception.exception_type,
- exception
- .exception_message
- .chars()
- .take(300)
- .collect::<String>()
- );
-
- content.push_str(&type_and_value);
-
- let Some(stack) = &exception.stack else {
- continue;
- };
-
- let frames = stack.get_frames();
-
- if truncate && frames.len() > 2 {
- content.push_str(&render_frame(&frames[0]));
- content.push_str("...\n");
- content.push_str(&render_frame(frames.last().unwrap()));
- } else {
- for frame in frames {
- content.push_str(&render_frame(frame));
- }
- }
- }
-
- content
-}
-
-fn render_frame(frame: &Frame) -> String {
- let mut output = String::new();
-
- if let Some(resolved_name) = &frame.resolved_name {
- output.push_str(resolved_name);
- } else {
- output.push_str(&frame.mangled_name);
- }
-
- if let Some(source) = &frame.source {
- output.push_str(&format!(" in {source}"));
- }
-
- if let Some(line) = frame.line {
- output.push_str(&format!(" line {line}"));
- }
-
- if let Some(column) = frame.column {
- output.push_str(&format!(" column {column}"));
- }
-
- output.push('\n');
- output
-}
diff --git a/rust/cymbal/src/modes/notifications/temporal.rs b/rust/cymbal/src/modes/notifications/temporal.rs
index 9c8a5deb4f26..67ce9d1b84dc 100644
--- a/rust/cymbal/src/modes/notifications/temporal.rs
+++ b/rust/cymbal/src/modes/notifications/temporal.rs
@@ -1,5 +1,3 @@
-use std::collections::HashSet;
-
use chrono::{DateTime, Utc};
use common_temporal::{
StartWorkflowOptions, StartWorkflowOutcome, TemporalClientConfig, TemporalWorkflowClient,
@@ -15,171 +13,76 @@ use crate::modes::notifications::config::NotificationsConfig;
struct WorkflowDefinition {
name: &'static str,
starts_metric: &'static str,
- routes_metric: &'static str,
}
-#[derive(Clone, Copy)]
-enum IssueLifecycleKind {
- Created,
- Reopened,
- Spiking,
-}
-
-impl IssueLifecycleKind {
- const fn workflow(self) -> WorkflowDefinition {
- match self {
- Self::Created => WorkflowDefinition {
- name: "error-tracking-issue-created",
- starts_metric: "cymbal_issue_created_workflow_starts_total",
- routes_metric: "cymbal_issue_created_workflow_routes_total",
- },
- Self::Reopened => WorkflowDefinition {
- name: "error-tracking-issue-reopened",
- starts_metric: "cymbal_issue_reopened_workflow_starts_total",
- routes_metric: "cymbal_issue_reopened_workflow_routes_total",
- },
- Self::Spiking => WorkflowDefinition {
- name: "error-tracking-issue-spiking",
- starts_metric: "cymbal_issue_spiking_workflow_starts_total",
- routes_metric: "cymbal_issue_spiking_workflow_routes_total",
- },
- }
- }
-}
-
-const ISSUE_CREATED_WORKFLOW: WorkflowDefinition = IssueLifecycleKind::Created.workflow();
-const ISSUE_REOPENED_WORKFLOW: WorkflowDefinition = IssueLifecycleKind::Reopened.workflow();
-const ISSUE_SPIKING_WORKFLOW: WorkflowDefinition = IssueLifecycleKind::Spiking.workflow();
-
-#[derive(Clone)]
-struct LifecycleWorkflowRoute {
- enabled_team_ids: Option<HashSet<i32>>,
-}
-
-impl LifecycleWorkflowRoute {
- fn is_enabled_for_team(&self, team_id: i32) -> bool {
- self.enabled_team_ids
- .as_ref()
- .is_none_or(|team_ids| team_ids.contains(&team_id))
- }
-}
+const ISSUE_CREATED_WORKFLOW: WorkflowDefinition = WorkflowDefinition {
+ name: "error-tracking-issue-created",
+ starts_metric: "cymbal_issue_created_workflow_starts_total",
+};
+const ISSUE_REOPENED_WORKFLOW: WorkflowDefinition = WorkflowDefinition {
+ name: "error-tracking-issue-reopened",
+ starts_metric: "cymbal_issue_reopened_workflow_starts_total",
+};
+const ISSUE_SPIKING_WORKFLOW: WorkflowDefinition = WorkflowDefinition {
+ name: "error-tracking-issue-spiking",
+ starts_metric: "cymbal_issue_spiking_workflow_starts_total",
+};
#[derive(Clone)]
pub struct IssueLifecycleWorkflowStarters {
- client: Option<TemporalWorkflowClient>,
+ client: TemporalWorkflowClient,
task_queue: String,
- created: Option<LifecycleWorkflowRoute>,
- reopened: Option<LifecycleWorkflowRoute>,
- spiking: Option<LifecycleWorkflowRoute>,
}
impl IssueLifecycleWorkflowStarters {
- pub fn from_config(
- config: &NotificationsConfig,
- client: Option<&TemporalWorkflowClient>,
- ) -> Result<Self, UnhandledError> {
- let created = build_route(
- config.issue_created_workflow_enabled,
- &config.issue_created_workflow_team_ids,
- "ERROR_TRACKING_ISSUE_CREATED_WORKFLOW_TEAM_IDS",
- )?;
- let reopened = build_route(
- config.issue_reopened_workflow_enabled,
- &config.issue_reopened_workflow_team_ids,
- "ERROR_TRACKING_ISSUE_REOPENED_WORKFLOW_TEAM_IDS",
- )?;
- let spiking = build_route(
- config.issue_spiking_workflow_enabled,
- &config.issue_spiking_workflow_team_ids,
- "ERROR_TRACKING_ISSUE_SPIKING_WORKFLOW_TEAM_IDS",
- )?;
- if (created.is_some() || reopened.is_some() || spiking.is_some()) && client.is_none() {
- return Err(UnhandledError::Other(
- "Temporal client missing for enabled lifecycle workflow".to_string(),
- ));
- }
+ pub async fn from_config(config: &NotificationsConfig) -> Result<Self, UnhandledError> {
+ let client = TemporalWorkflowClient::connect(TemporalClientConfig {
+ host: config.temporal_host.clone(),
+ port: config.temporal_port,
+ namespace: config.temporal_namespace.clone(),
+ client_cert: config.temporal_client_cert.clone(),
+ client_key: config.temporal_client_key.clone(),
+ // Temporal Cloud's server certificate chains to a public CA. Match the
+ // Python workers and use native roots rather than the injected CA,
+ // which is not the server certificate issuer.
+ server_root_ca_cert: None,
+ payload_encryption_key: config.temporal_secret_key.clone(),
+ identity: "cymbal-notifications".to_string(),
+ })
+ .await
+ .map_err(|error| UnhandledError::Other(error.to_string()))?;
Ok(Self {
- client: client.cloned(),
+ client,
task_queue: config.error_tracking_lifecycle_task_queue.clone(),
- created,
- reopened,
- spiking,
})
}
- pub async fn start_created_if_enabled(
- &self,
- notification: &IssueCreated,
- ) -> Result<bool, UnhandledError> {
- if !route_is_enabled(
- &self.created,
- notification.meta.team_id,
- ISSUE_CREATED_WORKFLOW,
- ) {
- return Ok(false);
- }
-
+ pub async fn start_created(&self, notification: &IssueCreated) -> Result<(), UnhandledError> {
self.start(
notification.meta.notification_id,
&IssueCreatedWorkflowInput::from(notification),
ISSUE_CREATED_WORKFLOW,
)
- .await?;
- record_route(ISSUE_CREATED_WORKFLOW, "temporal");
- Ok(true)
+ .await
}
- pub async fn start_reopened_if_enabled(
- &self,
- notification: &IssueReopened,
- ) -> Result<bool, UnhandledError> {
- if !has_event_reference(notification.event_uuid, &notification.event_timestamp) {
- record_route(ISSUE_REOPENED_WORKFLOW, "legacy_missing_event_reference");
- return Ok(false);
- }
- if !route_is_enabled(
- &self.reopened,
- notification.meta.team_id,
- ISSUE_REOPENED_WORKFLOW,
- ) {
- return Ok(false);
- }
-
+ pub async fn start_reopened(&self, notification: &IssueReopened) -> Result<(), UnhandledError> {
self.start(
notification.meta.notification_id,
&IssueReopenedWorkflowInput::from(notification),
ISSUE_REOPENED_WORKFLOW,
)
- .await?;
- record_route(ISSUE_REOPENED_WORKFLOW, "temporal");
- Ok(true)
+ .await
}
- pub async fn start_spiking_if_enabled(
- &self,
- notification: &IssueSpiking,
- ) -> Result<bool, UnhandledError> {
- if !has_event_reference(notification.event_uuid, &notification.event_timestamp) {
- record_route(ISSUE_SPIKING_WORKFLOW, "legacy_missing_event_reference");
- return Ok(false);
- }
- if !route_is_enabled(
- &self.spiking,
- notification.meta.team_id,
- ISSUE_SPIKING_WORKFLOW,
- ) {
- return Ok(false);
- }
-
+ pub async fn start_spiking(&self, notification: &IssueSpiking) -> Result<(), UnhandledError> {
self.start(
notification.meta.notification_id,
&IssueSpikingWorkflowInput::from(notification),
ISSUE_SPIKING_WORKFLOW,
)
- .await?;
- record_route(ISSUE_SPIKING_WORKFLOW, "temporal");
- Ok(true)
+ .await
}
async fn start<T: Serialize>(
@@ -189,12 +92,7 @@ impl IssueLifecycleWorkflowStarters {
workflow: WorkflowDefinition,
) -> Result<(), UnhandledError> {
let options = start_options(notification_id, &self.task_queue, workflow);
- let client = self.client.as_ref().ok_or_else(|| {
- UnhandledError::Other(
- "Temporal client missing for enabled lifecycle workflow".to_string(),
- )
- })?;
- match client.start_workflow(input, &options).await {
+ match self.client.start_workflow(input, &options).await {
Ok(StartWorkflowOutcome::Started { .. }) => {
metrics::counter!(workflow.starts_metric, "outcome" => "started").increment(1);
Ok(())
@@ -215,71 +113,6 @@ impl IssueLifecycleWorkflowStarters {
}
}
-pub async fn build_issue_lifecycle_temporal_client(
- config: &NotificationsConfig,
-) -> Result<Option<TemporalWorkflowClient>, UnhandledError> {
- if !config.issue_created_workflow_enabled
- && !config.issue_reopened_workflow_enabled
- && !config.issue_spiking_workflow_enabled
- {
- return Ok(None);
- }
-
- TemporalWorkflowClient::connect(TemporalClientConfig {
- host: config.temporal_host.clone(),
- port: config.temporal_port,
- namespace: config.temporal_namespace.clone(),
- client_cert: config.temporal_client_cert.clone(),
- client_key: config.temporal_client_key.clone(),
- // Temporal Cloud's server certificate chains to a public CA. Match the
- // Python workers and use native roots rather than the injected CA,
- // which is not the server certificate issuer.
- server_root_ca_cert: None,
- payload_encryption_key: config.temporal_secret_key.clone(),
- identity: "cymbal-notifications".to_string(),
- })
- .await
- .map(Some)
- .map_err(|error| UnhandledError::Other(error.to_string()))
-}
-
-fn build_route(
- enabled: bool,
- team_ids: &str,
- team_ids_env_var: &'static str,
-) -> Result<Option<LifecycleWorkflowRoute>, UnhandledError> {
- if !enabled {
- return Ok(None);
- }
- Ok(Some(LifecycleWorkflowRoute {
- enabled_team_ids: parse_team_ids(team_ids, team_ids_env_var)?,
- }))
-}
-
-fn route_is_enabled(
- route: &Option<LifecycleWorkflowRoute>,
- team_id: i32,
- workflow: WorkflowDefinition,
-) -> bool {
- let Some(route) = route else {
- record_route(workflow, "legacy");
- return false;
- };
- if !route.is_enabled_for_team(team_id) {
- record_route(workflow, "legacy");
- return false;
- }
- true
-}
-
-fn has_event_reference(event_uuid: Uuid, event_timestamp: &str) -> bool {
- !event_uuid.is_nil() && !event_timestamp.is_empty()
-}
-
-fn record_route(workflow: WorkflowDefinition, route: &'static str) {
- metrics::counter!(workflow.routes_metric, "route" => route).increment(1);
-}
-
fn start_options(
notification_id: Uuid,
task_queue: &str,
@@ -390,23 +223,6 @@ fn notification_time(notification_id: Uuid) -> DateTime<Utc> {
.unwrap_or_else(Utc::now)
}
-fn parse_team_ids(
- raw: &str,
- env_var: &'static str,
-) -> Result<Option<HashSet<i32>>, UnhandledError> {
- if raw.trim().is_empty() {
- return Ok(None);
- }
- raw.split(',')
- .map(|value| {
- value.trim().parse::<i32>().map_err(|error| {
- UnhandledError::Other(format!("invalid {env_var} entry {value:?}: {error}"))
- })
- })
- .collect::<Result<HashSet<_>, _>>()
- .map(Some)
-}
-
#[cfg(test)]
mod tests {
use chrono::Utc;
@@ -525,33 +341,4 @@ mod tests {
assert_eq!(options.task_queue, "error-tracking-lifecycle-task-queue");
}
}
-
- #[test]
- fn parses_rollout_team_allowlist() {
- assert_eq!(parse_team_ids("", "TEAM_IDS").unwrap(), None);
- assert_eq!(
- parse_team_ids("42, 43", "TEAM_IDS").unwrap(),
- Some(HashSet::from([42, 43]))
- );
- assert!(parse_team_ids("42,nope", "TEAM_IDS").is_err());
- }
-
- #[test]
- fn lifecycle_routes_support_disabled_global_and_allowlisted_rollouts() {
- assert!(build_route(false, "", "TEAM_IDS").unwrap().is_none());
-
- let global = build_route(true, "", "TEAM_IDS").unwrap().unwrap();
- assert!(global.is_enabled_for_team(42));
-
- let allowlisted = build_route(true, "42,43", "TEAM_IDS").unwrap().unwrap();
- assert!(allowlisted.is_enabled_for_team(42));
- assert!(!allowlisted.is_enabled_for_team(44));
- }
-
- #[test]
- fn reopened_and_spiking_require_event_references() {
- assert!(has_event_reference(Uuid::now_v7(), "2026-07-21T12:00:00Z"));
- assert!(!has_event_reference(Uuid::nil(), "2026-07-21T12:00:00Z"));
- assert!(!has_event_reference(Uuid::now_v7(), ""));
- }
}
diff --git a/rust/cymbal/src/modes/notifications/types.rs b/rust/cymbal/src/modes/notifications/types.rs
deleted file mode 100644
index 4448068f3125..000000000000
--- a/rust/cymbal/src/modes/notifications/types.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-use chrono::{DateTime, Utc};
-use uuid::Uuid;
-
-pub trait NotificationIssue {
- fn id(&self) -> Uuid;
- fn team_id(&self) -> i32;
- fn name(&self) -> Option<&str>;
- fn description(&self) -> Option<&str>;
- fn status(&self) -> &str;
- fn created_at(&self) -> DateTime<Utc>;
-}
-
-#[derive(Debug, Clone, sqlx::FromRow)]
-pub struct IssueNotificationData {
- pub id: Uuid,
- pub team_id: i32,
- pub status: String,
- pub name: Option<String>,
- pub description: Option<String>,
- pub created_at: DateTime<Utc>,
-}
-
-impl NotificationIssue for IssueNotificationData {
- fn id(&self) -> Uuid {
- self.id
- }
-
- fn team_id(&self) -> i32 {
- self.team_id
- }
-
- fn name(&self) -> Option<&str> {
- self.name.as_deref()
- }
-
- fn description(&self) -> Option<&str> {
- self.description.as_deref()
- }
-
- fn status(&self) -> &str {
- match self.status.as_str() {
- "archived" => "Archived",
- "active" => "Active",
- "resolved" => "Resolved",
- "pending_release" => "Pending Release",
- "suppressed" => "Suppressed",
- _ => &self.status,
- }
- }
-
- fn created_at(&self) -> DateTime<Utc> {
- self.created_at
- }
-}