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(alerts): add activity attempt telemetry (#98254)

Jon McCallumf3a96b4ec1f4
diff --git a/docs/internal/alerts-product-temporal.md b/docs/internal/alerts-product-temporal.md
index 537ef8877596..dd4ad33b87d9 100644
--- a/docs/internal/alerts-product-temporal.md
+++ b/docs/internal/alerts-product-temporal.md
@@ -45,3 +45,51 @@ Real notification delivery guarantees remain undecided.
This registration does not create schedules or deploy workers.
Schedule registration will set the evaluation workflow's 50-second execution timeout separately.
+
+## Activity logs
+
+Both Alerts queues use an activity-only interceptor that emits `alerts_product_activity_started` and `alerts_product_activity_finished` through the shared write-only logger.
+The shared logger's async methods keep log processing and writes off the activity event loop.
+Each retry emits its own start and finish events.
+The shared logger supplies `activity_id`, `activity_type`, `attempt`, `task_queue`, `workflow_id`, `workflow_namespace`, `workflow_run_id`, and `workflow_type`.
+Finish events add a monotonic `duration_ms` and an `outcome` of `success`, `failure`, or `cancellation`.
+Start, success, and cancellation events use INFO; a failed attempt uses WARNING and includes only the exception class in `exception_type`.
+A failed attempt does not mean the workflow has exhausted its retries.
+
+When a valid OpenTelemetry span is active, both events include hexadecimal `trace_id` and `span_id` fields.
+The interceptor does not log inputs, headers, exception messages, or locals, and does not capture exceptions separately.
+Telemetry errors cannot replace an activity's result, exception, or cancellation.
+Cancellation before the activity starts still propagates; cancellation while writing its finish log cannot replace the completed activity's outcome.
+Workflow logging and workflow bodies are unchanged.
+
+## Metrics
+
+The shared worker exposes these SDK histograms with `task_queue` labels:
+
+- `temporal_activity_schedule_to_start_latency`: time from the current attempt's scheduling to its start. Earlier attempts and retry backoff are excluded.
+- `temporal_activity_execution_latency`: worker-side execution time for an attempt, including interceptor overhead. This is not an end-to-end evaluation or delivery duration.
+
+Both histograms use milliseconds and the SDK's default buckets.
+Prometheus exposes their `_bucket`, `_sum`, and `_count` series.
+Native metrics retain the `temporal_` prefix. The `alerts_product_` convention applies only to custom metrics if those are added later.
+Do not add workflow or run IDs as metric labels.
+
+A worker killed before completion cannot emit a finish log or execution sample.
+Activities that never start produce no worker-side timing sample.
+Missing finish events are not evidence of success.
+
+## Tracing and deployment verification
+
+Both deployments must set `TEMPORAL_OTEL_PLUGIN_ENABLED=true`, a nonempty `OTEL_SERVICE_NAME`, and the appropriate OTLP gRPC exporter configuration.
+For example, configure `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` for the collector and any required credentials or TLS settings.
+The shared startup command initializes Temporal's replay-safe provider, and the client registers `OpenTelemetryPlugin(add_temporal_spans=True)`.
+Do not add the legacy tracing interceptor or another provider.
+
+The activity logs use the plugin's active attempt span.
+Evaluation, child delivery, and their activity spans retain their trace relationships even when delivery runs after evaluation finishes.
+Retries have separate activity attempt spans.
+
+Tests verify local logging, queue-labelled SDK metrics, and trace relationships without an application database or an external collector.
+Charts rollout must separately configure both deployments and verify Prometheus scraping and delivery to the tracing collector.
+This change does not configure deployments, dashboards, alert rules, or SLO emission.
+The `alerts-product` SLO area remains reserved without changes to shared SLO handling or workflow inputs.
diff --git a/posthog/temporal/common/worker.py b/posthog/temporal/common/worker.py
index b384021b4a86..2a5e4ac8ddcd 100644
--- a/posthog/temporal/common/worker.py
+++ b/posthog/temporal/common/worker.py
@@ -57,6 +57,7 @@ from posthog.temporal.usage_report.metrics import (
USAGE_REPORTS_LATENCY_HISTOGRAM_METRICS,
)
+from products.alerts.backend.facade.temporal import AlertsProductTelemetryInterceptor
from products.batch_exports.backend.temporal.metrics import BatchExportsMetricsInterceptor
from products.experiments.backend.temporal.recalculation_metrics import (
EXPERIMENT_METRICS_RECALCULATION_ATTEMPT_HISTOGRAM_BUCKETS,
@@ -168,6 +169,7 @@ ALL_INTERCEPTOR_CLASSES = [
LivenessInterceptor,
PostHogClientInterceptor,
SloInterceptor,
+ AlertsProductTelemetryInterceptor,
BatchExportsMetricsInterceptor,
DeleteRecordingsMetricsInterceptor,
SurfacingScoringMetricsInterceptor,
diff --git a/products/alerts/backend/facade/temporal.py b/products/alerts/backend/facade/temporal.py
index f12f07dc56a4..f5b56bf9917e 100644
--- a/products/alerts/backend/facade/temporal.py
+++ b/products/alerts/backend/facade/temporal.py
@@ -1,3 +1,4 @@
+from products.alerts.backend.temporal.telemetry import AlertsProductTelemetryInterceptor
from products.alerts.backend.temporal.workflows import (
DELIVERY_ACTIVITIES,
DELIVERY_WORKFLOWS,
@@ -5,4 +6,10 @@ from products.alerts.backend.temporal.workflows import (
EVALUATION_WORKFLOWS,
)
-__all__ = ["DELIVERY_ACTIVITIES", "DELIVERY_WORKFLOWS", "EVALUATION_ACTIVITIES", "EVALUATION_WORKFLOWS"]
+__all__ = [
+ "DELIVERY_ACTIVITIES",
+ "DELIVERY_WORKFLOWS",
+ "EVALUATION_ACTIVITIES",
+ "EVALUATION_WORKFLOWS",
+ "AlertsProductTelemetryInterceptor",
+]
diff --git a/products/alerts/backend/temporal/telemetry.py b/products/alerts/backend/temporal/telemetry.py
new file mode 100644
index 000000000000..122632fb585c
--- /dev/null
+++ b/products/alerts/backend/temporal/telemetry.py
@@ -0,0 +1,78 @@
+import time
+import asyncio
+
+from django.conf import settings
+
+from opentelemetry import trace
+from temporalio.exceptions import CancelledError
+from temporalio.worker import ActivityInboundInterceptor, ExecuteActivityInput, Interceptor
+
+from posthog.temporal.common.logger import get_write_only_logger
+
+LOGGER = get_write_only_logger(__name__)
+
+
+def _monotonic_time() -> float | None:
+ try:
+ return time.monotonic()
+ except Exception:
+ return None
+
+
+async def _log_activity_event(
+ event: str,
+ *,
+ started_at: float | None = None,
+ outcome: str | None = None,
+ exception_type: str | None = None,
+) -> None:
+ try:
+ fields: dict[str, str | float] = {}
+ if outcome is not None:
+ fields["outcome"] = outcome
+ if started_at is not None:
+ fields["duration_ms"] = (time.monotonic() - started_at) * 1000
+ if exception_type is not None:
+ fields["exception_type"] = exception_type
+ span_context = trace.get_current_span().get_span_context()
+ if span_context.is_valid:
+ fields["trace_id"] = trace.format_trace_id(span_context.trace_id)
+ fields["span_id"] = trace.format_span_id(span_context.span_id)
+ log = LOGGER.awarning if outcome == "failure" else LOGGER.ainfo
+ await log(event, **fields)
+ except Exception:
+ pass
+
+
+class AlertsProductTelemetryInterceptor(Interceptor):
+ task_queue = (settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE, settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE)
+
+ def intercept_activity(self, next: ActivityInboundInterceptor) -> ActivityInboundInterceptor:
+ return _AlertsProductActivityInterceptor(next)
+
+
+class _AlertsProductActivityInterceptor(ActivityInboundInterceptor):
+ async def execute_activity(self, input: ExecuteActivityInput) -> object:
+ started_at = _monotonic_time()
+ outcome = "success"
+ exception_type = None
+ try:
+ await _log_activity_event("alerts_product_activity_started")
+ return await super().execute_activity(input)
+ except (asyncio.CancelledError, CancelledError):
+ outcome = "cancellation"
+ raise
+ except BaseException as error:
+ outcome = "failure"
+ exception_type = type(error).__name__
+ raise
+ finally:
+ try:
+ await _log_activity_event(
+ "alerts_product_activity_finished",
+ started_at=started_at,
+ outcome=outcome,
+ exception_type=exception_type,
+ )
+ except asyncio.CancelledError:
+ pass
diff --git a/products/alerts/backend/tests/conftest.py b/products/alerts/backend/tests/conftest.py
new file mode 100644
index 000000000000..14ca9fc54272
--- /dev/null
+++ b/products/alerts/backend/tests/conftest.py
@@ -0,0 +1,43 @@
+from collections.abc import Iterator
+
+import pytest
+
+import structlog
+from opentelemetry import trace
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+from structlog.testing import LogCapture
+from structlog.typing import EventDict
+from temporalio.contrib.opentelemetry import create_tracer_provider
+
+from posthog.temporal.common.logger import configure_logger
+
+
+def activity_logs(settings) -> Iterator[list[EventDict]]:
+ previous_config = structlog.get_config()
+ previously_configured = structlog.is_configured()
+ capture = LogCapture()
+ settings.TEST = True
+ settings.TEMPORAL_LOG_LEVEL = "INFO"
+ configure_logger(cache_logger_on_first_use=False, otel_log_mirror=capture)
+ try:
+ yield capture.entries
+ finally:
+ if previously_configured:
+ structlog.configure(**previous_config)
+ else:
+ structlog.reset_defaults()
+
+
[email protected](scope="module")
+def span_exporter() -> Iterator[InMemorySpanExporter]:
+ exporter = InMemorySpanExporter()
+ provider = create_tracer_provider(shutdown_on_exit=False)
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+ with pytest.MonkeyPatch.context() as patch:
+ patch.setattr(trace, "_TRACER_PROVIDER", provider)
+ try:
+ yield exporter
+ finally:
+ provider.shutdown()
diff --git a/products/alerts/backend/tests/test_temporal_telemetry.py b/products/alerts/backend/tests/test_temporal_telemetry.py
new file mode 100644
index 000000000000..12164e61c36c
--- /dev/null
+++ b/products/alerts/backend/tests/test_temporal_telemetry.py
@@ -0,0 +1,215 @@
+import asyncio
+import threading
+from dataclasses import replace
+from types import SimpleNamespace
+
+import pytest
+from unittest.mock import AsyncMock, Mock
+
+from django.conf import settings
+
+import structlog
+from opentelemetry import trace
+from structlog.typing import EventDict, WrappedLogger
+from temporalio.api.common.v1 import Payload
+from temporalio.exceptions import CancelledError
+from temporalio.testing import ActivityEnvironment
+from temporalio.worker import ActivityInboundInterceptor, ExecuteActivityInput
+
+from posthog.temporal.common.interceptor import is_task_queue_supported
+from posthog.temporal.common.worker import ALL_INTERCEPTOR_CLASSES
+
+from products.alerts.backend.facade.temporal import AlertsProductTelemetryInterceptor
+from products.alerts.backend.temporal import telemetry
+
+
+ "error,outcome,level",
+ [
+ (None, "success", "info"),
+ (ValueError("sensitive exception message"), "failure", "warning"),
+ (asyncio.CancelledError("sensitive cancellation message"), "cancellation", "info"),
+ (CancelledError("sensitive cancellation message"), "cancellation", "info"),
+ ],
+)
[email protected]("tracing_enabled", [False, True])
+async def test_activity_attempt_logs(error, outcome, level, tracing_enabled, activity_logs, span_exporter, monkeypatch):
+ environment = ActivityEnvironment()
+ downstream = Mock(spec=ActivityInboundInterceptor)
+ result = object()
+ downstream.execute_activity = AsyncMock(return_value=result, side_effect=error)
+ interceptor = AlertsProductTelemetryInterceptor().intercept_activity(downstream)
+ activity_input = ExecuteActivityInput(
+ fn=downstream.execute_activity,
+ args=["sensitive activity input"],
+ executor=None,
+ headers={"private": Payload(data=b"sensitive header")},
+ )
+ monkeypatch.setattr(telemetry, "time", SimpleNamespace(monotonic=Mock(side_effect=[1.0, 1.125, 2.0, 2.5])))
+ span = (
+ trace.get_tracer(__name__).start_span("test-activity")
+ if tracing_enabled
+ else trace.NonRecordingSpan(trace.INVALID_SPAN_CONTEXT)
+ )
+ with trace.use_span(span, end_on_exit=True):
+ for attempt in (1, 2):
+ environment.info = replace(environment.info, attempt=attempt)
+ if error is None:
+ assert await environment.run(interceptor.execute_activity, activity_input) is result
+ else:
+ with pytest.raises(type(error)) as caught:
+ await environment.run(interceptor.execute_activity, activity_input)
+ assert caught.value is error
+
+ assert len(activity_logs) == 4
+ for attempt, duration_ms in ((1, 125.0), (2, 500.0)):
+ start, finish = activity_logs[(attempt - 1) * 2 : attempt * 2]
+ assert start["event"] == "alerts_product_activity_started"
+ assert start["log_level"] == "info"
+ assert "duration_ms" not in start
+ assert "outcome" not in start
+ assert finish["event"] == "alerts_product_activity_finished"
+ assert finish["log_level"] == level
+ assert finish["outcome"] == outcome
+ assert finish["duration_ms"] == duration_ms
+ if outcome == "failure":
+ assert finish["exception_type"] == "ValueError"
+ else:
+ assert "exception_type" not in finish
+ for entry in (start, finish):
+ assert entry["attempt"] == attempt
+ for field in (
+ "activity_id",
+ "activity_type",
+ "task_queue",
+ "workflow_id",
+ "workflow_namespace",
+ "workflow_run_id",
+ "workflow_type",
+ ):
+ assert entry[field] == getattr(environment.info, field)
+ if tracing_enabled:
+ assert entry["trace_id"] == trace.format_trace_id(span.get_span_context().trace_id)
+ assert entry["span_id"] == trace.format_span_id(span.get_span_context().span_id)
+ else:
+ assert "trace_id" not in entry
+ assert "span_id" not in entry
+ assert "exc_info" not in entry
+ assert "exception" not in entry
+ assert "sensitive" not in str(activity_logs)
+
+
[email protected]("error", [None, ValueError("original error"), asyncio.CancelledError(), CancelledError()])
[email protected]("failure_point", ["start", "finish", "trace", "clock"])
+async def test_telemetry_failure_preserves_activity_outcome(error, failure_point, activity_logs, monkeypatch):
+ environment = ActivityEnvironment()
+ downstream = Mock(spec=ActivityInboundInterceptor)
+ result = object()
+ downstream.execute_activity = AsyncMock(return_value=result, side_effect=error)
+ interceptor = AlertsProductTelemetryInterceptor().intercept_activity(downstream)
+ activity_input = ExecuteActivityInput(fn=downstream.execute_activity, args=[], executor=None, headers={})
+ telemetry_error = RuntimeError("telemetry unavailable")
+ if failure_point in ("start", "finish"):
+ outcomes = [telemetry_error, None] if failure_point == "start" else [None, telemetry_error]
+ failing_log = AsyncMock(side_effect=outcomes)
+ monkeypatch.setattr(telemetry, "LOGGER", SimpleNamespace(ainfo=failing_log, awarning=failing_log))
+ elif failure_point == "trace":
+ monkeypatch.setattr(telemetry, "trace", SimpleNamespace(get_current_span=Mock(side_effect=telemetry_error)))
+ else:
+ monkeypatch.setattr(telemetry, "time", SimpleNamespace(monotonic=Mock(side_effect=telemetry_error)))
+
+ if error is None:
+ assert await environment.run(interceptor.execute_activity, activity_input) is result
+ else:
+ with pytest.raises(type(error)) as caught:
+ await environment.run(interceptor.execute_activity, activity_input)
+ assert caught.value is error
+ downstream.execute_activity.assert_awaited_once_with(activity_input)
+
+
[email protected]("phase", ["started", "finished"])
+async def test_logging_does_not_block_activity_loop(phase: str, activity_logs: list[EventDict]) -> None:
+ environment = ActivityEnvironment()
+ downstream = Mock(spec=ActivityInboundInterceptor)
+ result = object()
+ downstream.execute_activity = AsyncMock(return_value=result)
+ interceptor = AlertsProductTelemetryInterceptor().intercept_activity(downstream)
+ activity_input = ExecuteActivityInput(fn=downstream.execute_activity, args=[], executor=None, headers={})
+ loop = asyncio.get_running_loop()
+ log_started = asyncio.Event()
+ release_log = threading.Event()
+ released: list[bool] = []
+
+ def block_log(_logger: WrappedLogger, _method_name: str, entry: EventDict) -> EventDict:
+ if entry["event"] == f"alerts_product_activity_{phase}":
+ loop.call_soon_threadsafe(log_started.set)
+ released.append(release_log.wait(timeout=10))
+ return entry
+
+ structlog.configure(processors=[block_log, *structlog.get_config()["processors"]])
+ activity_task = asyncio.create_task(environment.run(interceptor.execute_activity, activity_input))
+ try:
+ await asyncio.wait_for(log_started.wait(), timeout=15)
+ finally:
+ release_log.set()
+ assert await asyncio.wait_for(activity_task, timeout=15) is result
+ assert released == [True]
+
+
[email protected]("phase", ["started", "finished"])
[email protected]("error", [None, ValueError("original error"), asyncio.CancelledError(), CancelledError()])
+async def test_cancellation_during_logging_preserves_activity_outcome(
+ phase: str, error: BaseException | None, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ environment = ActivityEnvironment()
+ downstream = Mock(spec=ActivityInboundInterceptor)
+ result = object()
+ downstream.execute_activity = AsyncMock(return_value=result, side_effect=error)
+ interceptor = AlertsProductTelemetryInterceptor().intercept_activity(downstream)
+ activity_input = ExecuteActivityInput(fn=downstream.execute_activity, args=[], executor=None, headers={})
+ log_started = asyncio.Event()
+
+ async def wait_for_cancellation(event: str, **fields: object) -> None:
+ if event == f"alerts_product_activity_{phase}":
+ log_started.set()
+ await asyncio.Event().wait()
+
+ logger = AsyncMock(side_effect=wait_for_cancellation)
+ monkeypatch.setattr(telemetry, "LOGGER", SimpleNamespace(ainfo=logger, awarning=logger))
+ activity_task = asyncio.create_task(environment.run(interceptor.execute_activity, activity_input))
+ try:
+ await asyncio.wait_for(log_started.wait(), timeout=10)
+ activity_task.cancel()
+ if phase == "started":
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(activity_task, timeout=10)
+ downstream.execute_activity.assert_not_awaited()
+ assert logger.await_args_list[-1].kwargs["outcome"] == "cancellation"
+ elif error is None:
+ assert await asyncio.wait_for(activity_task, timeout=10) is result
+ else:
+ with pytest.raises(type(error)) as caught:
+ await asyncio.wait_for(activity_task, timeout=10)
+ assert caught.value is error
+ finally:
+ if not activity_task.done():
+ activity_task.cancel()
+ await asyncio.gather(activity_task, return_exceptions=True)
+
+
+ "task_queue,supported",
+ [
+ (settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE, True),
+ (settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE, True),
+ (settings.LOGS_ALERTING_TASK_QUEUE, False),
+ ("unrelated-task-queue", False),
+ ],
+)
+def test_telemetry_registration(task_queue, supported):
+ registered = [
+ interceptor
+ for interceptor in ALL_INTERCEPTOR_CLASSES
+ if interceptor is AlertsProductTelemetryInterceptor and is_task_queue_supported(task_queue, interceptor)
+ ]
+ assert registered == ([AlertsProductTelemetryInterceptor] if supported else [])
diff --git a/products/alerts/backend/tests/test_temporal_workflows.py b/products/alerts/backend/tests/test_temporal_workflows.py
index 7d6288335024..6c5a7ca1a261 100644
--- a/products/alerts/backend/tests/test_temporal_workflows.py
+++ b/products/alerts/backend/tests/test_temporal_workflows.py
@@ -10,10 +10,14 @@ import pytest
from django.conf import settings
import pytest_asyncio
+from opentelemetry import trace
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from temporalio import activity, workflow
from temporalio.api.enums.v1 import EventType
from temporalio.client import WorkflowExecutionStatus, WorkflowFailureError
+from temporalio.contrib.opentelemetry import OpenTelemetryPlugin
from temporalio.exceptions import ApplicationError, TerminatedError
+from temporalio.runtime import MetricBuffer, Runtime, TelemetryConfig
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
@@ -22,6 +26,7 @@ from products.alerts.backend.facade.temporal import (
DELIVERY_WORKFLOWS,
EVALUATION_ACTIVITIES,
EVALUATION_WORKFLOWS,
+ AlertsProductTelemetryInterceptor,
)
from products.alerts.backend.temporal.workflows import AlertsProductCheckDueWorkflow, AlertsProductInputs
@@ -37,27 +42,49 @@ class CloseAfterChildStartWorkflow:
await workflow.wait_condition(lambda: False)
[email protected](scope="module")
+def sdk_metrics() -> MetricBuffer:
+ return MetricBuffer(10000)
+
+
@pytest_asyncio.fixture(scope="module")
-async def environment() -> AsyncIterator[WorkflowEnvironment]:
- async with await WorkflowEnvironment.start_time_skipping() as env:
+async def environment(
+ sdk_metrics: MetricBuffer, span_exporter: InMemorySpanExporter
+) -> AsyncIterator[WorkflowEnvironment]:
+ runtime = Runtime(telemetry=TelemetryConfig(metrics=sdk_metrics))
+ async with await WorkflowEnvironment.start_time_skipping(
+ runtime=runtime, plugins=[OpenTelemetryPlugin(add_temporal_spans=True)]
+ ) as env:
yield env
@pytest.mark.asyncio
async def test_each_tick_starts_independent_delivery(
- environment: WorkflowEnvironment, caplog: pytest.LogCaptureFixture
+ environment: WorkflowEnvironment,
+ caplog: pytest.LogCaptureFixture,
+ sdk_metrics: MetricBuffer,
+ span_exporter: InMemorySpanExporter,
+ activity_logs,
) -> None:
caplog.set_level(logging.INFO, logger="temporalio.activity")
caplog.set_level(logging.INFO, logger="temporalio.workflow")
client = environment.client
workflow_id = str(uuid.uuid4())
child_ids: set[str] = set()
+ span_exporter.clear()
+ sdk_metrics.retrieve_updates()
+
+ @activity.defn(name="alerts_product_deliver_activity")
+ async def retry_delivery() -> None:
+ if activity.info().attempt == 1:
+ raise ApplicationError("sensitive retry exception")
async with Worker(
client,
task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,
workflows=EVALUATION_WORKFLOWS,
activities=EVALUATION_ACTIVITIES,
+ interceptors=[AlertsProductTelemetryInterceptor()],
workflow_runner=UnsandboxedWorkflowRunner(),
):
for _ in range(2):
@@ -90,12 +117,72 @@ async def test_each_tick_starts_independent_delivery(
client,
task_queue=settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE,
workflows=DELIVERY_WORKFLOWS,
- activities=DELIVERY_ACTIVITIES,
+ activities=[retry_delivery],
+ interceptors=[AlertsProductTelemetryInterceptor()],
workflow_runner=UnsandboxedWorkflowRunner(),
):
for child_id in child_ids:
assert await client.get_workflow_handle(child_id).result() is None
+ updates = sdk_metrics.retrieve_updates()
+ for metric_name in ("temporal_activity_schedule_to_start_latency", "temporal_activity_execution_latency"):
+ for task_queue, expected_attempts in (
+ (settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE, 2),
+ (settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE, 4),
+ ):
+ samples = [
+ update
+ for update in updates
+ if update.metric.name == metric_name and update.attributes.get("task_queue") == task_queue
+ ]
+ assert len(samples) == expected_attempts
+ assert all(sample.value >= 0 for sample in samples)
+
+ spans = span_exporter.get_finished_spans()
+ spans_by_id = {span.context.span_id: span for span in spans}
+ assert len(spans_by_id) == len(spans)
+ workflow_spans = [span for span in spans if span.name.startswith("RunWorkflow:")]
+ activity_spans = [span for span in spans if span.name.startswith("RunActivity:")]
+ assert len(workflow_spans) == 4
+ assert len(activity_spans) == 6
+ for delivery in (span for span in workflow_spans if span.name == "RunWorkflow:alerts-product-deliver"):
+ assert delivery.parent is not None
+ child_start = spans_by_id[delivery.parent.span_id]
+ assert child_start.parent is not None
+ evaluation = spans_by_id[child_start.parent.span_id]
+ assert child_start.name == "StartChildWorkflow:alerts-product-deliver"
+ assert evaluation.name == "RunWorkflow:alerts-product-check-due"
+ assert delivery.context.trace_id == child_start.context.trace_id == evaluation.context.trace_id
+ assert evaluation.end_time is not None and delivery.start_time is not None
+ assert evaluation.end_time <= delivery.start_time
+ for attempt_span in activity_spans:
+ assert attempt_span.parent is not None
+ activity_start = spans_by_id[attempt_span.parent.span_id]
+ assert activity_start.parent is not None
+ workflow_span = spans_by_id[activity_start.parent.span_id]
+ assert activity_start.name == attempt_span.name.replace("RunActivity:", "StartActivity:")
+ assert workflow_span in workflow_spans
+ assert attempt_span.context.trace_id == activity_start.context.trace_id == workflow_span.context.trace_id
+ assert attempt_span.attributes is not None and workflow_span.attributes is not None
+ assert attempt_span.attributes["temporalRunID"] == workflow_span.attributes["temporalRunID"]
+ entries = [
+ entry
+ for entry in activity_logs
+ if entry.get("span_id") == trace.format_span_id(attempt_span.context.span_id)
+ ]
+ assert [entry["event"] for entry in entries] == [
+ "alerts_product_activity_started",
+ "alerts_product_activity_finished",
+ ]
+ assert all(entry["trace_id"] == trace.format_trace_id(attempt_span.context.trace_id) for entry in entries)
+ assert entries[0]["attempt"] == entries[1]["attempt"]
+ assert entries[1]["outcome"] == (
+ "failure"
+ if attempt_span.name == "RunActivity:alerts_product_deliver_activity" and entries[1]["attempt"] == 1
+ else "success"
+ )
+ assert "sensitive" not in str(activity_logs)
+
@pytest.mark.asyncio
@pytest.mark.parametrize("close_mode", ["failed", "terminated"])