: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
refactor(alerts): let the evaluation admission limiter take its own key (#111203)
Jimmy Zhua1deeb4294ac
diff --git a/posthog/temporal/alerts/admission.py b/posthog/temporal/alerts/admission.pyindex 7002f3637d6b..7e145ab29c67 100644--- a/posthog/temporal/alerts/admission.py+++ b/posthog/temporal/alerts/admission.py@@ -10,6 +10,7 @@ from posthog.temporal.alerts.retry_policy import alert_timeoutslogger = structlog.get_logger(__name__)# Admitted alert ids scored by lease expiry; a check joins when started, not when its query runs.+# Production's set. A caller with its own budget passes its own key, so the two never share slots.INFLIGHT_KEY = "alerts:evaluations:inflight"# A check cannot outlive its workflow's execution timeout, so a lease this long can never lapse@@ -102,42 +103,46 @@ def _decode(member: bytes | str) -> str:return member.decode() if isinstance(member, bytes) else member-def admit_evaluation_slots(alert_ids: list[str], *, limit: int, expires_at: float) -> list[str]:+def admit_evaluation_slots(+ alert_ids: list[str], *, limit: int, expires_at: float, key: str = INFLIGHT_KEY+) -> list[str]:"""Admit candidates in order while the set has room and return the ids held under expires_at."""- admitted = redis.get_client().eval(_ADMIT_SCRIPT, 1, INFLIGHT_KEY, time.time(), limit, expires_at, *alert_ids)+ admitted = redis.get_client().eval(_ADMIT_SCRIPT, 1, key, time.time(), limit, expires_at, *alert_ids)return [_decode(member) for member in admitted]-def hold_evaluation_slot(alert_id: str, *, limit: int, lease_seconds: float = SLOT_LEASE_SECONDS) -> float | None:+def hold_evaluation_slot(+ alert_id: str, *, limit: int, lease_seconds: float = SLOT_LEASE_SECONDS, key: str = INFLIGHT_KEY+) -> float | None:"""Take the slot for a check that is about to run and return the expiry that identifies this holder.Returns None when the check no longer holds a slot and the set is full."""expires_at = time.time() + lease_seconds- held = redis.get_client().eval(_HOLD_SCRIPT, 1, INFLIGHT_KEY, time.time(), limit, expires_at, alert_id)+ held = redis.get_client().eval(_HOLD_SCRIPT, 1, key, time.time(), limit, expires_at, alert_id)return expires_at if held else None-def refresh_evaluation_slot(alert_id: str, *, held_until: float, expires_at: float) -> bool:+def refresh_evaluation_slot(alert_id: str, *, held_until: float, expires_at: float, key: str = INFLIGHT_KEY) -> bool:"""Move the holder's expiry to expires_at and report whether the holder still owned the slot."""- owned = redis.get_client().eval(_REFRESH_OWNED_SCRIPT, 1, INFLIGHT_KEY, alert_id, held_until, expires_at)+ owned = redis.get_client().eval(_REFRESH_OWNED_SCRIPT, 1, key, alert_id, held_until, expires_at)return bool(owned)-def release_evaluation_slots(alert_ids: list[str], *, held_until: float) -> None:+def release_evaluation_slots(alert_ids: list[str], *, held_until: float, key: str = INFLIGHT_KEY) -> None:"""Free the slots that still carry the expiry their writer was given."""if alert_ids:- redis.get_client().eval(_RELEASE_OWNED_SCRIPT, 1, INFLIGHT_KEY, held_until, *alert_ids)+ redis.get_client().eval(_RELEASE_OWNED_SCRIPT, 1, key, held_until, *alert_ids)-def release_evaluation_slot(alert_id: str, *, held_until: float) -> None:+def release_evaluation_slot(alert_id: str, *, held_until: float, key: str = INFLIGHT_KEY) -> None:"""Free a slot, but only if the holder identified by held_until still owns it.Best effort: the check this belongs to already ran, so a failure is logged rather than raised."""for attempt in range(_BOOKKEEPING_ATTEMPTS):try:- release_evaluation_slots([alert_id], held_until=held_until)+ release_evaluation_slots([alert_id], held_until=held_until, key=key)returnexcept Exception:if attempt == _BOOKKEEPING_ATTEMPTS - 1:@@ -146,7 +151,7 @@ def release_evaluation_slot(alert_id: str, *, held_until: float) -> None:time.sleep(_BOOKKEEPING_RETRY_SECONDS)-def inflight_alert_ids() -> set[str]:+def inflight_alert_ids(key: str = INFLIGHT_KEY) -> set[str]:client = redis.get_client()- client.zremrangebyscore(INFLIGHT_KEY, "-inf", time.time())- return {_decode(member) for member in client.zrange(INFLIGHT_KEY, 0, -1)}+ client.zremrangebyscore(key, "-inf", time.time())+ return {_decode(member) for member in client.zrange(key, 0, -1)}diff --git a/posthog/temporal/tests/test_alerts_admission.py b/posthog/temporal/tests/test_alerts_admission.pyindex 97335b2bbf7e..2ca6020eee6b 100644--- a/posthog/temporal/tests/test_alerts_admission.py+++ b/posthog/temporal/tests/test_alerts_admission.py@@ -15,14 +15,15 @@ from posthog.temporal.alerts.admission import (release_evaluation_slots,)+_OTHER_KEY = "test:alerts:evaluations:inflight"_AT_TEN = datetime(2026, 9, 22, 10, tzinfo=UTC).timestamp() # where the frozen clocks below start@pytest.fixture(autouse=True)def clear_inflight_slots():- get_client().delete(INFLIGHT_KEY)+ get_client().delete(INFLIGHT_KEY, _OTHER_KEY)yield- get_client().delete(INFLIGHT_KEY)+ get_client().delete(INFLIGHT_KEY, _OTHER_KEY)def _expiry(offset_seconds: float = 0) -> float:@@ -67,6 +68,16 @@ def test_admission_fills_only_the_free_capacity_and_slots_outlive_any_check() ->assert inflight_alert_ids() == {"c"}+def test_a_set_under_its_own_key_never_takes_the_production_sets_slots() -> None:+ with time_machine.travel(_at(0), tick=False):+ assert admit_evaluation_slots(["a"], limit=1, expires_at=_expiry()) == ["a"]+ assert admit_evaluation_slots(["b"], limit=1, expires_at=_expiry(), key=_OTHER_KEY) == ["b"]+ assert hold_evaluation_slot("c", limit=1, key=_OTHER_KEY) is None+ release_evaluation_slot("a", held_until=_expiry(), key=_OTHER_KEY)+ assert inflight_alert_ids() == {"a"}+ assert inflight_alert_ids(key=_OTHER_KEY) == {"b"}++def test_refresh_moves_only_the_expiry_its_holder_wrote() -> None:with time_machine.travel(_at(0), tick=False):held = _hold("running", limit=1, lease_seconds=120)