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): distinguish interactive signals runs from pipeline-started ones (#86485)

Georgiy Tarasovf2a24cb3f342
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index c4c75bde3e2a..6e5c758bfcab 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2184,6 +2184,9 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(
"loop_terminal_bookkeeping_complete",
# Stamped once at run creation. The review carve-outs read ai_stage="implementation" as proof
# a run is self-driving, so a PATCHable value would forge that and unlock the bot/draft bypass.
+ # is_interactive_signals_run reads its presence the same way, to tell a pipeline-started
+ # signals run from one a person started; forging it would move the run off the interactive
+ # budget and out of its per-run spend ceiling.
"ai_stage",
# The server-generated head branch the run->PR link is keyed on (find_signal_implementation_run).
# A PATCHable value would let a caller re-aim the approve-first carve-out at any App-authored
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index f9315dd306c6..43dd02bdac82 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -597,9 +597,7 @@ class TaskWriteSerializer(serializers.Serializer):
help_text="JSON schema used to validate the output of the task.",
)
# `internal` is deliberately not writable here: only server-side creators (auto-start,
- # research, loops) set it via the facade. A client-set `internal=True` on a signals-origin
- # task would drop the token's interactive-run marker and with it the `signals_interactive`
- # budget and per-task spend ceiling (see is_interactive_signals_task in temporal/oauth.py).
+ # research, loops) set it via the facade, and it decides whether the task is listed.
archived = serializers.BooleanField(
required=False,
help_text="If true, the task is hidden from default list responses.",
diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.py
index 3b3d5a11da3f..f45dd7d5ec1b 100644
--- a/products/tasks/backend/temporal/oauth.py
+++ b/products/tasks/backend/temporal/oauth.py
@@ -59,8 +59,7 @@ SIGNALS_ORIGIN_PRODUCTS = frozenset(
)
# Signals surfaces a person drives by hand: the Inbox report CTAs ("Create PR" / "Discuss")
-# and scout chat. Scheduled scouts and auto-started implementations are excluded — they carry
-# `internal=True`, and their volume is chosen by our own pipeline rather than by a customer.
+# and scout chat. Scheduled scouts run under their own reserved origin and never appear here.
INTERACTIVE_SIGNALS_ORIGIN_PRODUCTS = frozenset(
{
Task.OriginProduct.SIGNAL_REPORT,
@@ -77,9 +76,23 @@ def _oauth_application_for_task(task: Task) -> SandboxOAuthApplication:
return "array"
-def is_interactive_signals_task(task: Task) -> bool:
- """Whether this run exists because a person pressed something, not because we scheduled it."""
- return task.origin_product in INTERACTIVE_SIGNALS_ORIGIN_PRODUCTS and not task.internal
+def is_interactive_signals_run(task: Task, state: dict[str, Any] | None) -> bool:
+ """Whether *this run* exists because a person pressed something, not because we scheduled it.
+
+ Asks the run, not the task. `task.internal` is stamped once at creation and never
+ recomputed, so it only ever answers for the run that created the task: Signals auto-starts
+ an implementation task, and a person can later start a second run on that same task from
+ the report. One task, two runs, two different initiators.
+
+ `ai_stage` is the pipeline's own stamp on a run it started. It is absent from the task
+ create serializer and sits in `_PROTECTED_RUN_STATE_KEYS`, so no caller can set or forge
+ one — the review carve-outs already trust it as proof a run is self-driving. A signals run
+ without one therefore cannot have come from the pipeline, which makes the interactive
+ budget and its per-run ceiling the fail-closed default.
+ """
+ if task.origin_product not in INTERACTIVE_SIGNALS_ORIGIN_PRODUCTS:
+ return False
+ return not (state or {}).get("ai_stage")
def _scopes_for_loop_fired_run(scopes: PosthogMcpScopes) -> list[str]:
@@ -111,11 +124,15 @@ def create_oauth_access_token(
user: User | None = None,
allow_task_creator_fallback: bool = True,
loop_id: str | None = None,
+ run_state: dict[str, Any] | None = None,
) -> str:
"""Create an OAuth access token for the task's sandbox app, scoped to the task's team.
OAuth tokens auto-expire after 6 hours, so no cleanup is needed. Pass `loop_id` for a
loop-fired run so `loop:write` is stripped from the granted scopes regardless of `scopes`.
+ Pass `run_state` so the Signals budget is picked from the run's own provenance
+ (`is_interactive_signals_run`); omitting it bills a signals run as interactive, which is
+ the safe default but is never what a pipeline run wants.
"""
actor = user or (task.created_by if allow_task_creator_fallback else None)
if not actor:
@@ -142,7 +159,7 @@ def create_oauth_access_token(
# task needs a member-capable token, or every member-proxy call it was
# just granted would 403.
token_options["include_mcp_builtin_agent_scope"] = True
- if is_interactive_signals_task(task):
+ if is_interactive_signals_run(task, run_state):
token_options["include_interactive_run_scope"] = True
return create_oauth_access_token_for_user(actor, task.team_id, **token_options)
@@ -201,6 +218,7 @@ def create_oauth_access_token_for_run(
user=actor_user,
allow_task_creator_fallback=not is_slack_interaction_state(state),
loop_id=loop_id if isinstance(loop_id, str) else None,
+ run_state=state,
)
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index 7ee212bc7f94..148498e8ed06 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -48,7 +48,7 @@ from products.tasks.backend.logic.services.sandbox_config import (
)
from products.tasks.backend.models import SandboxCustomImage, SandboxEnvironment, Task, TaskRun
from products.tasks.backend.temporal.constants import resolve_inactivity_timeout, resolve_max_run_duration
-from products.tasks.backend.temporal.oauth import is_interactive_signals_task
+from products.tasks.backend.temporal.oauth import is_interactive_signals_run
from products.tasks.backend.temporal.observability import emit_agent_log, log_with_activity_context
from products.tasks.backend.temporal.process_task.utils import (
format_allowed_domains_for_log,
@@ -1112,7 +1112,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
interactive_max_run_duration_seconds = None
if (
(state or {}).get("mode") == "interactive"
- and is_interactive_signals_task(task)
+ and is_interactive_signals_run(task, state)
and settings.TASKS_INTERACTIVE_SIGNALS_MAX_RUN_DURATION_SECONDS > 0
):
interactive_max_run_duration_seconds = settings.TASKS_INTERACTIVE_SIGNALS_MAX_RUN_DURATION_SECONDS
diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.py
index 6ddd11170547..f97d84dc9d62 100644
--- a/products/tasks/backend/temporal/tests/test_oauth.py
+++ b/products/tasks/backend/temporal/tests/test_oauth.py
@@ -113,13 +113,22 @@ def test_default_task_uses_array_oauth_application(mock_create: MagicMock) -> No
@pytest.mark.parametrize(
- ("origin_product", "internal", "application", "interactive"),
+ ("origin_product", "internal", "run_state", "application", "interactive"),
[
- (Task.OriginProduct.SIGNAL_REPORT, False, "signals", True),
- (Task.OriginProduct.SIGNAL_REPORT, True, "signals", False),
- (Task.OriginProduct.SIGNALS_CHAT, False, "signals", True),
- (Task.OriginProduct.SIGNALS_SCOUT, True, "signals", False),
- (Task.OriginProduct.USER_CREATED, False, "array", False),
+ # Inbox CTA: a person creates the task, so no pipeline stage is ever stamped.
+ (Task.OriginProduct.SIGNAL_REPORT, False, None, "signals", True),
+ # Auto-started implementation: the pipeline stamps the run it started.
+ (Task.OriginProduct.SIGNAL_REPORT, True, {"ai_stage": "implementation"}, "signals", False),
+ # A person starting a second run on that same auto-started task. `internal` still says
+ # True because it answers for the task, but this run carries no stage of its own.
+ (Task.OriginProduct.SIGNAL_REPORT, True, {"mode": "interactive"}, "signals", True),
+ # A forged stage is impossible through the API, but an empty string must not read as one.
+ (Task.OriginProduct.SIGNAL_REPORT, True, {"ai_stage": ""}, "signals", True),
+ (Task.OriginProduct.SIGNAL_REPORT, True, {"ai_stage": "research"}, "signals", False),
+ (Task.OriginProduct.SIGNAL_REPORT, True, {"ai_stage": "custom_agent"}, "signals", False),
+ (Task.OriginProduct.SIGNALS_CHAT, False, None, "signals", True),
+ (Task.OriginProduct.SIGNALS_SCOUT, True, {"ai_stage": "scout"}, "signals", False),
+ (Task.OriginProduct.USER_CREATED, False, None, "array", False),
],
)
@patch("products.tasks.backend.temporal.oauth.is_builtin_agent_enforcement_enabled", return_value=False)
@@ -129,6 +138,7 @@ def test_signals_origins_mint_under_the_signals_app_and_mark_only_user_started_r
mock_enforcement: MagicMock,
origin_product: Task.OriginProduct,
internal: bool,
+ run_state: dict | None,
application: str,
interactive: bool,
) -> None:
@@ -140,7 +150,7 @@ def test_signals_origins_mint_under_the_signals_app_and_mark_only_user_started_r
internal=internal,
)
- assert create_oauth_access_token(task) == "token"
+ assert create_oauth_access_token(task, run_state=run_state) == "token"
expected: dict = {
"scopes": "read_only",
@@ -152,6 +162,31 @@ def test_signals_origins_mint_under_the_signals_app_and_mark_only_user_started_r
mock_create.assert_called_once_with(task.created_by, 123, **expected)
+@patch("products.tasks.backend.temporal.oauth.is_builtin_agent_enforcement_enabled", return_value=False)
+@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")
+def test_two_runs_on_one_auto_started_task_get_different_signals_budgets(
+ mock_create: MagicMock,
+ mock_enforcement: MagicMock,
+) -> None:
+ organization = Organization.objects.create(name="signals-budget-org")
+ team = Team.objects.create(organization=organization, name="signals-budget-team")
+ creator = User.objects.create(email="[email protected]")
+ task = Task.objects.create(
+ team=team,
+ title="Implementation: report",
+ created_by=creator,
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ internal=True,
+ )
+
+ create_oauth_access_token_for_run(task, {"ai_stage": "implementation", "mode": "background"})
+ assert "include_interactive_run_scope" not in mock_create.call_args.kwargs
+
+ create_oauth_access_token_for_run(task, {"mode": "interactive"})
+ assert mock_create.call_args.kwargs["include_interactive_run_scope"] is True
+
+
def test_oauth_token_can_disable_task_creator_fallback() -> None:
task = MagicMock(
id="task-id",