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.

feat(replay-vision): let workflow steps scan a session with any type (#115239)

Tue Haulund1bac6620e737
diff --git a/products/replay_vision/backend/facade/api.py b/products/replay_vision/backend/facade/api.py
index 24cc69cd86d2..6437dedcbea3 100644
--- a/products/replay_vision/backend/facade/api.py
+++ b/products/replay_vision/backend/facade/api.py
@@ -1,18 +1,93 @@
-from typing import TYPE_CHECKING
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Literal
+from uuid import UUID
from django.db.models import Case, When
+from django.utils import timezone
+
+from posthog.models.organization import OrganizationMembership
+from posthog.models.team.team import Team as TeamModel
+from posthog.models.user import User
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
+from products.replay_vision.backend.models.replay_observation_request import (
+ ObservationRequestSource,
+ ReplayObservationRequest,
+)
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
from products.replay_vision.backend.observation_formatting import format_line, read_output
-from products.replay_vision.backend.scanner_access import accessible_observations, readable_observation_scanner_ids
+from products.replay_vision.backend.scanner_access import (
+ accessible_observations,
+ can_read_targeted_experiment,
+ readable_observation_scanner_ids,
+)
+from products.replay_vision.backend.session_limits import MAX_SESSION_ID_LENGTH
from ee.hogai.utils.untrusted import as_untrusted_data
if TYPE_CHECKING:
from posthog.models.team.team import Team
- from posthog.models.user import User
+
+RejectionKind = Literal["not_found", "consent", "invalid", "forbidden", "rate_limited"]
+
+
+@dataclass(frozen=True, kw_only=True)
+class StartedObservationRequest:
+ request_id: UUID
+ # "completed" when the session already settled, for example because it was scanned before.
+ status: Literal["running", "completed"]
+ # False when the idempotency key matched an earlier request and nothing new started.
+ created: bool
+ # The step's answer, set only when the session was already scanned, so the caller has nothing to wait for.
+ result: dict[str, Any] | None = None
+
+
+# An experiment scan needs a saved scanner, so a workflow step can't run one inline.
+INLINE_SCAN_TYPES = (ScannerType.MONITOR, ScannerType.CLASSIFIER, ScannerType.SCORER, ScannerType.SUMMARIZER)
+
+
+@dataclass(frozen=True, kw_only=True)
+class WorkflowInlineScan:
+ scanner_type: str
+ # The type's `scanner_config`, prompt included, as a saved scanner of that type carries it.
+ scanner_config: dict[str, Any]
+
+
+class ObservationRequestRejected(Exception):
+ def __init__(self, detail: str, kind: RejectionKind) -> None:
+ super().__init__(detail)
+ self.detail = detail
+ self.kind = kind
+
+
+def parse_workflow_scan_setup(setup: Any) -> tuple[UUID | None, WorkflowInlineScan | None]:
+ """Read the step's "What should Replay Vision do?" input: a saved scanner, or an inline scan of a type.
+
+ Raises `ObservationRequestRejected` with a message for the step editor when the setup is incomplete.
+ """
+ # Deferred: scanner_config reaches the temporal package, whose activities import this facade.
+ from products.replay_vision.backend.scanner_config import scanner_config_error # noqa: PLC0415
+
+ if not isinstance(setup, dict) or not isinstance(setup.get("type"), str):
+ raise ObservationRequestRejected("Choose what Replay Vision should do.", "invalid")
+ if setup["type"] == "scanner":
+ try:
+ return UUID(str(setup.get("scanner_id"))), None
+ except ValueError:
+ raise ObservationRequestRejected("Choose a saved scanner.", "invalid")
+ if setup["type"] not in INLINE_SCAN_TYPES:
+ raise ObservationRequestRejected("Choose what Replay Vision should do.", "invalid")
+ config: dict[str, Any] = {"prompt": setup.get("prompt")}
+ if setup["type"] == ScannerType.CLASSIFIER:
+ config["tags"] = setup.get("tags")
+ if setup["type"] == ScannerType.SCORER:
+ config["scale"] = setup.get("scale")
+ error = scanner_config_error(ScannerType(setup["type"]), config)
+ if error is not None:
+ raise ObservationRequestRejected(error, "invalid")
+ return None, WorkflowInlineScan(scanner_type=setup["type"], scanner_config=config)
+
_MAX_PAGE_OBSERVATIONS = 30
@@ -94,3 +169,161 @@ def has_signal_emitting_scanner(team_id: int) -> bool:
signals tables alone. See `SignalSourceConfig.is_source_enabled`.
"""
return ReplayScanner.objects.filter(team_id=team_id, enabled=True, emits_signals=True).exists()
+
+
+def start_workflow_observation_request(
+ *,
+ team_id: int,
+ owner_id: int | None,
+ hog_flow_id: UUID,
+ session_id: str,
+ scanner_id: UUID | None,
+ inline: WorkflowInlineScan | None,
+ idempotency_key: str,
+ wait_for_session_end: bool,
+ per_workflow_daily_cap: int,
+ per_team_daily_cap: int,
+) -> StartedObservationRequest:
+ """Scan one session for a workflow step, with a saved scanner or an inline scan of any type.
+
+ The step runs as the workflow's owner, so it can only do what that owner could do from the API: read
+ recordings, and edit the scanner it names (or the project's scanners, to scan inline). Otherwise
+ anyone allowed to edit a workflow could forward recording contents they may not read. The daily caps
+ count the workflow's own requests and all workflow requests in the project. Raises
+ `ObservationRequestRejected` when the scan can't be requested.
+ """
+ # Deferred: these reach the temporal package, whose activities import them back while it loads.
+ from products.replay_vision.backend.observation_requests import ( # noqa: PLC0415
+ IdempotencyKeyConflict,
+ InlineScanSpec,
+ WorkflowScanCapReached,
+ WorkflowScanCaps,
+ create_observation_request,
+ recording_viewer_access,
+ request_progress,
+ step_result,
+ )
+ from products.replay_vision.backend.scanner_config import scanner_config_error # noqa: PLC0415
+
+ team = TeamModel.objects.select_related("organization").get(id=team_id)
+ if team.parent_team_id is not None:
+ raise ObservationRequestRejected(
+ "Replay Vision scans from workflows are only available in the project's main environment.", "invalid"
+ )
+ owner = _workflow_owner(team, owner_id)
+ access = recording_viewer_access(owner, team)
+ if access is None:
+ raise ObservationRequestRejected("The workflow's owner can't view session recordings.", "forbidden")
+ if not team.organization.is_ai_data_processing_approved:
+ raise ObservationRequestRejected(
+ "Your organization needs to allow AI analysis before a workflow can run a Replay Vision scan.", "consent"
+ )
+ session_id = session_id.strip()
+ if not session_id:
+ raise ObservationRequestRejected("No session to scan. The triggering event has no session ID.", "invalid")
+ if len(session_id) > MAX_SESSION_ID_LENGTH:
+ raise ObservationRequestRejected(f"Session IDs can be at most {MAX_SESSION_ID_LENGTH} characters.", "invalid")
+ if (scanner_id is None) == (inline is None):
+ raise ObservationRequestRejected("Choose a saved scanner or set up the scan in the step.", "invalid")
+
+ scanner: ReplayScanner | None = None
+ inline_spec: InlineScanSpec | None = None
+ if scanner_id is not None:
+ scanner = ReplayScanner.objects.filter(team_id=team.id, id=scanner_id).first()
+ if scanner is None:
+ raise ObservationRequestRejected("No scanner with this ID exists in this project.", "not_found")
+ if not _can_scan_with(access, team.id, scanner):
+ raise ObservationRequestRejected("The workflow's owner can't scan with this scanner.", "forbidden")
+ elif inline is not None:
+ if not access.check_access_level_for_resource("replay_scanner", required_level="editor"):
+ raise ObservationRequestRejected(
+ "Scanning from the step needs the workflow's owner to have edit access to the project's scanners.",
+ "forbidden",
+ )
+ if inline.scanner_type not in INLINE_SCAN_TYPES:
+ raise ObservationRequestRejected("This scan type needs a saved scanner.", "invalid")
+ scanner_type = ScannerType(inline.scanner_type)
+ error = scanner_config_error(scanner_type, inline.scanner_config)
+ if error is not None:
+ raise ObservationRequestRejected(error, "invalid")
+ inline_spec = InlineScanSpec(
+ scanner_type=scanner_type, scanner_config=inline.scanner_config, model=ScannerModel.GEMINI_3_FLASH_PREVIEW
+ )
+
+ try:
+ request, created = create_observation_request(
+ team=team,
+ user=owner,
+ source=ObservationRequestSource.WORKFLOW,
+ session_ids=[session_id],
+ scanner=scanner,
+ inline=inline_spec,
+ idempotency_key=idempotency_key,
+ reference=str(hog_flow_id),
+ wait_for_session_end=wait_for_session_end,
+ workflow_caps=WorkflowScanCaps(per_workflow=per_workflow_daily_cap, per_team=per_team_daily_cap),
+ )
+ except IdempotencyKeyConflict:
+ raise ObservationRequestRejected("This step's dispatch key is already used by another request.", "invalid")
+ except WorkflowScanCapReached as reached:
+ raise ObservationRequestRejected(_cap_message(reached.scope, reached.cap), "rate_limited")
+ progress = request_progress(request)
+ if not progress.settled:
+ return StartedObservationRequest(request_id=request.id, status="running", created=created)
+ # The step returns this answer now instead of parking, so no wake is owed and the sweep must skip it.
+ ReplayObservationRequest.objects.for_team(team.id).filter(id=request.id, completed_at__isnull=True).update(
+ completed_at=timezone.now()
+ )
+ return StartedObservationRequest(
+ request_id=request.id, status="completed", created=created, result=step_result(request, progress)
+ )
+
+
+def _can_scan_with(access: UserAccessControl, team_id: int, scanner: ReplayScanner) -> bool:
+ return bool(access.check_access_level_for_object(scanner, "editor")) and can_read_targeted_experiment(
+ access, team_id, scanner
+ )
+
+
+def workflow_scan_editor_error(*, user: User, team: "Team", scanner_id: UUID | None) -> str | None:
+ """Why this user may not set up a workflow step's scan, or None. `scanner_id` None means an inline scan.
+
+ The scan runs as the workflow's owner, but whoever saves or live-tests the step chooses the sessions it
+ reads, the scanner it uses and where the answers go, so they need the access the owner needs.
+ """
+ # Deferred: reach the temporal package, whose activities import this facade while it loads.
+ from products.replay_vision.backend.observation_requests import recording_viewer_access # noqa: PLC0415
+
+ access = recording_viewer_access(user, team)
+ if access is None:
+ return "You need access to session recordings to use the Replay Vision step."
+ if scanner_id is None:
+ if not access.check_access_level_for_resource("replay_scanner", required_level="editor"):
+ return "Setting up a scan in the step needs edit access to the project's scanners."
+ return None
+ scanner = ReplayScanner.objects.filter(team_id=team.id, id=scanner_id).first()
+ if scanner is None:
+ return "No scanner with this ID exists in this project."
+ if not _can_scan_with(access, team.id, scanner):
+ return "You need edit access to this scanner to use it in a workflow."
+ return None
+
+
+def _cap_message(scope: Literal["workflow", "team"], cap: int) -> str:
+ owner = "This workflow" if scope == "workflow" else "This project's workflows"
+ if cap == 0:
+ return f"Replay Vision scans are paused for {owner.lower()}. Raise the daily limit in project settings."
+ return (
+ f"{owner} reached the daily limit of {cap} Replay Vision scans. "
+ "The event was skipped. Scans resume automatically within 24 hours."
+ )
+
+
+def _workflow_owner(team: TeamModel, owner_id: int | None) -> User:
+ owner = User.objects.filter(id=owner_id, is_active=True).first() if owner_id is not None else None
+ if (
+ owner is None
+ or not OrganizationMembership.objects.filter(user=owner, organization_id=team.organization_id).exists()
+ ):
+ raise ObservationRequestRejected("The workflow has no owner who can run scans.", "forbidden")
+ return owner
diff --git a/products/replay_vision/backend/facade/workflow_scan_limits.py b/products/replay_vision/backend/facade/workflow_scan_limits.py
new file mode 100644
index 000000000000..febd3b1c0dd2
--- /dev/null
+++ b/products/replay_vision/backend/facade/workflow_scan_limits.py
@@ -0,0 +1,10 @@
+"""Default daily limits on Replay Vision scans that workflow steps request.
+
+A module of its own, free of imports, so the team settings serializer can read it cheaply.
+"""
+
+# A project raises its own limits in settings up to the self-serve ceiling; support goes past it in admin.
+WORKFLOW_SCAN_RATE_CAP_PER_DAY = 100
+WORKFLOW_SCAN_TEAM_RATE_CAP_PER_DAY = 500
+MAX_SELF_SERVE_WORKFLOW_SCAN_RATE_CAP_PER_DAY = WORKFLOW_SCAN_RATE_CAP_PER_DAY * 5
+MAX_SELF_SERVE_WORKFLOW_SCAN_TEAM_RATE_CAP_PER_DAY = WORKFLOW_SCAN_TEAM_RATE_CAP_PER_DAY * 5
diff --git a/products/replay_vision/backend/observation_requests.py b/products/replay_vision/backend/observation_requests.py
index d38cd243a67f..77339577c971 100644
--- a/products/replay_vision/backend/observation_requests.py
+++ b/products/replay_vision/backend/observation_requests.py
@@ -8,10 +8,11 @@ Nothing here checks consent or access; the caller does, as with `scanning`.
import time
from collections.abc import Sequence
from datetime import datetime, timedelta
-from typing import Any
-from uuid import NAMESPACE_URL, uuid5
+from typing import Any, Literal
+from uuid import NAMESPACE_URL, UUID, uuid5
-from django.db import IntegrityError, models, transaction
+from django.core.cache import cache
+from django.db import IntegrityError, connection, models, transaction
from django.db.models import F, Q
from django.utils import timezone
@@ -30,6 +31,7 @@ from products.cdp.backend.internal_events import (
flush_internal_events_producer,
produce_internal_event,
)
+from products.cdp.backend.workflow_step_resume import RESULT_BYTE_CAP, cap_value, emit_workflow_step_resume
from products.replay_vision.backend.distinct_ids import replay_vision_distinct_id
from products.replay_vision.backend.models.replay_observation import TERMINAL_STATUSES, ReplayObservation
from products.replay_vision.backend.models.replay_observation_request import (
@@ -38,7 +40,7 @@ from products.replay_vision.backend.models.replay_observation_request import (
)
from products.replay_vision.backend.models.replay_scanner import SETTLE_INTERVAL, ReplayScanner, ScannerType
from products.replay_vision.backend.queries.session_last_activity import fetch_session_last_activity
-from products.replay_vision.backend.scanner_access import can_read_targeted_experiment
+from products.replay_vision.backend.scanner_access import can_read_observation, can_read_targeted_experiment
from products.replay_vision.backend.scanning import run_inline_scan, scan_existing_scanner
from products.replay_vision.backend.temporal.constants import APPLY_SCANNER_EXECUTION_TIMEOUT
@@ -46,6 +48,7 @@ logger = structlog.get_logger(__name__)
COMPLETED_EVENT = "$replay_vision_request_completed"
+
_SWEEP_PAGE_SIZE = 500
# The longest a request waits for its sessions to end before scanning what has been recorded so far.
@@ -62,7 +65,14 @@ MAX_CHECKS_PER_TICK = 200
START_SWEEP_BUDGET_SECONDS = 15
COMPLETION_SWEEP_BUDGET_SECONDS = 20
+# Matches the `max_wait` the workflow step parks with (posthog-replay-vision.template.ts): the
+# longest wait for the sessions to end plus the scan itself.
+WORKFLOW_STEP_MAX_WAIT = timedelta(hours=8)
+
_DELIVERY_TIMEOUT_SECONDS = 10
+_SWEEP_CURSOR_KEY = "replay_vision:completion_sweep_cursor"
+_WRITER = "default"
+_SWEEP_CURSOR_TTL_SECONDS = 60 * 60
# Start outcomes that put a workflow behind the session, so an observation row is expected for it.
_OBSERVED_OUTCOMES = frozenset({"started", "already_running", "already_scanned"})
@@ -92,6 +102,21 @@ class IdempotencyKeyConflict(Exception):
"""The key already names a request someone else made, so it can't be handed back to this caller."""
+@frozen
+class WorkflowScanCaps:
+ """The most scan requests one workflow, and all of a project's workflows, may make in 24 hours."""
+
+ per_workflow: int
+ per_team: int
+
+
+class WorkflowScanCapReached(Exception):
+ def __init__(self, scope: Literal["workflow", "team"], cap: int) -> None:
+ super().__init__(f"The {scope} reached its daily cap of {cap} scans")
+ self.scope = scope
+ self.cap = cap
+
+
@frozen
class InlineScanSpec:
scanner_type: ScannerType
@@ -128,6 +153,7 @@ def create_observation_request(
idempotency_key: str | None,
reference: str,
wait_for_session_end: bool = False,
+ workflow_caps: WorkflowScanCaps | None = None,
) -> tuple[ReplayObservationRequest, bool]:
"""Start scans for the sessions and record them as one request. Returns (request, created).
@@ -139,15 +165,32 @@ def create_observation_request(
timeout never pays twice. The row is inserted before any scan starts, which makes the unique index
the arbiter between two concurrent calls with the same key. A key is only handed back to the same
caller: another one gets `IdempotencyKeyConflict`, never a request it may not be allowed to read.
+
+ With `workflow_caps`, `reference` names the workflow, and a request over either cap raises
+ `WorkflowScanCapReached`. A replayed key never counts against a cap.
"""
if (scanner is None) == (inline is None):
raise ValueError("Pass exactly one of scanner or inline.")
if idempotency_key:
existing = ReplayObservationRequest.objects.for_team(team.id).filter(idempotency_key=idempotency_key).first()
if existing is not None:
- return _same_caller(existing, team, source, user), False
+ return _same_caller(existing, team, source, user, reference), False
try:
with transaction.atomic():
+ if workflow_caps is not None:
+ _lock_workflow_scans(team.id)
+ # A same-key call that held the lock first has committed its row, which is visible now.
+ replayed = (
+ ReplayObservationRequest.objects.for_team(team.id)
+ .using(_WRITER)
+ .filter(idempotency_key=idempotency_key)
+ .first()
+ if idempotency_key
+ else None
+ )
+ if replayed is not None:
+ return _same_caller(replayed, team, source, user, reference), False
+ _check_workflow_caps(team.id, reference, workflow_caps)
request = ReplayObservationRequest.objects.for_team(team.id).create(
team=team,
scanner=scanner,
@@ -164,7 +207,7 @@ def create_observation_request(
if not idempotency_key:
raise
existing = ReplayObservationRequest.objects.for_team(team.id).get(idempotency_key=idempotency_key)
- return _same_caller(existing, team, source, user), False
+ return _same_caller(existing, team, source, user, reference), False
if wait_for_session_end:
return request, True
@@ -177,6 +220,25 @@ def create_observation_request(
return request, True
+def _lock_workflow_scans(team_id: int) -> None:
+ # Serializes the count and the insert, so two concurrent runs can't both take the last scan.
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", [f"replay-vision-workflow-scans:{team_id}"])
+
+
+def _check_workflow_caps(team_id: int, hog_flow_id: str, caps: WorkflowScanCaps) -> None:
+ # Counted on the writer, which the lock and the insert use: a lagging replica could miss the last scan taken.
+ recent = (
+ ReplayObservationRequest.objects.for_team(team_id)
+ .using(_WRITER)
+ .filter(source=ObservationRequestSource.WORKFLOW, created_at__gte=timezone.now() - timedelta(days=1))
+ )
+ if recent.filter(reference=hog_flow_id).count() >= caps.per_workflow:
+ raise WorkflowScanCapReached("workflow", caps.per_workflow)
+ if recent.count() >= caps.per_team:
+ raise WorkflowScanCapReached("team", caps.per_team)
+
+
def _inline_config(inline: InlineScanSpec | None) -> dict[str, Any] | None:
if inline is None:
return None
@@ -257,6 +319,20 @@ def start_waiting_requests(*, now: datetime | None = None, budget_seconds: float
return started
+def recording_viewer_access(user: User | None, team: Team) -> UserAccessControl | None:
+ """The user's access in the project, when they are active, a member and can view its recordings."""
+ if user is None or not user.is_active:
+ return None
+ if not OrganizationMembership.objects.filter(user=user, organization_id=team.organization_id).exists():
+ return None
+ access = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))
+ if not access.has_project_access:
+ return None
+ if not access.check_access_level_for_resource("session_recording", required_level="viewer"):
+ return None
+ return access
+
+
def _creator_still_allowed(request: ReplayObservationRequest) -> bool:
"""Whether the person a waiting request runs as can still start it, hours after asking.
@@ -265,16 +341,9 @@ def _creator_still_allowed(request: ReplayObservationRequest) -> bool:
"""
if request.source == ObservationRequestSource.PROJECT_SECRET_API_KEY:
return True
- user = request.created_by
- if user is None or not user.is_active:
- return False
team = request.team
- if not OrganizationMembership.objects.filter(user=user, organization_id=team.organization_id).exists():
- return False
- access = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))
- if not access.has_project_access:
- return False
- if not access.check_access_level_for_resource("session_recording", required_level="viewer"):
+ access = recording_viewer_access(request.created_by, team)
+ if access is None:
return False
if request.scanner is not None:
return access.check_access_level_for_object(request.scanner, "editor") is True and can_read_targeted_experiment(
@@ -310,10 +379,17 @@ def _inline_spec(request: ReplayObservationRequest) -> InlineScanSpec | None:
def _same_caller(
- request: ReplayObservationRequest, team: Team, source: ObservationRequestSource, user: User | None
+ request: ReplayObservationRequest,
+ team: Team,
+ source: ObservationRequestSource,
+ user: User | None,
+ reference: str,
) -> ReplayObservationRequest:
if request.source != source or request.created_by_id != (user.id if user is not None else None):
raise IdempotencyKeyConflict()
+ # One owner can have many workflows, so a workflow key is only handed back to the workflow that made it.
+ if source == ObservationRequestSource.WORKFLOW and request.reference != reference:
+ raise IdempotencyKeyConflict()
# Requests are stored under the project's canonical team, but scanners and observations stay per environment,
# so a key from another environment of the same project must not read this environment's results.
if request.scanner is not None and request.scanner.team_id != team.id:
@@ -390,31 +466,91 @@ def complete_settled_requests(
The event goes out before the row is stamped, so a crash between the two sends it again on the next
tick rather than never; a destination can therefore see a request complete twice. Open requests are
- walked oldest first in pages, so a request whose event keeps failing never hides the ones behind it.
+ walked oldest first in pages. A tick that runs out of time leaves a cursor, and the next tick starts
+ there and wraps around, so requests whose wakes keep failing never hold back the ones behind them.
"""
now = now or timezone.now()
deadline = time.monotonic() + budget_seconds
- open_requests = ReplayObservationRequest.objects.unscoped().filter(completed_at__isnull=True)
+ open_requests = (
+ ReplayObservationRequest.objects.unscoped()
+ .filter(completed_at__isnull=True)
+ .select_related("team", "created_by", "scanner")
+ .order_by("created_at", "id")
+ )
+ start = _load_sweep_cursor()
+ cursor = start
+ wrapped = start is None
completed = 0
- cursor: tuple[datetime, Any] | None = None
while time.monotonic() < deadline:
- page_qs = open_requests.order_by("created_at", "id")
+ page_qs = open_requests
if cursor is not None:
- page_qs = page_qs.filter(Q(created_at__gt=cursor[0]) | Q(created_at=cursor[0], id__gt=cursor[1]))
+ page_qs = page_qs.filter(_after(cursor))
+ if wrapped and start is not None:
+ page_qs = page_qs.exclude(_after(start))
page = list(page_qs[:_SWEEP_PAGE_SIZE])
if not page:
+ if wrapped:
+ _store_sweep_cursor(None)
+ return completed
+ wrapped, cursor = True, None
+ continue
+ page_completed, stopped_at = _complete_page(page, now, deadline)
+ completed += page_completed
+ if stopped_at is not None:
+ if stopped_at:
+ cursor = (page[stopped_at - 1].created_at, page[stopped_at - 1].id)
break
cursor = (page[-1].created_at, page[-1].id)
- completed += _complete_page(page, now)
+ _store_sweep_cursor(cursor)
return completed
-def _complete_page(page: list[ReplayObservationRequest], now: datetime) -> int:
+def _after(cursor: tuple[datetime, Any]) -> Q:
+ return Q(created_at__gt=cursor[0]) | Q(created_at=cursor[0], id__gt=cursor[1])
+
+
+def _store_sweep_cursor(cursor: tuple[datetime, Any] | None) -> None:
+ # Best effort: without the cache, a tick starts from the oldest open request, as before.
+ try:
+ if cursor is None:
+ cache.delete(_SWEEP_CURSOR_KEY)
+ else:
+ cache.set(_SWEEP_CURSOR_KEY, (cursor[0].isoformat(), str(cursor[1])), timeout=_SWEEP_CURSOR_TTL_SECONDS)
+ except Exception:
+ logger.warning("replay_vision.observation_request.sweep_cursor_unavailable", exc_info=True)
+
+
+def _load_sweep_cursor() -> tuple[datetime, Any] | None:
+ try:
+ stored = cache.get(_SWEEP_CURSOR_KEY)
+ except Exception:
+ logger.warning("replay_vision.observation_request.sweep_cursor_unavailable", exc_info=True)
+ return None
+ if not stored:
+ return None
+ try:
+ return datetime.fromisoformat(stored[0]), UUID(stored[1])
+ except (TypeError, ValueError, IndexError):
+ return None
+
+
+def _complete_page(page: list[ReplayObservationRequest], now: datetime, deadline: float) -> tuple[int, int | None]:
+ """Complete the page's settled requests. Also returns the index of the first one left for the next tick."""
progress = request_progress_many(page, now=now)
sent: list[tuple[ReplayObservationRequest, ProduceResult]] = []
- for request in page:
+ access_cache: _AccessCache = {}
+ stopped_at: int | None = None
+ for index, request in enumerate(page):
+ # A wake can block on the engine, so the rest of the page waits for the next tick.
+ if time.monotonic() >= deadline:
+ stopped_at = index
+ break
if not progress[request.id].settled:
continue
+ # The wake goes first, so a wake that fails leaves the request open without announcing it twice.
+ if request.source == ObservationRequestSource.WORKFLOW and request.idempotency_key:
+ if not _wake_workflow_step(request, progress[request.id], now, access_cache):
+ continue
try:
sent.append(
(
@@ -427,7 +563,7 @@ def _complete_page(page: list[ReplayObservationRequest], now: datetime) -> int:
except Exception:
logger.exception("replay_vision.observation_request.completion_event_failed", request_id=str(request.id))
if not sent:
- return 0
+ return 0, stopped_at
flush_internal_events_producer(_DELIVERY_TIMEOUT_SECONDS)
delivered: list[Any] = []
for request, result in sent:
@@ -437,18 +573,105 @@ def _complete_page(page: list[ReplayObservationRequest], now: datetime) -> int:
logger.warning("replay_vision.observation_request.completion_event_undelivered", request_id=str(request.id))
continue
delivered.append(request.id)
- return (
+ stamped = (
# nosemgrep: idor-lookup-without-team -- cross-team reconciler sweep; ids come from the page read above
ReplayObservationRequest.objects.unscoped()
.filter(id__in=delivered, completed_at__isnull=True)
.update(completed_at=now)
)
+ return stamped, stopped_at
+
+
+_STEP_ANSWER_BUDGET = RESULT_BYTE_CAP - 512
+
+
+# A page of completions shares one owner's access across that owner's requests.
+_AccessCache = dict[tuple[int | None, int], "UserAccessControl | None"]
+
+
+def step_result(
+ request: ReplayObservationRequest, progress: RequestProgress, access_cache: _AccessCache | None = None
+) -> dict[str, Any]:
+ """The answer for the step's one session, sized to fit the step result whichever way it returns.
+
+ Unlike the internal event, this stays inside the project's own workflow, so it carries the answer. The
+ owner's access is checked again here, because hours can pass between the start and the answer.
+ """
+ team = request.team
+ session = progress.sessions[0] if progress.sessions else None
+ cache_key = (request.created_by_id, team.id)
+ if access_cache is not None and cache_key in access_cache:
+ access = access_cache[cache_key]
+ else:
+ access = recording_viewer_access(request.created_by, team)
+ if access_cache is not None:
+ access_cache[cache_key] = access
+ if access is None or session is None:
+ return _step_answer("failed", None, ["The workflow's owner can no longer view session recordings."])
+ scanner = request.scanner
+ if scanner is not None:
+ can_read_scanner = bool(
+ access.check_access_level_for_object(scanner, "viewer")
+ ) and can_read_targeted_experiment(access, team.id, scanner)
+ else:
+ can_read_scanner = access.check_access_level_for_resource("replay_scanner", required_level="viewer")
+ if not can_read_scanner:
+ return _step_answer("failed", None, ["The workflow's owner can no longer read this scanner's answers."])
+ observation = session.observation
+ if observation is not None and not can_read_observation(access, team.id, observation):
+ return _step_answer("failed", None, ["The workflow's owner can't read this scanner's answers."])
+ output = (
+ (observation.scanner_result or {}).get("model_output")
+ if observation is not None and session.state == RequestSessionState.SUCCEEDED
+ else None
+ )
+ return _step_answer(session.state.value, output, [])
+
+
+def _step_answer(state: str, output: Any, warnings: list[str]) -> dict[str, Any]:
+ capped = cap_value(output, _STEP_ANSWER_BUDGET) if output is not None else None
+ if capped != output:
+ cut = [key for key in output if (capped or {}).get(key) != output[key]] if isinstance(output, dict) else []
+ warnings = [*warnings, "The answer was cut to fit the step result" + (f": {', '.join(cut)}" if cut else ".")]
+ return {"state": state, "output": capped, "warnings": warnings}
+
+
+def _state_counts(progress: RequestProgress) -> dict[str, int]:
+ states = [s.state for s in progress.sessions]
+ return {
+ "session_count": len(states),
+ **{
+ f"{state.value}_count": states.count(state)
+ for state in RequestSessionState
+ if state not in _UNSETTLED_STATES
+ },
+ }
+
+
+def _wake_workflow_step(
+ request: ReplayObservationRequest, progress: RequestProgress, now: datetime, access_cache: _AccessCache
+) -> bool:
+ """Wake the workflow step waiting on this request. False leaves the request open for the next tick."""
+ try:
+ emit_workflow_step_resume(
+ team_id=request.team_id,
+ origin_key=request.idempotency_key or "",
+ status="completed",
+ result=step_result(request, progress, access_cache),
+ raise_on_error=True,
+ # A step the worker still holds gets the wake on the next tick, not after seconds of sleeping here.
+ retry_delays=(),
+ )
+ except Exception:
+ logger.exception("replay_vision.observation_request.step_resume_failed", request_id=str(request.id))
+ # Past the step's own wait nobody is parked to take the wake, so the request stops retrying.
+ return now - request.created_at > WORKFLOW_STEP_MAX_WAIT
+ return True
def _completed_event(request: ReplayObservationRequest, progress: RequestProgress, now: datetime) -> InternalEventEvent:
# Counts only: anyone who can add a destination receives this, so session ids and answers stay
# behind the recording access that `GET /vision/requests/{id}/` enforces.
- states = [s.state for s in progress.sessions]
return InternalEventEvent(
event=COMPLETED_EVENT,
distinct_id=replay_vision_distinct_id(request.team_id),
@@ -460,11 +683,6 @@ def _completed_event(request: ReplayObservationRequest, progress: RequestProgres
# The caller writes `reference`, so Slack gets it escaped and can't be made to ping a channel.
"label_mrkdwn": escape_slack_mrkdwn(request.reference or str(request.id)),
"scanner_id": str(request.scanner_id) if request.scanner_id else None,
- "session_count": len(progress.sessions),
- **{
- f"{state.value}_count": states.count(state)
- for state in RequestSessionState
- if state not in _UNSETTLED_STATES
- },
+ **_state_counts(progress),
},
)
diff --git a/products/replay_vision/backend/scanner_access.py b/products/replay_vision/backend/scanner_access.py
index 23effa252a85..336348ac48f7 100644
--- a/products/replay_vision/backend/scanner_access.py
+++ b/products/replay_vision/backend/scanner_access.py
@@ -133,6 +133,18 @@ def accessible_observations(
return observations.filter(snapshot_experiment_scope_q(unrestricted=True, experiment_ids=accessible))
+def can_read_observation(access: UserAccessControl, team_id: int, observation: "ReplayObservation") -> bool:
+ """`accessible_observations` for one loaded row, read off its snapshot: no query for an untargeted scan,
+ and one targeted lookup otherwise, instead of every accessible experiment in the project."""
+ snapshot = observation.scanner_snapshot or {}
+ experiment_ids = {
+ experiment_id
+ for store in ("experiment_targeting", "scanner_config")
+ if (experiment_id := (snapshot.get(store) or {}).get("experiment_id")) is not None
+ }
+ return not experiment_ids or bool(_accessible_experiment_ids(access, team_id, experiment_ids) & experiment_ids)
+
+
def readable_observation_scanner_ids(access: UserAccessControl, team_id: int) -> list[uuid.UUID]:
"""Scanner ids whose observations the caller may read across scanners, experiment access included.
diff --git a/products/replay_vision/backend/scanner_config.py b/products/replay_vision/backend/scanner_config.py
index 175a582f539d..e381dd706921 100644
--- a/products/replay_vision/backend/scanner_config.py
+++ b/products/replay_vision/backend/scanner_config.py
@@ -29,6 +29,8 @@ def scanner_config_error(scanner_type: ScannerType, scanner_config: Any) -> str
return f"Prompt can be at most {MAX_PROMPT_LENGTH:,} characters."
if scanner_type == ScannerType.CLASSIFIER:
tags = scanner_config.get("tags") or []
+ if not isinstance(tags, list):
+ return "Categories must be a list."
if len(tags) == 0:
return "Add at least one category."
if len(tags) > MAX_TAGS:
diff --git a/products/replay_vision/backend/temporal/activities/complete_observation_requests.py b/products/replay_vision/backend/temporal/activities/complete_observation_requests.py
index 9d1695e07862..ec3edf1a3a1d 100644
--- a/products/replay_vision/backend/temporal/activities/complete_observation_requests.py
+++ b/products/replay_vision/backend/temporal/activities/complete_observation_requests.py
@@ -4,16 +4,21 @@ from temporalio import activity
from posthog.sync import database_sync_to_async
-from products.replay_vision.backend.observation_requests import complete_settled_requests, start_waiting_requests
-from products.replay_vision.backend.temporal.constants import REAPER_OP_TIMEOUT
+from products.replay_vision.backend.temporal.constants import COMPLETE_OBSERVATION_REQUESTS_TIMEOUT
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.query_budget import bounded_queries
@database_sync_to_async
def _complete_observation_requests() -> int:
+ # Deferred: observation_requests reaches scanner_config, which imports this package while it loads.
+ from products.replay_vision.backend.observation_requests import ( # noqa: PLC0415
+ complete_settled_requests,
+ start_waiting_requests,
+ )
+
# Isolated so a failure in one sweep still lets the other run; each also keeps to its own time budget.
- with bounded_queries(REAPER_OP_TIMEOUT):
+ with bounded_queries(COMPLETE_OBSERVATION_REQUESTS_TIMEOUT):
try:
start_waiting_requests()
except Exception:
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index 77c2d4bdfc4e..fec049c3e9da 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -138,6 +138,10 @@ RECONCILE_SCHEDULE_OP_TIMEOUT = dt.timedelta(seconds=60)
REAPER_OP_TIMEOUT = dt.timedelta(seconds=45)
REAPER_OP_SCHEDULE_TO_CLOSE = dt.timedelta(minutes=2)
REAPER_MAX_ATTEMPTS = 3
+# Room past both sweep budgets for one workflow-step wake that started just before the deadline: its POST
+# can time out and fall back to an internal event, the completion events still flush after it, and the
+# stamping queries still need room inside bounded_queries, which takes 75% of this.
+COMPLETE_OBSERVATION_REQUESTS_TIMEOUT = dt.timedelta(seconds=100)
# The backfill reaper pages through every backfill schedule and only applies fixes at the end, so a
# healthy pass needs minutes; per-page heartbeats catch a dead worker instead of a short attempt cap.
diff --git a/products/replay_vision/backend/temporal/reconciler.py b/products/replay_vision/backend/temporal/reconciler.py
index dd637c93f39e..ea95e4055e1a 100644
--- a/products/replay_vision/backend/temporal/reconciler.py
+++ b/products/replay_vision/backend/temporal/reconciler.py
@@ -14,6 +14,7 @@ from posthog.scheduling.jitter import deterministic_offset
from posthog.temporal.common.base import PostHogWorkflow
from products.replay_vision.backend.temporal.constants import (
+ COMPLETE_OBSERVATION_REQUESTS_TIMEOUT,
LIST_ENABLED_SCANNERS_TIMEOUT,
LIST_SCANNER_SCHEDULES_TIMEOUT,
REAP_BACKFILL_SCHEDULES_HEARTBEAT_TIMEOUT,
@@ -108,7 +109,9 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):
workflow.logger.exception("replay_vision.start_launched_scanners_failed")
try:
- await self._run_reaper(complete_observation_requests_activity)
+ await self._run_reaper(
+ complete_observation_requests_activity, start_to_close_timeout=COMPLETE_OBSERVATION_REQUESTS_TIMEOUT
+ )
except Exception:
workflow.logger.exception("replay_vision.complete_observation_requests_failed")
diff --git a/products/replay_vision/backend/tests/test_facade.py b/products/replay_vision/backend/tests/test_facade.py
index bc4d1a88a37a..8b2876d12feb 100644
--- a/products/replay_vision/backend/tests/test_facade.py
+++ b/products/replay_vision/backend/tests/test_facade.py
@@ -1,20 +1,35 @@
+import uuid
+from typing import Any
+
import pytest
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from django.utils import timezone
+from parameterized import parameterized
+
from posthog.constants import AvailableFeature
from posthog.models.organization import OrganizationMembership
+from posthog.models.team import Team
from posthog.models.user import User
from products.access_control.backend.models.access_control import AccessControl
-from products.replay_vision.backend.facade.api import fetch_page_session_observations
+from products.replay_vision.backend.facade.api import (
+ ObservationRequestRejected,
+ WorkflowInlineScan,
+ fetch_page_session_observations,
+ parse_workflow_scan_setup,
+ start_workflow_observation_request,
+)
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
ObservationTrigger,
ReplayObservation,
)
+from products.replay_vision.backend.models.replay_observation_request import ReplayObservationRequest
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
+from products.replay_vision.backend.tests.helpers import create_experiment, snapshot_for
class TestFetchPageSessionObservations(APIBaseTest):
@@ -86,3 +101,232 @@ class TestFetchPageSessionObservations(APIBaseTest):
assert block is not None
assert "readable summary" in block
assert "restricted summary" not in block
+
+
+class TestStartWorkflowObservationRequest(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ for target in ("api.trigger.async_to_sync", "api.trigger.sync_connect"):
+ patcher = patch(f"products.replay_vision.backend.{target}")
+ self.addCleanup(patcher.stop)
+ patcher.start()
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ self.hog_flow_id = uuid.uuid4()
+
+ def _start(self, **overrides: Any):
+ kwargs: dict[str, Any] = {
+ "team_id": self.team.id,
+ "owner_id": self.user.id,
+ "hog_flow_id": self.hog_flow_id,
+ "session_id": "s1",
+ "scanner_id": None,
+ "inline": WorkflowInlineScan(scanner_type="monitor", scanner_config={"prompt": "did they rage click?"}),
+ "idempotency_key": "run:step:1",
+ "wait_for_session_end": False,
+ "per_workflow_daily_cap": 100,
+ "per_team_daily_cap": 500,
+ **overrides,
+ }
+ return start_workflow_observation_request(**kwargs)
+
+ def _scanner_with_answer(self, model_output: dict[str, Any]) -> ReplayScanner:
+ scanner = ReplayScanner.objects.create(
+ team=self.team,
+ name="checkout",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "did the user check out?"},
+ model=ScannerModel.GEMINI_3_8_FLASH,
+ )
+ ReplayObservation.objects.create(
+ scanner=scanner,
+ team=self.team,
+ session_id="s1",
+ scanner_snapshot=snapshot_for(scanner),
+ triggered_by=ObservationTrigger.SCHEDULE,
+ status=ObservationStatus.SUCCEEDED,
+ scanner_result={"model_output": model_output},
+ completed_at=timezone.now(),
+ )
+ return scanner
+
+ @parameterized.expand(
+ [
+ ("monitor", {"prompt": "did they rage click?"}),
+ ("classifier", {"prompt": "what did they try to do?", "tags": ["checkout", "browse"]}),
+ ("scorer", {"prompt": "how frustrated were they?", "scale": {"min": 1, "max": 5}}),
+ ("summarizer", {"prompt": "summarize the session"}),
+ ]
+ )
+ def test_starts_an_inline_scan_of_any_type_as_the_workflow_owner(
+ self, scanner_type: str, scanner_config: dict[str, Any]
+ ) -> None:
+ started = self._start(inline=WorkflowInlineScan(scanner_type=scanner_type, scanner_config=scanner_config))
+
+ assert (started.status, started.created) == ("running", True)
+ request = ReplayObservationRequest.objects.for_team(self.team.id).get(id=started.request_id)
+ assert (request.inline_config or {})["scanner_type"] == scanner_type
+ assert request.reference == str(self.hog_flow_id)
+ assert self._start().request_id == started.request_id
+
+ @parameterized.expand(
+ [
+ ("short", {"verdict": "yes"}, {"verdict": "yes"}, []),
+ (
+ "too_long",
+ {"verdict": "yes", "reasoning": "x" * 5000},
+ {"verdict": "yes", "reasoning": "x" * 1500},
+ ["The answer was cut to fit the step result: reasoning"],
+ ),
+ ]
+ )
+ def test_returns_the_answer_at_once_when_the_session_was_already_scanned(
+ self, _name: str, model_output: dict[str, Any], output: dict[str, Any], warnings: list[str]
+ ) -> None:
+ scanner = self._scanner_with_answer(model_output)
+
+ started = self._start(scanner_id=scanner.id, inline=None)
+
+ assert started.status == "completed"
+ assert started.result == {"state": "succeeded", "output": output, "warnings": warnings}
+ # The step never parks, so the sweep must not try to wake it.
+ request = ReplayObservationRequest.objects.for_team(self.team.id).get(id=started.request_id)
+ assert request.completed_at is not None
+
+ def test_withholds_a_cached_answer_recorded_under_an_experiment_the_owner_cannot_view(self) -> None:
+ experiment = create_experiment(self.team, "restricted-flag")
+ scanner = ReplayScanner.objects.create(
+ team=self.team,
+ name="checkout",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "did the user check out?"},
+ model=ScannerModel.GEMINI_3_8_FLASH,
+ experiment_targeting={"experiment_id": experiment.id, "variant": "test"},
+ )
+ ReplayObservation.objects.create(
+ scanner=scanner,
+ team=self.team,
+ session_id="s1",
+ scanner_snapshot=snapshot_for(scanner),
+ triggered_by=ObservationTrigger.SCHEDULE,
+ status=ObservationStatus.SUCCEEDED,
+ scanner_result={"model_output": {"verdict": "yes"}},
+ completed_at=timezone.now(),
+ )
+ # Retargeting lets the scanner pass its own gate; the row's snapshot must still block it.
+ scanner.experiment_targeting = None
+ scanner.save(update_fields=["experiment_targeting"])
+
+ with patch(
+ "products.access_control.backend.facade.user_access_control.UserAccessControl.filter_queryset_by_access_level",
+ side_effect=lambda qs, **_: qs.exclude(pk=experiment.pk) if qs.model is type(experiment) else qs,
+ ):
+ started = self._start(scanner_id=scanner.id, inline=None)
+
+ assert started.result is not None
+ assert (started.result["state"], started.result["output"]) == ("failed", None)
+
+ def test_daily_caps_skip_new_runs_but_not_replays(self) -> None:
+ first = self._start(per_workflow_daily_cap=1)
+
+ assert self._start(per_workflow_daily_cap=1).request_id == first.request_id
+ with pytest.raises(ObservationRequestRejected) as workflow_capped:
+ self._start(per_workflow_daily_cap=1, idempotency_key="run:step:2")
+ with pytest.raises(ObservationRequestRejected) as team_capped:
+ self._start(hog_flow_id=uuid.uuid4(), idempotency_key="run:step:3", per_team_daily_cap=1)
+
+ assert (workflow_capped.value.kind, team_capped.value.kind) == ("rate_limited", "rate_limited")
+ assert "This workflow reached the daily limit of 1" in workflow_capped.value.detail
+ assert "This project's workflows reached the daily limit of 1" in team_capped.value.detail
+
+ def test_another_workflow_of_the_same_owner_cannot_replay_a_key(self) -> None:
+ self._start()
+
+ with pytest.raises(ObservationRequestRejected) as rejected:
+ self._start(hog_flow_id=uuid.uuid4())
+
+ assert rejected.value.kind == "invalid"
+
+ def test_a_replay_that_loses_the_race_for_the_last_slot_still_gets_its_request(self) -> None:
+ lock = "products.replay_vision.backend.observation_requests._lock_workflow_scans"
+ first: list[Any] = []
+
+ def concurrent_call_with_the_same_key(_team_id: int) -> None:
+ if not first:
+ with patch(lock):
+ first.append(self._start(per_workflow_daily_cap=1))
+
+ with patch(lock, side_effect=concurrent_call_with_the_same_key):
+ replayed = self._start(per_workflow_daily_cap=1)
+
+ assert (replayed.request_id, replayed.created) == (first[0].request_id, False)
+
+ @parameterized.expand(
+ [
+ ("no_ai_consent", {}, "consent"),
+ ("unknown_scanner", {"scanner_id": uuid.uuid4(), "inline": None}, "not_found"),
+ ("no_scan", {"inline": None}, "invalid"),
+ ("no_session", {"session_id": " "}, "invalid"),
+ ("no_owner", {"owner_id": None}, "forbidden"),
+ ("child_environment", {}, "invalid"),
+ ("owner_cannot_view_recordings", {}, "forbidden"),
+ (
+ "experiment_inline",
+ {"inline": WorkflowInlineScan(scanner_type="experiment", scanner_config={"prompt": "p"})},
+ "invalid",
+ ),
+ (
+ "classifier_without_categories",
+ {"inline": WorkflowInlineScan(scanner_type="classifier", scanner_config={"prompt": "p"})},
+ "invalid",
+ ),
+ ]
+ )
+ def test_refuses(self, name: str, overrides: dict[str, Any], kind: str) -> None:
+ if name == "no_ai_consent":
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save()
+ if name == "child_environment":
+ child = Team.objects.create(organization=self.organization, parent_team=self.team, name="child env")
+ overrides = {**overrides, "team_id": child.id}
+ if name == "owner_cannot_view_recordings":
+ # Without this, anyone who can edit a workflow could forward recording contents they may not read.
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ AccessControl.objects.create(team=self.team, resource="session_recording", access_level="none")
+
+ with pytest.raises(ObservationRequestRejected) as error:
+ self._start(**overrides)
+
+ assert error.value.kind == kind
+
+
+class TestParseWorkflowScanSetup:
+ @pytest.mark.parametrize(
+ "_name,setup,error",
+ [
+ ("scanner", {"type": "scanner", "scanner_id": "0192b2a3-5c7d-7e8f-9a0b-1c2d3e4f5a6b"}, None),
+ ("classifier", {"type": "classifier", "prompt": "intent?", "tags": ["buy"], "scale": {"min": 1}}, None),
+ ("scorer", {"type": "scorer", "prompt": "how bad?", "scale": {"min": 1, "max": 5}}, None),
+ ("not_an_object", "monitor", "Choose what Replay Vision should do."),
+ ("experiment", {"type": "experiment", "prompt": "p"}, "Choose what Replay Vision should do."),
+ ("scanner_without_id", {"type": "scanner", "scanner_id": ""}, "Choose a saved scanner."),
+ ("monitor_without_prompt", {"type": "monitor", "prompt": " "}, "Prompt is required."),
+ ("scorer_without_scale", {"type": "scorer", "prompt": "p"}, "Scale is required."),
+ ("scalar_categories", {"type": "classifier", "prompt": "p", "tags": 1}, "Categories must be a list."),
+ ("string_categories", {"type": "classifier", "prompt": "p", "tags": "buy"}, "Categories must be a list."),
+ ],
+ )
+ def test_reads_the_step_setup(self, _name: str, setup: Any, error: str | None) -> None:
+ if error is None:
+ scanner_id, inline = parse_workflow_scan_setup(setup)
+ assert (scanner_id is None) != (inline is None)
+ if inline is not None:
+ assert set(inline.scanner_config) <= {"prompt", "tags", "scale"}
+ assert ("tags" in inline.scanner_config) == (setup["type"] == "classifier")
+ return
+ with pytest.raises(ObservationRequestRejected) as rejected:
+ parse_workflow_scan_setup(setup)
+ assert (rejected.value.kind, rejected.value.detail) == ("invalid", error)
diff --git a/products/replay_vision/backend/tests/test_observation_requests_api.py b/products/replay_vision/backend/tests/test_observation_requests_api.py
index 63065f67b593..b7d60a9230ba 100644
--- a/products/replay_vision/backend/tests/test_observation_requests_api.py
+++ b/products/replay_vision/backend/tests/test_observation_requests_api.py
@@ -4,6 +4,7 @@ from typing import Any
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
+from django.core.cache import cache
from django.utils import timezone
from parameterized import parameterized
@@ -23,8 +24,11 @@ from products.replay_vision.backend.models.replay_observation import (
from products.replay_vision.backend.models.replay_observation_request import ReplayObservationRequest
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
from products.replay_vision.backend.observation_requests import (
+ _SWEEP_CURSOR_KEY,
MAX_SESSION_END_WAIT,
+ _complete_page,
complete_settled_requests,
+ recording_viewer_access,
request_progress,
start_waiting_requests,
)
@@ -319,16 +323,61 @@ class TestCompleteSettledRequests(APIBaseTest):
model=ScannerModel.GEMINI_3_8_FLASH,
)
- def _request(self, outcomes: dict[str, str]) -> ReplayObservationRequest:
+ def _request(self, outcomes: dict[str, str], **fields: Any) -> ReplayObservationRequest:
return ReplayObservationRequest.objects.for_team(self.team.id).create(
team=self.team,
scanner=self.scanner,
session_ids=list(outcomes),
start_outcomes=[{"session_id": sid, "scan_outcome": outcome} for sid, outcome in outcomes.items()],
- reference="job-7",
- source="project_secret_api_key",
+ **{"reference": "job-7", "source": "project_secret_api_key", **fields},
)
+ @patch("products.replay_vision.backend.observation_requests.emit_workflow_step_resume")
+ @patch("products.replay_vision.backend.observation_requests.produce_internal_event")
+ def test_one_owners_access_is_loaded_once_per_page(self, _produce: MagicMock, resume: MagicMock) -> None:
+ for key in ("run:step:1", "run:step:2", "run:step:3"):
+ self._request({"s1": "skipped_quota"}, source="workflow", idempotency_key=key, created_by=self.user)
+
+ with patch(
+ "products.replay_vision.backend.observation_requests.recording_viewer_access",
+ wraps=recording_viewer_access,
+ ) as load_access:
+ complete_settled_requests()
+
+ assert (resume.call_count, load_access.call_count) == (3, 1)
+
+ @patch("products.replay_vision.backend.observation_requests.produce_internal_event")
+ def test_the_sweep_still_completes_requests_when_the_cache_is_down(self, _produce: MagicMock) -> None:
+ request = self._request({"s1": "skipped_quota"})
+
+ with (
+ patch("products.replay_vision.backend.observation_requests.cache.get", side_effect=ConnectionError),
+ patch("products.replay_vision.backend.observation_requests.cache.delete", side_effect=ConnectionError),
+ patch("products.replay_vision.backend.observation_requests.cache.set", side_effect=ConnectionError),
+ ):
+ complete_settled_requests()
+
+ request.refresh_from_db()
+ assert request.completed_at is not None
+
+ @patch("products.replay_vision.backend.observation_requests.produce_internal_event")
+ def test_a_tick_resumes_where_the_last_one_ran_out_of_time_and_wraps_around(self, _produce: MagicMock) -> None:
+ first = self._request({"s1": "skipped_quota"})
+ second = self._request({"s2": "skipped_quota"})
+ cache.set(_SWEEP_CURSOR_KEY, (first.created_at.isoformat(), str(first.id)))
+
+ with patch(
+ "products.replay_vision.backend.observation_requests._complete_page", wraps=_complete_page
+ ) as complete_page:
+ complete_settled_requests()
+
+ assert [page[0].id for page, *_ in (call.args for call in complete_page.call_args_list)] == [
+ second.id,
+ first.id,
+ ]
+ assert ReplayObservationRequest.objects.for_team(self.team.id).filter(completed_at__isnull=True).count() == 0
+ assert cache.get(_SWEEP_CURSOR_KEY) is None
+
@parameterized.expand(
[
("settled_and_delivered", "skipped_quota", None, True),
@@ -380,6 +429,55 @@ class TestCompleteSettledRequests(APIBaseTest):
second.refresh_from_db()
self.assertEqual((first.completed_at is None, second.completed_at is not None), (True, True))
+ @parameterized.expand(
+ [
+ ("workflow_woken", "workflow", None, True, 1, True, "skipped"),
+ ("workflow_owner_lost_access", "workflow", None, False, 1, True, "failed"),
+ ("workflow_owner_lost_scanner_access", "workflow", None, True, 1, True, "failed"),
+ ("workflow_wake_failed", "workflow", RuntimeError("engine down"), True, 1, False, None),
+ ("api", "project_secret_api_key", None, True, 0, True, None),
+ ]
+ )
+ @patch("products.replay_vision.backend.observation_requests.emit_workflow_step_resume")
+ @patch("products.replay_vision.backend.observation_requests.produce_internal_event")
+ def test_wakes_only_the_workflow_step_that_started_it(
+ self,
+ _name: str,
+ source: str,
+ wake_error: Exception | None,
+ owner_active: bool,
+ wakes: int,
+ completes: bool,
+ state: str | None,
+ produce: MagicMock,
+ resume: MagicMock,
+ ) -> None:
+ resume.side_effect = wake_error
+ self.user.is_active = owner_active
+ self.user.save()
+ if _name == "workflow_owner_lost_scanner_access":
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ AccessControl.objects.create(
+ team=self.team, resource="replay_scanner", resource_id=str(self.scanner.id), access_level="none"
+ )
+ request = self._request(
+ {"s1": "skipped_quota"}, source=source, idempotency_key="run:step:1", created_by=self.user
+ )
+
+ complete_settled_requests()
+
+ request.refresh_from_db()
+ self.assertEqual((resume.call_count, request.completed_at is not None), (wakes, completes))
+ self.assertEqual(produce.call_count, 0 if wake_error else 1)
+ if state is not None:
+ kwargs = resume.call_args.kwargs
+ self.assertEqual((kwargs["origin_key"], kwargs["status"]), ("run:step:1", "completed"))
+ self.assertEqual(kwargs["result"]["state"], state)
+ self.assertIsNone(kwargs["result"]["output"])
+
class TestStartWaitingRequests(APIBaseTest):
def setUp(self) -> None: