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(slack_app): enforce trusted per-run spend circuit breaker (#92962)

posthog[bot]c9a224a0f966
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 18dff5a34d8b..e40a20e288c5 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -110,6 +110,7 @@ APIScopeObject = Literal[
"signal_scout_internal",
"signal_scout_report",
"signal_scratchpad_internal",
+ "slack_run",
"stamphog",
"streamlit_app",
"subscription",
@@ -136,9 +137,9 @@ APIScopeObject = Literal[
]
-# Server-only provenance marker for OAuth tokens minted for PostHog's built-in
-# agents. It is hidden from user-controlled scope selectors below.
+# Server-only provenance markers hidden from user-controlled scope selectors.
MCP_BUILT_IN_AGENT_SCOPE = "mcp_builtin_agent:read"
+SLACK_RUN_SCOPE = "slack_run:read"
APIScopeActions = Literal[
"read",
@@ -193,6 +194,9 @@ INTERNAL_API_SCOPE_OBJECTS: frozenset[APIScopeObject] = frozenset(
# pipeline's research and implementation runs need durable memory, and granting it
# through the scout object would hand them `emit_signal` and `record_output` too.
"signal_scratchpad_internal",
+ # Marks tokens minted for Slack tasks so spend policy does not depend on the
+ # caller-selected LLM gateway product route.
+ "slack_run",
}
)
diff --git a/posthog/temporal/oauth.py b/posthog/temporal/oauth.py
index d15c1a611ec4..266eddd800a3 100644
--- a/posthog/temporal/oauth.py
+++ b/posthog/temporal/oauth.py
@@ -17,6 +17,7 @@ from posthog.scopes import (
INTERNAL_API_SCOPE_OBJECTS,
MCP_BUILT_IN_AGENT_SCOPE,
OAUTH_HIDDEN_SCOPE_OBJECTS,
+ SLACK_RUN_SCOPE,
resolve_ceiling,
)
from posthog.utils import get_instance_region
@@ -568,6 +569,7 @@ def create_oauth_access_token_for_user(
include_internal_scopes: bool = True,
include_mcp_builtin_agent_scope: bool = False,
include_interactive_run_scope: bool = False,
+ include_slack_run_scope: bool = False,
application: SandboxOAuthApplication = "array",
sandbox_task_id: UUID | None = None,
) -> str:
@@ -581,6 +583,8 @@ def create_oauth_access_token_for_user(
# Provenance marker only — it grants no access. The LLM gateway meters a run
# carrying it against the interactive budget instead of the pipeline's.
resolved.append(INTERACTIVE_RUN_SCOPE)
+ if include_slack_run_scope:
+ resolved.append(SLACK_RUN_SCOPE)
app = get_sandbox_oauth_app(application)
return _mint_oauth_access_token(user, team_id, app=app, scopes=list(resolved), sandbox_task_id=sandbox_task_id)
diff --git a/posthog/temporal/tests/test_oauth.py b/posthog/temporal/tests/test_oauth.py
index 92937997c9ea..489079126465 100644
--- a/posthog/temporal/tests/test_oauth.py
+++ b/posthog/temporal/tests/test_oauth.py
@@ -12,7 +12,7 @@ from parameterized import parameterized
from temporalio.converter import JSONPlainPayloadConverter
from posthog.models import OAuthAccessToken, OAuthApplication, Organization, Team, User
-from posthog.scopes import MCP_BUILT_IN_AGENT_SCOPE
+from posthog.scopes import MCP_BUILT_IN_AGENT_SCOPE, SLACK_RUN_SCOPE
from posthog.temporal.oauth import (
ARRAY_APP_CLIENT_ID_DEV,
CONTEXT_LAYER_INTERNAL_SCOPE,
@@ -428,6 +428,17 @@ class TestCreateOAuthAccessTokenForUser(TestCase):
assert "task:read" in scopes
assert "task:write" in scopes
+ @override_settings(CLOUD_DEPLOYMENT="DEV")
+ def test_slack_run_scope_is_added_without_narrowing_scopes(self) -> None:
+ self._create_oauth_app(ARRAY_APP_CLIENT_ID_DEV, "Array Dev App")
+ user, team = self._create_user_and_team()
+
+ token = create_oauth_access_token_for_user(user, team.id, include_slack_run_scope=True)
+
+ scopes = set(OAuthAccessToken.objects.get(token=token).scope.split())
+ assert SLACK_RUN_SCOPE in scopes
+ assert "task:read" in scopes
+
class TestCreateWizardOAuthAccessTokenForUser(TestCase):
def _create_wizard_app(self, scopes: list[str]) -> OAuthApplication:
diff --git a/products/desktop/packages/agent/src/adapters/error-classification.test.ts b/products/desktop/packages/agent/src/adapters/error-classification.test.ts
index 899fd02d2222..d56494f10173 100644
--- a/products/desktop/packages/agent/src/adapters/error-classification.test.ts
+++ b/products/desktop/packages/agent/src/adapters/error-classification.test.ts
@@ -25,6 +25,10 @@ describe("classifyAgentError", () => {
["API Error: Connection error.", "upstream_connection_error"],
["ACP connection closed", "upstream_connection_error"],
["API Error: Request timed out.", "upstream_timeout"],
+ [
+ "API Error: 429 Rate limit exceeded: This agent run reached its spend limit. Try again in about 24 hours.",
+ "task_spend_limit",
+ ],
["API Error: 429 rate limited", "upstream_provider_failure"],
["API Error: 529 overloaded", "upstream_provider_failure"],
["API Error: Content block not found", "content_block_rejection"],
diff --git a/products/desktop/packages/agent/src/adapters/error-classification.ts b/products/desktop/packages/agent/src/adapters/error-classification.ts
index c15376bdf545..d07691fa438d 100644
--- a/products/desktop/packages/agent/src/adapters/error-classification.ts
+++ b/products/desktop/packages/agent/src/adapters/error-classification.ts
@@ -8,6 +8,7 @@ export type AgentErrorClassification =
| "content_block_rejection"
| "turn_ended_without_response"
| "subscription_usage_limit"
+ | "task_spend_limit"
| "agent_error";
const RETRYABLE_UPSTREAM_ERROR_CLASSIFICATIONS =
@@ -29,6 +30,8 @@ const UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN = /API Error:\s*(?:429|5\d\d)\b/i;
// "unexpected status <code> <reason>: <body>" instead of the "API Error:" wording.
const CODEX_PROVIDER_ERROR_STATUS_PATTERN =
/unexpected status\s*(?:429|5\d\d)\b/i;
+const SANDBOX_TASK_SPEND_LIMIT_PATTERN =
+ /This agent run reached its spend limit/i;
const TURN_ENDED_WITHOUT_RESPONSE_PATTERN =
/\[ede_diagnostic\]\s+result_type=user\b/i;
// Anthropic's exact CLI wording for a Claude Pro/Max own-subscription limit
@@ -75,6 +78,9 @@ export function classifyAgentError(
if (/API Error:.*\b(?:timed out|timeout)\b/i.test(text)) {
return "upstream_timeout";
}
+ if (SANDBOX_TASK_SPEND_LIMIT_PATTERN.test(text)) {
+ return "task_spend_limit";
+ }
if (
UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN.test(text) ||
CODEX_PROVIDER_ERROR_STATUS_PATTERN.test(text)
diff --git a/products/desktop/packages/agent/src/server/agent-server.ts b/products/desktop/packages/agent/src/server/agent-server.ts
index 4817fb2d8a66..548a126c0770 100644
--- a/products/desktop/packages/agent/src/server/agent-server.ts
+++ b/products/desktop/packages/agent/src/server/agent-server.ts
@@ -159,6 +159,7 @@ const agentErrorClassificationSchema = z.enum([
"content_block_rejection",
"turn_ended_without_response",
"subscription_usage_limit",
+ "task_spend_limit",
"agent_error",
]) satisfies z.ZodType<AgentErrorClassification>;
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index 9808981bd6c4..b289fd4439ea 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -33,6 +33,7 @@ UPSTREAM_PROVIDER_FAILURE_MESSAGE = (
"The upstream AI provider failed to process the request. Please retry the task in a few minutes."
)
UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN = re.compile(r"\bapi error:\s*(?:429|5\d\d)\b", re.IGNORECASE)
+SANDBOX_TASK_SPEND_LIMIT_MARKER = "this agent run reached its spend limit"
DEFAULT_FAILURE_RECOVERY_HINT = (
"Reply in this thread with `retry` to try again from the latest checkpoint, "
"or add the missing details and I'll re-plan before continuing."
@@ -94,6 +95,9 @@ def _format_task_error(error: str) -> str:
if not error:
return "Unknown error"
+ if SANDBOX_TASK_SPEND_LIMIT_MARKER in error.lower():
+ return error
+
if UPSTREAM_PROVIDER_ERROR_STATUS_PATTERN.search(error):
return UPSTREAM_PROVIDER_FAILURE_MESSAGE
diff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.py
index eb93f23e2ff5..f1db11dfa0eb 100644
--- a/products/slack_app/backend/tests/test_slack_thread.py
+++ b/products/slack_app/backend/tests/test_slack_thread.py
@@ -26,6 +26,11 @@ class TestSlackThreadHandler(SimpleTestCase):
("passthrough", "Internal error: something else", "Internal error: something else"),
("stripped_passthrough", " Internal error: something else ", "Internal error: something else"),
("rate_limit", "Internal error: API Error: 429 rate_limit_error", UPSTREAM_PROVIDER_FAILURE_MESSAGE),
+ (
+ "task_spend_limit",
+ "Internal error: API Error: 429 Rate limit exceeded: This agent run reached its spend limit. Try again in about 24 hours.",
+ "Internal error: API Error: 429 Rate limit exceeded: This agent run reached its spend limit. Try again in about 24 hours.",
+ ),
("overloaded", "Internal error: API Error: 529 overloaded_error", UPSTREAM_PROVIDER_FAILURE_MESSAGE),
("server_error", "Internal error: API Error: 500 internal_error", UPSTREAM_PROVIDER_FAILURE_MESSAGE),
]
diff --git a/products/tasks/backend/temporal/oauth.py b/products/tasks/backend/temporal/oauth.py
index 293e1c2f9ae1..555875246682 100644
--- a/products/tasks/backend/temporal/oauth.py
+++ b/products/tasks/backend/temporal/oauth.py
@@ -180,6 +180,8 @@ def create_oauth_access_token(
token_options["include_mcp_builtin_agent_scope"] = True
if is_interactive_signals_run(task, run_state):
token_options["include_interactive_run_scope"] = True
+ if task.origin_product == Task.OriginProduct.SLACK:
+ token_options["include_slack_run_scope"] = True
return create_oauth_access_token_for_user(actor, task.team_id, **token_options)
@@ -272,6 +274,7 @@ def create_oauth_access_token_for_user(
application: SandboxOAuthApplication = "array",
include_mcp_builtin_agent_scope: bool = False,
include_interactive_run_scope: bool = False,
+ include_slack_run_scope: bool = False,
sandbox_task_id: UUID | None = None,
) -> str:
"""Create an OAuth access token for a sandbox app, scoped to a specific team."""
@@ -285,6 +288,8 @@ def create_oauth_access_token_for_user(
token_options["include_mcp_builtin_agent_scope"] = True
if include_interactive_run_scope:
token_options["include_interactive_run_scope"] = True
+ if include_slack_run_scope:
+ token_options["include_slack_run_scope"] = True
return _create_oauth_access_token_for_user(user, team_id, **token_options)
except RuntimeError as err:
raise OAuthTokenError(str(err), {"team_id": team_id}, cause=err) from err
diff --git a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
index cbb2c31eb169..dd3f7ac40580 100644
--- a/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
+++ b/products/tasks/backend/temporal/process_task/activities/post_slack_update.py
@@ -24,6 +24,8 @@ SLACK_RECOVERY_STRATEGY_RETRY = "retry"
SLACK_RECOVERY_STRATEGY_CONNECT_THEN_REPLAN = "connect_then_replan"
SLACK_RECOVERY_STRATEGY_UNBLOCK_AND_REPLAN = "unblock_and_replan"
SLACK_RECOVERY_STRATEGY_CANCELLED = "cancelled_resume"
+SLACK_RECOVERY_STRATEGY_WAIT_FOR_SPEND_LIMIT = "wait_for_spend_limit"
+SLACK_SPEND_LIMIT_ERROR_FRAGMENT = "this agent run reached its spend limit"
_CONNECT_THEN_REPLAN_MARKERS = (
"not connected",
@@ -70,6 +72,9 @@ _RECOVERY_PROMPTS = {
SLACK_RECOVERY_STRATEGY_CANCELLED: (
"Reply in this thread when you want to resume, and include any new direction I should follow."
),
+ SLACK_RECOVERY_STRATEGY_WAIT_FOR_SPEND_LIMIT: (
+ "Wait for this run's spend limit to reset before replying in the thread."
+ ),
}
SLACK_DENIAL_STOP_MESSAGE = "Stopped after the denied action — reply here to continue with a different approach."
@@ -262,6 +267,8 @@ def _mark_terminal_notified(task_run: Any, status: str, error: str | None = None
def _classify_failure_recovery(error: str) -> str:
normalized = error.lower()
+ if SLACK_SPEND_LIMIT_ERROR_FRAGMENT in normalized:
+ return SLACK_RECOVERY_STRATEGY_WAIT_FOR_SPEND_LIMIT
if any(marker in normalized for marker in _CONNECT_THEN_REPLAN_MARKERS):
return SLACK_RECOVERY_STRATEGY_CONNECT_THEN_REPLAN
if any(marker in normalized for marker in _UNBLOCK_AND_REPLAN_MARKERS):
diff --git a/products/tasks/backend/temporal/tests/test_oauth.py b/products/tasks/backend/temporal/tests/test_oauth.py
index 578e676ab53e..295c54a2b1de 100644
--- a/products/tasks/backend/temporal/tests/test_oauth.py
+++ b/products/tasks/backend/temporal/tests/test_oauth.py
@@ -102,24 +102,34 @@ def test_built_in_agent_origin_keeps_member_token_until_gateway_flag_rollout(
)
+ ("origin_product", "slack_run"),
+ [
+ (Task.OriginProduct.USER_CREATED, False),
+ (Task.OriginProduct.SLACK, True),
+ ],
+)
@patch("products.tasks.backend.temporal.oauth._create_oauth_access_token_for_user", return_value="token")
-def test_default_task_uses_array_oauth_application(mock_create: MagicMock) -> None:
+def test_array_task_mints_only_slack_runs_with_the_slack_provenance_marker(
+ mock_create: MagicMock, origin_product: Task.OriginProduct, slack_run: bool
+) -> None:
task = MagicMock(
id="task-id",
created_by=MagicMock(),
team_id=123,
- origin_product=Task.OriginProduct.USER_CREATED,
+ origin_product=origin_product,
)
assert create_oauth_access_token(task) == "token"
- mock_create.assert_called_once_with(
- task.created_by,
- 123,
- scopes="read_only",
- application="array",
- sandbox_task_id=task.id,
- )
+ expected: dict[str, object] = {
+ "scopes": "read_only",
+ "application": "array",
+ "sandbox_task_id": task.id,
+ }
+ if slack_run:
+ expected["include_slack_run_scope"] = True
+ mock_create.assert_called_once_with(task.created_by, 123, **expected)
# is_interactive_signals_run short-circuits on origin, so an omitted one reads as
diff --git a/products/tasks/backend/tests/test_post_slack_update.py b/products/tasks/backend/tests/test_post_slack_update.py
index 11327437a8e7..93c8c97a7709 100644
--- a/products/tasks/backend/tests/test_post_slack_update.py
+++ b/products/tasks/backend/tests/test_post_slack_update.py
@@ -132,6 +132,25 @@ class TestPostSlackUpdate(TestCase):
mock_update_reaction.assert_called_once_with("x")
mock_post_error.assert_called_once()
+ @patch.object(SlackThreadHandler, "post_error")
+ @patch.object(SlackThreadHandler, "update_reaction")
+ @patch("products.tasks.backend.models.TaskRun")
+ def test_spend_limit_failure_tells_the_thread_to_wait(
+ self, mock_task_run_class, _mock_update_reaction, mock_post_error
+ ):
+ error = (
+ "API Error: 429 Rate limit exceeded: This agent run reached its spend limit. Try again in about 24 hours."
+ )
+ mock_run = self._make_mock_run(mock_task_run_class.Status.FAILED, error_message=error)
+ mock_task_run_class.objects.select_related.return_value.get.return_value = mock_run
+
+ post_slack_update(PostSlackUpdateInput(run_id="run-1", slack_thread_context=self.slack_thread_context))
+
+ assert mock_post_error.call_args.args[0] == error
+ assert mock_post_error.call_args.kwargs["recovery_hint"] == (
+ "Wait for this run's spend limit to reset before replying in the thread."
+ )
+
@patch.object(SlackThreadHandler, "post_cancelled")
@patch.object(SlackThreadHandler, "update_reaction")
@patch("products.tasks.backend.models.TaskRun")
diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.md
index 436b01695d1d..d818e7302dc0 100644
--- a/services/llm-gateway/README.md
+++ b/services/llm-gateway/README.md
@@ -329,13 +329,14 @@ User-level limits only apply when an `end_user_id` is present (OAuth token holde
### Per-run limits
A sandbox agent run can spend a whole window's budget in one conversation, because the person driving it decides when it ends.
-`DEFAULT_SANDBOX_TASK_COST_LIMITS` caps the total spend of a single run, keyed on the task the token was minted for (`posthog_oauthaccesstoken.sandbox_task_id`), not on anything the caller sends:
+`DEFAULT_SANDBOX_TASK_COST_LIMITS` limits the recorded spend of a single run, keyed on the task the token was minted for (`posthog_oauthaccesstoken.sandbox_task_id`), not on anything the caller sends:
```python
"my_budget": ProductCostLimit(limit_usd=50.0, window_seconds=604800) # $50 per run
```
Opt-in — a budget with no entry has no per-run ceiling, and a token with no task binding is never metered here.
+The Python gateway records cost after each request completes, so concurrent requests can overshoot a limit by their combined in-flight spend.
### Budget keys
@@ -344,6 +345,7 @@ The three limits above are usually keyed by product, but a product that serves b
Today that splits `signals`: a run started from the Inbox carries `interactive_run:read` and meters against `signals_interactive`, while the scheduled pipeline keeps `signals`.
`signals_interactive` is a budget name only — it is not in `PRODUCTS`, so no caller can request it.
+Slack task tokens carry `slack_run:read`, which keeps them on the `slack_app` budget even if the sandbox calls another product route that accepts the same OAuth application.
## Error handling
diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.py
index d2dc47f59eb0..eed0e83f23cb 100644
--- a/services/llm-gateway/src/llm_gateway/config.py
+++ b/services/llm-gateway/src/llm_gateway/config.py
@@ -95,6 +95,11 @@ DEFAULT_USER_COST_LIMITS: dict[str, "UserCostLimit"] = {
# runs are far shorter than this, so in practice each task gets one budget for its lifetime.
DEFAULT_SANDBOX_TASK_COST_LIMITS: dict[str, "ProductCostLimit"] = {
"signals_interactive": ProductCostLimit(limit_usd=50.0, window_seconds=604800),
+ # Slack runs had no cost circuit breaker beyond the duration cap. A Slack task is the thread,
+ # so the budget covers every reply in it; the one-day window lets an old thread recover sooner
+ # than the week-long Signals window. Accounting happens after each call, so parallel requests
+ # can overshoot this threshold by their in-flight spend.
+ "slack_app": ProductCostLimit(limit_usd=200.0, window_seconds=86400),
}
_COST_LIMIT_KEY_ALIASES: dict[str, str] = {
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index 3140f1a0f51b..1d3bc6a6722e 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -453,6 +453,10 @@ INTERNAL_RUN_SCOPE: Final[str] = "internal_run:read"
# it can't be self-granted. Used to pick the budget, never to grant access.
INTERACTIVE_RUN_SCOPE: Final[str] = "interactive_run:read"
+# Server-minted Slack task marker. Used to keep its cost key fixed when the sandbox selects
+# another product route that accepts the same OAuth application.
+SLACK_RUN_SCOPE: Final[str] = "slack_run:read"
+
# Not a product: no caller can declare it, and it never appears in PRODUCTS. It only names a
# budget in product_cost_limits / user_cost_limits, resolved from the token by resolve_cost_key.
SIGNALS_INTERACTIVE_COST_KEY: Final[str] = "signals_interactive"
@@ -522,17 +526,17 @@ def is_model_restricted_for_product(model: str, product: str) -> bool:
def resolve_cost_key(product: str, scopes: list[str] | None) -> str:
"""The budget a request meters against, which is not always its product.
- Signals runs a scheduled pipeline and a set of buttons in the Inbox through one product.
- Their volume has different owners — ours and the customer's — so they get separate budgets,
- resolved from the token's own provenance marker rather than from the product the caller
- declared, which a sandbox is free to choose.
+ Provenance markers pin budgets that cannot safely depend on the product the caller declares,
+ which a sandbox is free to choose. Slack tokens always resolve to `slack_app`; Signals uses a
+ separate key only for runs a person started.
- The marker decides alone, without also requiring the declared product to be `signals`: a run
- whose token still comes from the Array app (the fallback while a region has no Signals app
- row) can declare `posthog_code` or `background_agents` instead, and pairing the two would let
- that choice move the run off the interactive budget and out of the per-run spend ceiling.
- Only interactive Signals runs are ever minted with the scope, so keying on it is sufficient.
+ Each marker decides alone, without also requiring its matching declared product. Pairing the
+ two would let a sandbox choose another allowed route and leave its per-run spend limit. Only
+ Slack tasks receive `slack_run`, and only interactive Signals runs receive `interactive_run`,
+ so either scope is sufficient provenance for its budget.
"""
+ if SLACK_RUN_SCOPE in (scopes or []):
+ return "slack_app"
if INTERACTIVE_RUN_SCOPE in (scopes or []):
return SIGNALS_INTERACTIVE_COST_KEY
return resolve_product_alias(product)
diff --git a/services/llm-gateway/tests/test_cost_throttles.py b/services/llm-gateway/tests/test_cost_throttles.py
index 7eea91ec98c7..a7e22706b81a 100644
--- a/services/llm-gateway/tests/test_cost_throttles.py
+++ b/services/llm-gateway/tests/test_cost_throttles.py
@@ -36,6 +36,12 @@ def make_signals_user(interactive: bool, user_id: int = 1) -> AuthenticatedUser:
return user
+def make_slack_user(user_id: int = 1) -> AuthenticatedUser:
+ user = make_user(user_id=user_id)
+ user.scopes = ["llm_gateway:read", "internal_run:read", "slack_run:read"]
+ return user
+
+
def make_context(
user: AuthenticatedUser | None = None,
product: str = "posthog_code",
@@ -1246,7 +1252,7 @@ class TestCostAccumulatorTTL:
assert accumulator.get_current("user2") == 3.0
-class TestSignalsInteractiveCostKey:
+class TestProvenanceCostKey:
@pytest.mark.parametrize(
("product", "scopes", "expected"),
[
@@ -1254,6 +1260,8 @@ class TestSignalsInteractiveCostKey:
("signals", ["llm_gateway:read"], "signals"),
("posthog_code", ["llm_gateway:read"], "posthog_code"),
("background_agents", ["llm_gateway:read"], "background_agents"),
+ ("slack_app", ["llm_gateway:read", "slack_run:read"], "slack_app"),
+ ("background_agents", ["llm_gateway:read", "slack_run:read"], "slack_app"),
# The marker alone decides. A run still holding an Array-app token can declare either
# of these routes, and honouring the declaration would drop it off the interactive
# budget and out of the per-run ceiling, which only `signals_interactive` configures.
@@ -1314,14 +1322,35 @@ class TestSandboxTaskCostThrottle:
assert (await throttle.allow_request(context)).allowed is True
@pytest.mark.asyncio
- async def test_denies_the_run_that_exhausts_its_ceiling_and_leaves_its_siblings_alone(self) -> None:
+ @pytest.mark.parametrize(
+ ("product", "user"),
+ [
+ ("signals", make_signals_user(interactive=True)),
+ ("slack_app", make_slack_user()),
+ ],
+ )
+ async def test_denies_the_run_that_exhausts_its_ceiling_and_leaves_its_siblings_alone(
+ self, product: str, user: AuthenticatedUser
+ ) -> None:
throttle = SandboxTaskCostThrottle(redis=None)
- user = make_signals_user(interactive=True)
- spent = make_context(product="signals", user=user, sandbox_task_id="task-1")
- sibling = make_context(product="signals", user=user, sandbox_task_id="task-2")
+ spent = make_context(product=product, user=user, sandbox_task_id="task-1")
+ sibling = make_context(product=product, user=user, sandbox_task_id="task-2")
limit, _ = throttle._get_limit_and_window(spent)
await throttle.record_cost(spent, limit)
assert (await throttle.allow_request(spent)).allowed is False
assert (await throttle.allow_request(sibling)).allowed is True
+
+ @pytest.mark.asyncio
+ async def test_slack_token_cannot_leave_its_task_ceiling_by_declaring_another_product(self) -> None:
+ throttle = SandboxTaskCostThrottle(redis=None)
+ slack = make_context(product="slack_app", user=make_slack_user(), sandbox_task_id="task-1")
+ alternate = make_context(product="background_agents", user=slack.user, sandbox_task_id="task-1")
+ limit, _ = throttle._get_limit_and_window(slack)
+
+ await throttle.record_cost(slack, limit)
+
+ result = await throttle.allow_request(alternate)
+ assert result.allowed is False
+ assert result.retry_after == 86400