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): fall back when gateway routing fails (#102620)

Brandone26c0c116cfb
diff --git a/products/tasks/backend/temporal/process_task/ai_gateway_token.py b/products/tasks/backend/temporal/process_task/ai_gateway_token.py
index a502960e59bd..c008b339f3dc 100644
--- a/products/tasks/backend/temporal/process_task/ai_gateway_token.py
+++ b/products/tasks/backend/temporal/process_task/ai_gateway_token.py
@@ -145,7 +145,17 @@ def mint_refusal(
if not model_allowed_by_product_pin(ai_product, model):
return "model_outside_pin"
# The Python gateway refuses every call once AI credits run out; the Go gateway has no such check.
- if _team_over_ai_credit_budget(team_id):
+ # An unknown balance is no licence to spend.
+ try:
+ over_budget = _team_over_ai_credit_budget(team_id)
+ except Exception:
+ logger.warning(
+ "ai_gateway_token: ai credit lookup failed, run stays on the Python gateway",
+ extra={"team_id": team_id},
+ exc_info=True,
+ )
+ return "ai_credits_unknown"
+ if over_budget:
return "ai_credits_exhausted"
return None
diff --git a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
index 8ab8ab19867d..eb76cf22bdd9 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_ai_gateway_token.py
@@ -532,6 +532,37 @@ class TestProvisioningBoundaries:
utils.run_gateway_env_vars(ctx, self._task())
update.assert_called_once_with("run-1", remove_keys=["ai_gateway_product"])
+ def test_routing_failure_leaves_the_run_on_the_python_gateway(self, mint_settings):
+ with patch.object(utils, "ai_gateway_env_vars", side_effect=RuntimeError("billing is down")):
+ assert utils.run_gateway_env_vars(self._ctx(), self._task()) == {}
+
+ def test_a_pinned_token_the_stamp_could_not_record_is_dropped(self, mint_settings):
+ env = {"AI_GATEWAY_URL": "url", "AI_GATEWAY_TOKEN": "phe", "AI_GATEWAY_PRODUCT": "slack_app"}
+ with (
+ patch.object(utils, "ai_gateway_env_vars", return_value=env),
+ patch(
+ "products.tasks.backend.models.TaskRun.update_state_atomic",
+ side_effect=RuntimeError("postgres is down"),
+ ),
+ ):
+ out = utils.run_gateway_env_vars(self._ctx(), self._task())
+ assert "AI_GATEWAY_TOKEN" not in out
+ assert out["AI_GATEWAY_URL"] == "url"
+
+ def test_an_unpinned_token_survives_a_failed_stamp_removal(self, mint_settings):
+ ctx = self._ctx()
+ ctx.state = {"ai_stage": "scout:logs", "ai_gateway_product": "slack_app"}
+ env = {"AI_GATEWAY_TOKEN": "phe", "AI_GATEWAY_PRODUCT": "signals_scout"}
+ with (
+ patch.object(utils, "ai_gateway_env_vars", return_value=env),
+ patch(
+ "products.tasks.backend.models.TaskRun.update_state_atomic",
+ side_effect=RuntimeError("postgres is down"),
+ ),
+ ):
+ out = utils.run_gateway_env_vars(ctx, self._task())
+ assert out["AI_GATEWAY_TOKEN"] == "phe"
+
class TestUserPinAndCapOverride:
def _response(self, body):
@@ -676,6 +707,35 @@ class TestSlackAppMint:
assert "AI_GATEWAY_TOKEN" not in env
mint.assert_not_called()
+ def test_credit_lookup_failure_does_not_mint(self, mint_settings):
+ mint_settings.SANDBOX_AI_GATEWAY_PRODUCTS = "slack_app"
+ with (
+ patch("products.tasks.backend.temporal.process_task.utils.mint_scoped_token") as mint,
+ patch(
+ "products.tasks.backend.temporal.process_task.ai_gateway_token._team_over_ai_credit_budget",
+ side_effect=RuntimeError("billing is down"),
+ ),
+ ):
+ env = ai_gateway_env_vars(
+ team_id=123,
+ origin_product="slack",
+ state={"interaction_origin": "slack"},
+ model="claude-opus-5",
+ runtime="acp",
+ )
+ assert "AI_GATEWAY_TOKEN" not in env
+ mint.assert_not_called()
+
+ def test_credit_lookup_failure_names_its_own_refusal(self):
+ with patch(
+ "products.tasks.backend.temporal.process_task.ai_gateway_token._team_over_ai_credit_budget",
+ side_effect=RuntimeError("billing is down"),
+ ):
+ refusal = mint_refusal(
+ "slack_app", team_id=123, state={"interaction_origin": "slack"}, model=None, runtime="acp"
+ )
+ assert refusal == "ai_credits_unknown"
+
# The provenance gate is only as strong as PATCH protection on the key it reads.
def test_provenance_key_is_patch_protected(self):
from products.tasks.backend.facade.api import _PROTECTED_RUN_STATE_KEYS
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 6cfd5db28b13..3e0f30eb9da4 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -1327,26 +1327,39 @@ def run_gateway_env_vars(ctx, task) -> dict[str, str]:
"""
if ctx.claude_model_access == "own-subscription":
return {}
- env_vars = ai_gateway_env_vars(
- team_id=ctx.team_id,
- origin_product=ctx.origin_product,
- ai_stage=(ctx.state or {}).get("ai_stage"),
- internal=task.internal,
- distinct_id=ctx.distinct_id,
- state=ctx.state,
- model=ctx.model,
- runtime=ctx.task_runtime,
- )
- _record_pinned_gateway_product(ctx.run_id, ctx.state, env_vars.get("AI_GATEWAY_PRODUCT"))
+ try:
+ env_vars = ai_gateway_env_vars(
+ team_id=ctx.team_id,
+ origin_product=ctx.origin_product,
+ ai_stage=(ctx.state or {}).get("ai_stage"),
+ internal=task.internal,
+ distinct_id=ctx.distinct_id,
+ state=ctx.state,
+ model=ctx.model,
+ runtime=ctx.task_runtime,
+ )
+ except Exception:
+ # Degrading to the Python gateway beats failing the provisioning activity and the run.
+ AI_GATEWAY_TOKEN_MINTS.labels(result="error").inc()
+ logger.warning(
+ "ai_gateway_token: routing failed, run stays on the Python gateway",
+ extra={"run_id": ctx.run_id},
+ exc_info=True,
+ )
+ return {}
+ if not _record_pinned_gateway_product(ctx.run_id, ctx.state, env_vars.get("AI_GATEWAY_PRODUCT")):
+ # The model-change guard reads that stamp; unstamped, a run can move off its pin with no fallback.
+ env_vars.pop("AI_GATEWAY_TOKEN", None)
return env_vars
-def _record_pinned_gateway_product(run_id: str, state: dict | None, minted_product: str | None) -> None:
+def _record_pinned_gateway_product(run_id: str, state: dict | None, minted_product: str | None) -> bool:
+ """Stamp the run with the pinned product of its token. False leaves a pinned run unstamped."""
from products.tasks.backend.models import TaskRun # noqa: PLC0415
pinned = minted_product if minted_product in PRODUCT_ALLOWED_MODELS else None
if pinned == (state or {}).get(GATEWAY_PRODUCT_STATE_KEY):
- return
+ return True
try:
if pinned:
TaskRun.update_state_atomic(run_id, updates={GATEWAY_PRODUCT_STATE_KEY: pinned})
@@ -1354,6 +1367,8 @@ def _record_pinned_gateway_product(run_id: str, state: dict | None, minted_produ
TaskRun.update_state_atomic(run_id, remove_keys=[GATEWAY_PRODUCT_STATE_KEY])
except Exception:
logger.warning("ai_gateway_token: failed to record the pinned product", extra={"run_id": run_id}, exc_info=True)
+ return pinned is None
+ return True
def ai_gateway_env_vars(