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(tasks): route thin-tail run viewers agent-proxy (#101108)

Alessandro Pogliaghif619f38ecc7d
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index 37b35a81ecf2..8ce6296e12ae 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -5055,7 +5055,9 @@ describe('runStreamLogic', () => {
baseUrl: 'https://proxy.example/',
token: 'tok-1',
})
- expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledWith('997', 'task-1', 'run-1')
+ expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledWith('997', 'task-1', 'run-1', {
+ resync: true,
+ })
})
it('falls back to Django when the server resolves no base URL', async () => {
@@ -5082,7 +5084,7 @@ describe('runStreamLogic', () => {
logic.actions.openSseForRun({ taskId: 'task-1', runId: 'run-1' })
await flushPromises()
- expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledWith('997', 'task-1', 'run-1')
+ expect(tasksRunsStreamTokenRetrieve).toHaveBeenCalledWith('997', 'task-1', 'run-1', { resync: true })
expect(MockStream.latest().options.proxyTarget).toEqual({
baseUrl: 'https://proxy.example',
token: 'tok-1',
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index be2913deea52..b9e312f65310 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -235,7 +235,9 @@ export async function resolveStreamTarget(
return null
}
try {
- const { token, stream_base_url } = await tasksRunsStreamTokenRetrieve(projectId, taskId, runId)
+ const { token, stream_base_url } = await tasksRunsStreamTokenRetrieve(projectId, taskId, runId, {
+ resync: true,
+ })
if (!stream_base_url) {
return null
}
diff --git a/products/tasks/backend/facade/metrics.py b/products/tasks/backend/facade/metrics.py
index 5e89b80600de..92d4dea621c4 100644
--- a/products/tasks/backend/facade/metrics.py
+++ b/products/tasks/backend/facade/metrics.py
@@ -8,6 +8,7 @@ view imports them from here rather than reaching the internal ``metrics`` module
from products.tasks.backend.metrics import (
StreamConnectionOutcome,
+ StreamTokenRoute,
observe_stream_backlog_bytes,
observe_stream_backlog_gap,
observe_stream_backlog_oversized,
@@ -17,11 +18,13 @@ from products.tasks.backend.metrics import (
observe_stream_connection_opened,
observe_stream_length_on_connect,
observe_stream_resume_gap,
+ observe_stream_token_routed,
origin_product_label,
)
__all__ = [
"StreamConnectionOutcome",
+ "StreamTokenRoute",
"observe_stream_backlog_bytes",
"observe_stream_backlog_gap",
"observe_stream_backlog_oversized",
@@ -31,5 +34,6 @@ __all__ = [
"observe_stream_connection_opened",
"observe_stream_length_on_connect",
"observe_stream_resume_gap",
+ "observe_stream_token_routed",
"origin_product_label",
]
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index 40d003e8b9bf..8edec4994ecd 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -36,6 +36,7 @@ StreamConnectionOutcome = Literal[
"backlog_busy",
]
StreamWriteSkippedPath = Literal["ingest", "mirror", "relay"]
+StreamTokenRoute = Literal["proxy", "django", "thin_tail_withheld"]
_ALLOWED_MODES = {"background", "interactive"}
_ALLOWED_RUN_SOURCES = {"manual", "signal_report", "agent"}
_ALLOWED_RUNTIME_ADAPTERS = {"claude", "codex"}
@@ -314,6 +315,12 @@ TASK_RUN_STREAM_RESUME_GAP_TOTAL = Counter(
labelnames=["origin_product"],
)
+TASK_RUN_STREAM_TOKEN_ROUTED_TOTAL = Counter(
+ "posthog_tasks_task_run_stream_token_routed_total",
+ "Stream read tokens minted, labeled by the read leg the client was routed to and whether it asked to resync",
+ labelnames=["origin_product", "route", "resync_requested"],
+)
+
TASK_RUN_STREAM_WRITE_SKIPPED_TOTAL = Counter(
"posthog_tasks_task_run_stream_write_skipped_total",
"Task-run events not mirrored into Redis because presence gating found no attached reader",
@@ -656,6 +663,14 @@ def observe_stream_resume_gap(origin_product: str) -> None:
TASK_RUN_STREAM_RESUME_GAP_TOTAL.labels(origin_product=origin_product).inc()
+def observe_stream_token_routed(origin_product: str, route: StreamTokenRoute, resync_requested: bool) -> None:
+ TASK_RUN_STREAM_TOKEN_ROUTED_TOTAL.labels(
+ origin_product=_metric_label(origin_product),
+ route=route,
+ resync_requested="true" if resync_requested else "false",
+ ).inc()
+
+
def observe_stream_write_skipped(path: StreamWriteSkippedPath, origin_product: str | None = None) -> None:
TASK_RUN_STREAM_WRITE_SKIPPED_TOTAL.labels(path=path, origin_product=_metric_label(origin_product)).inc()
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index be77d349b422..5fe4c8c48001 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -3036,6 +3036,20 @@ class ConnectionTokenResponseSerializer(serializers.Serializer):
token = serializers.CharField(help_text="JWT token for authenticating with the sandbox")
+class StreamReadTokenQuerySerializer(serializers.Serializer):
+ """Query parameters for requesting a task run stream read token"""
+
+ resync = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "Set to true when the client can rebuild the run from its durable log after the agent-proxy "
+ "reports a trimmed stream cursor. Without it, runs that keep only a short live tail in Redis "
+ "are read from the Django endpoint, which replays the durable backlog itself."
+ ),
+ )
+
+
class StreamReadTokenResponseSerializer(serializers.Serializer):
"""Response containing a JWT token (and resolved base URL) for reading a task run's live event stream"""
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index da781ba34a78..3e4a4ff3c940 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -85,6 +85,7 @@ from products.tasks.backend.facade.compute_quota import ComputeBillingLimitExcee
from products.tasks.backend.facade.contracts import TaskAnalysisError, TaskRunLogAppendUnserialized
from products.tasks.backend.facade.metrics import (
StreamConnectionOutcome,
+ StreamTokenRoute,
observe_stream_backlog_bytes,
observe_stream_backlog_gap,
observe_stream_backlog_oversized,
@@ -94,6 +95,7 @@ from products.tasks.backend.facade.metrics import (
observe_stream_connection_opened,
observe_stream_length_on_connect,
observe_stream_resume_gap,
+ observe_stream_token_routed,
)
from products.tasks.backend.facade.model_catalogue import TASK_RUN_GATEWAY_PRODUCT, available_model_choices
from products.tasks.backend.facade.run_config import (
@@ -135,6 +137,7 @@ from products.tasks.backend.presentation.serializers import (
SlackThreadContextQuerySerializer,
SlackThreadContextResponseSerializer,
SlackThreadContextThreadSerializer,
+ StreamReadTokenQuerySerializer,
StreamReadTokenResponseSerializer,
TaskArtifactsResponseSerializer,
TaskBasicSerializer,
@@ -2947,6 +2950,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(ConnectionTokenResponseSerializer({"token": token}).data)
@validated_request(
+ query_serializer=StreamReadTokenQuerySerializer,
responses={
200: OpenApiResponse(
response=StreamReadTokenResponseSerializer,
@@ -2955,7 +2959,11 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
404: OpenApiResponse(description="Task run not found"),
},
summary="Get task run stream read token",
- description="Generate a run-scoped JWT that authorizes reading this task run's live event stream via the agent-proxy.",
+ description=(
+ "Generate a run-scoped JWT that authorizes reading this task run's live event stream via the agent-proxy. "
+ "A run that keeps only a short live tail in Redis is routed to the proxy only when the client sets "
+ "resync=true, meaning it rebuilds from the durable run log when the proxy reports a trimmed cursor."
+ ),
)
@action(
detail=True,
@@ -2969,18 +2977,21 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
token = tasks_facade.create_task_run_stream_read_token(pk, task_id, self.team_id)
if stream_info is None or token is None:
raise NotFound()
- # Only the Django read leg serves the durable backlog, so thin-tail runs must
- # not be routed to the agent-proxy — a proxy reader would silently lose
- # everything behind the 500-entry live window.
+ client_can_resync = bool(getattr(request, "validated_query_data", {}).get("resync"))
+ thin_tail_withheld = run_stream_thin_tail(stream_info.state) and not client_can_resync
stream_base_url = (
None
- if run_stream_thin_tail(stream_info.state)
+ if thin_tail_withheld
else tasks_facade.resolve_stream_base_url(
distinct_id=request.user.distinct_id,
organization_id=self.team.organization_id,
force_proxy=tasks_facade.task_uses_pi_runtime(task_id, self.team_id),
)
)
+ route: StreamTokenRoute = "thin_tail_withheld"
+ if not thin_tail_withheld:
+ route = "proxy" if stream_base_url else "django"
+ observe_stream_token_routed(stream_info.origin_product, route, client_can_resync)
return Response(StreamReadTokenResponseSerializer({"token": token, "stream_base_url": stream_base_url}).data)
@validated_request(
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 5966e393d886..c33ab5495a2a 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -9303,10 +9303,16 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["stream_base_url"], "https://agent-proxy.example.com")
+ @parameterized.expand(
+ [
+ ("resync_capable_client", "?resync=true", "https://agent-proxy.example.com", "proxy", True),
+ ("legacy_client", "", None, "thin_tail_withheld", False),
+ ]
+ )
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
- def test_stream_token_omits_proxy_url_for_thin_tail_run(self):
- # Only the Django read leg serves the durable backlog, so a thin-tail run must
- # never be routed to the agent-proxy even with the proxy flag enabled.
+ def test_stream_token_routes_thin_tail_run_by_client_resync_support(
+ self, _name, query, expected_base_url, expected_route, expected_resync_requested
+ ):
reset_sandbox_jwt_key_cache()
task = self.create_task()
@@ -9317,11 +9323,13 @@ class TestTaskRunAPI(BaseTaskAPITest):
with (
self.settings(TASKS_AGENT_PROXY_PUBLIC_URL="https://agent-proxy.example.com", DEBUG=False),
patch("products.tasks.backend.facade.api.posthoganalytics.feature_enabled", return_value=True),
+ patch("products.tasks.backend.presentation.views.api.observe_stream_token_routed") as observe_routed,
):
- response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")
+ response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/{query}")
self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertIsNone(response.json()["stream_base_url"])
+ self.assertEqual(response.json()["stream_base_url"], expected_base_url)
+ observe_routed.assert_called_once_with(task.origin_product, expected_route, expected_resync_requested)
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
def test_stream_token_omits_proxy_url_when_flag_disabled(self):
@@ -9341,11 +9349,13 @@ class TestTaskRunAPI(BaseTaskAPITest):
"products.tasks.backend.facade.api.posthoganalytics.feature_enabled",
side_effect=flag_enabled,
),
+ patch("products.tasks.backend.presentation.views.api.observe_stream_token_routed") as observe_routed,
):
response = self.client.get(f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/stream_token/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsNone(response.json()["stream_base_url"])
+ observe_routed.assert_called_once_with(task.origin_product, "django", False)
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
def test_stream_token_returns_proxy_url_for_pi_when_flag_disabled(self):
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 392180f9e703..0c77a8645732 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -5801,6 +5801,13 @@ export type TasksRunsStreamRetrieveParams = {
start?: string
}
+export type TasksRunsStreamTokenRetrieveParams = {
+ /**
+ * Set to true when the client can rebuild the run from its durable log after the agent-proxy reports a trimmed stream cursor. Without it, runs that keep only a short live tail in Redis are read from the Django endpoint, which replays the durable backlog itself.
+ */
+ resync?: boolean
+}
+
export type TasksThreadMessagesListParams = {
/**
* Number of results to return per page.
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index c2a30691a548..758ac77f0b18 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -150,6 +150,7 @@ import type {
TasksRunsListParams,
TasksRunsSessionLogsRetrieveParams,
TasksRunsStreamRetrieveParams,
+ TasksRunsStreamTokenRetrieveParams,
TasksSearchRetrieveParams,
TasksSlackThreadContextRetrieveParams,
TasksSummariesCreateParams,
@@ -2390,21 +2391,39 @@ export const tasksRunsStreamRetrieve = async (
})
}
-export const getTasksRunsStreamTokenRetrieveUrl = (projectId: string, taskId: string, id: string) => {
- return `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/stream_token/`
+export const getTasksRunsStreamTokenRetrieveUrl = (
+ projectId: string,
+ taskId: string,
+ id: string,
+ params?: TasksRunsStreamTokenRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/stream_token/?${stringifiedParams}`
+ : `/api/projects/${projectId}/tasks/${taskId}/runs/${id}/stream_token/`
}
/**
- * Generate a run-scoped JWT that authorizes reading this task run's live event stream via the agent-proxy.
+ * Generate a run-scoped JWT that authorizes reading this task run's live event stream via the agent-proxy. A run that keeps only a short live tail in Redis is routed to the proxy only when the client sets resync=true, meaning it rebuilds from the durable run log when the proxy reports a trimmed cursor.
* @summary Get task run stream read token
*/
export const tasksRunsStreamTokenRetrieve = async (
projectId: string,
taskId: string,
id: string,
+ params?: TasksRunsStreamTokenRetrieveParams,
options?: RequestInit
): Promise<StreamReadTokenResponseApi> => {
- return apiMutator<StreamReadTokenResponseApi>(getTasksRunsStreamTokenRetrieveUrl(projectId, taskId, id), {
+ return apiMutator<StreamReadTokenResponseApi>(getTasksRunsStreamTokenRetrieveUrl(projectId, taskId, id, params), {
...options,
method: 'GET',
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bc1e245bc91c..8164a6e1cf0c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -109200,6 +109200,13 @@ export namespace Schemas {
start?: string;
};
+ export type TasksRunsStreamTokenRetrieveParams = {
+ /**
+ * Set to true when the client can rebuild the run from its durable log after the agent-proxy reports a trimmed stream cursor. Without it, runs that keep only a short live tail in Redis are read from the Django endpoint, which replays the durable backlog itself.
+ */
+ resync?: boolean;
+ };
+
export type TasksThreadMessagesListParams = {
/**
* Number of results to return per page.