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(error-tracking): migrate reopened notifications to Temporal (#73229)

Hugues Pouillot4d544ba51572
diff --git a/products/error_tracking/backend/temporal/__init__.py b/products/error_tracking/backend/temporal/__init__.py
index c546fe651a99..d1d1b920bce8 100644
--- a/products/error_tracking/backend/temporal/__init__.py
+++ b/products/error_tracking/backend/temporal/__init__.py
@@ -8,6 +8,7 @@ from products.error_tracking.backend.temporal.lifecycle import (
ACTIVITIES as LIFECYCLE_ACTIVITIES,
WORKFLOWS as LIFECYCLE_WORKFLOWS,
ErrorTrackingIssueCreatedWorkflow,
+ ErrorTrackingIssueReopenedWorkflow,
)
from products.error_tracking.backend.temporal.recommendations_refresh import (
ACTIVITIES as RECOMMENDATIONS_REFRESH_ACTIVITIES,
@@ -49,6 +50,7 @@ __all__ = [
"WORKFLOWS",
"ErrorTrackingFingerprintEmbeddingResultWorkflow",
"ErrorTrackingIssueCreatedWorkflow",
+ "ErrorTrackingIssueReopenedWorkflow",
"ErrorTrackingRecommendationsRefreshWorkflow",
"ErrorTrackingSpikeEventCleanupWorkflow",
"ErrorTrackingSymbolSetCleanupWorkflow",
diff --git a/products/error_tracking/backend/temporal/lifecycle/__init__.py b/products/error_tracking/backend/temporal/lifecycle/__init__.py
index 7abe2e3942da..ec472fcf6d62 100644
--- a/products/error_tracking/backend/temporal/lifecycle/__init__.py
+++ b/products/error_tracking/backend/temporal/lifecycle/__init__.py
@@ -3,8 +3,18 @@ from products.error_tracking.backend.temporal.lifecycle.issue_created import (
WORKFLOWS as ISSUE_CREATED_WORKFLOWS,
ErrorTrackingIssueCreatedWorkflow,
)
+from products.error_tracking.backend.temporal.lifecycle.issue_reopened import (
+ ACTIVITIES as ISSUE_REOPENED_ACTIVITIES,
+ WORKFLOWS as ISSUE_REOPENED_WORKFLOWS,
+ ErrorTrackingIssueReopenedWorkflow,
+)
-WORKFLOWS = ISSUE_CREATED_WORKFLOWS
-ACTIVITIES = ISSUE_CREATED_ACTIVITIES
+WORKFLOWS = ISSUE_CREATED_WORKFLOWS + ISSUE_REOPENED_WORKFLOWS
+ACTIVITIES = ISSUE_CREATED_ACTIVITIES + ISSUE_REOPENED_ACTIVITIES
-__all__ = ["ACTIVITIES", "WORKFLOWS", "ErrorTrackingIssueCreatedWorkflow"]
+__all__ = [
+ "ACTIVITIES",
+ "WORKFLOWS",
+ "ErrorTrackingIssueCreatedWorkflow",
+ "ErrorTrackingIssueReopenedWorkflow",
+]
diff --git a/products/error_tracking/backend/temporal/lifecycle/event_properties.py b/products/error_tracking/backend/temporal/lifecycle/event_properties.py
new file mode 100644
index 000000000000..6306349de258
--- /dev/null
+++ b/products/error_tracking/backend/temporal/lifecycle/event_properties.py
@@ -0,0 +1,138 @@
+import json
+from datetime import UTC
+from typing import Protocol
+
+from django.conf import settings
+from django.utils.dateparse import parse_datetime
+
+from prometheus_client import Counter, Histogram
+from redis.exceptions import RedisError
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.client.connection import ClickHouseUser, Workload
+from posthog.models import Team
+from posthog.redis import get_client
+
+ERROR_TRACKING_EVENT_PROPERTIES_KEY_PREFIX = "error_tracking:event_properties:v1"
+
+ERROR_TRACKING_EVENT_PROPERTIES_READS = Counter(
+ "error_tracking_event_properties_reads_total",
+ "Error Tracking event property reads by storage source and outcome",
+ labelnames=("source", "outcome"),
+)
+ERROR_TRACKING_EVENT_PROPERTIES_READ_DURATION = Histogram(
+ "error_tracking_event_properties_read_duration_seconds",
+ "Duration of Error Tracking event property reads by storage source",
+ labelnames=("source",),
+)
+
+
+class IssueCreatedEventNotFoundError(RuntimeError):
+ pass
+
+
+class EventPropertiesIssueSnapshot(Protocol):
+ @property
+ def created_at(self) -> str: ...
+
+
+class EventPropertiesWorkflowInputs(Protocol):
+ @property
+ def team_id(self) -> int: ...
+
+ @property
+ def event_uuid(self) -> str: ...
+
+ @property
+ def event_timestamp(self) -> str: ...
+
+ @property
+ def issue(self) -> EventPropertiesIssueSnapshot: ...
+
+
+def error_tracking_event_properties_key(team_id: int, event_uuid: str) -> str:
+ return f"{ERROR_TRACKING_EVENT_PROPERTIES_KEY_PREFIX}:{team_id}:{event_uuid}"
+
+
+def _fetch_event_properties_from_valkey(inputs: EventPropertiesWorkflowInputs) -> dict[str, object] | None:
+ redis_url = settings.ERROR_TRACKING_EVENT_PROPERTIES_REDIS_URL
+ if not redis_url:
+ ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="valkey", outcome="not_configured").inc()
+ return None
+
+ key = error_tracking_event_properties_key(inputs.team_id, inputs.event_uuid)
+ try:
+ with ERROR_TRACKING_EVENT_PROPERTIES_READ_DURATION.labels(source="valkey").time():
+ payload = get_client(redis_url).get(key)
+ except RedisError:
+ ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="valkey", outcome="error").inc()
+ return None
+
+ if payload is None:
+ ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="valkey", outcome="miss").inc()
+ return None
+
+ try:
+ properties = json.loads(payload)
+ except (json.JSONDecodeError, TypeError, UnicodeDecodeError):
+ ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="valkey", outcome="invalid_payload").inc()
+ return None
+
+ if not isinstance(properties, dict):
+ ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="valkey", outcome="invalid_payload").inc()
+ return None
+
+ ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="valkey", outcome="hit").inc()
+ return properties
+
+
+def _fetch_event_properties_from_clickhouse(team: Team, inputs: EventPropertiesWorkflowInputs) -> dict[str, object]:
+ event_timestamp = parse_datetime(inputs.event_timestamp) or parse_datetime(inputs.issue.created_at)
+ if event_timestamp is None:
+ raise ValueError(f"Invalid exception timestamp: {inputs.event_timestamp}")
+ if event_timestamp.tzinfo is None:
+ event_timestamp = event_timestamp.replace(tzinfo=UTC)
+
+ query = parse_select(
+ """
+ SELECT properties
+ FROM events
+ WHERE uuid = {event_uuid}
+ AND timestamp >= {event_timestamp} - INTERVAL 1 MINUTE
+ AND timestamp <= {event_timestamp} + INTERVAL 1 MINUTE
+ LIMIT 1
+ """,
+ placeholders={
+ "event_uuid": ast.Constant(value=inputs.event_uuid),
+ "event_timestamp": ast.Constant(value=event_timestamp),
+ },
+ )
+ with ERROR_TRACKING_EVENT_PROPERTIES_READ_DURATION.labels(source="clickhouse").time():
+ response = execute_hogql_query(
+ query=query,
+ team=team,
+ query_type="ErrorTrackingIssueCreatedEventProperties",
+ workload=Workload.OFFLINE,
+ ch_user=ClickHouseUser.ERROR_TRACKING,
+ )
+ if not response.results:
+ ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="clickhouse", outcome="miss").inc()
+ raise IssueCreatedEventNotFoundError(f"Exception event {inputs.event_uuid} not found for team {inputs.team_id}")
+
+ properties = response.results[0][0]
+ if isinstance(properties, str):
+ properties = json.loads(properties)
+ if not isinstance(properties, dict):
+ raise TypeError(f"Exception event {inputs.event_uuid} returned invalid properties")
+ ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="clickhouse", outcome="hit").inc()
+ return properties
+
+
+def fetch_event_properties(team: Team, inputs: EventPropertiesWorkflowInputs) -> dict[str, object]:
+ properties = _fetch_event_properties_from_valkey(inputs)
+ if properties is not None:
+ return properties
+ return _fetch_event_properties_from_clickhouse(team, inputs)
diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py
index 74d140c8b6e9..b8e1162a4e9a 100644
--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py
+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py
@@ -1,38 +1,20 @@
import json
-from datetime import UTC, datetime
-from typing import cast
+from datetime import UTC
-from django.conf import settings
from django.utils.dateparse import parse_datetime
import httpx
import requests
-import tiktoken
import structlog
import posthoganalytics
-from asgiref.sync import sync_to_async
-from confluent_kafka import KafkaError, KafkaException
-from prometheus_client import Counter, Histogram
-from redis.exceptions import RedisError
+from prometheus_client import Counter
from temporalio import activity
from temporalio.exceptions import ApplicationError
-from posthog.hogql import ast
-from posthog.hogql.parser import parse_select
-from posthog.hogql.query import execute_hogql_query
-
from posthog.api.embedding_worker import generate_embedding
-from posthog.cdp.internal_events import InternalEventEvent, flush_internal_events_producer, produce_internal_event
-from posthog.clickhouse.client.connection import ClickHouseUser, Workload
-from posthog.helpers.tiktoken_encoding import (
- LLM_TOKEN_COUNT_PROXY_MODEL,
- TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL,
- get_tiktoken_encoding_for_model,
-)
from posthog.kafka_client.routing import producer_scope
from posthog.kafka_client.topics import KAFKA_DOCUMENT_EMBEDDINGS_TOPIC
from posthog.models import Team
-from posthog.redis import get_client
from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import close_db_connections
@@ -41,34 +23,27 @@ from products.error_tracking.backend.temporal.fingerprint_embedding_result.types
FingerprintEmbeddingMergeResult,
FingerprintEmbeddingResultInputs,
)
+from products.error_tracking.backend.temporal.lifecycle.event_properties import fetch_event_properties
from products.error_tracking.backend.temporal.lifecycle.issue_created.types import (
EMBEDDING_SERVICE_UNAVAILABLE_ERROR_TYPE,
GeneratedIssueEmbedding,
IssueCreatedWorkflowInputs,
IssueEmbeddingPreparationResult,
)
-from products.signals.backend.facade.api import emit_signal
+from products.error_tracking.backend.temporal.lifecycle.rendering import render_stacktrace
+from products.error_tracking.backend.temporal.lifecycle.side_effects import (
+ KAFKA_DELIVERY_TIMEOUT_SECONDS,
+ emit_issue_lifecycle_signal,
+ produce_issue_lifecycle_internal_event,
+)
logger = structlog.get_logger(__name__)
EMBEDDING_MODEL = "text-embedding-3-large-3072"
EMBEDDING_RENDERING = "type_message_and_stack"
EMBEDDING_MAX_TOKENS = 7000
-SIGNAL_MAX_TOKENS = 8000
-KAFKA_DELIVERY_TIMEOUT_SECONDS = 30
EMBEDDING_DISABLED_LIBRARIES = {"posthog-elixir"}
-ERROR_TRACKING_EVENT_PROPERTIES_KEY_PREFIX = "error_tracking:event_properties:v1"
-ERROR_TRACKING_EVENT_PROPERTIES_READS = Counter(
- "error_tracking_event_properties_reads_total",
- "Error Tracking event property reads by storage source and outcome",
- labelnames=("source", "outcome"),
-)
-ERROR_TRACKING_EVENT_PROPERTIES_READ_DURATION = Histogram(
- "error_tracking_event_properties_read_duration_seconds",
- "Duration of Error Tracking event property reads by storage source",
- labelnames=("source",),
-)
ERROR_TRACKING_EMBEDDING_UNAVAILABLE = Counter(
"error_tracking_issue_created_embedding_unavailable_total",
"Issue-created embedding attempts that failed because the embedding service was unavailable",
@@ -76,97 +51,17 @@ ERROR_TRACKING_EMBEDDING_UNAVAILABLE = Counter(
)
-class IssueCreatedEventNotFoundError(RuntimeError):
- pass
-
-
-def _as_dict(value: object) -> dict[str, object] | None:
- return cast(dict[str, object], value) if isinstance(value, dict) else None
-
-
-def _as_list(value: object) -> list[object]:
- return cast(list[object], value) if isinstance(value, list) else []
-
-
-def _string(value: object, default: str = "") -> str:
- return value if isinstance(value, str) else default
-
-
-def _render_frame(value: object) -> str:
- frame = _as_dict(value)
- if frame is None:
- return ""
-
- resolved_name = frame.get("resolved_name")
- function = resolved_name if isinstance(resolved_name, str) else _string(frame.get("mangled_name"))
- source = frame.get("source")
- line = frame.get("line")
- column = frame.get("column")
-
- rendered = function
- if isinstance(source, str):
- rendered += f" in {source}"
- if isinstance(line, int):
- rendered += f" line {line}"
- if isinstance(column, int):
- rendered += f" column {column}"
- return f"{rendered}\n"
-
-
-def _render_stacktrace_unbounded(event_properties: dict[str, object], truncate_frames: bool) -> str:
- rendered: list[str] = []
- for value in _as_list(event_properties.get("$exception_list")):
- exception = _as_dict(value)
- if exception is None:
- continue
-
- exception_type = _string(exception.get("type"), "Unknown")
- exception_value = _string(exception.get("value"))[:300]
- rendered.append(f"{exception_type}: {exception_value}\n")
-
- stacktrace = _as_dict(exception.get("stacktrace"))
- frames = _as_list(stacktrace.get("frames")) if stacktrace and stacktrace.get("type") == "resolved" else []
- if truncate_frames and len(frames) > 2:
- rendered.extend((_render_frame(frames[0]), "...\n", _render_frame(frames[-1])))
- else:
- rendered.extend(_render_frame(frame) for frame in frames)
-
- return "".join(rendered)
-
-
-def _decode_token_prefix(encoding: tiktoken.Encoding, tokens: list[int], max_tokens: int) -> str:
- prefix = tokens[:max_tokens]
- while prefix:
- try:
- return encoding.decode(prefix, errors="strict")
- except UnicodeDecodeError:
- prefix.pop()
- return ""
-
-
-def render_stacktrace(event_properties: dict[str, object], max_tokens: int) -> str:
- encoding = get_tiktoken_encoding_for_model(TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL)
- rendered = _render_stacktrace_unbounded(event_properties, truncate_frames=False)
- tokens = encoding.encode(rendered, allowed_special="all")
- if len(tokens) <= max_tokens:
- return rendered
-
- rendered = _render_stacktrace_unbounded(event_properties, truncate_frames=True)
- tokens = encoding.encode(rendered, allowed_special="all")
- if len(tokens) <= max_tokens:
- return rendered
-
- return _decode_token_prefix(encoding, tokens, max_tokens)
-
-
def _embedding_skip_reason(event_properties: dict[str, object]) -> str | None:
- for value in _as_list(event_properties.get("$exception_fingerprint_record")):
- record = _as_dict(value)
- record_type = _string(record.get("type")) if record else ""
- if record_type == "manual":
- return "manual_fingerprint"
- if record_type == "custom":
- return "custom_grouping_rule"
+ fingerprint_record = event_properties.get("$exception_fingerprint_record")
+ if isinstance(fingerprint_record, list):
+ for value in fingerprint_record:
+ if not isinstance(value, dict):
+ continue
+ record_type = value.get("type")
+ if record_type == "manual":
+ return "manual_fingerprint"
+ if record_type == "custom":
+ return "custom_grouping_rule"
library = event_properties.get("$lib")
if isinstance(library, str) and library in EMBEDDING_DISABLED_LIBRARIES:
@@ -174,91 +69,6 @@ def _embedding_skip_reason(event_properties: dict[str, object]) -> str | None:
return None
-def error_tracking_event_properties_key(team_id: int, event_uuid: str) -> str:
- return f"{ERROR_TRACKING_EVENT_PROPERTIES_KEY_PREFIX}:{team_id}:{event_uuid}"
-
-
-def _fetch_event_properties_from_valkey(inputs: IssueCreatedWorkflowInputs) -> dict[str, object] | None:
- redis_url = settings.ERROR_TRACKING_EVENT_PROPERTIES_REDIS_URL
- if not redis_url:
- ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="valkey", outcome="not_configured").inc()
- return None
-
- key = error_tracking_event_properties_key(inputs.team_id, inputs.event_uuid)
- try:
- with ERROR_TRACKING_EVENT_PROPERTIES_READ_DURATION.labels(source="valkey").time():
- payload = get_client(redis_url).get(key)
- except RedisError:
- ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="valkey", outcome="error").inc()
- return None
-
- if payload is None:
- ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="valkey", outcome="miss").inc()
- return None
-
- try:
- properties = json.loads(payload)
- except (json.JSONDecodeError, TypeError, UnicodeDecodeError):
- ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="valkey", outcome="invalid_payload").inc()
- return None
-
- if not isinstance(properties, dict):
- ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="valkey", outcome="invalid_payload").inc()
- return None
-
- ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="valkey", outcome="hit").inc()
- return properties
-
-
-def _fetch_event_properties_from_clickhouse(team: Team, inputs: IssueCreatedWorkflowInputs) -> dict[str, object]:
- event_timestamp = parse_datetime(inputs.event_timestamp) or parse_datetime(inputs.issue.created_at)
- if event_timestamp is None:
- raise ValueError(f"Invalid exception timestamp: {inputs.event_timestamp}")
- if event_timestamp.tzinfo is None:
- event_timestamp = event_timestamp.replace(tzinfo=UTC)
-
- query = parse_select(
- """
- SELECT properties
- FROM events
- WHERE uuid = {event_uuid}
- AND timestamp >= {event_timestamp} - INTERVAL 1 MINUTE
- AND timestamp <= {event_timestamp} + INTERVAL 1 MINUTE
- LIMIT 1
- """,
- placeholders={
- "event_uuid": ast.Constant(value=inputs.event_uuid),
- "event_timestamp": ast.Constant(value=event_timestamp),
- },
- )
- with ERROR_TRACKING_EVENT_PROPERTIES_READ_DURATION.labels(source="clickhouse").time():
- response = execute_hogql_query(
- query=query,
- team=team,
- query_type="ErrorTrackingIssueCreatedEventProperties",
- workload=Workload.OFFLINE,
- ch_user=ClickHouseUser.ERROR_TRACKING,
- )
- if not response.results:
- ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="clickhouse", outcome="miss").inc()
- raise IssueCreatedEventNotFoundError(f"Exception event {inputs.event_uuid} not found for team {inputs.team_id}")
-
- properties = response.results[0][0]
- if isinstance(properties, str):
- properties = json.loads(properties)
- if not isinstance(properties, dict):
- raise TypeError(f"Exception event {inputs.event_uuid} returned invalid properties")
- ERROR_TRACKING_EVENT_PROPERTIES_READS.labels(source="clickhouse", outcome="hit").inc()
- return properties
-
-
-def _fetch_event_properties(team: Team, inputs: IssueCreatedWorkflowInputs) -> dict[str, object]:
- properties = _fetch_event_properties_from_valkey(inputs)
- if properties is not None:
- return properties
- return _fetch_event_properties_from_clickhouse(team, inputs)
-
-
def _embedding_unavailable_error(inputs: IssueCreatedWorkflowInputs, reason: str, message: str) -> ApplicationError:
# A short embedding-service outage is expected and already tolerated — the workflow retries then
# fails open. Log and count it here so the outage is still observable, but leave capture to the
@@ -285,7 +95,7 @@ def _prepare_issue_created_embedding(inputs: IssueCreatedWorkflowInputs) -> Issu
skipped_reason="ai_data_processing_not_approved",
)
- event_properties = _fetch_event_properties(team, inputs)
+ event_properties = fetch_event_properties(team, inputs)
skipped_reason = _embedding_skip_reason(event_properties)
if skipped_reason is not None:
return IssueEmbeddingPreparationResult(team_exists=True, skipped_reason=skipped_reason)
@@ -388,97 +198,26 @@ def merge_issue_created_fingerprint_activity(
)
-def _produce_issue_created_internal_event(
- inputs: IssueCreatedWorkflowInputs, event_properties: dict[str, object]
-) -> None:
- exception_timestamp = parse_datetime(inputs.event_timestamp)
- if exception_timestamp is None:
- exception_timestamp = datetime.now(UTC)
- elif exception_timestamp.tzinfo is None:
- exception_timestamp = exception_timestamp.replace(tzinfo=UTC)
-
- properties: dict[str, object] = {
- "name": inputs.issue.name,
- "description": inputs.issue.description,
- "issue_description": inputs.issue.description,
- "first_seen": inputs.issue.created_at,
- "status": inputs.issue.status,
- "fingerprint": inputs.fingerprint,
- "exception_timestamp": exception_timestamp.isoformat(),
- "exception_props": event_properties,
- }
- if inputs.assignee is not None:
- properties["assignee"] = inputs.assignee
-
- def produce(event_properties: dict[str, object]) -> None:
- result = produce_internal_event(
- inputs.team_id,
- InternalEventEvent(
- event="$error_tracking_issue_created",
- distinct_id=inputs.issue_id,
- properties=event_properties,
- uuid=inputs.notification_id,
- ),
- )
- flush_internal_events_producer(KAFKA_DELIVERY_TIMEOUT_SECONDS)
- result.get(timeout=0)
-
- try:
- produce(properties)
- except KafkaException as error:
- kafka_error = error.args[0] if error.args else None
- if not isinstance(kafka_error, KafkaError) or kafka_error.name() != "MSG_SIZE_TOO_LARGE":
- raise
- properties.pop("exception_props", None)
- properties["message_was_too_large"] = True
- produce(properties)
-
-
@activity.defn
@posthoganalytics.scoped()
@close_db_connections
def emit_issue_created_internal_event_activity(inputs: IssueCreatedWorkflowInputs) -> None:
- try:
- team = Team.objects.get(id=inputs.team_id)
- except Team.DoesNotExist:
- return
-
- event_properties = _fetch_event_properties(team, inputs)
- _produce_issue_created_internal_event(inputs, event_properties)
+ produce_issue_lifecycle_internal_event(
+ inputs,
+ event="$error_tracking_issue_created",
+ exception_timestamp=inputs.event_timestamp,
+ humanize_status=False,
+ )
@activity.defn
@scoped_temporal()
@close_db_connections
async def emit_issue_created_signal_activity(inputs: IssueCreatedWorkflowInputs) -> None:
- try:
- team = await Team.objects.aget(id=inputs.team_id)
- except Team.DoesNotExist:
- return
-
- event_properties = await sync_to_async(_fetch_event_properties, thread_sensitive=False)(team, inputs)
- issue_name = inputs.issue.name or "Unknown"
- issue_description = inputs.issue.description or ""
- preamble = "New error tracking issue created - this particular exception was observed for the first time"
- header = f"{preamble}:\n{issue_name}: {issue_description}\n"
- encoding = get_tiktoken_encoding_for_model(TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL)
- stacktrace_tokens = max(SIGNAL_MAX_TOKENS - len(encoding.encode(header)), 0)
- stacktrace = render_stacktrace(event_properties, stacktrace_tokens)
- description = f"{header}\n```\n{stacktrace}\n```"
- signal_encoding = get_tiktoken_encoding_for_model(LLM_TOKEN_COUNT_PROXY_MODEL)
- signal_tokens = signal_encoding.encode(description)
- if len(signal_tokens) > SIGNAL_MAX_TOKENS:
- description = _decode_token_prefix(signal_encoding, signal_tokens, SIGNAL_MAX_TOKENS)
-
- await emit_signal(
- team=team,
- source_product="error_tracking",
+ await emit_issue_lifecycle_signal(
+ inputs,
source_type="issue_created",
- source_id=inputs.issue_id,
- description=description,
- weight=1.0,
- extra={"fingerprint": inputs.fingerprint},
- idempotency_key=inputs.notification_id,
+ preamble="New error tracking issue created - this particular exception was observed for the first time",
)
diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/test/test_workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/test/test_workflow.py
index 16e666da3952..cedd0c067996 100644
--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/test/test_workflow.py
+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/test/test_workflow.py
@@ -20,12 +20,12 @@ from products.error_tracking.backend.temporal.fingerprint_embedding_result.types
FingerprintEmbeddingMergeResult,
FingerprintEmbeddingResultInputs,
)
-from products.error_tracking.backend.temporal.lifecycle.issue_created.activities import (
- _decode_token_prefix,
- _fetch_event_properties,
+from products.error_tracking.backend.temporal.lifecycle.event_properties import (
error_tracking_event_properties_key,
+ fetch_event_properties,
+)
+from products.error_tracking.backend.temporal.lifecycle.issue_created.activities import (
generate_issue_created_embedding_activity,
- render_stacktrace,
)
from products.error_tracking.backend.temporal.lifecycle.issue_created.types import (
EMBEDDING_SERVICE_UNAVAILABLE_ERROR_TYPE,
@@ -36,6 +36,7 @@ from products.error_tracking.backend.temporal.lifecycle.issue_created.types impo
IssueEmbeddingPreparationResult,
)
from products.error_tracking.backend.temporal.lifecycle.issue_created.workflow import ErrorTrackingIssueCreatedWorkflow
+from products.error_tracking.backend.temporal.lifecycle.rendering import decode_token_prefix, render_stacktrace
def _inputs(fingerprint: str) -> IssueCreatedWorkflowInputs:
@@ -72,7 +73,7 @@ def test_decode_token_prefix_does_not_emit_replacement_characters() -> None:
tokens = encoding.encode("hello 💥")
assert encoding.decode(tokens[:2]) == "hello �"
- assert _decode_token_prefix(encoding, tokens, max_tokens=2) == "hello"
+ assert decode_token_prefix(encoding, tokens, max_tokens=2) == "hello"
def test_stacktrace_rendering_matches_cymbal_embedding_content() -> None:
@@ -131,7 +132,7 @@ def test_stacktrace_rendering_matches_cymbal_embedding_content() -> None:
)
@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.posthoganalytics.capture_exception")
@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.render_stacktrace")
-@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities._fetch_event_properties")
+@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.fetch_event_properties")
@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.Team.objects.get")
@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.generate_embedding")
def test_embedding_failure_classification_and_capture(
@@ -159,8 +160,8 @@ def test_embedding_failure_classification_and_capture(
@override_settings(ERROR_TRACKING_EVENT_PROPERTIES_REDIS_URL="redis://event-properties")
-@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.execute_hogql_query")
-@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.get_client")
+@patch("products.error_tracking.backend.temporal.lifecycle.event_properties.execute_hogql_query")
+@patch("products.error_tracking.backend.temporal.lifecycle.event_properties.get_client")
def test_fetches_full_event_properties_from_valkey_without_clickhouse(
get_client: MagicMock, execute_hogql_query: MagicMock
) -> None:
@@ -171,14 +172,14 @@ def test_fetches_full_event_properties_from_valkey_without_clickhouse(
}
get_client.return_value.get.return_value = json.dumps(properties, ensure_ascii=False).encode()
- assert _fetch_event_properties(MagicMock(), inputs) == properties
+ assert fetch_event_properties(MagicMock(), inputs) == properties
get_client.return_value.get.assert_called_once_with(error_tracking_event_properties_key(1, inputs.event_uuid))
execute_hogql_query.assert_not_called()
@override_settings(ERROR_TRACKING_EVENT_PROPERTIES_REDIS_URL="redis://event-properties")
-@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.execute_hogql_query")
-@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.get_client")
+@patch("products.error_tracking.backend.temporal.lifecycle.event_properties.execute_hogql_query")
+@patch("products.error_tracking.backend.temporal.lifecycle.event_properties.get_client")
def test_falls_back_to_clickhouse_when_valkey_payload_expired(
get_client: MagicMock, execute_hogql_query: MagicMock
) -> None:
@@ -187,7 +188,7 @@ def test_falls_back_to_clickhouse_when_valkey_payload_expired(
get_client.return_value.get.return_value = None
execute_hogql_query.return_value = SimpleNamespace(results=[[json.dumps(properties)]])
- assert _fetch_event_properties(MagicMock(), inputs) == properties
+ assert fetch_event_properties(MagicMock(), inputs) == properties
execute_hogql_query.assert_called_once()
diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/types.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/types.py
index 6d37992ee18e..5400e5af8923 100644
--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/types.py
+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/types.py
@@ -1,16 +1,12 @@
import dataclasses
from products.error_tracking.backend.temporal.fingerprint_embedding_result.types import FingerprintEmbeddingResultInputs
+from products.error_tracking.backend.temporal.lifecycle.types import LifecycleIssueSnapshot
EMBEDDING_SERVICE_UNAVAILABLE_ERROR_TYPE = "EmbeddingServiceUnavailable"
[email protected](frozen=True)
-class IssueCreatedSnapshot:
- name: str | None
- description: str | None
- status: str
- created_at: str
+IssueCreatedSnapshot = LifecycleIssueSnapshot
@dataclasses.dataclass(frozen=True)
@@ -18,7 +14,7 @@ class IssueCreatedWorkflowInputs:
notification_id: str
team_id: int
issue_id: str
- issue: IssueCreatedSnapshot
+ issue: LifecycleIssueSnapshot
fingerprint: str
event_uuid: str
event_timestamp: str
diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/__init__.py b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/__init__.py
new file mode 100644
index 000000000000..58d062e4faa1
--- /dev/null
+++ b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/__init__.py
@@ -0,0 +1,19 @@
+from products.error_tracking.backend.temporal.lifecycle.issue_reopened.activities import (
+ ACTIVITIES as ISSUE_REOPENED_ACTIVITIES,
+ emit_issue_reopened_internal_event_activity,
+ emit_issue_reopened_signal_activity,
+)
+from products.error_tracking.backend.temporal.lifecycle.issue_reopened.workflow import (
+ ErrorTrackingIssueReopenedWorkflow,
+)
+
+WORKFLOWS = [ErrorTrackingIssueReopenedWorkflow]
+ACTIVITIES = ISSUE_REOPENED_ACTIVITIES
+
+__all__ = [
+ "ACTIVITIES",
+ "WORKFLOWS",
+ "ErrorTrackingIssueReopenedWorkflow",
+ "emit_issue_reopened_internal_event_activity",
+ "emit_issue_reopened_signal_activity",
+]
diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/activities.py b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/activities.py
new file mode 100644
index 000000000000..e311fbfafd18
--- /dev/null
+++ b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/activities.py
@@ -0,0 +1,42 @@
+import posthoganalytics
+from temporalio import activity
+
+from posthog.temporal.common.scoped import scoped_temporal
+from posthog.temporal.common.utils import close_db_connections
+
+from products.error_tracking.backend.temporal.lifecycle.issue_reopened.types import IssueReopenedWorkflowInputs
+from products.error_tracking.backend.temporal.lifecycle.side_effects import (
+ emit_issue_lifecycle_signal,
+ produce_issue_lifecycle_internal_event,
+)
+
+
+@close_db_connections
+def emit_issue_reopened_internal_event_activity(inputs: IssueReopenedWorkflowInputs) -> None:
+ produce_issue_lifecycle_internal_event(
+ inputs,
+ event="$error_tracking_issue_reopened",
+ exception_timestamp=inputs.event_timestamp,
+ )
+
+
+@scoped_temporal()
+@close_db_connections
+async def emit_issue_reopened_signal_activity(inputs: IssueReopenedWorkflowInputs) -> None:
+ await emit_issue_lifecycle_signal(
+ inputs,
+ 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"
+ ),
+ )
+
+
+ACTIVITIES = [
+ emit_issue_reopened_internal_event_activity,
+ emit_issue_reopened_signal_activity,
+]
diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/test/test_issue_reopened_workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/test/test_issue_reopened_workflow.py
new file mode 100644
index 000000000000..8884c5aa67d7
--- /dev/null
+++ b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/test/test_issue_reopened_workflow.py
@@ -0,0 +1,87 @@
+import json
+import uuid
+import dataclasses
+
+import pytest
+
+from temporalio import activity
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from products.error_tracking.backend.temporal.lifecycle.issue_reopened.types import (
+ IssueReopenedSnapshot,
+ IssueReopenedWorkflowInputs,
+ IssueReopenedWorkflowResult,
+)
+from products.error_tracking.backend.temporal.lifecycle.issue_reopened.workflow import (
+ ErrorTrackingIssueReopenedWorkflow,
+)
+
+
+def _inputs() -> IssueReopenedWorkflowInputs:
+ return IssueReopenedWorkflowInputs(
+ notification_id=str(uuid.uuid4()),
+ team_id=1,
+ issue_id=str(uuid.uuid4()),
+ issue=IssueReopenedSnapshot(
+ name="TypeError",
+ description="Something failed",
+ status="active",
+ created_at="2026-07-21T12:00:00Z",
+ ),
+ fingerprint="fingerprint",
+ event_uuid=str(uuid.uuid4()),
+ event_timestamp="2026-07-21T12:00:00Z",
+ )
+
+
+def test_parse_inputs_accepts_cymbal_issue_reopened_notification() -> None:
+ inputs = _inputs()
+ payload = {
+ **dataclasses.asdict(inputs),
+ "type": "issue_reopened",
+ "event_properties": {"$exception_list": [{"type": "TypeError", "value": "boom"}]},
+ }
+
+ assert ErrorTrackingIssueReopenedWorkflow.parse_inputs([json.dumps(payload)]) == inputs
+
+
+async def test_retries_and_emits_both_reopened_side_effects() -> None:
+ emitted_events: list[str] = []
+ emitted_signals: list[str] = []
+ signal_attempts = 0
+
+ @activity.defn(name="emit_issue_reopened_internal_event_activity")
+ async def emit_event(inputs: IssueReopenedWorkflowInputs) -> None:
+ emitted_events.append(inputs.issue_id)
+
+ @activity.defn(name="emit_issue_reopened_signal_activity")
+ async def emit_signal(inputs: IssueReopenedWorkflowInputs) -> None:
+ nonlocal signal_attempts
+ signal_attempts += 1
+ if signal_attempts == 1:
+ raise RuntimeError("transient signal failure")
+ emitted_signals.append(inputs.issue_id)
+
+ task_queue = str(uuid.uuid4())
+ inputs = _inputs()
+ async with await WorkflowEnvironment.start_time_skipping() as environment:
+ async with Worker(
+ environment.client,
+ task_queue=task_queue,
+ workflows=[ErrorTrackingIssueReopenedWorkflow],
+ activities=[emit_event, emit_signal],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ result = await environment.client.execute_workflow(
+ ErrorTrackingIssueReopenedWorkflow.run,
+ inputs,
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+
+ assert result == IssueReopenedWorkflowResult(notified=True)
+ assert emitted_events == [inputs.issue_id]
+ assert emitted_signals == [inputs.issue_id]
+ assert signal_attempts == 2
diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/types.py b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/types.py
new file mode 100644
index 000000000000..73c98e57dacb
--- /dev/null
+++ b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/types.py
@@ -0,0 +1,22 @@
+import dataclasses
+
+from products.error_tracking.backend.temporal.lifecycle.types import LifecycleIssueSnapshot
+
+IssueReopenedSnapshot = LifecycleIssueSnapshot
+
+
[email protected](frozen=True)
+class IssueReopenedWorkflowInputs:
+ notification_id: str
+ team_id: int
+ issue_id: str
+ issue: LifecycleIssueSnapshot
+ fingerprint: str
+ event_uuid: str
+ event_timestamp: str
+ assignee: str | None = None
+
+
[email protected](frozen=True)
+class IssueReopenedWorkflowResult:
+ notified: bool = False
diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/workflow.py
new file mode 100644
index 000000000000..008d25f916cb
--- /dev/null
+++ b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/workflow.py
@@ -0,0 +1,54 @@
+import json
+from datetime import timedelta
+
+from temporalio import common, workflow
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+from products.error_tracking.backend.temporal.lifecycle.issue_reopened.types import (
+ IssueReopenedSnapshot,
+ IssueReopenedWorkflowInputs,
+ IssueReopenedWorkflowResult,
+)
+
+WORKFLOW_NAME = "error-tracking-issue-reopened"
+
+ACTIVITY_RETRY_POLICY = common.RetryPolicy(
+ initial_interval=timedelta(seconds=1),
+ maximum_interval=timedelta(seconds=15),
+ maximum_attempts=10,
+)
+ACTIVITY_START_TO_CLOSE_TIMEOUT = timedelta(minutes=5)
+
+
[email protected](name=WORKFLOW_NAME)
+class ErrorTrackingIssueReopenedWorkflow(PostHogWorkflow):
+ @staticmethod
+ def workflow_id_for(notification_id: str) -> str:
+ return f"{WORKFLOW_NAME}-{notification_id}"
+
+ @staticmethod
+ def parse_inputs(inputs: list[str]) -> IssueReopenedWorkflowInputs:
+ if len(inputs) != 1:
+ raise ValueError("Issue reopened workflow requires exactly one input")
+ data = json.loads(inputs[0])
+ data.pop("type", None)
+ data.pop("event_properties", None)
+ data["issue"] = IssueReopenedSnapshot(**data["issue"])
+ return IssueReopenedWorkflowInputs(**data)
+
+ @workflow.run
+ async def run(self, inputs: IssueReopenedWorkflowInputs) -> IssueReopenedWorkflowResult:
+ await workflow.execute_activity(
+ "emit_issue_reopened_internal_event_activity",
+ inputs,
+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+ await workflow.execute_activity(
+ "emit_issue_reopened_signal_activity",
+ inputs,
+ start_to_close_timeout=ACTIVITY_START_TO_CLOSE_TIMEOUT,
+ retry_policy=ACTIVITY_RETRY_POLICY,
+ )
+ return IssueReopenedWorkflowResult(notified=True)
diff --git a/products/error_tracking/backend/temporal/lifecycle/rendering.py b/products/error_tracking/backend/temporal/lifecycle/rendering.py
new file mode 100644
index 000000000000..80957c389ae5
--- /dev/null
+++ b/products/error_tracking/backend/temporal/lifecycle/rendering.py
@@ -0,0 +1,86 @@
+from typing import cast
+
+import tiktoken
+
+from posthog.helpers.tiktoken_encoding import TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model
+
+SIGNAL_MAX_TOKENS = 8000
+
+
+def _as_dict(value: object) -> dict[str, object] | None:
+ return cast(dict[str, object], value) if isinstance(value, dict) else None
+
+
+def _as_list(value: object) -> list[object]:
+ return cast(list[object], value) if isinstance(value, list) else []
+
+
+def _string(value: object, default: str = "") -> str:
+ return value if isinstance(value, str) else default
+
+
+def _render_frame(value: object) -> str:
+ frame = _as_dict(value)
+ if frame is None:
+ return ""
+
+ resolved_name = frame.get("resolved_name")
+ function = resolved_name if isinstance(resolved_name, str) else _string(frame.get("mangled_name"))
+ source = frame.get("source")
+ line = frame.get("line")
+ column = frame.get("column")
+
+ rendered = function
+ if isinstance(source, str):
+ rendered += f" in {source}"
+ if isinstance(line, int):
+ rendered += f" line {line}"
+ if isinstance(column, int):
+ rendered += f" column {column}"
+ return f"{rendered}\n"
+
+
+def _render_stacktrace_unbounded(event_properties: dict[str, object], truncate_frames: bool) -> str:
+ rendered: list[str] = []
+ for value in _as_list(event_properties.get("$exception_list")):
+ exception = _as_dict(value)
+ if exception is None:
+ continue
+
+ exception_type = _string(exception.get("type"), "Unknown")
+ exception_value = _string(exception.get("value"))[:300]
+ rendered.append(f"{exception_type}: {exception_value}\n")
+
+ stacktrace = _as_dict(exception.get("stacktrace"))
+ frames = _as_list(stacktrace.get("frames")) if stacktrace and stacktrace.get("type") == "resolved" else []
+ if truncate_frames and len(frames) > 2:
+ rendered.extend((_render_frame(frames[0]), "...\n", _render_frame(frames[-1])))
+ else:
+ rendered.extend(_render_frame(frame) for frame in frames)
+
+ return "".join(rendered)
+
+
+def decode_token_prefix(encoding: tiktoken.Encoding, tokens: list[int], max_tokens: int) -> str:
+ prefix = tokens[:max_tokens]
+ while prefix:
+ try:
+ return encoding.decode(prefix, errors="strict")
+ except UnicodeDecodeError:
+ prefix.pop()
+ return ""
+
+
+def render_stacktrace(event_properties: dict[str, object], max_tokens: int) -> str:
+ encoding = get_tiktoken_encoding_for_model(TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL)
+ rendered = _render_stacktrace_unbounded(event_properties, truncate_frames=False)
+ tokens = encoding.encode(rendered, allowed_special="all")
+ if len(tokens) <= max_tokens:
+ return rendered
+
+ rendered = _render_stacktrace_unbounded(event_properties, truncate_frames=True)
+ tokens = encoding.encode(rendered, allowed_special="all")
+ if len(tokens) <= max_tokens:
+ return rendered
+
+ return decode_token_prefix(encoding, tokens, max_tokens)
diff --git a/products/error_tracking/backend/temporal/lifecycle/side_effects.py b/products/error_tracking/backend/temporal/lifecycle/side_effects.py
new file mode 100644
index 000000000000..213c34805ba1
--- /dev/null
+++ b/products/error_tracking/backend/temporal/lifecycle/side_effects.py
@@ -0,0 +1,168 @@
+from datetime import UTC, datetime
+from typing import Protocol
+
+from django.utils.dateparse import parse_datetime
+
+from asgiref.sync import sync_to_async
+from confluent_kafka import KafkaError, KafkaException
+
+from posthog.cdp.internal_events import InternalEventEvent, flush_internal_events_producer, produce_internal_event
+from posthog.helpers.tiktoken_encoding import (
+ LLM_TOKEN_COUNT_PROXY_MODEL,
+ TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL,
+ get_tiktoken_encoding_for_model,
+)
+from posthog.models import Team
+
+from products.error_tracking.backend.temporal.lifecycle.event_properties import (
+ EventPropertiesIssueSnapshot,
+ fetch_event_properties,
+)
+from products.error_tracking.backend.temporal.lifecycle.rendering import (
+ SIGNAL_MAX_TOKENS,
+ decode_token_prefix,
+ render_stacktrace,
+)
+from products.signals.backend.facade.api import emit_signal
+
+KAFKA_DELIVERY_TIMEOUT_SECONDS = 30
+
+
+class IssueLifecycleSnapshot(EventPropertiesIssueSnapshot, Protocol):
+ @property
+ def name(self) -> str | None: ...
+
+ @property
+ def description(self) -> str | None: ...
+
+ @property
+ def status(self) -> str: ...
+
+
+class IssueLifecycleWorkflowInputs(Protocol):
+ @property
+ def notification_id(self) -> str: ...
+
+ @property
+ def team_id(self) -> int: ...
+
+ @property
+ def issue_id(self) -> str: ...
+
+ @property
+ def issue(self) -> IssueLifecycleSnapshot: ...
+
+ @property
+ def fingerprint(self) -> str: ...
+
+ @property
+ def event_uuid(self) -> str: ...
+
+ @property
+ def event_timestamp(self) -> str: ...
+
+ @property
+ def assignee(self) -> str | None: ...
+
+
+def produce_issue_lifecycle_internal_event(
+ inputs: IssueLifecycleWorkflowInputs,
+ *,
+ event: str,
+ exception_timestamp: str,
+ humanize_status: bool = True,
+) -> None:
+ try:
+ team = Team.objects.get(id=inputs.team_id)
+ except Team.DoesNotExist:
+ return
+
+ event_properties = fetch_event_properties(team, inputs)
+ timestamp = parse_datetime(exception_timestamp)
+ if timestamp is None:
+ timestamp = datetime.now(UTC)
+ elif timestamp.tzinfo is None:
+ timestamp = timestamp.replace(tzinfo=UTC)
+
+ properties: dict[str, object] = {
+ "name": inputs.issue.name,
+ "description": inputs.issue.description,
+ "issue_description": inputs.issue.description,
+ "first_seen": inputs.issue.created_at,
+ "fingerprint": inputs.fingerprint,
+ "exception_timestamp": timestamp.isoformat(),
+ "exception_props": event_properties,
+ }
+ status = inputs.issue.status
+ properties["status"] = (
+ {
+ "archived": "Archived",
+ "active": "Active",
+ "resolved": "Resolved",
+ "pending_release": "Pending Release",
+ "suppressed": "Suppressed",
+ }.get(status, status)
+ if humanize_status
+ else status
+ )
+ if inputs.assignee is not None:
+ properties["assignee"] = inputs.assignee
+
+ def produce(properties_to_send: dict[str, object]) -> None:
+ result = produce_internal_event(
+ inputs.team_id,
+ InternalEventEvent(
+ event=event,
+ distinct_id=inputs.issue_id,
+ properties=properties_to_send,
+ uuid=inputs.notification_id,
+ ),
+ )
+ flush_internal_events_producer(KAFKA_DELIVERY_TIMEOUT_SECONDS)
+ result.get(timeout=0)
+
+ try:
+ produce(properties)
+ except KafkaException as error:
+ kafka_error = error.args[0] if error.args else None
+ if not isinstance(kafka_error, KafkaError) or kafka_error.name() != "MSG_SIZE_TOO_LARGE":
+ raise
+ properties.pop("exception_props", None)
+ properties["message_was_too_large"] = True
+ produce(properties)
+
+
+async def emit_issue_lifecycle_signal(
+ inputs: IssueLifecycleWorkflowInputs,
+ *,
+ source_type: str,
+ preamble: str,
+) -> None:
+ try:
+ team = await Team.objects.aget(id=inputs.team_id)
+ except Team.DoesNotExist:
+ return
+
+ event_properties = await sync_to_async(fetch_event_properties, thread_sensitive=False)(team, inputs)
+ issue_name = inputs.issue.name or "Unknown"
+ issue_description = inputs.issue.description or ""
+ header = f"{preamble}:\n{issue_name}: {issue_description}\n"
+ encoding = get_tiktoken_encoding_for_model(TEXT_EMBEDDING_3_TOKEN_COUNT_PROXY_MODEL)
+ stacktrace_tokens = max(SIGNAL_MAX_TOKENS - len(encoding.encode(header)), 0)
+ stacktrace = render_stacktrace(event_properties, stacktrace_tokens)
+ description = f"{header}\n```\n{stacktrace}\n```"
+ signal_encoding = get_tiktoken_encoding_for_model(LLM_TOKEN_COUNT_PROXY_MODEL)
+ signal_tokens = signal_encoding.encode(description)
+ if len(signal_tokens) > SIGNAL_MAX_TOKENS:
+ description = decode_token_prefix(signal_encoding, signal_tokens, SIGNAL_MAX_TOKENS)
+
+ await emit_signal(
+ team=team,
+ source_product="error_tracking",
+ source_type=source_type,
+ source_id=inputs.issue_id,
+ description=description,
+ weight=1.0,
+ extra={"fingerprint": inputs.fingerprint},
+ idempotency_key=inputs.notification_id,
+ )
diff --git a/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py b/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py
new file mode 100644
index 000000000000..9af9112b7348
--- /dev/null
+++ b/products/error_tracking/backend/temporal/lifecycle/test/test_side_effects.py
@@ -0,0 +1,233 @@
+import copy
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from confluent_kafka import KafkaError, KafkaException
+
+from posthog.cdp.internal_events import InternalEventEvent
+from posthog.helpers.tiktoken_encoding import LLM_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model
+
+from products.error_tracking.backend.temporal.lifecycle.issue_created.types import (
+ IssueCreatedSnapshot,
+ IssueCreatedWorkflowInputs,
+)
+from products.error_tracking.backend.temporal.lifecycle.issue_reopened.types import (
+ IssueReopenedSnapshot,
+ IssueReopenedWorkflowInputs,
+)
+from products.error_tracking.backend.temporal.lifecycle.rendering import SIGNAL_MAX_TOKENS
+from products.error_tracking.backend.temporal.lifecycle.side_effects import (
+ emit_issue_lifecycle_signal,
+ produce_issue_lifecycle_internal_event,
+)
+
+
+def _inputs() -> IssueReopenedWorkflowInputs:
+ return IssueReopenedWorkflowInputs(
+ notification_id="01982721-5e00-7000-8000-000000000001",
+ team_id=42,
+ issue_id="01982721-5e00-7000-8000-000000000002",
+ issue=IssueReopenedSnapshot(
+ name="TypeError",
+ description="Something failed",
+ status="pending_release",
+ created_at="2026-07-21T12:00:00Z",
+ ),
+ fingerprint="fingerprint",
+ event_uuid="01982721-5e00-7000-8000-000000000003",
+ event_timestamp="2026-07-21T12:05:00Z",
+ assignee='{"type":"user","id":1}',
+ )
+
+
+def test_created_internal_event_preserves_raw_status() -> None:
+ inputs = IssueCreatedWorkflowInputs(
+ notification_id="01982721-5e00-7000-8000-000000000001",
+ team_id=42,
+ issue_id="01982721-5e00-7000-8000-000000000002",
+ issue=IssueCreatedSnapshot(
+ name="TypeError",
+ description="Something failed",
+ status="active",
+ created_at="2026-07-21T12:00:00Z",
+ ),
+ fingerprint="fingerprint",
+ event_uuid="01982721-5e00-7000-8000-000000000003",
+ event_timestamp="2026-07-21T12:05:00Z",
+ )
+ result = MagicMock()
+ sent_events: list[InternalEventEvent] = []
+
+ def capture_event(_team_id: int, event: InternalEventEvent) -> MagicMock:
+ sent_events.append(copy.deepcopy(event))
+ return result
+
+ with (
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.Team.objects.get",
+ return_value=MagicMock(),
+ ),
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.fetch_event_properties",
+ return_value={},
+ ),
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.produce_internal_event",
+ side_effect=capture_event,
+ ),
+ patch("products.error_tracking.backend.temporal.lifecycle.side_effects.flush_internal_events_producer"),
+ ):
+ produce_issue_lifecycle_internal_event(
+ inputs,
+ event="$error_tracking_issue_created",
+ exception_timestamp=inputs.event_timestamp,
+ humanize_status=False,
+ )
+
+ assert sent_events[0].event == "$error_tracking_issue_created"
+ assert sent_events[0].properties["status"] == "active"
+
+
+def test_oversized_internal_event_retries_without_exception_properties() -> None:
+ inputs = _inputs()
+ event_properties = {"$exception_list": [{"type": "TypeError", "value": "boom"}]}
+ oversized_result = MagicMock()
+ oversized_result.get.side_effect = KafkaException(KafkaError(KafkaError.MSG_SIZE_TOO_LARGE)) # type: ignore[attr-defined]
+ retry_result = MagicMock()
+ results = iter([oversized_result, retry_result])
+ sent_events: list[InternalEventEvent] = []
+
+ def capture_event(_team_id: int, event: InternalEventEvent) -> MagicMock:
+ sent_events.append(copy.deepcopy(event))
+ return next(results)
+
+ with (
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.Team.objects.get",
+ return_value=MagicMock(),
+ ),
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.fetch_event_properties",
+ return_value=event_properties,
+ ),
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.produce_internal_event",
+ side_effect=capture_event,
+ ) as produce_internal_event,
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.flush_internal_events_producer"
+ ) as flush,
+ ):
+ produce_issue_lifecycle_internal_event(
+ inputs,
+ event="$error_tracking_issue_reopened",
+ exception_timestamp="2026-07-21T12:05:00",
+ )
+
+ assert produce_internal_event.call_count == 2
+ assert len(sent_events) == 2
+ assert sent_events[0].event == "$error_tracking_issue_reopened"
+ assert sent_events[0].distinct_id == inputs.issue_id
+ assert sent_events[0].uuid == inputs.notification_id
+ assert sent_events[0].properties == {
+ "name": "TypeError",
+ "description": "Something failed",
+ "issue_description": "Something failed",
+ "first_seen": "2026-07-21T12:00:00Z",
+ "fingerprint": "fingerprint",
+ "exception_timestamp": "2026-07-21T12:05:00+00:00",
+ "exception_props": event_properties,
+ "status": "Pending Release",
+ "assignee": inputs.assignee,
+ }
+ assert sent_events[1].properties == {
+ key: value for key, value in sent_events[0].properties.items() if key != "exception_props"
+ } | {"message_was_too_large": True}
+ assert flush.call_count == 2
+ oversized_result.get.assert_called_once_with(timeout=0)
+ retry_result.get.assert_called_once_with(timeout=0)
+
+
+def test_internal_event_reraises_non_size_kafka_errors() -> None:
+ result = MagicMock()
+ result.get.side_effect = KafkaException(KafkaError(KafkaError._TRANSPORT)) # type: ignore[attr-defined]
+ sent_events: list[InternalEventEvent] = []
+
+ def capture_event(_team_id: int, event: InternalEventEvent) -> MagicMock:
+ sent_events.append(copy.deepcopy(event))
+ return result
+
+ with (
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.Team.objects.get",
+ return_value=MagicMock(),
+ ),
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.fetch_event_properties",
+ return_value={},
+ ),
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.produce_internal_event",
+ side_effect=capture_event,
+ ),
+ patch("products.error_tracking.backend.temporal.lifecycle.side_effects.flush_internal_events_producer"),
+ pytest.raises(KafkaException),
+ ):
+ produce_issue_lifecycle_internal_event(
+ _inputs(),
+ event="$error_tracking_issue_reopened",
+ exception_timestamp="invalid",
+ )
+
+ assert len(sent_events) == 1
+
+
+async def test_signal_is_truncated_and_uses_notification_id_for_idempotency() -> None:
+ inputs = _inputs()
+ team = MagicMock()
+ event_properties = {"$exception_list": [{"type": "TypeError", "value": "boom"}]}
+ stacktrace = "repeated stack frame\n" * 10_000
+
+ with (
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.Team.objects.aget",
+ new=AsyncMock(return_value=team),
+ ),
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.fetch_event_properties",
+ return_value=event_properties,
+ ),
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.render_stacktrace",
+ return_value=stacktrace,
+ ),
+ patch(
+ "products.error_tracking.backend.temporal.lifecycle.side_effects.emit_signal",
+ new=AsyncMock(),
+ ) as emit_signal,
+ ):
+ await emit_issue_lifecycle_signal(
+ inputs,
+ source_type="issue_reopened",
+ preamble="Previously resolved issue reappeared",
+ )
+
+ emit_signal.assert_awaited_once()
+ assert emit_signal.await_args is not None
+ call = emit_signal.await_args.kwargs
+ description = call["description"]
+ encoding = get_tiktoken_encoding_for_model(LLM_TOKEN_COUNT_PROXY_MODEL)
+ assert description.startswith("Previously resolved issue reappeared:\nTypeError: Something failed\n")
+ assert len(encoding.encode(description)) <= SIGNAL_MAX_TOKENS
+ assert call == {
+ "team": team,
+ "source_product": "error_tracking",
+ "source_type": "issue_reopened",
+ "source_id": inputs.issue_id,
+ "description": description,
+ "weight": 1.0,
+ "extra": {"fingerprint": inputs.fingerprint},
+ "idempotency_key": inputs.notification_id,
+ }
diff --git a/products/error_tracking/backend/temporal/lifecycle/types.py b/products/error_tracking/backend/temporal/lifecycle/types.py
new file mode 100644
index 000000000000..586e891fe111
--- /dev/null
+++ b/products/error_tracking/backend/temporal/lifecycle/types.py
@@ -0,0 +1,9 @@
+import dataclasses
+
+
[email protected](frozen=True)
+class LifecycleIssueSnapshot:
+ name: str | None
+ description: str | None
+ status: str
+ created_at: str
diff --git a/rust/cymbal/src/core/types/notification.rs b/rust/cymbal/src/core/types/notification.rs
index 5a9afff1b616..97bcaccaa2a4 100644
--- a/rust/cymbal/src/core/types/notification.rs
+++ b/rust/cymbal/src/core/types/notification.rs
@@ -70,10 +70,17 @@ impl<'de> Deserialize<'de> for IngestionNotification {
"issue_created:{}:{}:{}",
value.meta.team_id, value.issue.issue_id, value.event_uuid
),
- Self::IssueReopened(value) => format!(
- "issue_reopened:{}:{}:{}",
- value.meta.team_id, value.issue.issue_id, value.event_timestamp
- ),
+ Self::IssueReopened(value) => {
+ let event_reference = if value.event_uuid.is_nil() {
+ value.event_timestamp.clone()
+ } else {
+ value.event_uuid.to_string()
+ };
+ format!(
+ "issue_reopened:{}:{}:{}",
+ value.meta.team_id, value.issue.issue_id, event_reference
+ )
+ }
Self::IssueSpiking(value) => format!(
"issue_spiking:{}:{}:{}:{}",
value.meta.team_id,
@@ -205,6 +212,8 @@ pub struct IssueReopened {
pub meta: NotificationMeta,
#[serde(flatten)]
pub issue: IssueNotificationContext,
+ #[serde(default)]
+ pub event_uuid: Uuid,
pub event_timestamp: String,
pub assignee: Option<String>,
}
diff --git a/rust/cymbal/src/modes/notifications/config.rs b/rust/cymbal/src/modes/notifications/config.rs
index 75e7b827740d..7dff1af1347d 100644
--- a/rust/cymbal/src/modes/notifications/config.rs
+++ b/rust/cymbal/src/modes/notifications/config.rs
@@ -73,6 +73,15 @@ pub struct NotificationsConfig {
#[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 = "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 6967e58c5678..5f78bbbab5dc 100644
--- a/rust/cymbal/src/modes/notifications/context.rs
+++ b/rust/cymbal/src/modes/notifications/context.rs
@@ -9,7 +9,9 @@ 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::MaybeIssueCreatedWorkflowStarter;
+use crate::modes::notifications::temporal::{
+ build_issue_lifecycle_temporal_client, IssueLifecycleWorkflowStarters,
+};
#[derive(Clone)]
pub struct NotificationsContext {
@@ -19,7 +21,7 @@ pub struct NotificationsContext {
pub signal_client: MaybeSignalClient,
pub embedding_worker_topic: String,
pub internal_events_topic: String,
- pub issue_created_workflow_starter: MaybeIssueCreatedWorkflowStarter,
+ pub issue_lifecycle_workflow_starters: IssueLifecycleWorkflowStarters,
}
impl NotificationsContext {
@@ -30,6 +32,7 @@ impl NotificationsContext {
"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,
@@ -38,8 +41,10 @@ impl NotificationsContext {
signal_client: build_signal_client(config),
embedding_worker_topic: config.embedding_worker_topic.clone(),
internal_events_topic: config.internal_events_topic.clone(),
- issue_created_workflow_starter: MaybeIssueCreatedWorkflowStarter::from_config(config)
- .await?,
+ issue_lifecycle_workflow_starters: IssueLifecycleWorkflowStarters::from_config(
+ config,
+ lifecycle_temporal_client.as_ref(),
+ )?,
})
}
}
diff --git a/rust/cymbal/src/modes/notifications/issue_handler.rs b/rust/cymbal/src/modes/notifications/issue_handler.rs
index ab80c55ea451..ffb0d57831bd 100644
--- a/rust/cymbal/src/modes/notifications/issue_handler.rs
+++ b/rust/cymbal/src/modes/notifications/issue_handler.rs
@@ -21,8 +21,8 @@ pub async fn handle_issue_created(
notification: IssueCreated,
) -> Result<(), UnhandledError> {
if context
- .issue_created_workflow_starter
- .start_if_enabled(&notification)
+ .issue_lifecycle_workflow_starters
+ .start_created_if_enabled(&notification)
.await?
{
let sentry_integration = notification
@@ -88,11 +88,21 @@ 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,
diff --git a/rust/cymbal/src/modes/notifications/temporal.rs b/rust/cymbal/src/modes/notifications/temporal.rs
index 048f02e45ce0..03b5b3e21a19 100644
--- a/rust/cymbal/src/modes/notifications/temporal.rs
+++ b/rust/cymbal/src/modes/notifications/temporal.rs
@@ -7,117 +7,245 @@ use serde::Serialize;
use uuid::Uuid;
use crate::core::error::UnhandledError;
-use crate::core::types::notification::{IssueCreated, IssueSnapshot};
+use crate::core::types::notification::{IssueCreated, IssueReopened, IssueSnapshot};
use crate::modes::notifications::config::NotificationsConfig;
-const WORKFLOW_NAME: &str = "error-tracking-issue-created";
-const WORKFLOW_ID_PREFIX: &str = "error-tracking-issue-created";
-const WORKFLOW_STARTS_TOTAL: &str = "cymbal_issue_created_workflow_starts_total";
-const WORKFLOW_ROUTES_TOTAL: &str = "cymbal_issue_created_workflow_routes_total";
+#[derive(Clone, Copy)]
+struct WorkflowDefinition {
+ name: &'static str,
+ starts_metric: &'static str,
+ routes_metric: &'static str,
+}
-#[derive(Clone, Default)]
-pub struct MaybeIssueCreatedWorkflowStarter(Option<IssueCreatedWorkflowStarter>);
+#[derive(Clone, Copy)]
+enum IssueLifecycleKind {
+ Created,
+ Reopened,
+}
-impl MaybeIssueCreatedWorkflowStarter {
- pub async fn from_config(config: &NotificationsConfig) -> Result<Self, UnhandledError> {
- if !config.issue_created_workflow_enabled {
- return Ok(Self::default());
+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",
+ },
}
-
- Ok(Self(Some(
- IssueCreatedWorkflowStarter::from_config(config).await?,
- )))
}
+}
- pub async fn start_if_enabled(
- &self,
- notification: &IssueCreated,
- ) -> Result<bool, UnhandledError> {
- let Some(starter) = &self.0 else {
- metrics::counter!(WORKFLOW_ROUTES_TOTAL, "route" => "legacy").increment(1);
- return Ok(false);
- };
- if !starter.is_enabled_for_team(notification.meta.team_id) {
- metrics::counter!(WORKFLOW_ROUTES_TOTAL, "route" => "legacy").increment(1);
- return Ok(false);
- }
+const ISSUE_CREATED_WORKFLOW: WorkflowDefinition = IssueLifecycleKind::Created.workflow();
+const ISSUE_REOPENED_WORKFLOW: WorkflowDefinition = IssueLifecycleKind::Reopened.workflow();
- starter.start(notification).await?;
- metrics::counter!(WORKFLOW_ROUTES_TOTAL, "route" => "temporal").increment(1);
- Ok(true)
+#[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))
}
}
#[derive(Clone)]
-struct IssueCreatedWorkflowStarter {
- client: TemporalWorkflowClient,
+pub struct IssueLifecycleWorkflowStarters {
+ client: Option<TemporalWorkflowClient>,
task_queue: String,
- enabled_team_ids: Option<HashSet<i32>>,
+ created: Option<LifecycleWorkflowRoute>,
+ reopened: Option<LifecycleWorkflowRoute>,
}
-impl IssueCreatedWorkflowStarter {
- 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()))?;
+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",
+ )?;
+ if (created.is_some() || reopened.is_some()) && client.is_none() {
+ return Err(UnhandledError::Other(
+ "Temporal client missing for enabled lifecycle workflow".to_string(),
+ ));
+ }
Ok(Self {
- client,
+ client: client.cloned(),
task_queue: config.error_tracking_lifecycle_task_queue.clone(),
- enabled_team_ids: parse_team_ids(&config.issue_created_workflow_team_ids)?,
+ created,
+ reopened,
})
}
- 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))
+ 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);
+ }
+
+ self.start(
+ notification.meta.notification_id,
+ &IssueCreatedWorkflowInput::from(notification),
+ ISSUE_CREATED_WORKFLOW,
+ )
+ .await?;
+ record_route(ISSUE_CREATED_WORKFLOW, "temporal");
+ Ok(true)
+ }
+
+ 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);
+ }
+
+ self.start(
+ notification.meta.notification_id,
+ &IssueReopenedWorkflowInput::from(notification),
+ ISSUE_REOPENED_WORKFLOW,
+ )
+ .await?;
+ record_route(ISSUE_REOPENED_WORKFLOW, "temporal");
+ Ok(true)
}
- async fn start(&self, notification: &IssueCreated) -> Result<(), UnhandledError> {
- let options = start_options(notification, &self.task_queue);
- match self
- .client
- .start_workflow(&IssueCreatedWorkflowInput::from(notification), &options)
- .await
- {
+ async fn start<T: Serialize>(
+ &self,
+ notification_id: Uuid,
+ input: &T,
+ 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 {
Ok(StartWorkflowOutcome::Started { .. }) => {
- metrics::counter!(WORKFLOW_STARTS_TOTAL, "outcome" => "started").increment(1);
+ metrics::counter!(workflow.starts_metric, "outcome" => "started").increment(1);
Ok(())
}
Ok(StartWorkflowOutcome::Existing { .. }) => {
- metrics::counter!(WORKFLOW_STARTS_TOTAL, "outcome" => "already_started")
+ metrics::counter!(workflow.starts_metric, "outcome" => "already_started")
.increment(1);
Ok(())
}
Err(error) => {
- metrics::counter!(WORKFLOW_STARTS_TOTAL, "outcome" => "error").increment(1);
+ metrics::counter!(workflow.starts_metric, "outcome" => "error").increment(1);
Err(UnhandledError::Other(format!(
- "failed to start issue-created workflow: {error}"
+ "failed to start {} workflow: {error}",
+ workflow.name
)))
}
}
}
}
-fn start_options(notification: &IssueCreated, task_queue: &str) -> StartWorkflowOptions {
+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 {
+ 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,
+ workflow: WorkflowDefinition,
+) -> StartWorkflowOptions {
StartWorkflowOptions::idempotent(
- WORKFLOW_NAME,
+ workflow.name,
task_queue,
- format!("{WORKFLOW_ID_PREFIX}-{}", notification.meta.notification_id),
- notification.meta.notification_id.to_string(),
+ format!("{}-{notification_id}", workflow.name),
+ notification_id.to_string(),
)
}
@@ -148,16 +276,44 @@ impl<'a> From<&'a IssueCreated> for IssueCreatedWorkflowInput<'a> {
}
}
-fn parse_team_ids(raw: &str) -> Result<Option<HashSet<i32>>, UnhandledError> {
+#[derive(Serialize)]
+struct IssueReopenedWorkflowInput<'a> {
+ notification_id: Uuid,
+ team_id: i32,
+ issue_id: Uuid,
+ issue: &'a IssueSnapshot,
+ fingerprint: &'a str,
+ event_uuid: Uuid,
+ event_timestamp: &'a str,
+ assignee: Option<&'a str>,
+}
+
+impl<'a> From<&'a IssueReopened> for IssueReopenedWorkflowInput<'a> {
+ fn from(notification: &'a IssueReopened) -> Self {
+ Self {
+ notification_id: notification.meta.notification_id,
+ team_id: notification.meta.team_id,
+ issue_id: notification.issue.issue_id,
+ issue: &notification.issue.issue,
+ fingerprint: notification.issue.event_properties.fingerprint(),
+ event_uuid: notification.event_uuid,
+ event_timestamp: &notification.event_timestamp,
+ assignee: notification.assignee.as_deref(),
+ }
+ }
+}
+
+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 ERROR_TRACKING_ISSUE_CREATED_WORKFLOW_TEAM_IDS entry {value:?}: {error}"
- ))
+ UnhandledError::Other(format!("invalid {env_var} entry {value:?}: {error}"))
})
})
.collect::<Result<HashSet<_>, _>>()
@@ -177,71 +333,118 @@ mod tests {
Uuid::parse_str("018f3f58-7a7b-7c00-8000-000000000001").unwrap()
}
- fn notification() -> IssueCreated {
+ fn issue_context() -> IssueNotificationContext {
+ IssueNotificationContext {
+ issue_id: Uuid::nil(),
+ issue: IssueSnapshot {
+ name: Some("TypeError".to_string()),
+ description: Some("boom".to_string()),
+ status: "active".to_string(),
+ created_at: Utc::now(),
+ },
+ event_properties: serde_json::from_value::<ProcessedExceptionProperties>(
+ serde_json::json!({
+ "$exception_list": [{"type": "TypeError", "value": "boom"}],
+ "$exception_fingerprint": "fingerprint",
+ "$exception_fingerprint_record": [],
+ "$exception_issue_id": Uuid::nil(),
+ "$exception_handled": false,
+ "$exception_types": ["TypeError"],
+ "$exception_values": ["boom"],
+ "$exception_sources": [],
+ "$exception_functions": [],
+ }),
+ )
+ .unwrap(),
+ }
+ }
+
+ fn issue_created() -> IssueCreated {
IssueCreated {
meta: NotificationMeta {
notification_id: notification_id(),
team_id: 42,
},
- issue: IssueNotificationContext {
- issue_id: Uuid::nil(),
- issue: IssueSnapshot {
- name: Some("TypeError".to_string()),
- description: Some("boom".to_string()),
- status: "active".to_string(),
- created_at: Utc::now(),
- },
- event_properties: serde_json::from_value::<ProcessedExceptionProperties>(
- serde_json::json!({
- "$exception_list": [{"type": "TypeError", "value": "boom"}],
- "$exception_fingerprint": "fingerprint",
- "$exception_fingerprint_record": [],
- "$exception_issue_id": Uuid::nil(),
- "$exception_handled": false,
- "$exception_types": ["TypeError"],
- "$exception_values": ["boom"],
- "$exception_sources": [],
- "$exception_functions": [],
- }),
- )
- .unwrap(),
- },
+ issue: issue_context(),
fingerprint: "fingerprint".to_string(),
- event_uuid: Uuid::nil(),
+ event_uuid: Uuid::now_v7(),
+ event_timestamp: "2026-07-21T12:00:00Z".to_string(),
+ assignee: None,
+ }
+ }
+
+ fn issue_reopened() -> IssueReopened {
+ IssueReopened {
+ meta: NotificationMeta {
+ notification_id: notification_id(),
+ team_id: 42,
+ },
+ issue: issue_context(),
+ event_uuid: Uuid::now_v7(),
event_timestamp: "2026-07-21T12:00:00Z".to_string(),
assignee: None,
}
}
#[test]
- fn workflow_input_excludes_event_properties() {
- let value = serde_json::to_value(IssueCreatedWorkflowInput::from(&notification())).unwrap();
+ fn workflow_inputs_exclude_event_properties() {
+ let values = [
+ serde_json::to_value(IssueCreatedWorkflowInput::from(&issue_created())).unwrap(),
+ serde_json::to_value(IssueReopenedWorkflowInput::from(&issue_reopened())).unwrap(),
+ ];
- assert_eq!(value["team_id"], 42);
- assert_eq!(value["fingerprint"], "fingerprint");
- assert!(value.get("event_properties").is_none());
+ for value in values {
+ assert_eq!(value["team_id"], 42);
+ assert_eq!(value["fingerprint"], "fingerprint");
+ assert!(value.get("event_properties").is_none());
+ }
}
#[test]
fn start_options_are_idempotent_and_target_the_lifecycle_queue() {
- let options = start_options(&notification(), "error-tracking-lifecycle-task-queue");
+ for workflow in [ISSUE_CREATED_WORKFLOW, ISSUE_REOPENED_WORKFLOW] {
+ let options = start_options(
+ notification_id(),
+ "error-tracking-lifecycle-task-queue",
+ workflow,
+ );
- assert_eq!(options.workflow_name, "error-tracking-issue-created");
- assert_eq!(
- options.workflow_id,
- format!("error-tracking-issue-created-{}", notification_id())
- );
- assert_eq!(options.request_id, notification_id().to_string());
- assert_eq!(options.task_queue, "error-tracking-lifecycle-task-queue");
+ assert_eq!(options.workflow_name, workflow.name);
+ assert_eq!(
+ options.workflow_id,
+ format!("{}-{}", workflow.name, notification_id())
+ );
+ assert_eq!(options.request_id, notification_id().to_string());
+ assert_eq!(options.task_queue, "error-tracking-lifecycle-task-queue");
+ }
}
#[test]
fn parses_rollout_team_allowlist() {
- assert_eq!(parse_team_ids("").unwrap(), None);
+ assert_eq!(parse_team_ids("", "TEAM_IDS").unwrap(), None);
assert_eq!(
- parse_team_ids("42, 43").unwrap(),
+ parse_team_ids("42, 43", "TEAM_IDS").unwrap(),
Some(HashSet::from([42, 43]))
);
- assert!(parse_team_ids("42,nope").is_err());
+ 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_requires_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/processing/issue_resolution.rs b/rust/cymbal/src/modes/processing/issue_resolution.rs
index 11cd0f5b88f1..529c1823d155 100644
--- a/rust/cymbal/src/modes/processing/issue_resolution.rs
+++ b/rust/cymbal/src/modes/processing/issue_resolution.rs
@@ -388,6 +388,7 @@ pub async fn send_issue_created_notification(
context.config.event_properties_max_bytes,
issue.team_id,
event_uuid,
+ "issue_created",
&processed_properties,
)
.await;
@@ -415,21 +416,23 @@ async fn store_error_tracking_event_properties(
max_bytes: usize,
team_id: i32,
event_uuid: Uuid,
+ notification_type: &'static str,
processed_properties: &ProcessedExceptionProperties,
) {
let key = error_tracking_event_properties_key(team_id, event_uuid);
let payload = match serde_json::to_vec(processed_properties) {
Ok(payload) => payload,
Err(error) => {
- metrics::counter!(ISSUE_CREATED_EVENT_PROPERTIES_STORE_FAILED, "reason" => "serialization").increment(1);
- warn!(team_id, event_uuid = %event_uuid, error = %error, "failed to serialize issue-created event properties");
+ metrics::counter!(ISSUE_CREATED_EVENT_PROPERTIES_STORE_FAILED, "reason" => "serialization", "notification_type" => notification_type).increment(1);
+ warn!(team_id, event_uuid = %event_uuid, notification_type, error = %error, "failed to serialize lifecycle event properties");
return;
}
};
- metrics::histogram!(ISSUE_CREATED_EVENT_PROPERTIES_BYTES).record(payload.len() as f64);
+ metrics::histogram!(ISSUE_CREATED_EVENT_PROPERTIES_BYTES, "notification_type" => notification_type)
+ .record(payload.len() as f64);
if payload.len() > max_bytes {
- metrics::counter!(ISSUE_CREATED_EVENT_PROPERTIES_STORE_SKIPPED, "reason" => "payload_too_large")
+ metrics::counter!(ISSUE_CREATED_EVENT_PROPERTIES_STORE_SKIPPED, "reason" => "payload_too_large", "notification_type" => notification_type)
.increment(1);
return;
}
@@ -438,13 +441,14 @@ async fn store_error_tracking_event_properties(
.set_bytes(key.clone(), payload, Some(ttl_seconds))
.await
{
- metrics::counter!(ISSUE_CREATED_EVENT_PROPERTIES_STORE_FAILED, "reason" => "redis")
+ metrics::counter!(ISSUE_CREATED_EVENT_PROPERTIES_STORE_FAILED, "reason" => "redis", "notification_type" => notification_type)
.increment(1);
- warn!(team_id, event_uuid = %event_uuid, error = %error, "failed to store issue-created event properties");
+ warn!(team_id, event_uuid = %event_uuid, notification_type, error = %error, "failed to store lifecycle event properties");
return;
}
- metrics::counter!(ISSUE_CREATED_EVENT_PROPERTIES_STORED).increment(1);
+ metrics::counter!(ISSUE_CREATED_EVENT_PROPERTIES_STORED, "notification_type" => notification_type)
+ .increment(1);
}
pub async fn send_issue_reopened_notification(
@@ -452,13 +456,25 @@ pub async fn send_issue_reopened_notification(
issue: &Issue,
assignment: Option<Assignment>,
processed_properties: ProcessedExceptionProperties,
+ event_uuid: Uuid,
event_timestamp: &DateTime<Utc>,
) -> Result<(), UnhandledError> {
+ store_error_tracking_event_properties(
+ &*context.issue_buckets_redis_client,
+ context.config.event_properties_ttl_seconds,
+ context.config.event_properties_max_bytes,
+ issue.team_id,
+ event_uuid,
+ "issue_reopened",
+ &processed_properties,
+ )
+ .await;
publish_ingestion_notification(
context,
IngestionNotification::IssueReopened(IssueReopened {
meta: notification_meta(issue),
issue: issue_notification_context(issue, processed_properties),
+ event_uuid,
event_timestamp: event_timestamp.to_rfc3339(),
assignee: assignment_to_string(assignment)?,
}),
@@ -628,6 +644,7 @@ mod test {
1_048_576,
42,
event_uuid,
+ "issue_created",
&properties,
)
.await;
@@ -670,6 +687,7 @@ mod test {
128,
42,
Uuid::parse_str("01982721-5e00-7000-8000-000000000001").unwrap(),
+ "issue_created",
&properties,
)
.await;
diff --git a/rust/cymbal/src/modes/processing/stages/linking/issue.rs b/rust/cymbal/src/modes/processing/stages/linking/issue.rs
index 4847d672b170..541963a1838f 100644
--- a/rust/cymbal/src/modes/processing/stages/linking/issue.rs
+++ b/rust/cymbal/src/modes/processing/stages/linking/issue.rs
@@ -223,6 +223,7 @@ async fn load_and_maybe_reopen(
&issue,
assignment,
processed_properties,
+ event_properties.uuid(),
&event_timestamp,
)
.await?;
@@ -270,6 +271,7 @@ async fn resolve_issue(
&issue,
assignment,
processed_properties,
+ event_properties.uuid(),
&event_timestamp,
)
.await?;
@@ -346,6 +348,7 @@ async fn resolve_issue(
&issue,
assignment,
processed_properties,
+ event_properties.uuid(),
&event_timestamp,
)
.await?;