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(tasks): use the run uuid as the trace id for task runs (#116711)

Charles Vien578be132d838
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index c1897ba57ad5..62e7ac0399db 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -327,6 +327,13 @@ The agent-server exports run/turn/tool lifecycle metadata (never message content
Telemetry stays off when either of the first two vars is unset.
For local Docker sandboxes the localhost URLs are rewritten to `host.docker.internal` automatically; local ingestion requires the `capture-logs` service to be running.
+The trace id of a run is its run UUID without dashes, so `/tracing?trace=<run UUID without dashes>` in the telemetry project opens the run.
+The agent-server spans, the mirrored run logs and the `process-task` Temporal workflow spans all carry that trace id.
+The workflow spans carry it only when the run has the telemetry flag on.
+Those runs are also marked as sampled, so a parent-based sampler on the worker keeps every one of them.
+They show up in the same trace only if the Temporal worker's collector forwards to the telemetry project.
+The workflow and the agent-server share a trace id but no parent span, so the workflow spans sit under a `<parent span missing>` row beside `task_run`.
+
### MCP server `.env`
`MODAL_DOCKER` (and the local Docker provider) both depend on the MCP server running at `localhost:8787`. The server reads its config from `services/mcp/.env` — without it, things like `POSTHOG_API_BASE_URL`, the UI-apps token, and analytics keys are missing and the server will either refuse to start or return broken responses to the sandbox.
diff --git a/packages/agent/packages/agent/README.md b/packages/agent/packages/agent/README.md
index fa9e856f20b6..3f0a46dbca67 100644
--- a/packages/agent/packages/agent/README.md
+++ b/packages/agent/packages/agent/README.md
@@ -177,6 +177,10 @@ Optional run telemetry (the logs pair must both be set, otherwise telemetry stay
When set, `AgentServer` ships an allowlisted metadata subset of the session log (run/turn/tool lifecycle, usage, error provenance — never message content, tool arguments, or raw error text; see `src/otel-telemetry.ts`) to PostHog Logs, tagged with `service.name=posthog-code-agent` and `run_id`/`task_id`/`team_id`/`user_id`/`distinct_id` resource attributes so cloud runs are filterable per user. With the traces URL set, each run also produces an APM trace (`task_run` root span, a `turn` span per prompt, a `tool_call:<kind>` span per tool call; see `src/otel-trace-builder.ts`), and log records carry the matching trace/span ids so Logs and APM cross-link.
+The trace id is the run UUID without dashes.
+The backend starts the run's `process-task` workflow under the same trace id and stamps it on mirrored run logs, so all three share one trace.
+A run id that is not a UUID gets a random trace id.
+
The `task_run` root span is ended and exported at the run's in-process terminal point — a background run's prompt settling, a terminal failure, or session cleanup (`close`). It cannot wait for teardown: agent-server is an exec'd process inside the sandbox, so `docker stop` / Modal terminate kill it without SIGTERM ever arriving, and a span still open at that moment is lost. Interactive sessions that end via hard teardown (e.g. inactivity timeout) therefore lose the root span; turn/tool spans and logs still assemble under the same trace id.
When run tracing records spans, cloud Claude and Codex gateway requests include `task_run_trace_id` and `task_run_span_id` on their AI events.
diff --git a/packages/agent/packages/agent/src/otel-telemetry.test.ts b/packages/agent/packages/agent/src/otel-telemetry.test.ts
index c3ab1b10a399..855c01c6a13e 100644
--- a/packages/agent/packages/agent/src/otel-telemetry.test.ts
+++ b/packages/agent/packages/agent/src/otel-telemetry.test.ts
@@ -28,7 +28,7 @@ vi.mock("@opentelemetry/exporter-trace-otlp-http", () => ({
},
}));
-const RUN_ID = "run-456";
+const RUN_ID = "0190a5f0-7c3e-7d2a-9b1c-3f4e5d6c7b8a";
const RESOURCE = {
taskId: "task-123",
@@ -629,6 +629,7 @@ describe("OtelRunTelemetry", () => {
expect(tool.parentSpanContext?.spanId).toBe(turn.spanContext().spanId);
const traceId = root.spanContext().traceId;
+ expect(traceId).toBe(RUN_ID.replaceAll("-", ""));
expect(turn.spanContext().traceId).toBe(traceId);
expect(tool.spanContext().traceId).toBe(traceId);
diff --git a/packages/agent/packages/agent/src/otel-telemetry.ts b/packages/agent/packages/agent/src/otel-telemetry.ts
index 226ab19539f1..6b93c9a077f9 100644
--- a/packages/agent/packages/agent/src/otel-telemetry.ts
+++ b/packages/agent/packages/agent/src/otel-telemetry.ts
@@ -338,6 +338,7 @@ export class OtelRunTelemetry implements SessionLogSink {
{
url: config.tracesUrl,
token: config.token,
+ runId: resource.runId,
flushIntervalMs: config.flushIntervalMs,
},
otelResource,
diff --git a/packages/agent/packages/agent/src/otel-trace-builder.ts b/packages/agent/packages/agent/src/otel-trace-builder.ts
index 2714cf3d8312..4ae31f38e277 100644
--- a/packages/agent/packages/agent/src/otel-trace-builder.ts
+++ b/packages/agent/packages/agent/src/otel-trace-builder.ts
@@ -13,6 +13,8 @@ import type { Resource } from "@opentelemetry/resources";
import {
BasicTracerProvider,
BatchSpanProcessor,
+ type IdGenerator,
+ RandomIdGenerator,
} from "@opentelemetry/sdk-trace-base";
import { POSTHOG_NOTIFICATIONS } from "./acp-extensions";
import {
@@ -28,11 +30,25 @@ import {
} from "./otel-attributes";
import type { StoredNotification } from "./types";
+const TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;
+
+function runIdGenerator(runId: string): IdGenerator {
+ const random = new RandomIdGenerator();
+ // run_trace.py and run_log_mirror.py derive the same trace id. Change all three together.
+ const traceId = runId.replaceAll("-", "").toLowerCase();
+ if (!TRACE_ID_PATTERN.test(traceId)) return random;
+ return {
+ generateTraceId: () => traceId,
+ generateSpanId: () => random.generateSpanId(),
+ };
+}
+
export interface RunTraceBuilderConfig {
/** Full OTLP traces endpoint URL, e.g. "https://us.i.posthog.com/i/v1/traces" */
url: string;
/** Project API key sent as a Bearer token */
token: string;
+ runId: string;
/** Batch flush interval in ms (default: 2000) */
flushIntervalMs?: number;
}
@@ -76,6 +92,7 @@ export class RunTraceBuilder {
this.provider = new BasicTracerProvider({
resource,
+ idGenerator: runIdGenerator(config.runId),
spanProcessors: [
new BatchSpanProcessor(exporter, {
scheduledDelayMillis:
diff --git a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
index 5179a58da567..b49c53f19280 100644
--- a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
+++ b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
@@ -8,6 +8,7 @@ from datetime import timedelta
from functools import partial
from pathlib import Path
from time import monotonic
+from typing import Any
from django.conf import settings
from django.core.management.base import BaseCommand
@@ -16,7 +17,7 @@ from django.db import DatabaseError, close_old_connections
from asgiref.sync import sync_to_async
from prometheus_client import start_http_server
from temporalio.client import Client, WorkflowExecutionStatus
-from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
+from temporalio.common import WorkflowIDReusePolicy
from temporalio.exceptions import WorkflowAlreadyStartedError
from temporalio.service import RPCError, RPCStatusCode
@@ -48,7 +49,7 @@ from products.tasks.backend.metrics import (
observe_task_run_workflow_start,
)
from products.tasks.backend.models import Task, TaskRun, TaskWorkflowDispatch
-from products.tasks.backend.temporal.client import _capture_run_feature_flags
+from products.tasks.backend.temporal.client import _capture_run_feature_flags, start_process_task_workflow
from products.tasks.backend.temporal.process_task.workflow import ProcessTaskInput
from products.tasks.backend.visibility import task_control_q
@@ -84,6 +85,14 @@ def _scheduled_run_usage_error(user: User, team_id: int) -> str | None:
close_old_connections()
+def _capture_run_feature_flags_in_worker_thread(run_id: str) -> dict[str, Any]:
+ close_old_connections()
+ try:
+ return _capture_run_feature_flags(run_id)
+ finally:
+ close_old_connections()
+
+
async def dispatch_attempt_already_started(client: Client, dispatch: TaskWorkflowDispatch) -> bool:
try:
description = await client.get_workflow_handle(dispatch.workflow_id).describe(
@@ -250,7 +259,9 @@ class Command(BaseCommand):
await sync_to_async(mark_dead)(dispatch.id, instance_id, usage_error, "usage_limit")
WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="dead").inc()
return
- await sync_to_async(_capture_run_feature_flags, thread_sensitive=False)(str(run.id))
+ run_state = await sync_to_async(_capture_run_feature_flags_in_worker_thread, thread_sensitive=False)(
+ str(run.id)
+ )
if is_restart:
from products.tasks.backend.facade.streams import reset_task_run_stream # noqa: PLC0415
from products.tasks.backend.redis import run_uses_dedicated_stream # noqa: PLC0415
@@ -283,17 +294,16 @@ class Command(BaseCommand):
started = monotonic()
try:
try:
- await client.start_workflow(
- "process-task",
+ await start_process_task_workflow(
+ client,
workflow_input,
- id=dispatch.workflow_id,
+ workflow_id=dispatch.workflow_id,
id_reuse_policy=(
WorkflowIDReusePolicy.TERMINATE_IF_RUNNING
if is_restart
else WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY
),
- task_queue=settings.TASKS_TASK_QUEUE,
- retry_policy=RetryPolicy(maximum_attempts=3),
+ run_state=run_state,
rpc_timeout=timedelta(seconds=settings.TASKS_DISPATCHER_RPC_TIMEOUT_SECONDS),
)
finally:
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index 80b97612799d..40476dc2665c 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -25,7 +25,11 @@ from products.tasks.backend.constants import (
SANDBOX_EVENT_INGEST_FEATURE_FLAG,
)
from products.tasks.backend.error_telemetry import truncate_error_message
-from products.tasks.backend.feature_flags import is_agent_otel_telemetry_enabled, is_native_steering_signals_enabled
+from products.tasks.backend.feature_flags import (
+ agent_otel_telemetry_enabled_for_state,
+ is_agent_otel_telemetry_enabled,
+ is_native_steering_signals_enabled,
+)
from products.tasks.backend.logic.services.dev_stack_image import DEV_STACK_IMAGE_NAME
from products.tasks.backend.logic.services.dev_stack_image_refresh import reconcile_dev_stack_image
from products.tasks.backend.logic.services.dev_stack_image_state import DevStackImageState
@@ -43,10 +47,11 @@ from products.tasks.backend.temporal.constants import (
)
from products.tasks.backend.temporal.oauth import dispatched_run_scopes
from products.tasks.backend.temporal.process_task.workflow import PendingFollowup, ProcessTaskInput
+from products.tasks.backend.temporal.run_trace import run_trace_context
from products.tasks.backend.temporal.slack_relay.activities import RelaySlackMessageInput
if TYPE_CHECKING:
- pass
+ from temporalio.client import Client
logger = logging.getLogger(__name__)
@@ -151,16 +156,17 @@ def _evaluate_boot_rollout_flag(
return False
-def _capture_run_feature_flags(run_id: str) -> None:
+def _capture_run_feature_flags(run_id: str) -> dict[str, Any]:
"""Evaluate per-run rollout flags once at dispatch and stamp them into run state.
Idempotent per key, so retries and resumes keep the decision the run started with.
+ Returns the run state after stamping, or an empty state when the run is missing.
"""
try:
task_run = TaskRun.objects.select_related("task__created_by", "task__team").get(id=run_id)
except Exception:
logger.exception("run_feature_flag_capture_run_missing", extra={"run_id": run_id})
- return
+ return {}
state = task_run.state or {}
need_event_ingest = not isinstance(state.get("sandbox_event_ingest_enabled"), bool)
@@ -171,7 +177,7 @@ def _capture_run_feature_flags(run_id: str) -> None:
if not isinstance(state.get(state_key), bool)
]
if not need_event_ingest and not need_otel_telemetry and not pending_boot_flags:
- return
+ return state
task = task_run.task
organization_id = str(task.team.organization_id)
@@ -237,6 +243,28 @@ def _capture_run_feature_flags(run_id: str) -> None:
**{state_key: captured_state.get(state_key) for state_key, _ in _BOOT_ROLLOUT_FLAGS},
},
)
+ return captured_state
+
+
+async def start_process_task_workflow(
+ client: "Client",
+ workflow_input: ProcessTaskInput,
+ *,
+ workflow_id: str,
+ id_reuse_policy: WorkflowIDReusePolicy,
+ run_state: dict[str, Any],
+ rpc_timeout: timedelta | None = None,
+) -> None:
+ with run_trace_context(workflow_input.run_id, enabled=agent_otel_telemetry_enabled_for_state(run_state)):
+ await client.start_workflow(
+ "process-task",
+ workflow_input,
+ id=workflow_id,
+ id_reuse_policy=id_reuse_policy,
+ task_queue=settings.TASKS_TASK_QUEUE,
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ rpc_timeout=rpc_timeout,
+ )
async def _aget_task_run_for_metrics(run_id: str) -> TaskRun | None:
@@ -280,7 +308,7 @@ async def execute_task_processing_workflow_async(
task_run_for_metrics = await _aget_task_run_for_metrics(run_id)
observe_task_run_workflow_start(task_run_for_metrics, outcome="attempted", reason="requested")
await Team.objects.select_related("organization").aget(id=team_id)
- await sync_to_async(_capture_run_feature_flags)(run_id)
+ run_state = await sync_to_async(_capture_run_feature_flags)(run_id)
workflow_id = TaskRun.get_workflow_id(task_id, run_id, workflow_id_prefix)
if workflow_id_prefix:
@@ -302,13 +330,12 @@ async def execute_task_processing_workflow_async(
)
client = await async_connect()
- await client.start_workflow(
- "process-task",
+ await start_process_task_workflow(
+ client,
workflow_input,
- id=workflow_id,
+ workflow_id=workflow_id,
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
- task_queue=settings.TASKS_TASK_QUEUE,
- retry_policy=RetryPolicy(maximum_attempts=3),
+ run_state=run_state,
)
logger.info("task_processing_workflow_started", extra={"task_id": task_id, "run_id": run_id})
@@ -377,7 +404,7 @@ def execute_task_processing_workflow(
)
Team.objects.get(id=team_id)
- _capture_run_feature_flags(run_id)
+ run_state = _capture_run_feature_flags(run_id)
workflow_id = TaskRun.get_workflow_id(task_id, run_id, workflow_id_prefix)
if workflow_id_prefix:
@@ -406,13 +433,12 @@ def execute_task_processing_workflow(
)
asyncio.run(
- client.start_workflow(
- "process-task",
+ start_process_task_workflow(
+ client,
workflow_input,
- id=workflow_id,
+ workflow_id=workflow_id,
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
- task_queue=settings.TASKS_TASK_QUEUE,
- retry_policy=RetryPolicy(maximum_attempts=3),
+ run_state=run_state,
)
)
@@ -503,17 +529,16 @@ def redispatch_orphaned_task_run(run_id: str) -> str:
)
observe_task_run_workflow_start(task_run, outcome="attempted", reason="reconcile")
- _capture_run_feature_flags(run_id)
+ run_state = _capture_run_feature_flags(run_id)
try:
client = sync_connect()
asyncio.run(
- client.start_workflow(
- "process-task",
+ start_process_task_workflow(
+ client,
workflow_input,
- id=workflow_id,
+ workflow_id=workflow_id,
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,
- task_queue=settings.TASKS_TASK_QUEUE,
- retry_policy=RetryPolicy(maximum_attempts=3),
+ run_state=run_state,
)
)
except WorkflowAlreadyStartedError:
@@ -533,19 +558,18 @@ def redispatch_orphaned_task_run(run_id: str) -> str:
def resume_task_in_cloud_workflow(run_id: str, workflow_id: str) -> None:
- _capture_run_feature_flags(run_id)
+ run_state = _capture_run_feature_flags(run_id)
client = sync_connect()
asyncio.run(
- client.start_workflow(
- "process-task",
+ start_process_task_workflow(
+ client,
ProcessTaskInput(run_id=run_id),
- id=workflow_id,
+ workflow_id=workflow_id,
# TERMINATE_IF_RUNNING closes any prior workflow under this ID
# atomically before starting the new one, avoiding the async-cancel
# race where a best-effort cancel signal hasn't landed yet.
id_reuse_policy=WorkflowIDReusePolicy.TERMINATE_IF_RUNNING,
- task_queue=settings.TASKS_TASK_QUEUE,
- retry_policy=RetryPolicy(maximum_attempts=3),
+ run_state=run_state,
)
)
diff --git a/products/tasks/backend/temporal/run_trace.py b/products/tasks/backend/temporal/run_trace.py
new file mode 100644
index 000000000000..aeffbd7d68dc
--- /dev/null
+++ b/products/tasks/backend/temporal/run_trace.py
@@ -0,0 +1,39 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
+from uuid import UUID
+
+from opentelemetry import (
+ context as otel_context,
+ trace,
+)
+from opentelemetry.trace import NonRecordingSpan, SpanContext, TraceFlags
+
+_SPAN_ID_BITS = 64
+
+
+def run_span_context(run_id: str) -> SpanContext | None:
+ # otel-trace-builder.ts and run_log_mirror.py derive the same trace id. Change all three together.
+ try:
+ run_uuid = UUID(run_id)
+ except ValueError:
+ return None
+ return SpanContext(
+ trace_id=run_uuid.int,
+ span_id=run_uuid.int & ((1 << _SPAN_ID_BITS) - 1),
+ is_remote=True,
+ trace_flags=TraceFlags(TraceFlags.SAMPLED),
+ )
+
+
+@contextmanager
+def run_trace_context(run_id: str, *, enabled: bool) -> Iterator[None]:
+ span_context = run_span_context(run_id) if enabled else None
+ if span_context is None:
+ yield
+ return
+
+ token = otel_context.attach(trace.set_span_in_context(NonRecordingSpan(span_context)))
+ try:
+ yield
+ finally:
+ otel_context.detach(token)
diff --git a/products/tasks/backend/tests/test_temporal_client.py b/products/tasks/backend/tests/test_temporal_client.py
index 6d198a2d449a..4c81ba4dbf36 100644
--- a/products/tasks/backend/tests/test_temporal_client.py
+++ b/products/tasks/backend/tests/test_temporal_client.py
@@ -3,6 +3,7 @@ from unittest.mock import AsyncMock, Mock, patch
from django.test import SimpleTestCase, TestCase, override_settings
from asgiref.sync import async_to_sync
+from opentelemetry import propagate
from parameterized import parameterized
from temporalio.common import WorkflowIDReusePolicy
from temporalio.exceptions import WorkflowAlreadyStartedError
@@ -23,6 +24,7 @@ from products.tasks.backend.temporal.constants import (
STEERING_PROTOCOL_QUERY,
STEERING_PROTOCOL_QUERY_TIMEOUT,
)
+from products.tasks.backend.temporal.run_trace import run_trace_context
@override_settings(DEBUG=False)
@@ -119,6 +121,16 @@ class TestSignalTaskFollowupMessage(SimpleTestCase):
handle.query.assert_not_awaited()
+class TestRunTraceContext(SimpleTestCase):
+ def test_run_id_that_is_not_a_uuid_leaves_the_trace_context_alone(self) -> None:
+ propagated: dict[str, str] = {}
+
+ with run_trace_context("not-a-uuid", enabled=True):
+ propagate.inject(propagated)
+
+ self.assertEqual(propagated, {})
+
+
@override_settings(DEBUG=False)
class TestExecuteTaskProcessingWorkflow(TestCase):
def setUp(self) -> None:
@@ -253,6 +265,46 @@ class TestExecuteTaskProcessingWorkflow(TestCase):
send_feature_flag_events=False,
)
+ @parameterized.expand(
+ [
+ ("sync_telemetry_on", "sync", True),
+ ("async_telemetry_on", "async", True),
+ ("sync_telemetry_off", "sync", False),
+ ("async_telemetry_off", "async", False),
+ ]
+ )
+ def test_starts_workflow_in_the_run_trace_only_when_telemetry_is_enabled(
+ self, _name: str, executor: str, telemetry_enabled: bool
+ ) -> None:
+ run = self._create_run()
+ propagated: dict[str, str] = {}
+
+ async def record_propagated_context(*args: object, **kwargs: object) -> None:
+ propagate.inject(propagated)
+
+ client = Mock()
+ client.start_workflow = AsyncMock(side_effect=record_propagated_context)
+
+ connect_target = (
+ "products.tasks.backend.temporal.client.sync_connect"
+ if executor == "sync"
+ else "products.tasks.backend.temporal.client.async_connect"
+ )
+ connect_mock = Mock(return_value=client) if executor == "sync" else AsyncMock(return_value=client)
+
+ with (
+ patch(connect_target, connect_mock),
+ patch(
+ "products.tasks.backend.temporal.client.posthoganalytics.feature_enabled",
+ return_value=telemetry_enabled,
+ ),
+ ):
+ self._execute_workflow(executor, run, self.user.id)
+
+ client.start_workflow.assert_awaited_once()
+ expected = {"traceparent": f"00-{run.id.hex}-{run.id.hex[16:]}-01"} if telemetry_enabled else {}
+ self.assertEqual(propagated, expected)
+
def test_boot_flag_capture_keeps_existing_stamp_and_survives_one_flag_error(self) -> None:
run = self._create_run()
TaskRun.update_state_atomic(str(run.id), updates={"overlap_clone_boot_enabled": False})
diff --git a/products/tasks/backend/tests/test_workflow_dispatch.py b/products/tasks/backend/tests/test_workflow_dispatch.py
index a1975a4130e8..f2d62693149c 100644
--- a/products/tasks/backend/tests/test_workflow_dispatch.py
+++ b/products/tasks/backend/tests/test_workflow_dispatch.py
@@ -46,6 +46,7 @@ from products.tasks.backend.logic.services.workflow_dispatch import (
)
from products.tasks.backend.management.commands.run_task_workflow_dispatcher import (
Command,
+ _capture_run_feature_flags_in_worker_thread,
_scheduled_run_usage_error,
_user_can_dispatch,
dispatch_attempt_already_started,
@@ -960,6 +961,23 @@ class TestWorkflowDispatchPermissions(SimpleTestCase):
self.assertEqual(_scheduled_run_usage_error(user, 1), error)
self.assertEqual(close_connections.call_count, 2)
+ @parameterized.expand([("captured", False), ("error", True)])
+ @patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher.close_old_connections")
+ @patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher._capture_run_feature_flags")
+ def test_flag_capture_worker_releases_connections(
+ self, _name: str, capture_fails: bool, capture_flags: Mock, close_connections: Mock
+ ) -> None:
+ if capture_fails:
+ capture_flags.side_effect = RuntimeError("database unavailable")
+ with self.assertRaises(RuntimeError):
+ _capture_run_feature_flags_in_worker_thread("run-id")
+ else:
+ capture_flags.return_value = {"agent_otel_telemetry_enabled": True}
+ self.assertEqual(
+ _capture_run_feature_flags_in_worker_thread("run-id"), {"agent_otel_telemetry_enabled": True}
+ )
+ self.assertEqual(close_connections.call_count, 2)
+
def test_scheduled_usage_checks_do_not_block_each_other(self) -> None:
barrier = threading.Barrier(2, timeout=5)
run = Mock(status=TaskRun.Status.QUEUED, scheduled_at=django_timezone.now())