: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): label stream skip metrics with origin product (#92643)
Alessandro Pogliaghiaab5d665a67f
diff --git a/products/tasks/backend/logic/services/connection_token.py b/products/tasks/backend/logic/services/connection_token.pyindex 46b28274ddc2..2e06977e0fb4 100644--- a/products/tasks/backend/logic/services/connection_token.py+++ b/products/tasks/backend/logic/services/connection_token.py@@ -41,6 +41,7 @@ class SandboxEventIngestTokenPayload:team_id: intsandbox_id: str | Nonepresence_gated: bool = False+ origin_product: str | None = None@dataclass(frozen=True)@@ -56,6 +57,7 @@ class StreamReadTokenPayload:task_id: strteam_id: intpresence_gated: bool = False+ origin_product: str | None = Nonedef _normalize_pem_key(key: str) -> str:@@ -267,7 +269,11 @@ def create_sandbox_event_ingest_token(task_run,SANDBOX_EVENT_INGEST_AUDIENCE,ttl,- {"sandbox_id": active_sandbox_id, "presence_gated": presence_gated},+ {+ "sandbox_id": active_sandbox_id,+ "presence_gated": presence_gated,+ "origin_product": task_run.task.origin_product,+ },)@@ -279,6 +285,7 @@ def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenPateam_id = payload.get("team_id")sandbox_id = payload.get("sandbox_id")presence_gated = payload.get("presence_gated", False)+ origin_product = payload.get("origin_product")if not isinstance(run_id, str) or not isinstance(task_id, str) or type(team_id) is not int:raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")@@ -286,6 +293,8 @@ def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenParaise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")if not isinstance(presence_gated, bool):raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")+ if origin_product is not None and not isinstance(origin_product, str):+ raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")return SandboxEventIngestTokenPayload(run_id=run_id,@@ -293,6 +302,7 @@ def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenPateam_id=team_id,sandbox_id=sandbox_id,presence_gated=presence_gated,+ origin_product=origin_product,)@@ -306,7 +316,12 @@ def create_stream_read_token(task_run: TaskRun, ttl: timedelta = STREAM_READ_TOKtask run's stream."""presence_gated = run_stream_presence_gated(task_run.state)- return _encode_run_scoped_token(task_run, STREAM_READ_AUDIENCE, ttl, {"presence_gated": presence_gated})+ return _encode_run_scoped_token(+ task_run,+ STREAM_READ_AUDIENCE,+ ttl,+ {"presence_gated": presence_gated, "origin_product": task_run.task.origin_product},+ )def validate_stream_read_token(token: str) -> StreamReadTokenPayload:@@ -316,10 +331,19 @@ def validate_stream_read_token(token: str) -> StreamReadTokenPayload:task_id = payload.get("task_id")team_id = payload.get("team_id")presence_gated = payload.get("presence_gated", False)+ origin_product = payload.get("origin_product")if not isinstance(run_id, str) or not isinstance(task_id, str) or type(team_id) is not int:raise jwt.InvalidTokenError("Stream read token has invalid claims")if not isinstance(presence_gated, bool):raise jwt.InvalidTokenError("Stream read token has invalid claims")+ if origin_product is not None and not isinstance(origin_product, str):+ raise jwt.InvalidTokenError("Stream read token has invalid claims")- return StreamReadTokenPayload(run_id=run_id, task_id=task_id, team_id=team_id, presence_gated=presence_gated)+ return StreamReadTokenPayload(+ run_id=run_id,+ task_id=task_id,+ team_id=team_id,+ presence_gated=presence_gated,+ origin_product=origin_product,+ )diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.pyindex 6367bf81e5b3..e3c3710abbea 100644--- a/products/tasks/backend/logic/stream/event_ingest.py+++ b/products/tasks/backend/logic/stream/event_ingest.py@@ -126,7 +126,11 @@ async def handle_task_run_event_ingest(scope: ASGIMessage, receive: ASGIReceive,await _send_json(send, error.status_code, error.payload)return True- redis_stream = TaskRunRedisStream(get_task_run_stream_key(claims.run_id), presence_gated=claims.presence_gated)+ redis_stream = TaskRunRedisStream(+ get_task_run_stream_key(claims.run_id),+ presence_gated=claims.presence_gated,+ origin_product=claims.origin_product,+ )try:result = await _ingest_event_lines(@@ -207,7 +211,7 @@ async def _ingest_event_lines(result.last_accepted_seq = max(result.last_accepted_seq, await redis_stream.get_last_sequence())continueif write.skipped:- observe_stream_write_skipped("ingest")+ observe_stream_write_skipped("ingest", claims.origin_product)result.accepted += 1result.last_accepted_seq = sequencediff --git a/products/tasks/backend/logic/stream/redis_stream.py b/products/tasks/backend/logic/stream/redis_stream.pyindex bb02c2189dad..ea9228d2a66d 100644--- a/products/tasks/backend/logic/stream/redis_stream.py+++ b/products/tasks/backend/logic/stream/redis_stream.py@@ -168,6 +168,7 @@ class TaskRunRedisStream:max_length: int = TASK_RUN_STREAM_MAX_LENGTH,*,presence_gated: bool = False,+ origin_product: str | None = None,):self._stream_key = stream_keyself._redis_client = get_tasks_stream_redis_async(use_dedicated)@@ -176,6 +177,7 @@ class TaskRunRedisStream:self._completed_timeout = min(timeout, TASK_RUN_STREAM_COMPLETED_TIMEOUT)self._max_length = max_lengthself._presence_gated = presence_gated+ self._origin_product = origin_productself._watched_cached_until = 0.0self._last_watched_refresh_at: float | None = None@@ -364,7 +366,7 @@ class TaskRunRedisStream:Terminal sentinels bypass this gate."""if self._presence_gated and not await self._is_watched():- observe_stream_write_skipped("relay")+ observe_stream_write_skipped("relay", self._origin_product)return Nonereturn await self._xadd_event(event, ttl=ttl)@@ -727,7 +729,12 @@ def reset_task_run_stream(run_id: str, use_dedicated: bool = False) -> bool:def publish_task_run_stream_event(- run_id: str, event: dict, use_dedicated: bool = False, *, presence_gated: bool = False+ run_id: str,+ event: dict,+ use_dedicated: bool = False,+ *,+ presence_gated: bool = False,+ origin_product: str | None = None,) -> str | None:"""Synchronously publish a task-run event to Redis.@@ -745,7 +752,7 @@ def publish_task_run_stream_event(client = get_tasks_stream_redis_sync(use_dedicated)try:if presence_gated and not client.exists(get_task_run_stream_watched_key(stream_key)):- observe_stream_write_skipped("mirror")+ observe_stream_write_skipped("mirror", origin_product)return Noneraw = json.dumps(event)stream_id = client.xadd(stream_key, {DATA_KEY: raw}, maxlen=TASK_RUN_STREAM_MAX_LENGTH, approximate=True)diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.pyindex 6026e7057bfe..4f5e7f9bde9f 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -249,7 +249,7 @@ TASK_RUN_STREAM_RESUME_GAP_TOTAL = Counter(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",- labelnames=["path"],+ labelnames=["path", "origin_product"],)TASK_RUN_AGENT_FAILURE_TOTAL = Counter(@@ -593,8 +593,8 @@ def observe_stream_resume_gap(origin_product: str) -> None:TASK_RUN_STREAM_RESUME_GAP_TOTAL.labels(origin_product=origin_product).inc()-def observe_stream_write_skipped(path: StreamWriteSkippedPath) -> None:- TASK_RUN_STREAM_WRITE_SKIPPED_TOTAL.labels(path=path).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()def observe_task_run_failed(properties: dict[str, object]) -> None:diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex b01156c7353e..0c202783786d 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -2779,6 +2779,7 @@ class TaskRun(models.Model):event,run_uses_dedicated_stream(self.state),presence_gated=run_stream_presence_gated(self.state),+ origin_product=self.task.origin_product,)def publish_stream_state_event(self) -> None:diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex f0fc438a7355..f6dc184371cb 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -149,6 +149,7 @@ async def _relay_sandbox_events(input: RelaySandboxEventsInput, *, finalize_strestream_key,run_uses_dedicated_stream(task_run.state),presence_gated=run_stream_presence_gated(task_run.state),+ origin_product=origin_product,)await redis_stream.initialize()diff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.pyindex a29c1201ae76..3b44cbd99bfd 100644--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py@@ -334,6 +334,7 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:error_msg,run_uses_dedicated_stream(task_run.state),run_stream_presence_gated(task_run.state),+ task_run.task.origin_product,)raise RuntimeError(f"send_followup failed: {error_msg}")@@ -432,6 +433,7 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:error_msg,run_uses_dedicated_stream(task_run.state),run_stream_presence_gated(task_run.state),+ task_run.task.origin_product,)raise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)@@ -477,6 +479,7 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:_get_stop_reason(result.data),run_uses_dedicated_stream(task_run.state),run_stream_presence_gated(task_run.state),+ task_run.task.origin_product,)logger.info("send_followup_delivered", run_id=input.run_id)elif result.turn_in_flight:@@ -506,6 +509,7 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:DENIED_PERMISSION_STOP_MESSAGE,run_uses_dedicated_stream(task_run.state),run_stream_presence_gated(task_run.state),+ task_run.task.origin_product,)raise ApplicationError(f"send_followup failed: {result.error}", non_retryable=True)# Retry transport failures and known transient agent errors. message_id@@ -534,6 +538,7 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:error_msg,run_uses_dedicated_stream(task_run.state),run_stream_presence_gated(task_run.state),+ task_run.task.origin_product,)raise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)else:@@ -549,6 +554,7 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:error_msg,run_uses_dedicated_stream(task_run.state),run_stream_presence_gated(task_run.state),+ task_run.task.origin_product,)# Propagate failure to the workflow.raise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)@@ -677,6 +683,7 @@ def _deliver_peer_message(input: SendFollowupToSandboxInput, task_run: TaskRun,_get_stop_reason(result.data),run_uses_dedicated_stream(task_run.state),run_stream_presence_gated(task_run.state),+ task_run.task.origin_product,)return Noneif result.turn_in_flight:@@ -1050,6 +1057,7 @@ def _write_turn_complete(stop_reason: str = STOP_REASON_END_TURN,use_dedicated: bool = False,presence_gated: bool = False,+ origin_product: str | None = None,) -> None:"""Write a synthetic turn_complete event to the Redis stream."""event = {@@ -1059,11 +1067,17 @@ def _write_turn_complete("params": {"source": "posthog", "stopReason": stop_reason},},}- publish_task_run_stream_event(run_id, event, use_dedicated, presence_gated=presence_gated)+ publish_task_run_stream_event(+ run_id, event, use_dedicated, presence_gated=presence_gated, origin_product=origin_product+ )def _write_error_and_complete(- run_id: str, error_message: str, use_dedicated: bool = False, presence_gated: bool = False+ run_id: str,+ error_message: str,+ use_dedicated: bool = False,+ presence_gated: bool = False,+ origin_product: str | None = None,) -> None:"""Write an error event followed by turn_complete to the Redis stream."""error_event = {@@ -1073,5 +1087,9 @@ def _write_error_and_complete("params": {"message": error_message},},}- publish_task_run_stream_event(run_id, error_event, use_dedicated, presence_gated=presence_gated)- _write_turn_complete(run_id, use_dedicated=use_dedicated, presence_gated=presence_gated)+ publish_task_run_stream_event(+ run_id, error_event, use_dedicated, presence_gated=presence_gated, origin_product=origin_product+ )+ _write_turn_complete(+ run_id, use_dedicated=use_dedicated, presence_gated=presence_gated, origin_product=origin_product+ )diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.pyindex b7e4dd944996..d8bd78f51eab 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py@@ -285,7 +285,14 @@ class TestRelaySandboxEventsCancellation:)class StubTaskRunRedisStream:- def __init__(self, stream_key: str, use_dedicated: bool = False, *, presence_gated: bool = False) -> None:+ def __init__(+ self,+ stream_key: str,+ use_dedicated: bool = False,+ *,+ presence_gated: bool = False,+ origin_product: str | None = None,+ ) -> None:self.stream_key = stream_keyasync def initialize(self) -> None:@@ -353,7 +360,14 @@ class TestRelaySandboxEventsPresenceGating:constructed: list[bool] = []class StubTaskRunRedisStream:- def __init__(self, stream_key: str, use_dedicated: bool = False, *, presence_gated: bool = False) -> None:+ def __init__(+ self,+ stream_key: str,+ use_dedicated: bool = False,+ *,+ presence_gated: bool = False,+ origin_product: str | None = None,+ ) -> None:constructed.append(presence_gated)async def initialize(self) -> None:@@ -414,7 +428,14 @@ class TestRelaySandboxEventsMissingActor:)class StubTaskRunRedisStream:- def __init__(self, stream_key: str, use_dedicated: bool = False, *, presence_gated: bool = False) -> None:+ def __init__(+ self,+ stream_key: str,+ use_dedicated: bool = False,+ *,+ presence_gated: bool = False,+ origin_product: str | None = None,+ ) -> None:self.stream_key = stream_keyasync def initialize(self) -> None:@@ -1014,7 +1035,14 @@ class TestRelaySandboxEventsErrorHandling:)class StubTaskRunRedisStream:- def __init__(self, stream_key: str, use_dedicated: bool = False, *, presence_gated: bool = False) -> None:+ def __init__(+ self,+ stream_key: str,+ use_dedicated: bool = False,+ *,+ presence_gated: bool = False,+ origin_product: str | None = None,+ ) -> None:self.stream_key = stream_keyasync def initialize(self) -> None:diff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.pyindex c0b89ca0fd0b..35189e18b8a7 100644--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py@@ -971,6 +971,7 @@ class TestSendFollowupTurnTimeout:"The model response could not be completed. Please retry the task.",False,False,+ "user_created",)_patches["turn_complete"].assert_not_called()@@ -1045,7 +1046,7 @@ class TestSendFollowupTurnTimeout:send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1"))assert exc_info.value.non_retryable is True- _patches["error"].assert_called_once_with("run-1", DENIED_PERMISSION_STOP_MESSAGE, False, False)+ _patches["error"].assert_called_once_with("run-1", DENIED_PERMISSION_STOP_MESSAGE, False, False, "user_created")def test_a_steer_never_claims_the_denial_that_ended_its_turn(self, _patches):_patches["denial_state"].update(diff --git a/products/tasks/backend/tests/test_connection_token.py b/products/tasks/backend/tests/test_connection_token.pyindex adf54a1ec82f..210feb8129d4 100644--- a/products/tasks/backend/tests/test_connection_token.py+++ b/products/tasks/backend/tests/test_connection_token.py@@ -153,22 +153,27 @@ class TestSandboxJwtRotation(SimpleTestCase):self.assertEqual(payload.run_id, str(run.id))self.assertIsNone(payload.sandbox_id)self.assertIs(payload.presence_gated, False)+ self.assertIsNone(payload.origin_product)@parameterized.expand([(True,), (False,)])@override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None)def test_ingest_token_carries_pinned_presence_gating(self, gated: bool) -> None:reset_sandbox_jwt_key_cache()- token = create_sandbox_event_ingest_token(_fake_run({"stream_presence_gated": gated}))+ token = create_sandbox_event_ingest_token(_fake_run({"stream_presence_gated": gated}, "signals_scout"))- self.assertIs(validate_sandbox_event_ingest_token(token).presence_gated, gated)+ payload = validate_sandbox_event_ingest_token(token)+ self.assertIs(payload.presence_gated, gated)+ self.assertEqual(payload.origin_product, "signals_scout")@parameterized.expand([(True,), (False,)])@override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None)def test_stream_read_token_carries_pinned_presence_gating(self, gated: bool) -> None:reset_sandbox_jwt_key_cache()- token = create_stream_read_token(_fake_run({"stream_presence_gated": gated}))+ token = create_stream_read_token(_fake_run({"stream_presence_gated": gated}, "signals_scout"))- self.assertIs(validate_stream_read_token(token).presence_gated, gated)+ payload = validate_stream_read_token(token)+ self.assertIs(payload.presence_gated, gated)+ self.assertEqual(payload.origin_product, "signals_scout")@override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None)def test_legacy_stream_read_token_without_presence_claim_remains_valid(self) -> None:@@ -193,6 +198,7 @@ class TestSandboxJwtRotation(SimpleTestCase):self.assertEqual(payload.run_id, str(run.id))self.assertIs(payload.presence_gated, False)+ self.assertIsNone(payload.origin_product)def test_ingest_token_validates_after_primary_rotation(self) -> None:# Ingest is rotation-safe: a token signed under the old primary keeps validating after thediff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.pyindex 172aa3abe761..e22914894e74 100644--- a/products/tasks/backend/tests/test_event_ingest.py+++ b/products/tasks/backend/tests/test_event_ingest.py@@ -11,6 +11,7 @@ from django.test import TestCase, override_settingsfrom asgiref.sync import async_to_syncfrom parameterized import parameterized+from prometheus_client import REGISTRYfrom posthog.models import Organization, Team, Userfrom posthog.redis import TEST_clear_clients@@ -39,6 +40,8 @@ from products.tasks.backend.logic.stream.redis_stream import (from products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.tests.test_api import TEST_RSA_PRIVATE_KEY+SKIP_COUNTER_SAMPLE = "posthog_tasks_task_run_stream_write_skipped_total"+class TestTaskRunEventIngest(TestCase):def setUp(self) -> None:@@ -506,6 +509,8 @@ class TestTaskRunEventIngest(TestCase):self.task_run.state = {**(self.task_run.state or {}), "stream_presence_gated": True}self.task_run.save(update_fields=["state", "updated_at"])token = self._create_token()+ skip_labels = {"path": "ingest", "origin_product": Task.OriginProduct.USER_CREATED.value}+ skips_before = REGISTRY.get_sample_value(SKIP_COUNTER_SAMPLE, skip_labels) or 0.0with patch.object(TaskRun, "heartbeat_workflow"):status, body = self._call_ingest(@@ -521,6 +526,8 @@ class TestTaskRunEventIngest(TestCase):self.assertEqual(body["duplicate"], 0)self.assertEqual(body["last_accepted_seq"], 2)self.assertEqual(self._read_stream_events(), [])+ skips_after = REGISTRY.get_sample_value(SKIP_COUNTER_SAMPLE, skip_labels) or 0.0+ self.assertEqual(skips_after - skips_before, 2.0)@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)def test_duplicate_terminal_sequence_does_not_complete_without_completion_line(self) -> None:diff --git a/services/agent-proxy/src/hono/app.ts b/services/agent-proxy/src/hono/app.tsindex 2a34f137aa98..e134e240d5a3 100644--- a/services/agent-proxy/src/hono/app.ts+++ b/services/agent-proxy/src/hono/app.ts@@ -119,7 +119,7 @@ export function createApp(redis: Redis, config: Config, publicKeys: CryptoKey[])const openedAt = Date.now()// Wire disconnect: when the client drops, abort the SSE generator.const generator = streamTaskRunEvents(streamKey, redis, {- originProduct: 'unknown',+ originProduct: claims.originProduct,lastEventId,startLatest,presenceGated: claims.presenceGated,diff --git a/services/agent-proxy/src/hono/ingest-handler.ts b/services/agent-proxy/src/hono/ingest-handler.tsindex 9e3812a65808..f5fc9d24d81e 100644--- a/services/agent-proxy/src/hono/ingest-handler.ts+++ b/services/agent-proxy/src/hono/ingest-handler.ts@@ -254,7 +254,7 @@ async function ingestEventLines(}if (write.streamId === null) {- observeStreamWriteSkipped('ingest')+ observeStreamWriteSkipped('ingest', claims.originProduct)}result.accepted++diff --git a/services/agent-proxy/src/hono/metrics.ts b/services/agent-proxy/src/hono/metrics.tsindex fd8ea7150e1f..82be5c137ac6 100644--- a/services/agent-proxy/src/hono/metrics.ts+++ b/services/agent-proxy/src/hono/metrics.ts@@ -86,7 +86,7 @@ export const streamIngestEventsTotal = new Counter({export const taskRunStreamWriteSkippedTotal = new Counter({name: 'posthog_tasks_task_run_stream_write_skipped_total',help: 'Task-run events not mirrored into Redis because presence gating found no attached reader',- labelNames: ['path'],+ labelNames: ['path', 'origin_product'],registers: [register],})@@ -196,8 +196,8 @@ export function observeStreamIngestEvents(opts: { accepted: number; duplicate: n}}-export function observeStreamWriteSkipped(path: StreamWriteSkippedPath): void {- taskRunStreamWriteSkippedTotal.labels({ path }).inc()+export function observeStreamWriteSkipped(path: StreamWriteSkippedPath, originProduct: string): void {+ taskRunStreamWriteSkippedTotal.labels({ path, origin_product: originProduct }).inc()}export function observeIngestClientDisconnect(classification: DisconnectClassification): void {diff --git a/services/agent-proxy/src/lib/jwt.ts b/services/agent-proxy/src/lib/jwt.tsindex add6d2584289..3b85c5959cef 100644--- a/services/agent-proxy/src/lib/jwt.ts+++ b/services/agent-proxy/src/lib/jwt.ts@@ -68,6 +68,14 @@ function assertPresenceGatedClaim(payload: Record<string, unknown>): boolean {return presenceGated ?? false}+function assertOriginProductClaim(payload: Record<string, unknown>): string {+ const originProduct = payload['origin_product']+ if (originProduct !== undefined && typeof originProduct !== 'string') {+ throw new Error('Token has invalid claim: origin_product must be a string')+ }+ return originProduct ?? 'unknown'+}+// Verify a token against every configured public key, returning the payload from the first key// whose signature validates. Only a signature mismatch advances to the next key; expiry, wrong// audience and malformed claims are key-independent and fail fast. This is what makes a@@ -95,7 +103,8 @@ async function verifyWithKeys(token: string, publicKeys: CryptoKey[], audience:// Audience: posthog:stream_read// Required claims: run_id (string), task_id (string), team_id (integer)-// Optional claim: presence_gated (boolean, absent means false)+// Optional claims: presence_gated (boolean, absent means false),+// origin_product (string, absent means "unknown")// Algorithm: RS256, no clockTolerance (matches Python leeway=0 default)//// Throws jose error subtypes (JWTExpired, JWTInvalid, JWSSignatureVerificationFailed,@@ -104,7 +113,11 @@ async function verifyWithKeys(token: string, publicKeys: CryptoKey[], audience:export async function validateStreamReadToken(token: string, publicKeys: CryptoKey[]): Promise<StreamReadTokenPayload> {const payload = await verifyWithKeys(token, publicKeys, STREAM_READ_AUDIENCE)const claims = payload as Record<string, unknown>- return { ...assertStreamClaims(claims), presenceGated: assertPresenceGatedClaim(claims) }+ return {+ ...assertStreamClaims(claims),+ presenceGated: assertPresenceGatedClaim(claims),+ originProduct: assertOriginProductClaim(claims),+ }}// ---------------------------------------------------------------------------@@ -113,7 +126,8 @@ export async function validateStreamReadToken(token: string, publicKeys: CryptoK// Audience: posthog:sandbox_event_ingest// Required claims: run_id (string), task_id (string), team_id (integer)-// Optional claim: presence_gated (boolean, absent means false)+// Optional claims: presence_gated (boolean, absent means false),+// origin_product (string, absent means "unknown")// Algorithm: RS256, no clockTolerance (matches Python leeway=0 default)//// Same error semantics as validateStreamReadToken.@@ -123,5 +137,9 @@ export async function validateSandboxEventIngestToken(): Promise<SandboxEventIngestTokenPayload> {const payload = await verifyWithKeys(token, publicKeys, SANDBOX_EVENT_INGEST_AUDIENCE)const claims = payload as Record<string, unknown>- return { ...assertStreamClaims(claims), presenceGated: assertPresenceGatedClaim(claims) }+ return {+ ...assertStreamClaims(claims),+ presenceGated: assertPresenceGatedClaim(claims),+ originProduct: assertOriginProductClaim(claims),+ }}diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.tsindex 15aedd4f7c11..c61c49aba476 100644--- a/services/agent-proxy/src/lib/types.ts+++ b/services/agent-proxy/src/lib/types.ts@@ -102,6 +102,7 @@ export interface StreamReadTokenPayload {taskId: stringteamId: numberpresenceGated: boolean+ originProduct: string}// Claims extracted from a posthog:sandbox_event_ingest JWT (POST /v1/runs/:run/ingest leg)@@ -110,6 +111,7 @@ export interface SandboxEventIngestTokenPayload {taskId: stringteamId: numberpresenceGated: boolean+ originProduct: string}// ---------------------------------------------------------------------------diff --git a/services/agent-proxy/tests/hono/app.test.ts b/services/agent-proxy/tests/hono/app.test.tsindex 4bbae82f74d4..10ff4da79e47 100644--- a/services/agent-proxy/tests/hono/app.test.ts+++ b/services/agent-proxy/tests/hono/app.test.ts@@ -35,7 +35,13 @@ function makeConfig(): Config {describe('app onError', () => {beforeEach(() => {vi.clearAllMocks()- mockValidate.mockResolvedValue({ runId: 'run-123', taskId: 'task-abc', teamId: 42, presenceGated: false })+ mockValidate.mockResolvedValue({+ runId: 'run-123',+ taskId: 'task-abc',+ teamId: 42,+ presenceGated: false,+ originProduct: 'unknown',+ })})it('logs unexpected route errors with request context and returns JSON 500', async () => {diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.tsindex 1b6c574e9588..c0b76ce574ac 100644--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts@@ -18,6 +18,7 @@import type { Redis } from 'ioredis'import { describe, it, expect, vi, beforeEach } from 'vitest'+import { observeStreamWriteSkipped } from '@/hono/metrics.js'import type { Config } from '@/lib/config.js'import {MAX_EVENT_LINE_BYTES,@@ -304,6 +305,7 @@ function makeClaims(overrides?: Partial<SandboxEventIngestTokenPayload>): SandbotaskId: 'task-abc',teamId: 42,presenceGated: false,+ originProduct: 'unknown',...overrides,}}@@ -471,7 +473,7 @@ describe('ingest-handler', () => {{ name: 'skips the mirror when no reader is attached', watched: false, expectedEntries: 0 },{ name: 'mirrors when a reader is attached', watched: true, expectedEntries: 1 },])('presence-gated ingest $name', async ({ watched, expectedEntries }) => {- mockValidate.mockResolvedValue(makeClaims({ presenceGated: true }))+ mockValidate.mockResolvedValue(makeClaims({ presenceGated: true, originProduct: 'signals_scout' }))if (watched) {await fakeRedis.set(getWatchedKey(getStreamKey(RUN_ID)), '1', 'EX', 300)}@@ -485,6 +487,11 @@ describe('ingest-handler', () => {expect(await decodeJson(res)).toMatchObject({ accepted: 1, duplicate: 0, last_accepted_seq: 1 })expect(await redisStream.getLastSequence()).toBe(1)expect(await fakeRedis.xrange(getStreamKey(RUN_ID))).toHaveLength(expectedEntries)+ if (watched) {+ expect(observeStreamWriteSkipped).not.toHaveBeenCalled()+ } else {+ expect(observeStreamWriteSkipped).toHaveBeenCalledWith('ingest', 'signals_scout')+ }})it('still writes the completion sentinel for a presence-gated run with no reader', async () => {diff --git a/services/agent-proxy/tests/lib/jwt.test.ts b/services/agent-proxy/tests/lib/jwt.test.tsindex 458552610e9f..b3154807c50e 100644--- a/services/agent-proxy/tests/lib/jwt.test.ts+++ b/services/agent-proxy/tests/lib/jwt.test.ts@@ -58,6 +58,7 @@ interface TokenOptions {omitExp?: booleansigningKey?: CryptoKeypresenceGated?: unknown+ originProduct?: unknown}async function signToken(opts: TokenOptions = {}): Promise<string> {@@ -70,12 +71,16 @@ async function signToken(opts: TokenOptions = {}): Promise<string> {omitExp = false,signingKey,presenceGated,+ originProduct,} = optsconst claims: Record<string, unknown> = { run_id: runId, task_id: taskId, team_id: teamId }if (presenceGated !== undefined) {claims['presence_gated'] = presenceGated}+ if (originProduct !== undefined) {+ claims['origin_product'] = originProduct+ }const builder = new SignJWT(claims).setProtectedHeader({alg: 'RS256',@@ -128,6 +133,27 @@ describe('jwt', () => {})+ it.each([+ { name: 'a string claim', claim: 'signals_scout', expected: 'signals_scout' },+ { name: 'an absent claim as unknown', claim: undefined, expected: 'unknown' },+ ])('carries $name for origin_product', async ({ claim, expected }) => {+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, originProduct: claim })+ const payload = await validateStreamReadToken(token, keys.publicKeys)++ expect(payload.originProduct).toBe(expected)+ })++ it.each([{ claim: 1 }, { claim: null }, { claim: true }])(+ 'rejects a non-string origin_product claim ($claim)',+ async ({ claim }) => {+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, originProduct: claim })++ await expect(validateStreamReadToken(token, keys.publicKeys)).rejects.toThrow(+ 'origin_product must be a string'+ )+ }+ )+it('rejects a token with the wrong audience (sandbox_event_ingest)', async () => {const token = await signToken({ audience: SANDBOX_EVENT_INGEST_AUDIENCE })