: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
feat(replay): hard cap on replay vision summaries per team per month (#57313)
Arnaud Hillen666c36b16e5a
diff --git a/.husky/pre-commit b/.husky/pre-commitindex e995d5debaf5..4a0219d3e5a0 100755--- a/.husky/pre-commit+++ b/.husky/pre-commit@@ -12,7 +12,9 @@ export POSTHOG_TELEMETRY_OPT_OUT=1# Activate Flox environment if available and not already active# This ensures lint-staged commands work in GUI Git clients (GitHub Desktop, etc.)if command -v flox > /dev/null 2>&1 && [ -d ".flox/cache" ] && [ -z "$FLOX_ENV" ]; then- exec "$(command -v flox)" activate -- bash -c "POSTHOG_TELEMETRY_OPT_OUT=1 NODE_OPTIONS='--max-old-space-size=8192' pnpm lint-staged"+ # CI=true so pnpm in flox's on-activate hook doesn't ask for a TTY when+ # cleaning stale node_modules. Pre-commit has no TTY, same as real CI.+ exec env CI=true "$(command -v flox)" activate -- bash -c "POSTHOG_TELEMETRY_OPT_OUT=1 NODE_OPTIONS='--max-old-space-size=8192' pnpm lint-staged"else# Fallback: run without Flox (for non-Flox users or if already activated)NODE_OPTIONS='--max-old-space-size=8192' pnpm lint-stageddiff --git a/posthog/session_recordings/ai_summary_cap.py b/posthog/session_recordings/ai_summary_cap.pynew file mode 100644index 000000000000..dae6c93392dc--- /dev/null+++ b/posthog/session_recordings/ai_summary_cap.py@@ -0,0 +1,204 @@+"""Per-team monthly hard cap for Replay Vision summaries.++Backstop against runaway LLM cost. One Redis counter per team per calendar+month; auto-resets on the 1st. A team can use up to 2x the cap across a month+boundary — fine for a backstop, not for billing.++Cap value: `DEFAULT_MAX_SUMMARIES_PER_PERIOD`, optionally lowered (never+raised) by `SignalSourceConfig.config["max_summaries_per_period"]`.++Importable from both DRF and Temporal activities — keep this module+dependency-light.+"""++from __future__ import annotations++from dataclasses import dataclass+from datetime import UTC, datetime++import structlog+from redis.exceptions import ResponseError++from posthog.redis import get_client++logger = structlog.get_logger(__name__)++# Bump in a deploy. Per-team lowering is allowed via SignalSourceConfig.+DEFAULT_MAX_SUMMARIES_PER_PERIOD = 4 * 1000++# JSON key on SignalSourceConfig.config.+CONFIG_KEY = "max_summaries_per_period"++_REDIS_KEY_PREFIX = "posthog/replay-summary-cap"++# 32 days — slightly longer than any month so the bucket outlives its read+# window. Redis GCs the key on its own.+_KEY_TTL_SECONDS = 32 * 24 * 60 * 60+++@dataclass(frozen=True)+class CapDecision:+ allowed: bool+ used: int+ cap: int+++def coerce_max_summaries_per_period(value: object) -> int:+ """Validate a raw cap override value. Anything malformed falls back to+ the default — admin JSON should never take down the summarize path.++ Bools are rejected explicitly because they inherit from int and would+ otherwise coerce to 0/1.+ """+ if value is None or isinstance(value, bool):+ return DEFAULT_MAX_SUMMARIES_PER_PERIOD+ if not isinstance(value, (int, float, str, bytes, bytearray)):+ return DEFAULT_MAX_SUMMARIES_PER_PERIOD+ try:+ cap = int(value)+ except (ValueError, OverflowError):+ return DEFAULT_MAX_SUMMARIES_PER_PERIOD+ if cap <= 0:+ return DEFAULT_MAX_SUMMARIES_PER_PERIOD+ return cap+++def get_cap_for_team(team_id: int) -> int:+ """Return the effective per-team monthly cap.++ The override on `SignalSourceConfig.config` can only LOWER the default —+ never raise it. Project members can edit that config row via API, so+ treating it as a raise vector would be a privilege escalation around the+ backstop.+ """+ # Lazy import: this module is imported by Temporal activities that load+ # before Django apps.+ from products.signals.backend.models import SignalSourceConfig++ row = (+ SignalSourceConfig.objects.filter(+ team_id=team_id,+ source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,+ source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,+ )+ .only("config")+ .first()+ )+ if row is None or not isinstance(row.config, dict):+ return DEFAULT_MAX_SUMMARIES_PER_PERIOD+ override = coerce_max_summaries_per_period(row.config.get(CONFIG_KEY))+ return min(override, DEFAULT_MAX_SUMMARIES_PER_PERIOD)+++def _redis_key(team_id: int, *, now: datetime | None = None) -> str:+ bucket = (now or datetime.now(UTC)).strftime("%Y-%m")+ return f"{_REDIS_KEY_PREFIX}:{team_id}:{bucket}"+++def current_usage(team_id: int, *, now: datetime | None = None) -> int:+ raw = get_client().get(_redis_key(team_id, now=now))+ if raw is None:+ return 0+ try:+ return int(raw)+ except (TypeError, ValueError):+ # Corrupt key — log and treat as zero so summaries don't break.+ logger.warning("replay_summary_cap.corrupt_counter", team_id=team_id, raw=raw)+ return 0+++def headroom(team_id: int, *, now: datetime | None = None) -> int:+ """Remaining quota for the team this month. Never negative.++ Used by the autonomous sweep to slice its dispatch list before starting+ children, otherwise a runaway sweep could starve interactive DRF users.+ """+ return max(0, get_cap_for_team(team_id) - current_usage(team_id, now=now))+++def _incrby(client, key: str, n: int) -> int:+ """INCRBY with WRONGTYPE recovery. Returns the new counter value.++ Recovery: if somebody SET the key to a non-integer string, reset it and+ retry. Losing the (uncountable) prior usage is fine for a backstop.+ """+ try:+ return int(client.incrby(key, n))+ except ResponseError:+ logger.warning("replay_summary_cap.corrupt_counter_on_write", key=key)+ client.delete(key)+ return int(client.incrby(key, n))+++def consume_summary_quota(team_id: int, n: int = 1, *, now: datetime | None = None) -> int:+ """Increment the counter by `n`. Sets TTL on first write. Returns the new+ value. No bound check — caller is responsible for that."""+ if n <= 0:+ return current_usage(team_id, now=now)+ key = _redis_key(team_id, now=now)+ client = get_client()+ new_value = _incrby(client, key, n)+ # First write of the month: set the TTL so abandoned keys GC themselves.+ if new_value == n:+ client.expire(key, _KEY_TTL_SECONDS)+ return new_value+++def atomic_check_and_consume(team_id: int, *, requested: int = 1, now: datetime | None = None) -> CapDecision:+ """Reserve `requested` slots in one Redis round-trip. Returns the decision.++ If the new counter exceeds the cap, the reservation is rolled back and+ `allowed=False` is returned. This closes the TOCTOU window between a+ naive read-then-write check, so concurrent requests can't all pass and+ then collectively overshoot.++ Callers MUST `refund(team_id, n)` if they later decide not to do the+ work (e.g. `start_workflow` failed). The split between reservation and+ commit lives in the caller.+ """+ if requested < 0:+ raise ValueError(f"requested must be >= 0, got {requested}")+ if requested == 0:+ return CapDecision(allowed=True, used=current_usage(team_id, now=now), cap=get_cap_for_team(team_id))++ cap = get_cap_for_team(team_id)+ key = _redis_key(team_id, now=now)+ client = get_client()+ new_value = _incrby(client, key, requested)+ if new_value == requested:+ client.expire(key, _KEY_TTL_SECONDS)+ if new_value > cap:+ # Roll back: keep the counter at-or-below cap so a steady-state team+ # doesn't permanently look over.+ client.decrby(key, requested)+ return CapDecision(allowed=False, used=new_value - requested, cap=cap)+ return CapDecision(allowed=True, used=new_value, cap=cap)+++def refund(team_id: int, n: int = 1, *, now: datetime | None = None) -> None:+ """Roll back a previous `atomic_check_and_consume(...n)` reservation.++ Best-effort: failures are logged, not raised. We don't want a Redis blip+ to fail a request that already succeeded (or failed) on its main path.+ """+ if n <= 0:+ return+ try:+ get_client().decrby(_redis_key(team_id, now=now), n)+ except Exception as e:+ logger.warning("replay_summary_cap.refund_failed", team_id=team_id, n=n, error=str(e))+++def check_only(team_id: int, *, requested: int = 1, now: datetime | None = None) -> CapDecision:+ """Read-only: decide whether `requested` slots fit, without reserving.++ Use this when you can't tolerate the boundary effect of a reserve-then-+ refund cycle (e.g. health checks). For request-handling paths that may+ commit to LLM work, prefer `atomic_check_and_consume`.+ """+ if requested < 0:+ raise ValueError(f"requested must be >= 0, got {requested}")+ now = now or datetime.now(UTC)+ cap = get_cap_for_team(team_id)+ used = current_usage(team_id, now=now)+ return CapDecision(allowed=used + requested <= cap, used=used, cap=cap)diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.pyindex 5cb5f21bd2b1..99ecc7cd16e5 100644--- a/posthog/session_recordings/session_recording_api.py+++ b/posthog/session_recordings/session_recording_api.py@@ -1536,6 +1536,12 @@ class SessionRecordingViewSet():raise exceptions.ValidationError("session summary is not enabled for this user")session_id = str(recording.session_id)++ # Per-team monthly hard cap as a cost backstop is enforced inside+ # `execute_summarize_session_video_stream`, just before a *fresh*+ # workflow start — gating it here would 402 cached-summary fast-path+ # hits and silent-attach (`id_conflict_policy=USE_EXISTING`) cases that+ # don't issue any LLM work.tracking_id = generate_tracking_id()force_restart = bool(request.data.get("force_restart", False)) if isinstance(request.data, dict) else Falseproduct_context, custom_tags = self._load_team_summary_config()diff --git a/posthog/session_recordings/test/test_ai_summary_cap.py b/posthog/session_recordings/test/test_ai_summary_cap.pynew file mode 100644index 000000000000..f28edbe98dd2--- /dev/null+++ b/posthog/session_recordings/test/test_ai_summary_cap.py@@ -0,0 +1,411 @@+import re+import threading+from datetime import UTC, datetime++import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from parameterized import parameterized+from redis.exceptions import ResponseError++from posthog.models.team import Team+from posthog.redis import get_client+from posthog.session_recordings.ai_summary_cap import (+ DEFAULT_MAX_SUMMARIES_PER_PERIOD,+ CapDecision,+ _redis_key,+ atomic_check_and_consume,+ check_only,+ coerce_max_summaries_per_period,+ consume_summary_quota,+ current_usage,+ get_cap_for_team,+ headroom,+ refund,+)++from products.signals.backend.models import SignalSourceConfig+++def _create_cluster_config(team: Team, *, enabled: bool = True, **config_overrides) -> SignalSourceConfig:+ """Most tests need the same boilerplate row — keep it here."""+ return SignalSourceConfig.objects.create(+ team=team,+ source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,+ source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,+ enabled=enabled,+ config=config_overrides,+ )+++class TestCoerceMaxSummariesPerPeriod(BaseTest):+ @parameterized.expand(+ [+ # Falls back to default+ ("none", None, DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ ("zero", 0, DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ ("negative_int", -10, DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ ("negative_float_truncates_to_negative", -3.5, DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ ("non_numeric_string", "abc", DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ ("empty_string", "", DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ ("hex_string", "0x10", DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ ("bool_true", True, DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ ("bool_false", False, DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ ("nan_value", float("nan"), DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ # `int(float("inf"))` raises OverflowError, not ValueError — must be caught.+ ("inf", float("inf"), DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ ("negative_inf", float("-inf"), DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ ("list", [5], DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ ("dict", {"x": 5}, DEFAULT_MAX_SUMMARIES_PER_PERIOD),+ # Accepted (matches lenient `coerce_sample_rate` semantics)+ ("numeric_string", "100", 100),+ # int() strips ASCII whitespace; documented behavior we lean on.+ ("padded_numeric_string", " 50 ", 50),+ ("leading_zero_string", "007", 7),+ ("float_truncates", 3.7, 3),+ ("valid_one", 1, 1),+ ("valid_large", 99999, 99999),+ ("very_large_int", 10**12, 10**12),+ ]+ )+ def test_coerce(self, _name, value, expected):+ assert coerce_max_summaries_per_period(value) == expected+++class TestGetCapForTeam(BaseTest):+ def test_default_when_no_config_row(self):+ assert not SignalSourceConfig.objects.filter(team_id=self.team.pk).exists()+ assert get_cap_for_team(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD++ def test_default_when_row_has_no_cap_key(self):+ _create_cluster_config(self.team, sample_rate=0.5)+ assert get_cap_for_team(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD++ def test_override_can_only_lower(self):+ # Overrides ≤ default are honored.+ _create_cluster_config(self.team, max_summaries_per_period=7)+ assert get_cap_for_team(self.team.pk) == 7++ def test_override_above_default_is_clamped(self):+ # Cap-the-cap: project members can edit SignalSourceConfig, so an+ # override is allowed to lower the backstop but never raise it.+ _create_cluster_config(self.team, max_summaries_per_period=DEFAULT_MAX_SUMMARIES_PER_PERIOD * 1000)+ assert get_cap_for_team(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD++ def test_disabled_row_still_supplies_cap(self):+ # Sweep gating uses `enabled=True`, but the cap should apply even when the+ # autonomous sweep is off — DRF summarize is what we're protecting.+ _create_cluster_config(self.team, enabled=False, max_summaries_per_period=3)+ assert get_cap_for_team(self.team.pk) == 3++ def test_default_when_config_value_uncoerceable(self):+ _create_cluster_config(self.team, max_summaries_per_period="abc")+ assert get_cap_for_team(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD++ def test_default_when_config_is_list(self):+ # Pathological but valid JSON — `.config.get(...)` would AttributeError without the guard.+ SignalSourceConfig.objects.create(+ team=self.team,+ source_product=SignalSourceConfig.SourceProduct.SESSION_REPLAY,+ source_type=SignalSourceConfig.SourceType.SESSION_ANALYSIS_CLUSTER,+ config=[],+ )+ assert get_cap_for_team(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD++ def test_cross_team_isolation(self):+ other_team = Team.objects.create(organization=self.organization, name="other")+ _create_cluster_config(other_team, max_summaries_per_period=99)+ assert get_cap_for_team(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD+ assert get_cap_for_team(other_team.pk) == 99+++class TestRedisKey(BaseTest):+ def test_format(self):+ key = _redis_key(42, now=datetime(2026, 5, 5, tzinfo=UTC))+ assert key == "posthog/replay-summary-cap:42:2026-05"+ assert re.fullmatch(r"posthog/replay-summary-cap:\d+:\d{4}-\d{2}", key)++ def test_zero_padded_month(self):+ # Catch a future drift to %Y-%-m or similar — ops scripts will rely on+ # lexicographic sort, and "2026-1" sorts after "2026-10".+ assert _redis_key(1, now=datetime(2026, 1, 31, tzinfo=UTC)).endswith(":2026-01")+ assert _redis_key(1, now=datetime(2026, 12, 1, tzinfo=UTC)).endswith(":2026-12")++ def test_uses_utc_when_now_omitted(self):+ # We never want a worker's local TZ to determine the bucket — pin it to UTC.+ with patch("posthog.session_recordings.ai_summary_cap.datetime") as mock_dt:+ mock_dt.now.return_value = datetime(2026, 5, 5, 12, 0, 0, tzinfo=UTC)+ key = _redis_key(1)+ mock_dt.now.assert_called_once_with(UTC)+ assert key.endswith(":2026-05")+++class TestCounter(BaseTest):+ def test_current_usage_zero_for_unseen_team(self):+ assert current_usage(self.team.pk) == 0++ def test_consume_increments_and_returns_new_value(self):+ assert consume_summary_quota(self.team.pk, 1) == 1+ assert current_usage(self.team.pk) == 1+ assert consume_summary_quota(self.team.pk, 4) == 5+ assert current_usage(self.team.pk) == 5++ def test_consume_zero_is_noop(self):+ consume_summary_quota(self.team.pk, 1)+ assert consume_summary_quota(self.team.pk, 0) == 1+ assert consume_summary_quota(self.team.pk, -3) == 1+ assert current_usage(self.team.pk) == 1++ def test_ttl_set_on_first_write_only(self):+ client = get_client()+ consume_summary_quota(self.team.pk, 1)+ first_ttl = client.ttl(_redis_key(self.team.pk))+ assert first_ttl > 0 # an EXPIRE was issued++ # Force the key's TTL to a sentinel; a second consume must NOT re-issue EXPIRE.+ client.expire(_redis_key(self.team.pk), 999)+ consume_summary_quota(self.team.pk, 1)+ second_ttl = client.ttl(_redis_key(self.team.pk))+ assert second_ttl <= 999++ def test_corrupt_counter_treated_as_zero(self):+ get_client().set(_redis_key(self.team.pk), "not-a-number")+ assert current_usage(self.team.pk) == 0++ def test_consume_recovers_from_corrupt_key(self):+ # Real bug if unhandled: Redis INCRBY on a non-integer string raises+ # WRONGTYPE → we'd crash the summarize path. Reset + retry instead.+ client = get_client()+ client.set(_redis_key(self.team.pk), "not-a-number")+ # Sanity: raw INCRBY would explode.+ with pytest.raises(ResponseError):+ client.incrby(_redis_key(self.team.pk), 1)+ # consume_summary_quota must absorb it and re-establish the counter.+ assert consume_summary_quota(self.team.pk, 2) == 2+ assert current_usage(self.team.pk) == 2++ def test_consume_returns_int_even_when_redis_returns_bytes_via_round_trip(self):+ # Belt-and-braces: INCRBY returns int already, but `current_usage` reads+ # via GET which can return bytes depending on client config. Make sure we+ # still cast cleanly.+ consume_summary_quota(self.team.pk, 7)+ raw = get_client().get(_redis_key(self.team.pk))+ assert raw is not None+ assert int(raw) == 7 # what current_usage does internally+ assert current_usage(self.team.pk) == 7+++class TestCheckOnly(BaseTest):+ """`check_only` is the entrypoint primitive used at the cost-backstop+ check. The defining invariant: it MUST NEVER advance the counter, no+ matter the decision. Pair with a later `consume_summary_quota` once the+ caller commits to actual LLM work.+ """++ def setUp(self):+ super().setUp()+ _create_cluster_config(self.team, max_summaries_per_period=3)++ def test_allows_under_cap_without_incrementing(self):+ # Repeated check_only must not move the counter — that's the whole point.+ for _ in range(5):+ decision = check_only(self.team.pk)+ assert decision == CapDecision(allowed=True, used=0, cap=3)+ assert current_usage(self.team.pk) == 0++ def test_blocks_at_cap_without_incrementing(self):+ consume_summary_quota(self.team.pk, 3)+ decision = check_only(self.team.pk)+ assert decision == CapDecision(allowed=False, used=3, cap=3)+ assert current_usage(self.team.pk) == 3++ def test_reflects_existing_usage(self):+ consume_summary_quota(self.team.pk, 2)+ assert check_only(self.team.pk) == CapDecision(allowed=True, used=2, cap=3)+ assert current_usage(self.team.pk) == 2 # unchanged++ def test_requested_more_than_headroom_blocks(self):+ consume_summary_quota(self.team.pk, 2)+ assert check_only(self.team.pk, requested=2) == CapDecision(allowed=False, used=2, cap=3)+ assert current_usage(self.team.pk) == 2++ def test_requested_equal_to_headroom_allowed(self):+ consume_summary_quota(self.team.pk, 1)+ assert check_only(self.team.pk, requested=2) == CapDecision(allowed=True, used=1, cap=3)+ assert current_usage(self.team.pk) == 1 # NOT advanced — we only checked++ def test_exactly_at_cap_then_blocks(self):+ # Boundary regression: off-by-one in the `<=` comparator would flip these.+ consume_summary_quota(self.team.pk, 2)+ assert check_only(self.team.pk).allowed is True+ consume_summary_quota(self.team.pk, 1) # caller commits to the work+ assert check_only(self.team.pk).allowed is False++ def test_requested_zero_is_allowed_noop(self):+ decision = check_only(self.team.pk, requested=0)+ assert decision.allowed is True+ assert current_usage(self.team.pk) == 0++ def test_requested_negative_raises(self):+ with pytest.raises(ValueError, match="requested must be >= 0"):+ check_only(self.team.pk, requested=-1)++ def test_check_only_then_consume_advances_counter_only_when_committed(self):+ # The split (check_only + consume) must advance the counter exactly+ # once per committed work item, never on the check itself.+ for _ in range(3):+ decision = check_only(self.team.pk)+ if decision.allowed:+ consume_summary_quota(self.team.pk, 1)+ assert current_usage(self.team.pk) == 3+ assert check_only(self.team.pk).allowed is False++ def test_no_consume_on_short_circuit(self):+ # The motivating case for the split: a caller that bails out of LLM work+ # after `check_only` (cache hit, in-flight workflow dedup) must NOT have+ # burned quota.+ for _ in range(10):+ decision = check_only(self.team.pk)+ assert decision.allowed is True+ # Caller short-circuits — no consume call.+ assert current_usage(self.team.pk) == 0+++class TestHeadroom(BaseTest):+ def test_headroom_default_when_unseen(self):+ assert headroom(self.team.pk) == DEFAULT_MAX_SUMMARIES_PER_PERIOD++ def test_headroom_decreases_with_usage(self):+ _create_cluster_config(self.team, max_summaries_per_period=10)+ assert headroom(self.team.pk) == 10+ consume_summary_quota(self.team.pk, 4)+ assert headroom(self.team.pk) == 6++ def test_headroom_clamped_to_zero_when_overconsumed(self):+ _create_cluster_config(self.team, max_summaries_per_period=5)+ consume_summary_quota(self.team.pk, 12)+ assert headroom(self.team.pk) == 0+++class TestAtomicCheckAndConsume(BaseTest):+ """`atomic_check_and_consume` is the request-handling primitive: reserves a+ slot in one Redis round-trip and reverts if the new value exceeds the cap.+ """++ def setUp(self):+ super().setUp()+ _create_cluster_config(self.team, max_summaries_per_period=3)++ def test_first_n_calls_allowed_then_blocks(self):+ # Within the cap: each call advances the counter by 1.+ for i in range(1, 4):+ decision = atomic_check_and_consume(self.team.pk)+ assert decision == CapDecision(allowed=True, used=i, cap=3)+ assert current_usage(self.team.pk) == i+ # Cap reached: next call is blocked and reverted.+ decision = atomic_check_and_consume(self.team.pk)+ assert decision == CapDecision(allowed=False, used=3, cap=3)+ assert current_usage(self.team.pk) == 3++ def test_block_reverts_so_steady_state_stays_at_cap(self):+ # The blocked branch must DECRBY back to the cap, otherwise repeated+ # blocked calls would inflate the counter unboundedly.+ consume_summary_quota(self.team.pk, 3)+ for _ in range(20):+ assert atomic_check_and_consume(self.team.pk).allowed is False+ assert current_usage(self.team.pk) == 3++ def test_requested_more_than_headroom_blocks_and_reverts(self):+ consume_summary_quota(self.team.pk, 2)+ decision = atomic_check_and_consume(self.team.pk, requested=2)+ # Cap=3, used=2, requested=2 → would be 4 → block + revert.+ assert decision == CapDecision(allowed=False, used=2, cap=3)+ assert current_usage(self.team.pk) == 2++ def test_requested_zero_is_allowed_noop(self):+ decision = atomic_check_and_consume(self.team.pk, requested=0)+ assert decision.allowed is True+ assert current_usage(self.team.pk) == 0++ def test_requested_negative_raises(self):+ with pytest.raises(ValueError, match="requested must be >= 0"):+ atomic_check_and_consume(self.team.pk, requested=-1)++ def test_atomic_check_and_consume_is_overshoot_free(self):+ # The defining invariant of the atomic API: concurrent callers can+ # never collectively pass more than `cap`. The split check_only ++ # consume pattern can; the atomic one cannot.+ #+ # Mock the cap lookup so we don't hit Django's connection-per-thread+ # transaction isolation (test row written in the main thread isn't+ # visible to worker threads with fresh connections).+ n_threads = 20+ barrier = threading.Barrier(n_threads)+ results: list[CapDecision] = []+ results_lock = threading.Lock()++ def worker():+ barrier.wait()+ decision = atomic_check_and_consume(self.team.pk)+ with results_lock:+ results.append(decision)++ with patch("posthog.session_recordings.ai_summary_cap.get_cap_for_team", return_value=3):+ threads = [threading.Thread(target=worker) for _ in range(n_threads)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ allowed_count = sum(1 for r in results if r.allowed)+ # Cap is 3 — no concurrency can break that.+ assert allowed_count == 3+ # Counter equals exactly cap. All blocked attempts reverted.+ assert current_usage(self.team.pk) == 3+++class TestRefund(BaseTest):+ def setUp(self):+ super().setUp()+ _create_cluster_config(self.team, max_summaries_per_period=3)++ def test_refund_undoes_a_prior_atomic_reservation(self):+ atomic_check_and_consume(self.team.pk)+ assert current_usage(self.team.pk) == 1+ refund(self.team.pk, 1)+ assert current_usage(self.team.pk) == 0++ def test_refund_zero_or_negative_is_noop(self):+ consume_summary_quota(self.team.pk, 2)+ refund(self.team.pk, 0)+ refund(self.team.pk, -5)+ assert current_usage(self.team.pk) == 2++ def test_refund_swallows_redis_errors(self):+ # A flaky DECR must not raise — refund is best-effort.+ with patch("posthog.session_recordings.ai_summary_cap.get_client") as mock_client:+ mock_client.return_value.decrby.side_effect = ConnectionError("redis down")+ refund(self.team.pk, 1)+++class TestMonthBoundary(BaseTest):+ def test_independent_buckets_across_months(self):+ jan = datetime(2026, 1, 31, 23, 59, 59, tzinfo=UTC)+ feb = datetime(2026, 2, 1, 0, 0, 1, tzinfo=UTC)++ consume_summary_quota(self.team.pk, 5, now=jan)+ assert current_usage(self.team.pk, now=jan) == 5+ assert current_usage(self.team.pk, now=feb) == 0++ consume_summary_quota(self.team.pk, 2, now=feb)+ assert current_usage(self.team.pk, now=feb) == 2+ assert current_usage(self.team.pk, now=jan) == 5++ def test_check_only_uses_now_for_bucket(self):+ feb = datetime(2026, 2, 15, 12, 0, 0, tzinfo=UTC)+ consume_summary_quota(self.team.pk, 5, now=feb)++ with patch("posthog.session_recordings.ai_summary_cap.datetime") as mock_dt:+ mock_dt.now.return_value = feb+ assert check_only(self.team.pk) == CapDecision(allowed=True, used=5, cap=DEFAULT_MAX_SUMMARIES_PER_PERIOD)diff --git a/posthog/temporal/session_replay/session_summary/workflow.py b/posthog/temporal/session_replay/session_summary/workflow.pyindex 513daef5d95a..f406b121b511 100644--- a/posthog/temporal/session_replay/session_summary/workflow.py+++ b/posthog/temporal/session_replay/session_summary/workflow.py@@ -19,13 +19,16 @@ from temporalio.common import (WorkflowIDReusePolicy,)from temporalio.exceptions import ApplicationError, WorkflowAlreadyStartedError+from temporalio.service import RPCError, RPCStatusCodefrom posthog.schema import ReplayInactivityPeriod+from posthog.event_usage import groupsfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.redis import get_client+from posthog.session_recordings.ai_summary_cap import atomic_check_and_consume, refundfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.client import async_connect@@ -617,6 +620,28 @@ async def _check_handle_data(return desc.status, final_result+async def _workflow_is_running(client: Any, workflow_id: str) -> bool:+ """True iff a workflow with this id is currently RUNNING.++ Discriminates fresh LLM runs from silent attaches: ``_start_video_summary_workflow``+ uses ``USE_EXISTING``, so starting twice with the same id returns a handle+ without raising.++ Error handling is asymmetric on purpose:+ - ``NOT_FOUND`` → ``False`` (fresh start path; caller must charge the cap).+ - Any other ``RPCError`` is re-raised so a flaky Temporal blip surfaces as+ ``session-summary-error`` rather than silently double-charging.+ """+ handle = client.get_workflow_handle(workflow_id)+ try:+ desc = await handle.describe()+ except RPCError as e:+ if e.status == RPCStatusCode.NOT_FOUND:+ return False+ raise+ return desc.status == WorkflowExecutionStatus.RUNNING++def _prepare_execution(session_id: str,user: User,@@ -830,12 +855,70 @@ async def execute_summarize_session_video_stream()client = await async_connect()++ # The cap only fires on a fresh LLM run. If `_start_video_summary_workflow`+ # is about to attach via USE_EXISTING to someone else's in-flight run, skip+ # the cap so we don't 402 a teammate reading already-paid-for work.+ # `force_restart` always preempts via TERMINATE_EXISTING — counts as fresh.+ will_start_fresh_run = force_restart or not await _workflow_is_running(client, workflow_id)++ quota_reserved = False+ if will_start_fresh_run:+ # Reserve a slot atomically (INCR + revert if over cap). One round-trip+ # closes the TOCTOU window where concurrent requests can all read the+ # same `used` and then collectively overshoot. Redis failures fail open+ # — a flaky counter must not break the summarize path.+ try:+ cap_decision = await database_sync_to_async(atomic_check_and_consume, thread_sensitive=False)(team.id)+ except Exception as e:+ logger.warning(+ "video summary cap reservation failed (fail-open)",+ team_id=team.id,+ session_id=session_id,+ error=str(e),+ signals_type="session-summaries",+ )+ cap_decision = None++ if cap_decision is not None and not cap_decision.allowed:+ posthoganalytics.capture(+ distinct_id=user.distinct_id,+ event="replay summary quota blocked",+ properties={+ "team_id": team.id,+ "used": cap_decision.used,+ "cap": cap_decision.cap,+ "source": "dock",+ },+ groups=groups(None, team),+ )+ yield serialize_to_sse_event(+ event_label="session-summary-error",+ event_data=(+ "You've reached this team's monthly limit for AI session summaries "+ f"({cap_decision.used}/{cap_decision.cap}). Try again next month."+ ),+ )+ return++ quota_reserved = cap_decision is not None and cap_decision.allowed+try:handle = await _start_video_summary_workflow(inputs=session_input, workflow_id=workflow_id, force_restart=force_restart)except WorkflowAlreadyStartedError:+ # Race: someone else started the same workflow between our describe and+ # start call. Attach to theirs and refund the slot we reserved.handle = client.get_workflow_handle(workflow_id)+ if quota_reserved:+ await database_sync_to_async(refund, thread_sensitive=False)(team.id, 1)+ quota_reserved = False+ except Exception:+ # Any other start failure: never went to the LLM, give the slot back.+ if quota_reserved:+ await database_sync_to_async(refund, thread_sensitive=False)(team.id, 1)+ raiselogger.info("video summary polling loop starting",diff --git a/posthog/temporal/session_replay/summarization_sweep/__init__.py b/posthog/temporal/session_replay/summarization_sweep/__init__.pyindex 5c04f37db70c..faa7b1796523 100644--- a/posthog/temporal/session_replay/summarization_sweep/__init__.py+++ b/posthog/temporal/session_replay/summarization_sweep/__init__.py@@ -6,6 +6,7 @@ keeps the set of schedules in sync with Postgres."""from posthog.temporal.session_replay.summarization_sweep.activities import (+ consume_summary_quota_activity,delete_team_schedule_activity,find_sessions_for_team_activity,list_enabled_teams_activity,@@ -25,4 +26,5 @@ SUMMARIZATION_SWEEP_ACTIVITIES = [list_enabled_teams_activity,list_summarization_schedule_team_ids_activity,upsert_team_schedule_activity,+ consume_summary_quota_activity,]diff --git a/posthog/temporal/session_replay/summarization_sweep/activities.py b/posthog/temporal/session_replay/summarization_sweep/activities.pyindex a50396420c68..7b35a51ae86b 100644--- a/posthog/temporal/session_replay/summarization_sweep/activities.py+++ b/posthog/temporal/session_replay/summarization_sweep/activities.py@@ -9,6 +9,7 @@ from temporalio import activityfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.redis import get_async_client+from posthog.session_recordings.ai_summary_cap import consume_summary_quota, headroomfrom posthog.sync import database_sync_to_async, database_sync_to_async_poolfrom posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_FINGERPRINT_KEYfrom posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter import read_stuck_session_ids@@ -26,6 +27,7 @@ from posthog.temporal.session_replay.summarization_sweep.session_candidates impofilter_session_ids_with_events,)from posthog.temporal.session_replay.summarization_sweep.types import (+ ConsumeSummaryQuotaInput,DeleteTeamScheduleInput,FindSessionsInput,FindSessionsResult,@@ -134,6 +136,14 @@ async def find_sessions_for_team_activity(inputs: FindSessionsInput) -> FindSessstuck = await _stuck_session_ids(inputs.team_id, sessions_to_summarize)sessions_to_summarize = [sid for sid in sessions_to_summarize if sid not in stuck]+ # Hard-cap the dispatch list by the team's remaining monthly headroom. Without+ # this, an autonomous sweep can drain the bucket and starve the DRF entrypoint.+ # Race against concurrent DRF traffic is fine — the cap is a backstop, not billing.+ available = await database_sync_to_async(headroom, thread_sensitive=False)(inputs.team_id)+ if available <= 0:+ return FindSessionsResult(team_id=inputs.team_id)+ sessions_to_summarize = sessions_to_summarize[:available]+return FindSessionsResult(team_id=inputs.team_id,session_ids=sessions_to_summarize,@@ -232,3 +242,13 @@ async def upsert_team_schedule_activity(inputs: UpsertTeamScheduleInput) -> Nonefrom posthog.temporal.session_replay.summarization_sweep.schedule import a_upsert_team_scheduleawait a_upsert_team_schedule(inputs.team_id)+++async def consume_summary_quota_activity(inputs: ConsumeSummaryQuotaInput) -> None:+ """Increment the team's monthly summary counter by `n`. Called once per+ sweep tick after children have been started, so we only count what we+ actually dispatched. Workflow can't touch Redis directly (sandbox)."""+ if inputs.n <= 0:+ return+ await database_sync_to_async(consume_summary_quota, thread_sensitive=False)(inputs.team_id, inputs.n)diff --git a/posthog/temporal/session_replay/summarization_sweep/types.py b/posthog/temporal/session_replay/summarization_sweep/types.pyindex e7feddd7b6a1..604cae24d106 100644--- a/posthog/temporal/session_replay/summarization_sweep/types.py+++ b/posthog/temporal/session_replay/summarization_sweep/types.py@@ -30,6 +30,12 @@ class UpsertTeamScheduleInput:team_id: int+@dataclass+class ConsumeSummaryQuotaInput:+ team_id: int+ n: int++@dataclassclass ReconcileSchedulesInputs:passdiff --git a/posthog/temporal/session_replay/summarization_sweep/workflow.py b/posthog/temporal/session_replay/summarization_sweep/workflow.pyindex 5c562aac9fa9..a5dae05937bb 100644--- a/posthog/temporal/session_replay/summarization_sweep/workflow.py+++ b/posthog/temporal/session_replay/summarization_sweep/workflow.py@@ -20,7 +20,11 @@ from posthog.temporal.session_replay.summarization_sweep.constants import (SESSION_LOOKBACK_MINUTES,WORKFLOW_NAME,)-from posthog.temporal.session_replay.summarization_sweep.types import FindSessionsInput, SummarizeTeamSessionsInputs+from posthog.temporal.session_replay.summarization_sweep.types import (+ ConsumeSummaryQuotaInput,+ FindSessionsInput,+ SummarizeTeamSessionsInputs,+)from ee.hogai.session_summaries.constants import DEFAULT_VIDEO_UNDERSTANDING_MODEL@@ -30,7 +34,10 @@ with workflow.unsafe.imports_passed_through():from posthog.temporal.session_replay.session_summary.types.inputs import SingleSessionSummaryInputsfrom posthog.temporal.session_replay.session_summary.workflow import SummarizeSingleSessionWorkflow- from posthog.temporal.session_replay.summarization_sweep.activities import find_sessions_for_team_activity+ from posthog.temporal.session_replay.summarization_sweep.activities import (+ consume_summary_quota_activity,+ find_sessions_for_team_activity,+ )@workflow.defn(name=WORKFLOW_NAME)@@ -87,6 +94,28 @@ class SummarizeTeamSessionsWorkflow(PostHogWorkflow):type="AllChildStartsFailed",)+ # Charge the cap by what we actually dispatched. Skipped/failed children+ # never reach the LLM, so don't count them.+ #+ # `maximum_attempts=1` + swallow exceptions: INCRBY is non-idempotent, so+ # a retry after a Redis blip would silently inflate the counter for the+ # rest of the month. Losing one increment is recoverable on the next+ # sweep tick; an inflated counter is not. Bookkeeping must never fail a+ # sweep whose children all dispatched.+ if started > 0:+ try:+ await workflow.execute_activity(+ consume_summary_quota_activity,+ args=[ConsumeSummaryQuotaInput(team_id=inputs.team_id, n=started)],+ start_to_close_timeout=timedelta(seconds=15),+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ except Exception as e:+ workflow.logger.warning(+ "summarization_sweep.consume_quota_failed",+ extra={"team_id": inputs.team_id, "n": started, "error": str(e)},+ )+return {"team_id": inputs.team_id,"workflows_started": started,diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex c6ed44018857..4a3862e201cd 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -211,6 +211,7 @@ class TestSummarizationSweepModuleIntegrity:"list_enabled_teams_activity","list_summarization_schedule_team_ids_activity","upsert_team_schedule_activity",+ "consume_summary_quota_activity",]actual_activity_names = [a.__name__ for a in SUMMARIZATION_SWEEP_ACTIVITIES]assert len(actual_activity_names) == len(expected_activities), (diff --git a/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py b/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.pyindex 9c418010c6b1..53d682c22bd0 100644--- a/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py+++ b/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py@@ -1,5 +1,6 @@import json-from collections.abc import AsyncGenerator, Callable+from collections.abc import AsyncGenerator, Callable, Iterator+from types import SimpleNamespacefrom typing import Anyimport pytest@@ -132,6 +133,34 @@ class TestFetchSessionDataActivity:class TestExecuteSummarizeSessionVideoStream:+ @pytest.fixture(autouse=True)+ def cap_mocks(self) -> Iterator[SimpleNamespace]:+ """Default cap behavior for the happy path: no in-flight workflow,+ cap not exhausted. Tests that need to block, refund, or simulate Redis+ failures flip the relevant return value rather than re-patching."""+ workflow_is_running = AsyncMock(return_value=False)+ atomic = MagicMock(return_value=MagicMock(allowed=True, used=1, cap=4000))+ refund = MagicMock(return_value=None)+ with (+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._workflow_is_running",+ workflow_is_running,+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.atomic_check_and_consume",+ atomic,+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.refund",+ refund,+ ),+ ):+ yield SimpleNamespace(+ workflow_is_running=workflow_is_running,+ atomic=atomic,+ refund=refund,+ )+@staticmethoddef _make_handle(check_handle_data_side_effect: list[tuple[Any, Any]]) -> MagicMock:handle = MagicMock()@@ -587,6 +616,412 @@ class TestExecuteSummarizeSessionVideoStream:assert kwargs["id_reuse_policy"] == WorkflowIDReusePolicy.ALLOW_DUPLICATEassert kwargs["id_conflict_policy"] == expected_conflict_policy+ @pytest.mark.asyncio+ async def test_attach_to_running_workflow_skips_check_and_consume(+ self,+ cap_mocks: SimpleNamespace,+ mock_session_id: str,+ mock_user: MagicMock,+ mock_team: MagicMock,+ mock_enriched_llm_json_response: dict[str, Any],+ ):+ """When the same workflow is already RUNNING (silent attach via+ ``id_conflict_policy=USE_EXISTING``), the cap MUST NOT fire. The other+ caller already paid the LLM cost — gating here would 402 a teammate+ reading work-in-progress."""+ cap_mocks.workflow_is_running.return_value = True+ handle = self._make_handle([(WorkflowExecutionStatus.COMPLETED, None)])+ completed_summary = MagicMock()+ completed_summary.id = "id"+ completed_summary.summary = mock_enriched_llm_json_response++ with (+ patch.object(+ SingleSessionSummary.objects,+ "get_summary",+ MagicMock(side_effect=[None, completed_summary]),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._prepare_execution",+ return_value=(None, None, None, MagicMock(), "workflow-id"),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._start_video_summary_workflow",+ AsyncMock(return_value=handle),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.async_connect",+ AsyncMock(return_value=MagicMock()),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.asyncio.sleep",+ AsyncMock(),+ ),+ ):+ await self._collect(+ execute_summarize_session_video_stream(+ session_id=mock_session_id,+ user=mock_user,+ team=mock_team,+ )+ )++ cap_mocks.atomic.assert_not_called()+ cap_mocks.refund.assert_not_called()++ @pytest.mark.asyncio+ async def test_force_restart_charges_cap_even_when_already_running(+ self,+ cap_mocks: SimpleNamespace,+ mock_session_id: str,+ mock_user: MagicMock,+ mock_team: MagicMock,+ mock_enriched_llm_json_response: dict[str, Any],+ ):+ """``force_restart=True`` uses TERMINATE_EXISTING — that's a fresh LLM+ run regardless of what was running before. The cap and consume must both+ fire on this path."""+ cap_mocks.workflow_is_running.return_value = True+ handle = self._make_handle([(WorkflowExecutionStatus.COMPLETED, None)])+ completed_summary = MagicMock()+ completed_summary.id = "id"+ completed_summary.summary = mock_enriched_llm_json_response++ with (+ patch.object(+ SingleSessionSummary.objects,+ "get_summary",+ MagicMock(side_effect=[None, completed_summary]),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._prepare_execution",+ return_value=(None, None, None, MagicMock(), "workflow-id"),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._start_video_summary_workflow",+ AsyncMock(return_value=handle),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.async_connect",+ AsyncMock(return_value=MagicMock()),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.asyncio.sleep",+ AsyncMock(),+ ),+ ):+ await self._collect(+ execute_summarize_session_video_stream(+ session_id=mock_session_id,+ user=mock_user,+ team=mock_team,+ force_restart=True,+ )+ )++ cap_mocks.atomic.assert_called_once_with(mock_team.id)+ cap_mocks.refund.assert_not_called()++ @pytest.mark.asyncio+ async def test_quota_blocked_emits_error_and_skips_workflow_start(+ self,+ cap_mocks: SimpleNamespace,+ mock_session_id: str,+ mock_user: MagicMock,+ mock_team: MagicMock,+ ):+ """When `atomic_check_and_consume` returns `allowed=False`, the generator+ yields a session-summary-error event and never starts a workflow.+ The atomic op already rolled the counter back, so no refund needed."""+ cap_mocks.atomic.return_value = MagicMock(allowed=False, used=4000, cap=4000)+ start_mock = AsyncMock()+ with (+ patch.object(SingleSessionSummary.objects, "get_summary", MagicMock(return_value=None)),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._prepare_execution",+ return_value=(None, None, None, MagicMock(), "workflow-id"),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._start_video_summary_workflow",+ start_mock,+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.async_connect",+ AsyncMock(return_value=MagicMock()),+ ),+ patch("posthog.temporal.session_replay.session_summary.workflow.posthoganalytics.capture") as mock_capture,+ ):+ events = await self._collect(+ execute_summarize_session_video_stream(+ session_id=mock_session_id,+ user=mock_user,+ team=mock_team,+ )+ )++ assert len(events) == 1+ assert events[0].startswith("event: session-summary-error\n")+ assert "4000/4000" in events[0]+ start_mock.assert_not_called()+ cap_mocks.refund.assert_not_called()+ mock_capture.assert_called_once()+ assert mock_capture.call_args.kwargs["event"] == "replay summary quota blocked"+ assert mock_capture.call_args.kwargs["properties"]["used"] == 4000+ assert mock_capture.call_args.kwargs["properties"]["cap"] == 4000++ @pytest.mark.asyncio+ async def test_cached_summary_fast_path_bypasses_cap_entirely(+ self,+ cap_mocks: SimpleNamespace,+ mock_session_id: str,+ mock_user: MagicMock,+ mock_team: MagicMock,+ mock_enriched_llm_json_response: dict[str, Any],+ ):+ """A cached SingleSessionSummary returns immediately — the cap MUST NOT+ be consulted at all on this path, even when the team is over the cap.+ This is the exact regression the gate-relocation fix targets."""+ cached_summary = MagicMock()+ cached_summary.id = "cached-id"+ cached_summary.summary = mock_enriched_llm_json_response+ with (+ patch.object(SingleSessionSummary.objects, "get_summary", return_value=cached_summary),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._start_video_summary_workflow"+ ) as mock_start,+ ):+ await self._collect(+ execute_summarize_session_video_stream(+ session_id=mock_session_id,+ user=mock_user,+ team=mock_team,+ )+ )++ cap_mocks.atomic.assert_not_called()+ cap_mocks.refund.assert_not_called()+ mock_start.assert_not_called()+++class TestVideoStreamCapEndToEnd:+ """Load-style cap regression: drive the video-stream entrypoint past the+ cap with the LLM commit point (`_start_video_summary_workflow`) stubbed+ out, so the only "real" thing under test is the cap module against the+ real Redis counter.++ Verifies, in one test:+ - Requests 1..cap pass through and bump the counter.+ - Requests cap+1..N yield `session-summary-error` and never call+ `_start_video_summary_workflow`.+ - The Redis counter ends at exactly cap (no overshoot in the sequential+ case — concurrency is covered by `test_atomic_check_and_consume_is_overshoot_free`).+ - One `replay summary quota blocked` analytics event per blocked request.++ Cap is overridden to a small value via `get_cap_for_team` so the test+ runs in <1s — the production default of 4000 would just multiply the+ iteration count, not exercise any new behavior.+ """++ @pytest.fixture(autouse=True)+ def _isolate_redis_key(self, mock_team: MagicMock) -> Iterator[None]:+ from datetime import UTC, datetime++ from posthog.redis import get_client+ from posthog.session_recordings.ai_summary_cap import _redis_key++ key = _redis_key(mock_team.id, now=datetime.now(UTC))+ client = get_client()+ client.delete(key)+ try:+ yield+ finally:+ client.delete(key)++ @pytest.mark.asyncio+ async def test_cap_blocks_after_quota_exhausted_under_load(+ self,+ mock_user: MagicMock,+ mock_team: MagicMock,+ mock_enriched_llm_json_response: dict[str, Any],+ ):+ from posthog.session_recordings.ai_summary_cap import current_usage++ cap = 5+ n_iterations = cap + 3 # 5 allowed, 3 blocked++ completed_summary = MagicMock()+ completed_summary.id = "completed-id"+ completed_summary.summary = mock_enriched_llm_json_response++ # Each iteration uses a unique session_id so we can use a per-session+ # call counter instead of a global rotating side_effect — keeps the+ # mapping trivial regardless of which iterations get blocked.+ get_summary_calls: dict[str, int] = {}++ def get_summary_fn(*args: Any, **kwargs: Any) -> Any:+ sid = kwargs["session_id"]+ n = get_summary_calls.get(sid, 0)+ get_summary_calls[sid] = n + 1+ # First call per session is the cache check (miss). Any later call+ # is the post-COMPLETED read of the freshly written row.+ return None if n == 0 else completed_summary++ # Temporal handle that resolves to COMPLETED on the first describe so+ # the polling loop exits without calling handle.query.+ def _make_handle() -> MagicMock:+ handle = MagicMock()+ handle.describe = AsyncMock(return_value=MagicMock(status=WorkflowExecutionStatus.COMPLETED))+ handle.query = AsyncMock(return_value={})+ handle.result = AsyncMock(return_value=None)+ return handle++ start_mock = AsyncMock(side_effect=lambda *a, **kw: _make_handle())++ with (+ # Cap value comes from the production code path, but we override+ # the Postgres lookup so we don't need a real SignalSourceConfig.+ patch(+ "posthog.session_recordings.ai_summary_cap.get_cap_for_team",+ return_value=cap,+ ),+ patch.object(+ SingleSessionSummary.objects,+ "get_summary",+ side_effect=get_summary_fn,+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._workflow_is_running",+ AsyncMock(return_value=False),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._prepare_execution",+ return_value=(None, None, None, MagicMock(), "workflow-id"),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._start_video_summary_workflow",+ start_mock,+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.async_connect",+ AsyncMock(return_value=MagicMock()),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.asyncio.sleep",+ AsyncMock(),+ ),+ patch("posthog.temporal.session_replay.session_summary.workflow.posthoganalytics.capture") as mock_capture,+ ):+ allowed_count = 0+ blocked_count = 0+ for i in range(n_iterations):+ session_id = f"00000000-0000-0000-0001-{i:012d}"+ events: list[str] = []+ async for event in execute_summarize_session_video_stream(+ session_id=session_id,+ user=mock_user,+ team=mock_team,+ ):+ events.append(event)++ assert events, f"iteration {i}: generator yielded zero events"+ last = events[-1]+ if last.startswith("event: session-summary-error\n"):+ blocked_count += 1+ assert f"{cap}/{cap}" in last, f"iteration {i}: missing used/cap in {last!r}"+ else:+ allowed_count += 1+ assert any(e.startswith("event: session-summary-stream\n") for e in events), (+ f"iteration {i}: no success event in {events!r}"+ )++ assert allowed_count == cap, f"expected {cap} allowed, got {allowed_count}"+ assert blocked_count == n_iterations - cap, f"expected {n_iterations - cap} blocked, got {blocked_count}"++ # The LLM commit point fired exactly `cap` times — never on a blocked iteration.+ assert start_mock.call_count == cap, (+ f"_start_video_summary_workflow called {start_mock.call_count} times; expected {cap}"+ )++ # Real Redis counter advanced exactly to the cap (sequential — no overshoot expected).+ assert current_usage(mock_team.id) == cap++ # Each blocked iteration emitted exactly one quota-blocked analytics event.+ blocked_capture_calls = [+ c for c in mock_capture.call_args_list if c.kwargs.get("event") == "replay summary quota blocked"+ ]+ assert len(blocked_capture_calls) == n_iterations - cap+++class TestWorkflowIsRunning:+ """`_workflow_is_running` is the discriminator between a fresh LLM run (cap+ applies) and a silent attach (cap must not). Behavior pinned with explicit+ tests so a future refactor can't quietly flip it."""++ @pytest.mark.asyncio+ async def test_returns_true_when_status_is_running(self) -> None:+ from posthog.temporal.session_replay.session_summary.workflow import _workflow_is_running++ client = MagicMock()+ handle = MagicMock()+ handle.describe = AsyncMock(return_value=MagicMock(status=WorkflowExecutionStatus.RUNNING))+ client.get_workflow_handle = MagicMock(return_value=handle)++ assert await _workflow_is_running(client, "wfid") is True++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "terminal_status",+ [+ WorkflowExecutionStatus.COMPLETED,+ WorkflowExecutionStatus.FAILED,+ WorkflowExecutionStatus.CANCELED,+ WorkflowExecutionStatus.TERMINATED,+ WorkflowExecutionStatus.TIMED_OUT,+ ],+ )+ async def test_returns_false_for_terminal_statuses(+ self,+ terminal_status: WorkflowExecutionStatus,+ ) -> None:+ from posthog.temporal.session_replay.session_summary.workflow import _workflow_is_running++ client = MagicMock()+ handle = MagicMock()+ handle.describe = AsyncMock(return_value=MagicMock(status=terminal_status))+ client.get_workflow_handle = MagicMock(return_value=handle)++ assert await _workflow_is_running(client, "wfid") is False++ @pytest.mark.asyncio+ async def test_returns_false_when_workflow_not_found(self) -> None:+ from temporalio.service import RPCError, RPCStatusCode++ from posthog.temporal.session_replay.session_summary.workflow import _workflow_is_running++ client = MagicMock()+ handle = MagicMock()+ handle.describe = AsyncMock(side_effect=RPCError("not found", RPCStatusCode.NOT_FOUND, b""))+ client.get_workflow_handle = MagicMock(return_value=handle)++ assert await _workflow_is_running(client, "wfid") is False++ @pytest.mark.asyncio+ async def test_reraises_non_not_found_rpc_errors(self) -> None:+ # An UNAVAILABLE Temporal frontend should surface, not silently bypass+ # the cap by claiming "not running".+ from temporalio.service import RPCError, RPCStatusCode++ from posthog.temporal.session_replay.session_summary.workflow import _workflow_is_running++ client = MagicMock()+ handle = MagicMock()+ handle.describe = AsyncMock(side_effect=RPCError("unavailable", RPCStatusCode.UNAVAILABLE, b""))+ client.get_workflow_handle = MagicMock(return_value=handle)++ with pytest.raises(RPCError):+ await _workflow_is_running(client, "wfid")+class TestStartVideoSummaryWorkflow:@pytest.mark.asynciodiff --git a/posthog/temporal/tests/session_replay/summarization_sweep/test_workflow.py b/posthog/temporal/tests/session_replay/summarization_sweep/test_workflow.pyindex af274595d56f..e142d69acdbe 100644--- a/posthog/temporal/tests/session_replay/summarization_sweep/test_workflow.py+++ b/posthog/temporal/tests/session_replay/summarization_sweep/test_workflow.py@@ -9,6 +9,7 @@ from temporalio.worker import Workerfrom posthog.temporal.session_replay.summarization_sweep.constants import WORKFLOW_NAMEfrom posthog.temporal.session_replay.summarization_sweep.types import (+ ConsumeSummaryQuotaInput,FindSessionsInput,FindSessionsResult,SummarizeTeamSessionsInputs,@@ -43,3 +44,101 @@ async def test_workflow_noop_when_no_sessions():"workflows_started": 0,"workflows_skipped_already_running": 0,}+++async def _fake_start_child(+ self: SummarizeTeamSessionsWorkflow,+ team_id: int,+ session_id: str,+ user_id: int,+ user_distinct_id: str | None,+) -> bool:+ """Replacement for `_start_child` in tests so we don't have to register a+ real child workflow + worker. With ABANDON parent-close + time skipping,+ pending children keep the test env alive until their execution_timeout+ (~45 minutes), which deadlocks the test."""+ return True+++async def test_workflow_consumes_quota_after_dispatching_children(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(SummarizeTeamSessionsWorkflow, "_start_child", _fake_start_child)++ @activity.defn(name="find_sessions_for_team_activity")+ async def find_sessions_mocked(inputs: FindSessionsInput) -> FindSessionsResult:+ return FindSessionsResult(+ team_id=inputs.team_id,+ session_ids=["s1"],+ user_id=7,+ user_distinct_id="distinct",+ )++ consume_calls: list[ConsumeSummaryQuotaInput] = []++ @activity.defn(name="consume_summary_quota_activity")+ async def consume_mocked(inputs: ConsumeSummaryQuotaInput) -> None:+ consume_calls.append(inputs)++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[SummarizeTeamSessionsWorkflow],+ activities=[find_sessions_mocked, consume_mocked],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ WORKFLOW_NAME,+ SummarizeTeamSessionsInputs(team_id=42),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert result["workflows_started"] == 1+ assert len(consume_calls) == 1+ assert consume_calls[0].team_id == 42+ assert consume_calls[0].n == 1+++async def test_workflow_does_not_fail_when_consume_quota_activity_fails(monkeypatch: pytest.MonkeyPatch):+ """A transient Redis blip in the bookkeeping activity must not roll up as+ a workflow failure — the children were dispatched successfully, and the+ next sweep tick refills the increment naturally."""+ monkeypatch.setattr(SummarizeTeamSessionsWorkflow, "_start_child", _fake_start_child)++ @activity.defn(name="find_sessions_for_team_activity")+ async def find_sessions_mocked(inputs: FindSessionsInput) -> FindSessionsResult:+ return FindSessionsResult(+ team_id=inputs.team_id,+ session_ids=["s1"],+ user_id=7,+ user_distinct_id="distinct",+ )++ @activity.defn(name="consume_summary_quota_activity")+ async def consume_failing(inputs: ConsumeSummaryQuotaInput) -> None:+ raise RuntimeError("redis is on fire")++ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[SummarizeTeamSessionsWorkflow],+ activities=[find_sessions_mocked, consume_failing],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ WORKFLOW_NAME,+ SummarizeTeamSessionsInputs(team_id=42),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert result == {+ "team_id": 42,+ "workflows_started": 1,+ "workflows_skipped_already_running": 0,+ }