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(signals): limit jev requests across workers (#108294)

Alessandro Pogliaghi5f9012438644
diff --git a/posthog/test/test_token_bucket.py b/posthog/test/test_token_bucket.py
index b18e649e5ad2..bd517d2a30f8 100644
--- a/posthog/test/test_token_bucket.py
+++ b/posthog/test/test_token_bucket.py
@@ -3,6 +3,7 @@ from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase
+from fakeredis import FakeRedis
from parameterized import parameterized
from redis.exceptions import ConnectionError as RedisConnectionError
@@ -51,6 +52,19 @@ class TestTokenBucket(SimpleTestCase):
assert isinstance(decision, BucketDecision)
assert decision.remaining == ONE_PER_SECOND.burst - 1
+ def test_explicit_client_overrides_cached_scripts(self) -> None:
+ budget = Budget(burst=1, per_hour=3600)
+ with time_machine.travel("2026-01-01", tick=False):
+ consume("bucket:client", budget)
+ client = FakeRedis()
+ first = consume("bucket:client", budget, client=client)
+ second = consume("bucket:client", budget, client=client)
+ default = consume("bucket:client", budget)
+
+ assert isinstance(first, BucketDecision) and first.allowed
+ assert isinstance(second, BucketDecision) and not second.allowed
+ assert isinstance(default, BucketDecision) and not default.allowed
+
def test_refund_returns_tokens_capped_at_capacity(self) -> None:
with time_machine.travel("2026-01-01 00:00:00", tick=False):
for _ in range(3):
diff --git a/posthog/token_bucket.py b/posthog/token_bucket.py
index 38c0d880dff7..8e43c73582df 100644
--- a/posthog/token_bucket.py
+++ b/posthog/token_bucket.py
@@ -24,6 +24,7 @@ from __future__ import annotations
import math
import time
+from typing import TYPE_CHECKING
import structlog
from redis.commands.core import Script
@@ -32,6 +33,9 @@ from redis.exceptions import RedisError
from posthog.dataclasses import frozen
from posthog.redis import get_client
+if TYPE_CHECKING:
+ from redis import Redis
+
logger = structlog.get_logger(__name__)
@@ -150,11 +154,13 @@ def _scripts() -> _Scripts:
return _registered_scripts
-def consume(key: str, budget: Budget, cost: int = 1) -> BucketDecision | BucketUnavailable:
+def consume(
+ key: str, budget: Budget, cost: int = 1, *, client: Redis | None = None
+) -> BucketDecision | BucketUnavailable:
"""Atomically refill the bucket and take ``cost`` tokens if available."""
if cost < 1 or cost > budget.burst:
raise ValueError(f"cost must be between 1 and burst ({budget.burst}), got {cost}")
- consume_script = _scripts().consume
+ consume_script = client.register_script(_CONSUME_LUA) if client is not None else _scripts().consume
try:
allowed, remaining, retry_after_ms, reset_ms = consume_script(
keys=[key],
diff --git a/products/signals/backend/temporal/report_safety_judge.py b/products/signals/backend/temporal/report_safety_judge.py
index f9c63c4ef775..92a97bdada04 100644
--- a/products/signals/backend/temporal/report_safety_judge.py
+++ b/products/signals/backend/temporal/report_safety_judge.py
@@ -1,11 +1,13 @@
import re
import json
+import asyncio
from dataclasses import dataclass
from typing import Optional
import structlog
import temporalio
from pydantic import BaseModel, Field, model_validator
+from temporalio.exceptions import ApplicationError
from posthog.sync import database_sync_to_async
from posthog.temporal.common.scoped import scoped_temporal
@@ -29,6 +31,7 @@ logger = structlog.get_logger(__name__)
_SIGNAL_DATA_TAG = re.compile(r"<(/?)signal_data\b", re.IGNORECASE)
# A UTF-8 byte can become one token, so this leaves room under the deployed model's 8,192-token cap for framing.
JEV_REPORT_STATE_MAX_BYTES = 6 * 1024
+JEV_REPORT_TIMEOUT_SECONDS = 240.0
class SafetyJudgeResponse(BaseModel):
@@ -202,10 +205,18 @@ async def judge_report_safety(
"Shorten or remove that signal, then try again."
),
)
- for chunk in chunks:
- result = await judge_once(chunk, mode)
- if not result.choice:
- return result
+ try:
+ async with asyncio.timeout(JEV_REPORT_TIMEOUT_SECONDS):
+ for chunk in chunks:
+ result = await judge_once(chunk, mode)
+ if not result.choice:
+ return result
+ except TimeoutError:
+ raise ApplicationError(
+ "The report safety check exceeded its time limit.",
+ type="ReportSafetyTimeout",
+ non_retryable=True,
+ ) from None
return SafetyJudgeResponse(choice=True)
diff --git a/products/signals/backend/test/test_report_safety_judge.py b/products/signals/backend/test/test_report_safety_judge.py
index a6a42713e9ec..e9d9598ff07c 100644
--- a/products/signals/backend/test/test_report_safety_judge.py
+++ b/products/signals/backend/test/test_report_safety_judge.py
@@ -1,13 +1,20 @@
import json
+import asyncio
from datetime import UTC, datetime
+from threading import Event
import pytest
-from unittest.mock import patch
+import time_machine
+from unittest.mock import AsyncMock, patch
+
+from fakeredis import FakeRedis
+from temporalio.exceptions import ApplicationError
from products.ml_inference.backend.facade.contracts import ChoiceAnswer, DecisionResult, NoulAnswer
from products.signals.backend.temporal.llm import SAFETY_MODEL
from products.signals.backend.temporal.report_safety_judge import (
JEV_REPORT_STATE_MAX_BYTES,
+ JEV_REPORT_TIMEOUT_SECONDS,
SafetyJudgeResponse,
judge_report_safety,
)
@@ -113,7 +120,8 @@ async def test_typesafe_block_explains_the_category(
@pytest.mark.asyncio
-async def test_typesafe_only_checks_a_large_report_in_complete_chunks() -> None:
[email protected]("deadline_expired", [False, True])
+async def test_typesafe_only_checks_a_large_report_in_complete_chunks(deadline_expired: bool) -> None:
decision = DecisionResult(
model="jevk5-fp8-0.2",
answers={
@@ -134,14 +142,44 @@ async def test_typesafe_only_checks_a_large_report_in_complete_chunks() -> None:
)
for index, character in enumerate(("a", "b"), start=1)
]
+ loop = asyncio.get_running_loop()
+ report_deadline = asyncio.timeout(JEV_REPORT_TIMEOUT_SECONDS)
+ original_timeout = asyncio.timeout
+ release_gateway = Event()
+ calls = 0
+
+ def timeout(seconds: float | None) -> asyncio.Timeout:
+ return report_deadline if seconds == JEV_REPORT_TIMEOUT_SECONDS else original_timeout(seconds)
+
+ def gateway(*_args: object, **_kwargs: object) -> DecisionResult:
+ nonlocal calls
+ calls += 1
+ if deadline_expired and calls == 2:
+ loop.call_soon_threadsafe(report_deadline.reschedule, 0)
+ release_gateway.wait(5)
+ return decision
+
with (
+ time_machine.travel("2026-01-01", tick=False) as clock,
patch(f"{DECISION_MODULE_PATH}.posthoganalytics.get_feature_flag", return_value="typesafe-only"),
patch(f"{DECISION_MODULE_PATH}.posthoganalytics.capture"),
- patch(f"{DECISION_MODULE_PATH}.decision_api.decide_when_available", return_value=decision) as decide,
+ patch(f"{DECISION_MODULE_PATH}.get_client", return_value=FakeRedis()),
+ patch(f"{DECISION_MODULE_PATH}.decision_api.decide_when_available", side_effect=gateway) as decide,
+ patch(f"{DECISION_MODULE_PATH}.asyncio.sleep", AsyncMock(side_effect=clock.shift)),
+ patch(f"{MODULE_PATH}.asyncio.timeout", side_effect=timeout),
):
- result = await judge_report_safety(team_id=1, signals=signals, report_id="report-1")
+ try:
+ if deadline_expired:
+ with pytest.raises(ApplicationError, match="exceeded its time limit") as error:
+ await judge_report_safety(team_id=1, signals=signals, report_id="report-1")
+ assert error.value.non_retryable
+ assert error.value.type == "ReportSafetyTimeout"
+ else:
+ result = await judge_report_safety(team_id=1, signals=signals, report_id="report-1")
+ assert result.choice is True
+ finally:
+ release_gateway.set()
- assert result.choice is True
assert decide.call_count == 2
states = [call.args[0].state for call in decide.call_args_list]
assert all(len(json.dumps(state, ensure_ascii=False).encode()) <= JEV_REPORT_STATE_MAX_BYTES for state in states)
diff --git a/products/signals/backend/test/test_typesafe_decision.py b/products/signals/backend/test/test_typesafe_decision.py
index cf815bcd24b5..453e405d0d56 100644
--- a/products/signals/backend/test/test_typesafe_decision.py
+++ b/products/signals/backend/test/test_typesafe_decision.py
@@ -1,10 +1,19 @@
import asyncio
-from collections.abc import Awaitable, Callable
+from collections.abc import Awaitable, Callable, Iterator
+from contextlib import AbstractContextManager
from uuid import UUID
import pytest
+import time_machine
from unittest.mock import AsyncMock, MagicMock, patch
+from django.core.exceptions import ImproperlyConfigured
+
+from fakeredis import FakeRedis
+from redis.exceptions import ConnectionError as RedisConnectionError
+
+from posthog.token_bucket import TEST_reset_scripts
+
from products.ml_inference.backend.facade.contracts import (
ChoiceAnswer,
DecisionGatewayError,
@@ -19,6 +28,7 @@ from products.signals.backend.temporal.safety_filter import SafetyFilterJudgeRes
from products.signals.backend.typesafe_decision import (
JEV_MODEL,
JEV_TIMEOUT_SECONDS,
+ ModelMode,
SignalsDecision,
SignalsDecisionError,
_query,
@@ -26,6 +36,18 @@ from products.signals.backend.typesafe_decision import (
)
[email protected](autouse=True)
+def reset_jev_budget() -> Iterator[MagicMock]:
+ TEST_reset_scripts()
+ with (
+ patch("products.signals.backend.typesafe_decision.get_client", return_value=FakeRedis()) as get_redis,
+ patch("products.signals.backend.typesafe_decision.JEV_ADMISSION_TIMEOUT_SECONDS", 600),
+ patch("products.signals.backend.typesafe_decision.JEV_SHADOW_ADMISSION_TIMEOUT_SECONDS", 600),
+ ):
+ yield get_redis
+ TEST_reset_scripts()
+
+
def _actionability_result(probability: float = 0.98) -> DecisionResult:
return DecisionResult(
model="jevk5-fp8-0.2",
@@ -51,12 +73,14 @@ def _safety_result(probability: float = 0.2) -> DecisionResult:
async def _run_actionability(
*,
+ team_id: int = 7,
+ stage: str = "actionability",
traditional: Callable[[str | None], Awaitable[bool]] | None = None,
typesafe_result: Callable[[bool, str | None], bool] | None = None,
) -> bool:
return await run_model_decision(
- team_id=7,
- stage="actionability",
+ team_id=team_id,
+ stage=stage,
primary_model="claude-sonnet-5",
source_id="issue-1",
source_product="linear",
@@ -84,6 +108,7 @@ async def test_safety_requests_category_through_the_shared_gateway_client() -> N
"decision-1",
"issue-1",
"linear",
+ "typesafe-only",
)
decide.assert_called_once()
@@ -170,6 +195,136 @@ async def test_shadow_disagreement_keeps_primary_result_and_records_usage() -> N
assert decide.call_args.args[0].trace_id == trace_id
+async def test_shadow_budget_is_shared_across_teams_and_stages() -> None:
+ with (
+ time_machine.travel("2026-01-01", tick=False),
+ patch(
+ "products.signals.backend.typesafe_decision.posthoganalytics.get_feature_flag",
+ return_value="typesafe-shadow",
+ ),
+ patch("products.signals.backend.typesafe_decision.posthoganalytics.capture") as capture,
+ patch(
+ "products.signals.backend.typesafe_decision.decision_api.decide_when_available",
+ side_effect=lambda request, **kwargs: (
+ _actionability_result() if "actionable" in request.questions else _safety_result()
+ ),
+ ) as decide,
+ ):
+ results = await asyncio.gather(
+ *[
+ _run_actionability(team_id=team_id, stage=stage)
+ for team_id, stage in [(7, "actionability"), (8, "signal_safety"), (9, "report_safety")]
+ ]
+ )
+
+ assert results == [False, False, False]
+ assert decide.call_count == 2
+ statuses = [call.kwargs["properties"]["typesafe_status"] for call in capture.call_args_list]
+ assert sorted(statuses) == ["ok", "ok", "skipped_overload"]
+ assert all(call.kwargs["properties"]["deciding_provider"] == "traditional" for call in capture.call_args_list)
+
+
[email protected]("mode", ["traditional-shadow", "typesafe-only"])
+async def test_primary_waits_for_budget_refill(mode: ModelMode, reset_jev_budget: MagicMock) -> None:
+ with (
+ time_machine.travel("2026-01-01", tick=False) as clock,
+ patch("products.signals.backend.typesafe_decision.posthoganalytics.get_feature_flag", return_value=mode),
+ patch("products.signals.backend.typesafe_decision.posthoganalytics.capture"),
+ patch(
+ "products.signals.backend.typesafe_decision.decision_api.decide_when_available",
+ return_value=_actionability_result(),
+ ) as decide,
+ patch("products.signals.backend.typesafe_decision.asyncio.sleep", AsyncMock(side_effect=clock.shift)) as sleep,
+ ):
+ results = [await _run_actionability() for _ in range(3)]
+
+ assert results == [True, True, True]
+ assert decide.call_count == 3
+ assert all(call.kwargs["timeout_seconds"] == JEV_TIMEOUT_SECONDS for call in decide.call_args_list)
+ assert sleep.await_count == 2
+ assert all(2 <= call.args[0] <= 2.25 for call in sleep.await_args_list)
+ reset_jev_budget.assert_called_with(socket_timeout=0.1, socket_connect_timeout=0.1)
+
+
+async def test_busy_team_leaves_capacity_for_another_teams_primary_checks() -> None:
+ with (
+ time_machine.travel("2026-01-01", tick=False) as clock,
+ patch(
+ "products.signals.backend.typesafe_decision.posthoganalytics.get_feature_flag",
+ return_value="typesafe-shadow",
+ ) as flag,
+ patch("products.signals.backend.typesafe_decision.posthoganalytics.capture"),
+ patch(
+ "products.signals.backend.typesafe_decision.decision_api.decide_when_available",
+ return_value=_actionability_result(),
+ ) as decide,
+ patch(
+ "products.signals.backend.typesafe_decision.asyncio.sleep",
+ AsyncMock(side_effect=AssertionError("The other team must not wait for capacity")),
+ ),
+ ):
+ for second in range(6):
+ flag.return_value = "typesafe-shadow"
+ await asyncio.gather(*[_run_actionability(team_id=7) for _ in range(20)])
+ if second % 2 == 0:
+ flag.return_value = "typesafe-only"
+ assert await _run_actionability(team_id=8) is True
+ clock.shift(1)
+
+ teams = [call.args[0].team_id for call in decide.call_args_list]
+ assert teams.count(7) == 3
+ assert teams.count(8) == 3
+
+
[email protected]("mode", ["typesafe-shadow", "traditional-shadow", "typesafe-only"])
[email protected]("failure", ["redis", "redis_config", "timeout"])
+async def test_admission_failure_preserves_mode_semantics(mode: ModelMode, failure: str) -> None:
+ traditional = AsyncMock(return_value=False)
+ broken_redis = MagicMock()
+ broken_redis.register_script.return_value.side_effect = RedisConnectionError("unavailable")
+ failure_patch: AbstractContextManager[object]
+ if failure == "redis":
+ failure_patch = patch("products.signals.backend.typesafe_decision.get_client", return_value=broken_redis)
+ elif failure == "redis_config":
+ failure_patch = patch(
+ "products.signals.backend.typesafe_decision.get_client", side_effect=ImproperlyConfigured("unconfigured")
+ )
+ else:
+ timeout = (
+ "JEV_SHADOW_ADMISSION_TIMEOUT_SECONDS" if mode == "typesafe-shadow" else "JEV_ADMISSION_TIMEOUT_SECONDS"
+ )
+ failure_patch = patch(f"products.signals.backend.typesafe_decision.{timeout}", 0)
+ with (
+ failure_patch,
+ patch("products.signals.backend.typesafe_decision.posthoganalytics.get_feature_flag", return_value=mode),
+ patch("products.signals.backend.typesafe_decision.posthoganalytics.capture") as capture,
+ patch("products.signals.backend.typesafe_decision.decision_api.decide_when_available") as decide,
+ ):
+ if mode == "typesafe-only":
+ with pytest.raises(SignalsDecisionError):
+ await _run_actionability(traditional=traditional)
+ traditional.assert_not_awaited()
+ else:
+ assert await _run_actionability(traditional=traditional) is False
+ traditional.assert_awaited_once()
+
+ decide.assert_not_called()
+ properties = capture.call_args.kwargs["properties"]
+ assert properties["typesafe_status"] == ("admission_timeout" if failure == "timeout" else "admission_unavailable")
+ assert (
+ properties["deciding_provider"]
+ == {
+ "typesafe-shadow": "traditional",
+ "traditional-shadow": "traditional_fallback",
+ "typesafe-only": "typesafe",
+ }[mode]
+ )
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
"mode,gateway_error,expected_status",
diff --git a/products/signals/backend/typesafe_decision.py b/products/signals/backend/typesafe_decision.py
index 7916c88f8ce7..c92f08431fb6 100644
--- a/products/signals/backend/typesafe_decision.py
+++ b/products/signals/backend/typesafe_decision.py
@@ -1,4 +1,5 @@
import math
+import random
import asyncio
from collections.abc import Awaitable, Callable
from contextlib import suppress
@@ -6,11 +7,17 @@ from time import perf_counter
from typing import Generic, Literal, TypeVar
from uuid import uuid4
+from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
+
import structlog
import posthoganalytics
from prometheus_client import Counter, Histogram
+from redis.exceptions import RedisError
from posthog.dataclasses import frozen
+from posthog.redis import get_client
+from posthog.token_bucket import BucketUnavailable, Budget, consume
from products.ml_inference.backend.facade import api as decision_api
from products.ml_inference.backend.facade.contracts import (
@@ -30,6 +37,11 @@ ModelMode = Literal["traditional-only", "typesafe-shadow", "traditional-shadow",
JEV_MODEL = "posthog/hogference/jevk5-fp8-0.2"
JEV_INPUT_USD_PER_MILLION = 0.042
JEV_TIMEOUT_SECONDS = 3.0
+JEV_ADMISSION_TIMEOUT_SECONDS = 10.0
+JEV_SHADOW_ADMISSION_TIMEOUT_SECONDS = 0.5
+JEV_REDIS_TIMEOUT_SECONDS = 0.1
+JEV_BUDGET = Budget(burst=2, per_hour=3600)
+JEV_TEAM_BUDGET = Budget(burst=1, per_hour=1800)
ACTIONABILITY_THRESHOLD = 0.85
SIGNAL_SAFETY_THRESHOLD = 0.90
@@ -48,6 +60,11 @@ _CALLS = Counter(
"TypeSafe decisions by stage and outcome.",
["stage", "outcome"],
)
+_ADMISSIONS = Counter(
+ "signals_typesafe_admissions",
+ "Jev admission attempts by stage and outcome.",
+ ["stage", "outcome"],
+)
_DISAGREEMENTS = Counter(
"signals_typesafe_decision_disagreements",
"TypeSafe decisions that disagreed with the traditional verdict.",
@@ -85,6 +102,12 @@ class SignalsDecisionError(RuntimeError):
pass
+class _JevAdmissionError(SignalsDecisionError):
+ def __init__(self, status: Literal["skipped_overload", "admission_unavailable", "admission_timeout"]) -> None:
+ self.status = status
+ super().__init__(status)
+
+
@frozen
class SignalsDecision:
probability: float
@@ -116,6 +139,33 @@ async def model_mode(team_id: int) -> ModelMode:
return "traditional-only"
+async def _admit_jev(team_id: int, stage: str, mode: ModelMode) -> None:
+ key = f"signals:jev:admission:{settings.CLOUD_DEPLOYMENT or 'local'}"
+ try:
+ timeout = JEV_SHADOW_ADMISSION_TIMEOUT_SECONDS if mode == "typesafe-shadow" else JEV_ADMISSION_TIMEOUT_SECONDS
+ async with asyncio.timeout(timeout):
+ client = get_client(
+ socket_timeout=JEV_REDIS_TIMEOUT_SECONDS, socket_connect_timeout=JEV_REDIS_TIMEOUT_SECONDS
+ )
+ while True:
+ decision = await asyncio.to_thread(consume, f"{key}:team:{team_id}", JEV_TEAM_BUDGET, client=client)
+ if not isinstance(decision, BucketUnavailable) and decision.allowed:
+ decision = await asyncio.to_thread(consume, key, JEV_BUDGET, client=client)
+ if isinstance(decision, BucketUnavailable):
+ raise _JevAdmissionError("admission_unavailable")
+ if decision.allowed:
+ _ADMISSIONS.labels(stage, "admitted").inc()
+ return
+ if mode == "typesafe-shadow":
+ raise _JevAdmissionError("skipped_overload")
+ _ADMISSIONS.labels(stage, "deferred").inc()
+ await asyncio.sleep(decision.retry_after + random.uniform(0, 0.25))
+ except (RedisError, ImproperlyConfigured):
+ raise _JevAdmissionError("admission_unavailable") from None
+ except TimeoutError:
+ raise _JevAdmissionError("admission_timeout") from None
+
+
async def _query(
team_id: int,
stage: str,
@@ -124,7 +174,9 @@ async def _query(
trace_id: str,
source_id: str | None,
source_product: str | None,
+ mode: ModelMode,
) -> SignalsDecision:
+ await _admit_jev(team_id, stage, mode)
question_name = "actionable" if stage == "actionability" else "safe"
questions = {
question_name: DecisionQuestion(type=DecisionQuestionType.NOUL, instructions=instructions),
@@ -223,8 +275,11 @@ async def run_model_decision(
async def run_typesafe() -> _SignalsModelCallResult[SignalsDecision]:
started = perf_counter()
try:
- result = await _query(team_id, stage, state, instructions, trace_id, source_id, source_product)
+ result = await _query(team_id, stage, state, instructions, trace_id, source_id, source_product, mode)
return _SignalsModelCallResult(value=result, error=None, latency_seconds=perf_counter() - started)
+ except _JevAdmissionError as error:
+ _ADMISSIONS.labels(stage, error.status).inc()
+ return _SignalsModelCallResult(value=None, error=error, latency_seconds=perf_counter() - started)
except Exception as error:
logger.warning("TypeSafe call failed", stage=stage, error_type=type(error).__name__)
return _SignalsModelCallResult(value=None, error=error, latency_seconds=perf_counter() - started)
@@ -281,6 +336,8 @@ async def run_model_decision(
if conversion_error is not None
else "ok"
if typesafe is not None
+ else typesafe_call.error.status
+ if isinstance(typesafe_call.error, _JevAdmissionError)
else type(typesafe_call.error).__name__
)
_CALLS.labels(stage, typesafe_status).inc()