: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-vision): add ScannerCandidateQuery for Phase 2 sweep (#60617)
Tue Haulund6481db2f7747
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex f1b988126fa5..f6d75ea0dfc6 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -54,6 +54,7 @@ class Product(StrEnum):PLATFORM_AND_SUPPORT = "platform_and_support"PRODUCT_ANALYTICS = "product_analytics"REPLAY = "replay"+ REPLAY_VISION = "replay_vision"REVENUE_ANALYTICS = "revenue_analytics"SDK_DOCTOR = "sdk_doctor"SESSION_SUMMARY = "session_summary"diff --git a/products/replay_vision/backend/queries/__init__.py b/products/replay_vision/backend/queries/__init__.pyindex 5534d114563f..80259a9acaca 100644--- a/products/replay_vision/backend/queries/__init__.py+++ b/products/replay_vision/backend/queries/__init__.py@@ -1,6 +1,23 @@+from products.replay_vision.backend.queries.scanner_candidate_query import (+ DEFAULT_CANDIDATE_LIMIT,+ DEFAULT_MAX_EXECUTION_SECONDS,+ SAMPLE_RATE_PRECISION,+ SETTLE_INTERVAL,+ CandidateSession,+ ScannerCandidateQuery,+)from products.replay_vision.backend.queries.scanner_volume_estimate import (ScannerVolumeEstimate,estimate_scanner_session_volume,)-__all__ = ["ScannerVolumeEstimate", "estimate_scanner_session_volume"]+__all__ = [+ "DEFAULT_CANDIDATE_LIMIT",+ "DEFAULT_MAX_EXECUTION_SECONDS",+ "SAMPLE_RATE_PRECISION",+ "SETTLE_INTERVAL",+ "CandidateSession",+ "ScannerCandidateQuery",+ "ScannerVolumeEstimate",+ "estimate_scanner_session_volume",+]diff --git a/products/replay_vision/backend/queries/scanner_candidate_query.py b/products/replay_vision/backend/queries/scanner_candidate_query.pynew file mode 100644index 000000000000..e4e9555a54f0--- /dev/null+++ b/products/replay_vision/backend/queries/scanner_candidate_query.py@@ -0,0 +1,159 @@+"""Find session recordings a scanner should observe: ended past the watermark and quiet for 35+ minutes."""++import datetime as dt+from dataclasses import dataclass+from typing import cast++import structlog+from opentelemetry import trace++from posthog.schema import RecordingsQuery++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.models import Team+from posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery++logger = structlog.get_logger(__name__)+tracer = trace.get_tracer(__name__)++# 30-min inactivity timeout + 5-min merge-lag buffer.+SETTLE_INTERVAL = dt.timedelta(minutes=35)++# Partition prune anchored to the SDK's 24h session_id rotation + 2h headroom for skew and lag.+_PARTITION_LOOKBACK = dt.timedelta(hours=26)++SAMPLE_RATE_PRECISION = 10_000+DEFAULT_CANDIDATE_LIMIT = 5_000+DEFAULT_MAX_EXECUTION_SECONDS = 180++# Excludes attacker-supplied over-length session_ids that would later wedge wire-payload validation.+_MAX_SESSION_ID_LENGTH = 128+++@dataclass(frozen=True)+class CandidateSession:+ session_id: str+ session_end: dt.datetime+++class ScannerCandidateQuery:+ def __init__(+ self,+ *,+ team: Team,+ query: RecordingsQuery,+ last_swept_at: dt.datetime,+ sampling_rate: float,+ last_seen_session_id: str | None = None,+ candidate_limit: int = DEFAULT_CANDIDATE_LIMIT,+ max_execution_time_seconds: int = DEFAULT_MAX_EXECUTION_SECONDS,+ ) -> None:+ if not isinstance(last_swept_at, dt.datetime):+ raise TypeError(f"last_swept_at must be a datetime, got {type(last_swept_at).__name__}")+ if last_swept_at.tzinfo is None:+ raise ValueError("last_swept_at must be timezone-aware")+ if candidate_limit <= 0:+ raise ValueError(f"candidate_limit must be positive, got {candidate_limit}")+ if max_execution_time_seconds <= 0:+ raise ValueError(f"max_execution_time_seconds must be positive, got {max_execution_time_seconds}")++ self._team = team+ self._last_swept_at = last_swept_at+ self._last_seen_session_id = last_seen_session_id+ self._sampling_rate = max(0.0, min(1.0, sampling_rate))+ self._candidate_limit = candidate_limit+ self._max_execution_time_seconds = max_execution_time_seconds++ # The schedule owns the time window, not the user.+ inner_query = query.model_copy(deep=True)+ inner_query.date_from = (last_swept_at - _PARTITION_LOOKBACK).isoformat()+ inner_query.date_to = None+ inner_query.limit = None+ inner_query.offset = None+ inner_query.after = None++ # Sampling in the inner HAVING drops un-sampled sessions before outer aggregation.+ extra_having: list[ast.Expr] = []+ if (sampling := self._sampling_predicate()) is not None:+ extra_having.append(sampling)++ self._inner = SessionRecordingListFromQuery(team=team, query=inner_query, extra_having_predicates=extra_having)++ @tracer.start_as_current_span("ScannerCandidateQuery.run")+ def run(self) -> list[CandidateSession]:+ with tags_context(product=Product.REPLAY_VISION, feature=Feature.ENRICHMENT):+ response = execute_hogql_query(+ query=self.get_query(),+ team=self._team,+ query_type="ReplayVisionScannerCandidateQuery",+ settings=HogQLGlobalSettings(max_execution_time=self._max_execution_time_seconds),+ )+ return [CandidateSession(session_id=row[0], session_end=row[1]) for row in (response.results or [])]++ def get_query(self) -> ast.SelectQuery:+ # `_inner.get_query()` re-parses every call, so in-place mutation is safe.+ inner = self._inner.get_query()+ inner.order_by = None++ where_exprs: list[ast.Expr] = [+ self._watermark_predicate(),+ ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq,+ left=ast.Field(chain=["sessions", "end_time"]),+ right=ast.Constant(value=dt.datetime.now(dt.UTC) - SETTLE_INTERVAL),+ ),+ ast.CompareOperation(+ op=ast.CompareOperationOp.LtEq,+ left=ast.Call(name="length", args=[ast.Field(chain=["sessions", "session_id"])]),+ right=ast.Constant(value=_MAX_SESSION_ID_LENGTH),+ ),+ ]++ return ast.SelectQuery(+ select=[+ ast.Field(chain=["sessions", "session_id"]),+ ast.Alias(alias="session_end", expr=ast.Field(chain=["sessions", "end_time"])),+ ],+ select_from=ast.JoinExpr(table=cast(ast.SelectQuery, inner), alias="sessions"),+ where=ast.And(exprs=where_exprs),+ order_by=[+ ast.OrderExpr(expr=ast.Field(chain=["session_end"]), order="ASC"),+ ast.OrderExpr(expr=ast.Field(chain=["sessions", "session_id"]), order="ASC"),+ ],+ limit=ast.Constant(value=self._candidate_limit),+ )++ def _watermark_predicate(self) -> ast.Expr:+ end_time = ast.Field(chain=["sessions", "end_time"])+ watermark = ast.Constant(value=self._last_swept_at)+ strict = ast.CompareOperation(op=ast.CompareOperationOp.Gt, left=end_time, right=watermark)+ if self._last_seen_session_id is None:+ return strict+ # Lexicographic tuple comparison gives keyset semantics for resuming past saturated batches.+ return ast.CompareOperation(+ op=ast.CompareOperationOp.Gt,+ left=ast.Tuple(exprs=[end_time, ast.Field(chain=["sessions", "session_id"])]),+ right=ast.Tuple(exprs=[watermark, ast.Constant(value=self._last_seen_session_id)]),+ )++ def _sampling_predicate(self) -> ast.Expr | None:+ if self._sampling_rate >= 1.0:+ return None+ threshold = max(0, int(self._sampling_rate * SAMPLE_RATE_PRECISION))+ if threshold <= 0:+ return ast.Constant(value=False)+ return ast.CompareOperation(+ op=ast.CompareOperationOp.Lt,+ left=ast.Call(+ name="modulo",+ args=[+ ast.Call(name="cityHash64", args=[ast.Field(chain=["s", "session_id"])]),+ ast.Constant(value=SAMPLE_RATE_PRECISION),+ ],+ ),+ right=ast.Constant(value=threshold),+ )diff --git a/products/replay_vision/backend/tests/test_scanner_candidate_query.py b/products/replay_vision/backend/tests/test_scanner_candidate_query.pynew file mode 100644index 000000000000..7f0952da6384--- /dev/null+++ b/products/replay_vision/backend/tests/test_scanner_candidate_query.py@@ -0,0 +1,532 @@+import datetime as dt++import pytest+from freezegun import freeze_time+from posthog.test.base import ClickhouseTestMixin++from posthog.schema import EventPropertyFilter, PropertyOperator, RecordingPropertyFilter, RecordingsQuery++from posthog.hogql import ast++from posthog.clickhouse.client import sync_execute+from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary+from posthog.session_recordings.sql.session_replay_event_sql import TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL++from products.replay_vision.backend.queries.scanner_candidate_query import (+ DEFAULT_CANDIDATE_LIMIT,+ SAMPLE_RATE_PRECISION,+ SETTLE_INTERVAL,+ ScannerCandidateQuery,+)++_NOW = dt.datetime(2026, 5, 1, 12, 0, 0, tzinfo=dt.UTC)+_FROZEN_TIME = _NOW.strftime("%Y-%m-%dT%H:%M:%SZ")+++# Construction-time sanitization (no DB needed).+++def _make_query(**kwargs) -> ScannerCandidateQuery:+ return ScannerCandidateQuery(+ team=kwargs.pop("team", None),+ query=kwargs.pop("query", RecordingsQuery()),+ last_swept_at=kwargs.pop("last_swept_at", _NOW - dt.timedelta(hours=1)),+ sampling_rate=kwargs.pop("sampling_rate", 1.0),+ **kwargs,+ )+++ "bad_last_swept_at",+ [+ "2026-01-01T00:00:00Z",+ 12345,+ None,+ ],+)+def test_rejects_non_datetime_last_swept_at(bad_last_swept_at):+ with pytest.raises(TypeError):+ _make_query(last_swept_at=bad_last_swept_at)+++def test_rejects_naive_last_swept_at():+ with pytest.raises(ValueError, match="timezone-aware"):+ _make_query(last_swept_at=dt.datetime(2026, 1, 1, 0, 0, 0))+++def test_rejects_non_positive_candidate_limit():+ with pytest.raises(ValueError, match="candidate_limit must be positive"):+ _make_query(candidate_limit=0)+ with pytest.raises(ValueError, match="candidate_limit must be positive"):+ _make_query(candidate_limit=-5)+++def test_rejects_non_positive_max_execution_time_seconds():+ with pytest.raises(ValueError, match="max_execution_time_seconds must be positive"):+ _make_query(max_execution_time_seconds=0)+ with pytest.raises(ValueError, match="max_execution_time_seconds must be positive"):+ _make_query(max_execution_time_seconds=-1)+++ "raw,expected_internal",+ [+ (1.0, 1.0),+ (0.0, 0.0),+ (0.25, 0.25),+ (2.0, 1.0),+ (-0.1, 0.0),+ ],+)+def test_sampling_rate_clamped_on_construction(raw, expected_internal):+ q = _make_query(sampling_rate=raw)+ assert q._sampling_rate == expected_internal+++ "stripped_field, value", [("date_to", "-1d"), ("limit", 17), ("offset", 42), ("after", "abc123")]+)+def test_strips_schedule_controlled_inputs(stripped_field, value):+ raw_query = RecordingsQuery(**{stripped_field: value})+ q = _make_query(query=raw_query)+ assert getattr(q._inner._query, stripped_field) is None+++def test_inner_date_from_is_partition_prune_relative_to_watermark():+ last_swept_at = _NOW - dt.timedelta(hours=2)+ q = _make_query(query=RecordingsQuery(date_from="-30d"), last_swept_at=last_swept_at)+ assert q._inner._query.date_from is not None+ assert q._inner._query.date_from != "-30d"+++# Sampling predicate (no DB).+++def test_sampling_predicate_passthrough_at_full_rate():+ q = _make_query(sampling_rate=1.0)+ assert q._sampling_predicate() is None+++def test_sampling_predicate_emits_false_at_zero():+ q = _make_query(sampling_rate=0.0)+ expr = q._sampling_predicate()+ assert isinstance(expr, ast.Constant) and expr.value is False+++def test_sampling_predicate_emits_modulo_compare_at_partial_rate():+ q = _make_query(sampling_rate=0.25)+ expr = q._sampling_predicate()+ assert isinstance(expr, ast.CompareOperation)+ assert expr.op == ast.CompareOperationOp.Lt+ assert isinstance(expr.right, ast.Constant)+ assert expr.right.value == int(0.25 * SAMPLE_RATE_PRECISION)+ modulo = expr.left+ assert isinstance(modulo, ast.Call) and modulo.name == "modulo"+ city = modulo.args[0]+ assert isinstance(city, ast.Call) and city.name == "cityHash64"+++# Integration: actual ClickHouse query.+++@freeze_time(_FROZEN_TIME)+class TestScannerCandidateQueryAgainstClickHouse(ClickhouseTestMixin):+ def setup_method(self, _method) -> None:+ sync_execute(TRUNCATE_SESSION_REPLAY_EVENTS_TABLE_SQL())++ @staticmethod+ def _produce(team_id: int, session_id: str, first: dt.datetime, last: dt.datetime, **kwargs) -> None:+ produce_replay_summary(+ team_id=team_id,+ session_id=session_id,+ first_timestamp=first.isoformat(),+ last_timestamp=last.isoformat(),+ **kwargs,+ )++ @pytest.mark.django_db+ def test_returns_sessions_in_chronological_order_with_session_end(self, team) -> None:+ settle_bound = _NOW - SETTLE_INTERVAL+ self._produce(+ team.id, "sess-a", settle_bound - dt.timedelta(minutes=20), settle_bound - dt.timedelta(minutes=10)+ )+ self._produce(+ team.id, "sess-b", settle_bound - dt.timedelta(minutes=40), settle_bound - dt.timedelta(minutes=30)+ )+ self._produce(+ team.id, "sess-c", settle_bound - dt.timedelta(minutes=10), settle_bound - dt.timedelta(minutes=5)+ )++ results = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=2))++ assert [r.session_id for r in results] == ["sess-b", "sess-a", "sess-c"]+ assert results[0].session_end == settle_bound - dt.timedelta(minutes=30)+ assert results[2].session_end == settle_bound - dt.timedelta(minutes=5)++ @pytest.mark.django_db+ def test_watermark_excludes_sessions_ended_before_or_equal(self, team) -> None:+ last_swept_at = _NOW - dt.timedelta(hours=2)+ self._produce(team.id, "exactly-on-watermark", last_swept_at - dt.timedelta(minutes=10), last_swept_at)+ self._produce(+ team.id,+ "just-after-watermark",+ last_swept_at,+ last_swept_at + dt.timedelta(seconds=1),+ )++ results = self._run(team=team, last_swept_at=last_swept_at)++ assert [r.session_id for r in results] == ["just-after-watermark"]++ @pytest.mark.django_db+ def test_settle_window_excludes_sessions_still_settling(self, team) -> None:+ settle_bound = _NOW - SETTLE_INTERVAL+ self._produce(+ team.id, "settled", settle_bound - dt.timedelta(minutes=10), settle_bound - dt.timedelta(seconds=1)+ )+ self._produce(team.id, "on-settle", settle_bound - dt.timedelta(minutes=5), settle_bound)+ self._produce(+ team.id, "still-settling", settle_bound - dt.timedelta(minutes=5), settle_bound + dt.timedelta(seconds=1)+ )++ results = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=2))++ session_ids = {r.session_id for r in results}+ assert "settled" in session_ids+ assert "on-settle" in session_ids++ assert "still-settling" not in session_ids++ @pytest.mark.django_db+ def test_aggregates_multiple_rows_per_session(self, team) -> None:+ first = _NOW - dt.timedelta(hours=2)+ for i, last in enumerate(+ [+ _NOW - dt.timedelta(minutes=90),+ _NOW - dt.timedelta(minutes=60),+ _NOW - dt.timedelta(minutes=45),+ ]+ ):+ self._produce(+ team.id,+ "multi-row",+ first + dt.timedelta(seconds=i),+ last,+ )++ results = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=4))++ assert len(results) == 1+ assert results[0].session_id == "multi-row"+ assert results[0].session_end == _NOW - dt.timedelta(minutes=45)++ @pytest.mark.django_db+ def test_zero_sampling_returns_empty(self, team) -> None:+ self._produce(team.id, "would-match", _NOW - dt.timedelta(hours=2), _NOW - dt.timedelta(minutes=40))+ results = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=2), sampling_rate=0.0)+ assert results == []++ @pytest.mark.django_db+ def test_full_sampling_returns_all_candidates(self, team) -> None:+ for i in range(5):+ self._produce(+ team.id,+ f"sess-{i:02d}",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40 + i),+ )+ results = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=2), sampling_rate=1.0)+ assert len(results) == 5++ @pytest.mark.django_db+ def test_partial_sampling_is_deterministic_per_session(self, team) -> None:+ for i in range(40):+ self._produce(+ team.id,+ f"stable-{i:04x}",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40 + i // 5),+ )+ first = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=4), sampling_rate=0.5)+ second = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=4), sampling_rate=0.5)+ assert [r.session_id for r in first] == [r.session_id for r in second]+ assert 0 < len(first) < 40++ @pytest.mark.django_db+ def test_excludes_deleted_recordings(self, team) -> None:+ self._produce(team.id, "kept", _NOW - dt.timedelta(hours=2), _NOW - dt.timedelta(minutes=40))+ self._produce(+ team.id,+ "deleted",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40),+ is_deleted=True,+ )+ results = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=2))+ assert [r.session_id for r in results] == ["kept"]++ @pytest.mark.django_db+ def test_respects_candidate_limit(self, team) -> None:+ for i in range(10):+ self._produce(+ team.id,+ f"limit-{i:02d}",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40 + (10 - i)), # limit-00 ends first, limit-09 last+ )+ results = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=2), candidate_limit=3)+ assert [r.session_id for r in results] == ["limit-00", "limit-01", "limit-02"]++ @pytest.mark.django_db+ def test_filters_by_distinct_id(self, team) -> None:+ self._produce(+ team.id,+ "matched",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40),+ distinct_id="alice",+ )+ self._produce(+ team.id,+ "unmatched",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40),+ distinct_id="bob",+ )+ query = RecordingsQuery(distinct_ids=["alice"])+ results = self._run(team=team, query=query, last_swept_at=_NOW - dt.timedelta(hours=2))+ assert [r.session_id for r in results] == ["matched"]++ @pytest.mark.django_db+ def test_routes_dollar_lib_event_property_to_having(self, team) -> None:+ self._produce(+ team.id,+ "web",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40),+ snapshot_library="web",+ )+ self._produce(+ team.id,+ "mobile",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40),+ snapshot_library="posthog-ios",+ )+ query = RecordingsQuery(+ properties=[EventPropertyFilter(key="$lib", operator=PropertyOperator.EXACT, value="web")]+ )+ results = self._run(team=team, query=query, last_swept_at=_NOW - dt.timedelta(hours=2))+ assert [r.session_id for r in results] == ["web"]++ @pytest.mark.django_db+ def test_honors_having_predicate_from_recordings_query(self, team) -> None:+ self._produce(+ team.id,+ "long",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40),+ active_milliseconds=120_000,+ )+ self._produce(+ team.id,+ "short",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40),+ active_milliseconds=5_000,+ )+ query = RecordingsQuery(+ having_predicates=[+ RecordingPropertyFilter(type="recording", key="active_seconds", operator=PropertyOperator.GTE, value=30)+ ]+ )+ results = self._run(team=team, query=query, last_swept_at=_NOW - dt.timedelta(hours=2))+ assert [r.session_id for r in results] == ["long"]++ @pytest.mark.django_db+ def test_filter_test_accounts_excludes_internal_users(self, team) -> None:+ # test_account_filters are exclusion-style — the operator picks the accounts to drop.+ team.test_account_filters = [+ {+ "key": "email",+ "operator": "not_icontains",+ "value": "@posthog.com",+ "type": "person",+ }+ ]+ team.save(update_fields=["test_account_filters"])+ from posthog.models.person import Person++ Person.objects.create(team=team, distinct_ids=["internal"], properties={"email": "[email protected]"})+ Person.objects.create(team=team, distinct_ids=["external"], properties={"email": "[email protected]"})++ self._produce(+ team.id,+ "internal-session",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40),+ distinct_id="internal",+ )+ self._produce(+ team.id,+ "external-session",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40),+ distinct_id="external",+ )++ query = RecordingsQuery(filter_test_accounts=True)+ results = self._run(team=team, query=query, last_swept_at=_NOW - dt.timedelta(hours=2))+ assert [r.session_id for r in results] == ["external-session"]++ @pytest.mark.django_db+ def test_long_running_session_within_24h_cap_is_returned(self, team) -> None:+ last_swept_at = _NOW - dt.timedelta(hours=1)+ self._produce(+ team.id,+ "long-running",+ _NOW - dt.timedelta(hours=10),+ last_swept_at + dt.timedelta(minutes=1),+ )++ results = self._run(team=team, last_swept_at=last_swept_at)++ assert [r.session_id for r in results] == ["long-running"]++ @pytest.mark.django_db+ def test_straddling_session_keeps_full_aggregates(self, team) -> None:+ last_swept_at = _NOW - dt.timedelta(hours=1)+ # Three rows totalling 36 active seconds — passes the 30s HAVING bound only if all rows are aggregated.+ for last_offset_minutes, ms in (+ (75, 12_000),+ (45, 12_000),+ (40, 12_000),+ ):+ self._produce(+ team.id,+ "straddler",+ _NOW - dt.timedelta(minutes=80),+ _NOW - dt.timedelta(minutes=last_offset_minutes),+ active_milliseconds=ms,+ )+ # Control: only 18s of activity — should fail HAVING.+ self._produce(+ team.id,+ "post-watermark-short",+ _NOW - dt.timedelta(minutes=50),+ _NOW - dt.timedelta(minutes=40),+ active_milliseconds=18_000,+ )++ query = RecordingsQuery(+ having_predicates=[+ RecordingPropertyFilter(type="recording", key="active_seconds", operator=PropertyOperator.GTE, value=30)+ ]+ )+ results = self._run(team=team, query=query, last_swept_at=last_swept_at)++ assert [r.session_id for r in results] == ["straddler"]++ @pytest.mark.django_db+ def test_session_still_settling_is_not_emitted(self, team) -> None:+ settle_bound = _NOW - SETTLE_INTERVAL+ # Two rows: one outside settle, one inside — session is still live.+ self._produce(+ team.id,+ "still-live",+ settle_bound - dt.timedelta(hours=2),+ settle_bound - dt.timedelta(minutes=30),+ )+ self._produce(+ team.id,+ "still-live",+ settle_bound - dt.timedelta(hours=2),+ settle_bound + dt.timedelta(minutes=1),+ )++ results = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=4))++ assert results == []++ @pytest.mark.django_db+ def test_excludes_overlong_session_ids(self, team) -> None:+ # Attacker-supplied session_ids over the 128-char cap would otherwise wedge wire-payload validation.+ self._produce(team.id, "x" * 129, _NOW - dt.timedelta(hours=2), _NOW - dt.timedelta(minutes=40))+ self._produce(team.id, "ok", _NOW - dt.timedelta(hours=2), _NOW - dt.timedelta(minutes=40))++ results = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=2))++ assert [r.session_id for r in results] == ["ok"]++ @pytest.mark.django_db+ def test_excludes_recordings_past_retention(self, team) -> None:+ self._produce(+ team.id,+ "expired",+ _NOW - dt.timedelta(days=120),+ _NOW - dt.timedelta(days=120) + dt.timedelta(minutes=5),+ retention_period_days=0,+ )+ self._produce(+ team.id,+ "fresh",+ _NOW - dt.timedelta(hours=2),+ _NOW - dt.timedelta(minutes=40),+ retention_period_days=30,+ )++ results = self._run(team=team, last_swept_at=_NOW - dt.timedelta(days=365))++ assert [r.session_id for r in results] == ["fresh"]++ @pytest.mark.django_db+ def test_keyset_resume_includes_ties_after_last_seen(self, team) -> None:+ boundary = _NOW - dt.timedelta(hours=1)+ for sid in ("aaa", "bbb", "ccc"):+ self._produce(team.id, sid, boundary - dt.timedelta(minutes=10), boundary)++ results = self._run(+ team=team,+ last_swept_at=boundary,+ last_seen_session_id="aaa",+ )++ assert [r.session_id for r in results] == ["bbb", "ccc"]++ @pytest.mark.django_db+ def test_keyset_resume_still_includes_strictly_later_sessions(self, team) -> None:+ boundary = _NOW - dt.timedelta(hours=1)+ # Names ordered so the resumed id comes after the skipped one lexicographically.+ self._produce(team.id, "aaa-tied-skipped", boundary - dt.timedelta(minutes=10), boundary)+ self._produce(team.id, "bbb-tied-resumed", boundary - dt.timedelta(minutes=10), boundary)+ self._produce(+ team.id, "ccc-strictly-later", boundary - dt.timedelta(minutes=5), boundary + dt.timedelta(seconds=1)+ )++ results = self._run(team=team, last_swept_at=boundary, last_seen_session_id="aaa-tied-skipped")++ assert sorted(r.session_id for r in results) == ["bbb-tied-resumed", "ccc-strictly-later"]++ @pytest.mark.django_db+ def test_returns_empty_list_when_no_sessions(self, team) -> None:+ results = self._run(team=team, last_swept_at=_NOW - dt.timedelta(hours=2))+ assert results == []++ @staticmethod+ def _run(+ *,+ team,+ last_swept_at: dt.datetime,+ query: RecordingsQuery | None = None,+ sampling_rate: float = 1.0,+ candidate_limit: int = DEFAULT_CANDIDATE_LIMIT,+ last_seen_session_id: str | None = None,+ ):+ return ScannerCandidateQuery(+ team=team,+ query=query if query is not None else RecordingsQuery(),+ last_swept_at=last_swept_at,+ sampling_rate=sampling_rate,+ candidate_limit=candidate_limit,+ last_seen_session_id=last_seen_session_id,+ ).run()