Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(signals): Use async decorator for `posthoganalytics.scoped()` to support Temporal (#58125)

Alex Lebedevf8e382a9770b
diff --git a/posthog/temporal/common/scoped.py b/posthog/temporal/common/scoped.py
new file mode 100644
index 000000000000..2ba1a2a5cd34
--- /dev/null
+++ b/posthog/temporal/common/scoped.py
@@ -0,0 +1,31 @@
+import inspect
+import functools
+from collections.abc import Callable, Coroutine
+from typing import Any, ParamSpec, TypeVar
+
+import posthoganalytics
+
+P = ParamSpec("P")
+R = TypeVar("R")
+
+_AsyncFn = Callable[P, Coroutine[Any, Any, R]]
+
+
+# Async-aware variant of posthoganalytics.scoped(), safe to stack on async Temporal activities.
+# The regular version returns an unawaited coroutine and crashes on JSON encoding.
+def scoped_temporal(fresh: bool = False, capture_exceptions: bool = True) -> Callable[[_AsyncFn[P, R]], _AsyncFn[P, R]]:
+ def decorator(func: _AsyncFn[P, R]) -> _AsyncFn[P, R]:
+ if not inspect.iscoroutinefunction(func):
+ raise TypeError(
+ f"@scoped_temporal() requires an async function; got {func!r}. "
+ f"Use @posthoganalytics.scoped() for sync functions."
+ )
+
+ @functools.wraps(func)
+ async def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ with posthoganalytics.new_context(fresh=fresh, capture_exceptions=capture_exceptions):
+ return await func(*args, **kwargs)
+
+ return wrapper
+
+ return decorator
diff --git a/posthog/temporal/common/test_scoped.py b/posthog/temporal/common/test_scoped.py
new file mode 100644
index 000000000000..00a78a8bb871
--- /dev/null
+++ b/posthog/temporal/common/test_scoped.py
@@ -0,0 +1,144 @@
+import json
+import asyncio
+import inspect
+
+import pytest
+
+import posthoganalytics
+import temporalio.activity
+from temporalio.testing import ActivityEnvironment
+
+from posthog.temporal.common.scoped import scoped_temporal
+
+
+def test_scoped_temporal_preserves_iscoroutinefunction() -> None:
+ """This is the exact predicate Temporal uses at temporalio/worker/_activity.py:781
+ to decide between async dispatch and the sync threadpool. If our wrapper fails it,
+ Temporal routes the activity to the threadpool and the unawaited coroutine result
+ fails JSON encoding — which is the production bug."""
+
+ @scoped_temporal()
+ async def my_activity(x: int) -> int:
+ return x + 1
+
+ assert inspect.iscoroutinefunction(my_activity)
+
+
+def test_scoped_temporal_returns_unwrapped_value_when_awaited() -> None:
+ """Awaiting a wrapped activity must yield the inner function's return value, not
+ a nested coroutine — the latter is what Temporal's payload converter chokes on."""
+
+ @scoped_temporal()
+ async def my_activity(x: int) -> int:
+ return x + 1
+
+ assert asyncio.run(my_activity(41)) == 42
+
+
+def test_scoped_temporal_rejects_sync_function() -> None:
+ """Defensive: applying scoped_temporal to a sync def raises immediately at decoration
+ time so misuse can't silently regress to the production failure mode."""
+
+ def my_sync_activity(x: int) -> int:
+ return x + 1
+
+ with pytest.raises(TypeError, match="async function"):
+ scoped_temporal()(my_sync_activity) # type: ignore[arg-type]
+
+
+def test_scoped_temporal_propagates_exceptions() -> None:
+ @scoped_temporal()
+ async def my_activity() -> None:
+ raise ValueError("boom")
+
+ with pytest.raises(ValueError, match="boom"):
+ asyncio.run(my_activity())
+
+
+def test_scoped_temporal_preserves_function_metadata() -> None:
+ """functools.wraps copies __name__/__qualname__/__doc__ — needed so Temporal's
+ activity registry resolves the right name."""
+
+ @scoped_temporal()
+ async def my_activity(x: int) -> int:
+ """An activity."""
+ return x + 1
+
+ assert my_activity.__name__ == "my_activity"
+ assert my_activity.__doc__ == "An activity."
+
+
+# ---------------------------------------------------------------------------
+# Regression tests for the upstream bug we shim around. If a future upstream
+# release ships an async-aware scoped(), these turn red and prompt removing
+# our wrapper.
+# ---------------------------------------------------------------------------
+
+
+def test_upstream_scoped_breaks_iscoroutinefunction_on_async_fn() -> None:
+ """Documents the upstream bug: posthoganalytics.scoped() wraps an async function
+ in a synchronous wrapper, defeating the iscoroutinefunction check Temporal uses
+ to dispatch activities."""
+
+ @posthoganalytics.scoped()
+ async def my_activity(x: int) -> int:
+ return x + 1
+
+ assert not inspect.iscoroutinefunction(my_activity)
+ coro = my_activity(1)
+ try:
+ assert inspect.iscoroutine(coro)
+ finally:
+ coro.close()
+
+
+def test_upstream_scoped_result_fails_json_encoding() -> None:
+ """Reproduce the exact production failure: an upstream-scoped async activity
+ returns an unawaited coroutine, and json.dumps raises the same TypeError that
+ appears in Temporal's payload-encoder traceback."""
+
+ @posthoganalytics.scoped()
+ async def my_activity(x: int) -> int:
+ return x + 1
+
+ result = my_activity(1)
+ try:
+ with pytest.raises(TypeError, match="coroutine"):
+ json.dumps(result)
+ finally:
+ result.close()
+
+
+# ---------------------------------------------------------------------------
+# End-to-end via Temporal's real ActivityEnvironment dispatch path.
+#
+# ActivityEnvironment._Activity.__init__ runs the same iscoroutinefunction check
+# the production worker uses, then routes to the async-await path or the
+# sync-threadpool path accordingly. So these tests exercise the same dispatch
+# that failed in production.
+# ---------------------------------------------------------------------------
+
+
+async def test_scoped_temporal_routes_through_async_temporal_dispatch() -> None:
+ @temporalio.activity.defn
+ @scoped_temporal()
+ async def echo_activity(x: int) -> int:
+ return x * 2
+
+ assert await ActivityEnvironment().run(echo_activity, 21) == 42
+
+
+# ---------------------------------------------------------------------------
+# Smoke test against a real converted activity from the signals package.
+# ---------------------------------------------------------------------------
+
+
+def test_real_signals_activity_is_dispatched_as_async() -> None:
+ """Sanity check that a real activity from products/signals/, with the production
+ decorator stack (@temporalio.activity.defn + @scoped_temporal()), passes the
+ dispatch predicate — i.e., the bug that surfaced in the production trace cannot
+ recur for activities decorated this way."""
+ from products.signals.backend.temporal.summary import mark_report_failed_activity
+
+ assert inspect.iscoroutinefunction(mark_report_failed_activity)
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index 4aa867cbe17d..ae916c4fd810 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -22,6 +22,19 @@ Two additional Signals workflows also exist but are not part of the main report
- `backfill-error-tracking` (`backend/temporal/backfill_error_tracking.py`) — backfills recent error tracking issues as signals
- `emit-eval-signal` (`backend/temporal/emit_eval_signal.py`) — converts LLMA evaluation results into Signals inputs on the Signals worker queue
+### Activity decoration
+
+Every async Signals Temporal activity is decorated with `@scoped_temporal()` from `posthog/temporal/common/scoped.py` (not upstream `@posthoganalytics.scoped()`). It scopes `posthoganalytics.tag()` calls to the activity invocation and auto-captures uncaught exceptions into PostHog error tracking with the workflow's tags attached. The upstream decorator wraps `async def` in a sync wrapper, breaking Temporal's `iscoroutinefunction` dispatch — the worker returns the unawaited coroutine and crashes on JSON encoding. `scoped_temporal()` is the async-aware equivalent (sync helpers can keep using upstream `@posthoganalytics.scoped()`).
+
+```python
+from posthog.temporal.common.scoped import scoped_temporal
+
+@scoped_temporal()
+async def my_activity(input: ...) -> ...:
+ ...
+```
+
### Signal Ingestion Pipeline (v2)
The v1 `TeamSignalGroupingWorkflow` buffered raw `EmitSignalInputs` in memory and carried them over on `continue_as_new`. Under higher signal volume the `continue_as_new` payload could grow too large. The v2 pipeline fixes that by flushing buffered signals to object storage and passing only lightweight object keys between workflows.
diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.py
index bc4fa6141b23..620a94082e28 100644
--- a/products/signals/backend/temporal/agentic/report.py
+++ b/products/signals/backend/temporal/agentic/report.py
@@ -12,6 +12,7 @@ from pydantic import ValidationError
from posthog.models import Team, User
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
+from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.models import (
SignalReport,
@@ -413,7 +414,7 @@ async def _persist_agentic_report_artefacts(
@temporalio.activity.defn
+@scoped_temporal()
async def run_agentic_report_activity(input: RunAgenticReportInput) -> RunAgenticReportOutput:
"""Run the sandbox-backed report research and persist its artefacts after full success."""
try:
diff --git a/products/signals/backend/temporal/agentic/select_repository.py b/products/signals/backend/temporal/agentic/select_repository.py
index 8200e63f43c6..69b466cea0e8 100644
--- a/products/signals/backend/temporal/agentic/select_repository.py
+++ b/products/signals/backend/temporal/agentic/select_repository.py
@@ -10,6 +10,7 @@ from posthog.models.integration import GitHubIntegrationError
from posthog.models.team.team import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
+from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.models import SignalReportArtefact
from products.signals.backend.report_generation.select_repo import (
@@ -99,7 +100,7 @@ def _load_previous_repo_selection(report_id: str) -> RepoSelectionResult | None:
@temporalio.activity.defn
+@scoped_temporal()
async def select_repository_activity(input: SelectRepositoryInput) -> RepoSelectionResult:
"""Select the most relevant repository for a report's signals."""
team = await Team.objects.select_related("organization").aget(pk=input.team_id)
diff --git a/products/signals/backend/temporal/backfill_error_tracking.py b/products/signals/backend/temporal/backfill_error_tracking.py
index 0a97d49e3b06..e6a7dc1c0f75 100644
--- a/products/signals/backend/temporal/backfill_error_tracking.py
+++ b/products/signals/backend/temporal/backfill_error_tracking.py
@@ -6,6 +6,8 @@ import posthoganalytics
from temporalio import activity, workflow
from temporalio.common import RetryPolicy
+from posthog.temporal.common.scoped import scoped_temporal
+
@dataclass
class BackfillErrorTrackingInput:
@@ -27,7 +29,7 @@ class EmitBackfillSignalInput:
@activity.defn
+@scoped_temporal()
async def fetch_error_tracking_issues_activity(input: BackfillErrorTrackingInput) -> list[ErrorTrackingIssueData]:
"""Fetch the 100 most recent error tracking issues ordered by first seen."""
from posthog.schema import DateRange, ErrorTrackingQuery
@@ -86,7 +88,7 @@ async def fetch_error_tracking_issues_activity(input: BackfillErrorTrackingInput
@activity.defn
+@scoped_temporal()
async def emit_backfill_signal_activity(input: EmitBackfillSignalInput) -> None:
"""Emit an issue_created signal for a single error tracking issue."""
from posthog.models import Team
diff --git a/products/signals/backend/temporal/buffer.py b/products/signals/backend/temporal/buffer.py
index e88c921725c8..82d70b7c25ef 100644
--- a/products/signals/backend/temporal/buffer.py
+++ b/products/signals/backend/temporal/buffer.py
@@ -16,6 +16,7 @@ from temporalio.common import MetricCounter, RetryPolicy
from posthog.storage import object_storage
from posthog.temporal.common.client import async_connect
+from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.temporal.grouping_v2 import TeamSignalGroupingV2Workflow
from products.signals.backend.temporal.safety_filter import SafetyFilterInput, safety_filter_activity
@@ -43,7 +44,7 @@ class FlushBufferOutput:
@activity.defn
+@scoped_temporal()
async def flush_signals_to_s3_activity(input: FlushBufferInput) -> FlushBufferOutput:
batch_id = str(uuid.uuid4())
object_key = f"{OBJECT_STORAGE_SIGNALS_PREFIX}/{batch_id}"
@@ -68,7 +69,7 @@ class SignalWithStartGroupingV2Input:
@activity.defn
+@scoped_temporal()
async def signal_with_start_grouping_v2_activity(input: SignalWithStartGroupingV2Input) -> None:
"""Signal-with-start the grouping v2 workflow, creating it if it doesn't exist."""
client = await async_connect()
@@ -93,7 +94,7 @@ BACKPRESSURE_POLL_INTERVAL_SECONDS = 1
@activity.defn
+@scoped_temporal()
async def submit_signal_to_buffer_activity(input: SubmitSignalToBufferInput) -> None:
"""Poll the buffer workflow's size via query, then send the signal once there's space."""
client = await async_connect()
diff --git a/products/signals/backend/temporal/emit_eval_signal.py b/products/signals/backend/temporal/emit_eval_signal.py
index 05a977f2b1e9..c8eb9797d253 100644
--- a/products/signals/backend/temporal/emit_eval_signal.py
+++ b/products/signals/backend/temporal/emit_eval_signal.py
@@ -12,6 +12,7 @@ from temporalio.common import RetryPolicy
from posthog.models.team import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.base import PostHogWorkflow
+from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.models import SignalSourceConfig
from products.signals.backend.temporal.llm import call_llm
@@ -111,7 +112,7 @@ async def summarize_eval_for_signal(inputs: EmitEvalSignalInputs) -> EvalSignalS
@temporalio.activity.defn
+@scoped_temporal()
async def emit_eval_signal_activity(inputs: EmitEvalSignalInputs) -> None:
def _is_eval_enabled() -> Team | None:
"""Check SignalSourceConfig and return Team if this eval is enabled, else None."""
diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.py
index 72d806be8c70..a2c8450065e0 100644
--- a/products/signals/backend/temporal/grouping.py
+++ b/products/signals/backend/temporal/grouping.py
@@ -26,6 +26,7 @@ from posthog.api.embedding_worker import async_generate_embedding, emit_embeddin
from posthog.event_usage import groups
from posthog.models import Team
from posthog.sync import database_sync_to_async
+from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.models import SignalReport
from products.signals.backend.temporal.llm import MAX_QUERY_TOKENS, call_llm, truncate_query_to_token_limit
@@ -80,7 +81,7 @@ class GenerateEmbeddingOutput:
@temporalio.activity.defn
+@scoped_temporal()
async def get_embedding_activity(input: GenerateEmbeddingInput) -> GenerateEmbeddingOutput:
"""Generate embedding for signal content using the embedding worker API."""
try:
@@ -186,7 +187,7 @@ class GenerateSearchQueriesOutput:
@temporalio.activity.defn
+@scoped_temporal()
async def generate_search_queries_activity(input: GenerateSearchQueriesInput) -> GenerateSearchQueriesOutput:
"""Use LLM to generate 1-3 search queries for finding related signals."""
try:
@@ -473,7 +474,7 @@ class MatchSignalToReportInput:
@temporalio.activity.defn
+@scoped_temporal()
async def match_signal_to_report_activity(input: MatchSignalToReportInput) -> MatchResult:
"""Determine if a new signal matches an existing report or needs a new one."""
try:
@@ -513,7 +514,7 @@ class FetchReportContextsOutput:
@temporalio.activity.defn
+@scoped_temporal()
async def fetch_report_contexts_activity(input: FetchReportContextsInput) -> FetchReportContextsOutput:
"""Fetch lightweight context (title, signal count) for reports from Postgres."""
if not input.report_ids:
@@ -591,7 +592,7 @@ async def verify_match_specificity(
@temporalio.activity.defn
+@scoped_temporal()
async def verify_match_specificity_activity(input: VerifyMatchSpecificityInput) -> VerifyMatchSpecificityOutput:
"""Verify that adding a signal to a group produces a specific-enough PR title."""
try:
@@ -647,7 +648,7 @@ class AssignAndEmitSignalOutput:
@temporalio.activity.defn
+@scoped_temporal()
async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> AssignAndEmitSignalOutput:
match_result = input.match_result
diff --git a/products/signals/backend/temporal/grouping_v2.py b/products/signals/backend/temporal/grouping_v2.py
index b43b75bcdc10..10b622ecab97 100644
--- a/products/signals/backend/temporal/grouping_v2.py
+++ b/products/signals/backend/temporal/grouping_v2.py
@@ -15,6 +15,7 @@ from temporalio.service import RPCError, RPCStatusCode
from posthog.storage import object_storage
from posthog.temporal.common.client import async_connect
+from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.temporal.grouping import (
TYPE_EXAMPLES_CACHE_TTL,
@@ -52,7 +53,7 @@ class CollectedBatch:
@activity.defn
+@scoped_temporal()
async def read_signals_from_s3_activity(input: ReadSignalsFromS3Input) -> ReadSignalsFromS3Output:
raw = await sync_to_async(object_storage.read, thread_sensitive=False)(input.object_key)
if raw is None:
diff --git a/products/signals/backend/temporal/reingestion.py b/products/signals/backend/temporal/reingestion.py
index 35c38ee9cc7a..513c469800cb 100644
--- a/products/signals/backend/temporal/reingestion.py
+++ b/products/signals/backend/temporal/reingestion.py
@@ -16,6 +16,7 @@ from posthog.hogql import ast
from posthog.api.embedding_worker import emit_embedding_request
from posthog.models import Team
from posthog.sync import database_sync_to_async
+from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.api import emit_signal
from products.signals.backend.models import SignalReport, SignalReportArtefact
@@ -53,7 +54,7 @@ class SoftDeleteReportSignalsInput:
@temporalio.activity.defn
+@scoped_temporal()
async def soft_delete_report_signals_activity(input: SoftDeleteReportSignalsInput) -> None:
"""Soft-delete all ClickHouse signals for a report by re-emitting with metadata.deleted=True."""
team = await Team.objects.aget(pk=input.team_id)
@@ -76,7 +77,7 @@ class DeleteReportInput:
@temporalio.activity.defn
+@scoped_temporal()
async def delete_report_activity(input: DeleteReportInput) -> None:
"""Transition a report to DELETED status in Postgres. Idempotent — no-ops if already deleted."""
@@ -102,7 +103,7 @@ class ReingestSignalsInput:
@temporalio.activity.defn
+@scoped_temporal()
async def reingest_signals_activity(input: ReingestSignalsInput) -> None:
"""Re-emit all signals via emit_signal() through the active Signals pipeline."""
team = await Team.objects.aget(pk=input.team_id)
@@ -160,7 +161,7 @@ class DeleteTeamReportsInput:
@temporalio.activity.defn
+@scoped_temporal()
async def process_team_signals_batch_activity(input: ProcessTeamSignalsBatchInput) -> ProcessTeamSignalsBatchOutput:
team = await Team.objects.aget(pk=input.team_id)
@@ -258,7 +259,7 @@ async def process_team_signals_batch_activity(input: ProcessTeamSignalsBatchInpu
@temporalio.activity.defn
+@scoped_temporal()
async def pause_grouping_until_activity(input: PauseGroupingUntilInput) -> None:
await TeamSignalGroupingV2Workflow.pause_until(input.team_id, input.timestamp)
logger.info(
@@ -269,13 +270,13 @@ async def pause_grouping_until_activity(input: PauseGroupingUntilInput) -> None:
@temporalio.activity.defn
+@scoped_temporal()
async def get_grouping_paused_state_activity(input: GetGroupingPausedStateInput) -> datetime | None:
return await TeamSignalGroupingV2Workflow.paused_state(input.team_id)
@temporalio.activity.defn
+@scoped_temporal()
async def restore_grouping_pause_activity(input: RestoreGroupingPauseInput) -> None:
if input.paused_until is not None and input.paused_until > datetime.now(tz=UTC):
await TeamSignalGroupingV2Workflow.pause_until(input.team_id, input.paused_until)
@@ -291,7 +292,7 @@ async def restore_grouping_pause_activity(input: RestoreGroupingPauseInput) -> N
@temporalio.activity.defn
+@scoped_temporal()
async def delete_team_reports_activity(input: DeleteTeamReportsInput) -> None:
def do_delete() -> tuple[int, int]:
artefact_count = SignalReportArtefact.objects.filter(team_id=input.team_id).count()
diff --git a/products/signals/backend/temporal/report_safety_judge.py b/products/signals/backend/temporal/report_safety_judge.py
index 63db08611cbf..75572cc2d5b5 100644
--- a/products/signals/backend/temporal/report_safety_judge.py
+++ b/products/signals/backend/temporal/report_safety_judge.py
@@ -4,9 +4,10 @@ from typing import Optional
import structlog
import temporalio
-import posthoganalytics
from pydantic import BaseModel, Field, model_validator
+from posthog.temporal.common.scoped import scoped_temporal
+
from products.signals.backend.models import SignalReportArtefact
from products.signals.backend.temporal.llm import call_llm
from products.signals.backend.temporal.types import SignalData, render_signals_to_text
@@ -109,7 +110,7 @@ class SafetyJudgeOutput:
@temporalio.activity.defn
+@scoped_temporal()
async def report_safety_judge_activity(input: SafetyJudgeInput) -> SafetyJudgeOutput:
"""Assess report for prompt injection attacks and store result as artefact."""
try:
diff --git a/products/signals/backend/temporal/safety_filter.py b/products/signals/backend/temporal/safety_filter.py
index 622d5a7aefa3..306e8bc02ca9 100644
--- a/products/signals/backend/temporal/safety_filter.py
+++ b/products/signals/backend/temporal/safety_filter.py
@@ -3,10 +3,11 @@ from dataclasses import dataclass
from typing import Optional
import structlog
-import posthoganalytics
from pydantic import BaseModel, Field, model_validator
from temporalio import activity
+from posthog.temporal.common.scoped import scoped_temporal
+
from products.signals.backend.temporal.llm import EmptyLLMResponseError, call_llm
logger = structlog.get_logger(__name__)
@@ -130,7 +131,7 @@ async def safety_filter(description: str) -> SafetyFilterJudgeResponse:
@activity.defn
+@scoped_temporal()
async def safety_filter_activity(input: SafetyFilterInput) -> SafetyFilterOutput:
"""Filter out unsafe signals before passing them through the pipeline."""
try:
diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.py
index 90f817a1c7e1..b5c4ca235992 100644
--- a/products/signals/backend/temporal/signal_queries.py
+++ b/products/signals/backend/temporal/signal_queries.py
@@ -6,7 +6,6 @@ from typing import Union
import structlog
import temporalio
-import posthoganalytics
from posthog.schema import EmbeddingModelName
@@ -16,6 +15,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.api.embedding_worker import emit_embedding_request
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.models import Team
+from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.temporal.clickhouse import execute_hogql_query_with_retry
from products.signals.backend.temporal.types import SignalCandidate, SignalData, SignalTypeExample
@@ -174,7 +174,7 @@ class FetchSignalTypeExamplesOutput:
@temporalio.activity.defn
+@scoped_temporal()
async def fetch_signal_type_examples_activity(input: FetchSignalTypeExamplesInput) -> FetchSignalTypeExamplesOutput:
"""Fetch one example signal per unique (source_product, source_type) pair from ClickHouse."""
try:
@@ -257,7 +257,7 @@ class RunSignalSemanticSearchOutput:
@temporalio.activity.defn
+@scoped_temporal()
async def run_signal_semantic_search_activity(input: RunSignalSemanticSearchInput) -> RunSignalSemanticSearchOutput:
"""Run a nearest neighbor query against the signal embeddings in ClickHouse."""
try:
@@ -337,7 +337,7 @@ class WaitForClickHouseInput:
@temporalio.activity.defn
+@scoped_temporal()
async def wait_for_signal_in_clickhouse_activity(input: WaitForClickHouseInput) -> None:
"""Poll ClickHouse until all emitted signals appear, or give up after max_wait_time_seconds.
@@ -440,7 +440,7 @@ class FetchSignalsForReportOutput:
@temporalio.activity.defn
+@scoped_temporal()
async def fetch_signals_for_report_activity(input: FetchSignalsForReportInput) -> FetchSignalsForReportOutput:
try:
team = await Team.objects.aget(pk=input.team_id)
diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.py
index 1c2d742c41ef..4dbebc69a547 100644
--- a/products/signals/backend/temporal/summary.py
+++ b/products/signals/backend/temporal/summary.py
@@ -17,6 +17,7 @@ from posthog.kafka_client.routing import get_producer
from posthog.kafka_client.topics import KAFKA_SIGNALS_REPORT_COMPLETED
from posthog.models import Organization, Team
from posthog.sync import database_sync_to_async
+from posthog.temporal.common.scoped import scoped_temporal
from products.signals.backend.models import SignalReport
from products.signals.backend.report_generation.research import ActionabilityChoice
@@ -353,7 +354,7 @@ class MarkReportInProgressInput:
@temporalio.activity.defn
+@scoped_temporal()
async def mark_report_in_progress_activity(input: MarkReportInProgressInput) -> None:
"""Mark a report as in_progress and advance signals_at_run by 3.
@@ -406,7 +407,7 @@ class MarkReportReadyInput:
@temporalio.activity.defn
+@scoped_temporal()
async def mark_report_ready_activity(input: MarkReportReadyInput) -> bool:
"""Mark a report as ready. Returns True if new signals arrived during the run."""
try:
@@ -463,7 +464,7 @@ class MarkReportFailedInput:
@temporalio.activity.defn
+@scoped_temporal()
async def mark_report_failed_activity(input: MarkReportFailedInput) -> None:
"""Mark a report as failed and store the error message."""
try:
@@ -514,7 +515,7 @@ class MarkReportPendingInput:
@temporalio.activity.defn
+@scoped_temporal()
async def mark_report_pending_input_activity(input: MarkReportPendingInput) -> None:
"""Mark a report as pending human input, storing the draft title/summary for human review."""
try:
@@ -564,7 +565,7 @@ class ResetReportToPotentialInput:
@temporalio.activity.defn
+@scoped_temporal()
async def reset_report_to_potential_activity(input: ResetReportToPotentialInput) -> None:
"""Reset a report's weight to 0 and status to potential (e.g. when deemed not actionable)."""
try:
@@ -610,7 +611,7 @@ class PublishReportCompletedInput:
@temporalio.activity.defn
+@scoped_temporal()
async def publish_report_completed_activity(input: PublishReportCompletedInput) -> None:
"""Publish a message to Kafka when a report is generated or re-generated."""
try: