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): scan sessions inline without saving a scanner (#78118)

Tue Haulundb09bbc332ece
diff --git a/products/replay_vision/README.md b/products/replay_vision/README.md
index 71f4f0cde119..8b5ff06a8601 100644
--- a/products/replay_vision/README.md
+++ b/products/replay_vision/README.md
@@ -6,6 +6,8 @@ A sub-product of Session Replay. Users configure named **scanners** that PostHog
**Scanner** — a configured probe scoped to a team. Carries a prompt, a scanner type (`monitor` / `classifier` / `scorer` / `summarizer`), a `RecordingsQuery` that selects matching sessions, and a sampling rate. Each enabled scanner has a Temporal schedule that fires every 5 minutes and sweeps for newly settled recordings past the scanner's watermark (`last_swept_at`); disabling a scanner removes its schedule, and re-enabling restarts the sweep from now rather than backfilling the gap. Summarizers always emit per-facet embeddings for downstream free-text search.
+**Inline scan** — a prompt pointed at named sessions with nothing saved, for a one-off question (`POST /vision/scanners/inline_scan/`, and the path agents take instead of creating a throwaway scanner). An observation belongs to a scanner, so a scan mints one keyed by a fingerprint of its config: the same question reuses the observations it already has, a different question gets its own. Those rows carry `origin=inline`, are never listed or swept, and are reaped once they have nothing to show. See `backend/inline_scan.py` for why they exist and `backend/scanner_access.py` for how results are read back.
+
**Observation** — one application of a scanner to a session, unique per (scanner, session). Created in `pending` when triggered (by the scanner's schedule or the `/observe/` action), transitions to `running` while `ApplyScannerWorkflow` executes (rasterize the recording to video → upload to Gemini → multi-turn scan), and lands in `succeeded` (result persisted, then a `$recording_observed` event plus embeddings/tags emitted fail-soft), `failed` (with a `kind:message` `error_reason`), or `ineligible` (the session doesn't qualify — too short, too idle, no recording). Each observation snapshots the full scanner state (`scanner_snapshot`) that produced it, so subsequent edits to the scanner don't retro-mutate history. Rows stranded in `pending`/`running` by a dead workflow are failed as `orphaned` by a reaper on the reconciler tick.
**Quota** — succeeded observations write an immutable usage receipt; usage (receipts + in-flight rows) is counted against a monthly per-organization quota, with per-scanner volume estimates summed into a projected-usage prognosis shown at configuration time.
diff --git a/products/replay_vision/backend/api/observation_progress.py b/products/replay_vision/backend/api/observation_progress.py
index 7851143c8c9c..086a05e5b1e0 100644
--- a/products/replay_vision/backend/api/observation_progress.py
+++ b/products/replay_vision/backend/api/observation_progress.py
@@ -11,7 +11,11 @@ import structlog
from posthog.sync import database_sync_to_async
from posthog.temporal.common.client import async_connect
-from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+from products.replay_vision.backend.models.replay_observation import (
+ TERMINAL_STATUSES,
+ ObservationStatus,
+ ReplayObservation,
+)
from products.replay_vision.backend.temporal.types import (
OBSERVATION_PHASE_INDEX,
OBSERVATION_PHASE_ORDER,
@@ -27,8 +31,6 @@ PROGRESS_POLL_INTERVAL_S = 1.5
# client never disconnects. Observations finish in minutes; well past that we close and free the worker.
MAX_STREAM_DURATION_S = 10 * 60
-_TERMINAL_STATUSES = frozenset({ObservationStatus.SUCCEEDED, ObservationStatus.FAILED, ObservationStatus.INELIGIBLE})
-
def _sse_event(label: str, data: str) -> str:
return f"event: {label}\ndata: {data}\n\n"
@@ -105,7 +107,7 @@ async def stream_observation_progress(observation: ReplayObservation) -> AsyncGe
team_id = observation.team_id
# Fast path: already settled (e.g. details page opened after completion) — close immediately.
- if observation.status in _TERMINAL_STATUSES:
+ if observation.status in TERMINAL_STATUSES:
yield _sse_event("observation-complete", json.dumps({"status": observation.status}))
return
@@ -127,7 +129,7 @@ async def stream_observation_progress(observation: ReplayObservation) -> AsyncGe
yield _sse_event("observation-error", "Observation not found")
return
status, workflow_id = state.status, state.workflow_id
- if status in _TERMINAL_STATUSES:
+ if status in TERMINAL_STATUSES:
yield _sse_event("observation-complete", json.dumps({"status": status}))
return
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index 522bb0cc6a7c..0cceb1dc1069 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -61,6 +61,10 @@ from products.replay_vision.backend.models.replay_observation import (
)
from products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabel
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerType
+from products.replay_vision.backend.scanner_access import (
+ scanner_for_reading_observations,
+ scanners_for_reading_observations,
+)
from products.replay_vision.backend.temporal.scanners.monitor import MonitorVerdict
from products.replay_vision.backend.temporal.types import ScannerResult, ScannerSnapshot
from products.tasks.backend.facade import api as tasks_facade
@@ -726,7 +730,7 @@ class ReplayObservationViewSet(
scanner_id = uuid.UUID(self.kwargs["parent_lookup_scanner_id"])
except (KeyError, ValueError):
raise NotFound()
- scanner = ReplayScanner.objects.filter(team_id=self.team_id, id=scanner_id).first()
+ scanner = scanner_for_reading_observations(self.team_id, scanner_id)
if scanner is None:
raise NotFound()
# Observations expose recording-derived output, so they inherit the scanner's RBAC and also require session_recording read.
@@ -1096,7 +1100,7 @@ class SessionReplayObservationViewSet(ReplayObservationViewSet):
# row rather than its scanner, so scope explicitly to the scanners this caller can read.
readable_scanner_ids = list(
self.user_access_control.filter_queryset_by_access_level(
- ReplayScanner.objects.filter(team_id=self.team_id)
+ scanners_for_reading_observations(self.team_id)
).values_list("id", flat=True)
)
queryset = (
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 4f7d9eb3c768..27d2fb54d661 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -1,3 +1,4 @@
+from dataclasses import dataclass
from typing import Any, NoReturn, cast
from django.db import IntegrityError
@@ -59,7 +60,9 @@ from products.replay_vision.backend.impact import (
compute_scanner_impact,
create_affected_cohort,
)
+from products.replay_vision.backend.inline_scan import create_inline_scanner, find_inline_scanner, inline_scan_key
from products.replay_vision.backend.models.replay_observation import (
+ TERMINAL_STATUSES,
ObservationStatus,
ObservationTrigger,
ReplayObservation,
@@ -694,6 +697,20 @@ class ObserveResponseSerializer(serializers.Serializer):
BULK_OBSERVE_MAX_SESSIONS = 200
+@dataclass(frozen=True, kw_only=True)
+class _Headroom:
+ """What `_scan_headroom` worked out, kept together so a request computes it once.
+
+ Keyword-only because `team_rows` and `scanner_rows` are both counts of in-flight observations, and
+ swapping them would silently loosen one of the two caps.
+ """
+
+ max_starts: int
+ skip_reason: str
+ team_rows: int
+ scanner_rows: int
+
+
class BulkObserveRequestSerializer(serializers.Serializer):
"""Body of POST /vision/scanners/{id}/bulk_observe/."""
@@ -719,15 +736,30 @@ class BulkObserveResultSerializer(serializers.Serializer):
choices=[
("started", "Started"),
("already_running", "Already running"),
- ("skipped_limit", "Skipped — in-flight limit reached"),
- ("skipped_quota", "Skipped — monthly credit quota reached"),
+ ("already_scanned", "Already scanned"),
+ ("skipped_limit", "Skipped - in-flight limit reached"),
+ ("skipped_quota", "Skipped - monthly credit quota reached"),
("failed", "Failed to start"),
],
help_text=(
- "'started' — a scan workflow was kicked off; 'already_running' — a scan for this session is "
- "already in flight (no-op, not recharged); 'skipped_limit' — the in-flight cap was reached "
- "before this session; 'skipped_quota' — the monthly credit quota would be exceeded; "
- "'failed' — the workflow failed to start."
+ "'started' - a scan workflow was kicked off; 'already_running' - a scan for this session is "
+ "already in flight (no-op, not recharged); 'already_scanned' - this scanner already has a "
+ "finished observation for this session, so nothing was started and nothing was charged (read "
+ "it back, or use the retry action to run it again); 'skipped_limit' - the in-flight cap was "
+ "reached before this session; 'skipped_quota' - the monthly credit quota would be exceeded; "
+ "'failed' - the workflow failed to start."
+ ),
+ )
+
+
+class ObserveAlreadyScannedSerializer(serializers.Serializer):
+ """200 from POST /vision/scanners/{id}/observe/ - nothing started, the answer already exists."""
+
+ observation_id = serializers.UUIDField(
+ help_text=(
+ "The settled observation this scanner already has for the session. Nothing was started and "
+ "nothing was charged; read it from /vision/scanners/{id}/observations/, or use the retry "
+ "action on it to scan the session again."
),
)
@@ -742,6 +774,73 @@ class BulkObserveResponseSerializer(serializers.Serializer):
)
+class InlineScanRequestSerializer(serializers.Serializer):
+ """Body of POST /vision/scanners/inline_scan/ - a prompt plus the sessions to point it at."""
+
+ session_ids = serializers.ListField(
+ child=serializers.CharField(max_length=MAX_SESSION_ID_LENGTH),
+ allow_empty=False,
+ max_length=BULK_OBSERVE_MAX_SESSIONS,
+ help_text=(
+ f"Session recording IDs to scan, at most {BULK_OBSERVE_MAX_SESSIONS} per request. Scans start "
+ "until the in-flight limit or monthly credit quota is reached; the rest are reported as "
+ "skipped rather than failing the whole batch."
+ ),
+ )
+ prompt = serializers.CharField(
+ max_length=_MAX_PROMPT_LENGTH,
+ help_text="What to look for in these sessions, in plain language. The same instruction a saved scanner carries.",
+ )
+ scanner_type = serializers.ChoiceField(
+ choices=ScannerType.choices,
+ required=False,
+ default=ScannerType.MONITOR,
+ help_text="What the scan produces. Defaults to monitor, an open-ended observation against the prompt.",
+ )
+ scanner_config = serializers.JSONField(
+ required=False,
+ default=dict,
+ help_text=(
+ "Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, "
+ "optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` "
+ "field and is rejected here."
+ ),
+ )
+ model = serializers.ChoiceField(
+ choices=ScannerModel.choices,
+ required=False,
+ default=ScannerModel.GEMINI_3_FLASH_PREVIEW,
+ help_text="Model to scan with. Determines what each observation costs in credits.",
+ )
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ config = attrs["scanner_config"]
+ if not isinstance(config, dict):
+ raise serializers.ValidationError({"scanner_config": "Scanner configuration must be a JSON object."})
+ if "prompt" in config:
+ raise serializers.ValidationError({"scanner_config": "Set the prompt in `prompt`, not here."})
+ # One config from here on, validated exactly like a saved scanner's. The key covers it whole.
+ merged = {**config, "prompt": attrs["prompt"]}
+ message = _scanner_config_error_message(ScannerType(attrs["scanner_type"]), merged)
+ if message is not None:
+ raise serializers.ValidationError({"scanner_config": message})
+ attrs["scanner_config"] = merged
+ return attrs
+
+
+class InlineScanResponseSerializer(BulkObserveResponseSerializer):
+ """`bulk_observe`'s partial-success shape plus the id to read the results back through."""
+
+ scan_id = serializers.UUIDField(
+ allow_null=True,
+ help_text=(
+ "Read results from `/vision/scanners/{scan_id}/observations/`. Stable for a given prompt and "
+ "model, so asking the same question again returns the same id. Null when nothing was started "
+ "and nothing existed to read, which happens when the quota is already used up."
+ ),
+ )
+
+
class EstimateRequestSerializer(serializers.Serializer):
"""Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config."""
@@ -1046,7 +1145,15 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
scope_object = "replay_scanner"
# Custom actions must be listed explicitly or personal-API-key callers 403 silently.
scope_object_read_actions = ["list", "retrieve", "creators", "stats"]
- scope_object_write_actions = ["create", "update", "partial_update", "destroy", "observe", "bulk_observe"]
+ scope_object_write_actions = [
+ "create",
+ "update",
+ "partial_update",
+ "destroy",
+ "observe",
+ "bulk_observe",
+ "inline_scan",
+ ]
permission_classes = [ReplayVisionEnabledPermission]
serializer_class = ReplayScannerSerializer
queryset = ReplayScanner.objects.all()
@@ -1072,6 +1179,9 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
raise PermissionDenied("Configuring a Replay Vision scanner requires session_recording read access.")
def safely_get_queryset(self, queryset: QuerySet[ReplayScanner]) -> QuerySet[ReplayScanner]:
+ # `queryset` comes off the fail-closed default manager, so every action here — list, retrieve,
+ # update, destroy — is configured-only. An inline scan's id is not a scanner id as far as this
+ # viewset is concerned; its results are read through the observations endpoint instead.
return queryset.filter(team_id=self.team_id).select_related("created_by").order_by("name", "id")
def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:
@@ -1136,6 +1246,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
@extend_schema(
request=ObserveRequestSerializer,
responses={
+ 200: ObserveAlreadyScannedSerializer,
202: ObserveResponseSerializer,
503: OpenApiResponse(
response=ReplayVisionErrorSerializer, description="The observation workflow couldn't be started."
@@ -1170,6 +1281,17 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
workflow_id, outcome = start_apply_scanner_workflow(
scanner, session_id, triggered_by_user_id=user.id, trigger=ObservationTrigger.ON_DEMAND
)
+ if outcome is WorkflowStartOutcome.ALREADY_SCANNED:
+ existing = ReplayObservation.objects.filter(scanner_id=scanner.id, session_id=session_id).only("id").first()
+ if existing is not None:
+ # 200, not 202: nothing was accepted for processing, so hand back what already exists.
+ return Response(
+ ObserveAlreadyScannedSerializer({"observation_id": existing.id}).data,
+ status=status.HTTP_200_OK,
+ )
+ # A concurrent retry deleted the row between the check and here, so there is neither a
+ # started workflow nor a result to return. Falls through to the same retryable 503.
+ outcome = WorkflowStartOutcome.FAILED
if outcome is WorkflowStartOutcome.CAPPED:
# The pre-check above passed on a snapshot; the atomic claim is the authoritative gate.
raise Throttled(detail="This team is at its in-flight observation limit. Try again in a few minutes.")
@@ -1220,30 +1342,188 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
session_ids = list(dict.fromkeys(body.validated_data["session_ids"]))
user = cast(User, request.user)
- # "Scan what fits": compute how many NEW scans can start once, up front. The tighter of the
- # in-flight caps and the remaining monthly quota bounds it; the loser names the skip reason so
- # the user knows which limit they hit. Decrementing a local counter as we start models each new
- # in-flight row without re-querying (a started scan consumes exactly one slot).
- max_starts, skip_reason, team_rows, scanner_rows = self._bulk_observe_headroom(scanner)
+ started, results = self._start_observations(
+ scanner,
+ session_ids,
+ user,
+ headroom=self._scan_headroom(model=scanner.model, scanner=scanner),
+ finished=self._finished_sessions(scanner, session_ids),
+ )
+
+ report_user_action(
+ user,
+ "replay_vision_bulk_scan_started",
+ {
+ "scanner_id": str(scanner.id),
+ "scanner_type": scanner.scanner_type,
+ "requested": len(session_ids),
+ "started": started,
+ },
+ team=self.team,
+ request=request,
+ )
+ # Key off the outcomes, not skip_reason: skip_reason only names the limit that would bind
+ # first, and a batch that never reached the cap must not report exhaustion.
+ if any(result["scan_outcome"] == "skipped_quota" for result in results):
+ self._report_quota_exhausted(scanner, "bulk")
+ return Response(
+ BulkObserveResponseSerializer({"started": started, "results": results}).data,
+ status=status.HTTP_202_ACCEPTED,
+ )
+
+ @extend_schema(
+ request=InlineScanRequestSerializer,
+ responses={202: InlineScanResponseSerializer},
+ )
+ @action(
+ detail=False,
+ methods=["post"],
+ url_path="inline_scan",
+ required_scopes=["replay_scanner:write", "session_recording:read"],
+ )
+ def inline_scan(self, request: Request, **kwargs: Any) -> Response:
+ """Scan named sessions against a prompt without saving a scanner first, for one-off questions.
+
+ The config resolves to a scanner minted on first use, so asking the same question twice reuses
+ the observations it already has, while a different question about the same session gets its own.
+ """
+ # This action is `detail=False`, so the generic gate settles for editor access to any one
+ # scanner and there is no object afterwards to narrow that against. An inline scan mints a
+ # scanner and spends credits exactly as `create` does, so hold it to `create`'s bar.
+ if not self.user_access_control.check_access_level_for_resource("replay_scanner", required_level="editor"):
+ raise PermissionDenied("Running an inline scan requires edit access to this project's scanners.")
+ # Observation output exposes recording contents, so this requires session_recording read.
+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
+ raise PermissionDenied("Running an inline scan requires session_recording read access.")
+ # The scan sends recordings to an LLM, the same reason saving a scanner gates on this.
+ if not self.team.organization.is_ai_data_processing_approved:
+ raise ValidationError(
+ "Your organization needs to allow AI analysis before you can run a Replay Vision scan."
+ )
+
+ body = InlineScanRequestSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ # Dedup preserving order — the same session twice in one batch would just be a wasted no-op.
+ session_ids = list(dict.fromkeys(body.validated_data["session_ids"]))
+ user = cast(User, request.user)
+ scanner_type = ScannerType(body.validated_data["scanner_type"])
+ scanner_config = body.validated_data["scanner_config"]
+ model = body.validated_data["model"]
+
+ key = inline_scan_key(scanner_type=scanner_type, scanner_config=scanner_config, model=model)
+ scanner = find_inline_scanner(team=self.team, key=key)
+ headroom = self._scan_headroom(model=model, scanner=scanner)
+ if scanner is None:
+ # Mint only once something can actually start, so an org with no headroom doesn't leave a
+ # scanner behind for every question it was unable to answer.
+ if headroom.max_starts <= 0:
+ if headroom.skip_reason == "skipped_quota":
+ self._report_quota_exhausted(None, "inline")
+ return Response(
+ InlineScanResponseSerializer(
+ {
+ "scan_id": None,
+ "started": 0,
+ "results": [{"session_id": s, "scan_outcome": headroom.skip_reason} for s in session_ids],
+ }
+ ).data,
+ status=status.HTTP_202_ACCEPTED,
+ )
+ scanner = create_inline_scanner(
+ team=self.team,
+ key=key,
+ scanner_type=scanner_type,
+ scanner_config=scanner_config,
+ model=model,
+ )
+ # A scanner that did not exist a statement ago has no observations to have settled.
+ finished: frozenset[str] = frozenset()
+ else:
+ finished = self._finished_sessions(scanner, session_ids)
+
+ started, results = self._start_observations(scanner, session_ids, user, headroom=headroom, finished=finished)
+
+ report_user_action(
+ user,
+ "replay_vision_inline_scan_requested",
+ {
+ "scan_id": str(scanner.id),
+ "scanner_type": scanner.scanner_type,
+ "model": scanner.model,
+ "requested": len(session_ids),
+ "started": started,
+ },
+ team=self.team,
+ request=request,
+ )
+ if any(result["scan_outcome"] == "skipped_quota" for result in results):
+ self._report_quota_exhausted(scanner, "inline")
+ return Response(
+ InlineScanResponseSerializer({"scan_id": scanner.id, "started": started, "results": results}).data,
+ status=status.HTTP_202_ACCEPTED,
+ )
+
+ def _finished_sessions(self, scanner: ReplayScanner, session_ids: list[str]) -> frozenset[str]:
+ """Sessions this scanner already settled on.
+
+ A terminal observation makes (scanner, session) permanently taken, so starting a workflow for one
+ would burn a run only to lose the INSERT and hand back the row we can already see.
+ """
+ return frozenset(
+ ReplayObservation.objects.filter(
+ scanner_id=scanner.id,
+ session_id__in=session_ids,
+ status__in=TERMINAL_STATUSES,
+ ).values_list("session_id", flat=True)
+ )
+
+ def _start_observations(
+ self,
+ scanner: ReplayScanner,
+ session_ids: list[str],
+ user: User,
+ *,
+ headroom: _Headroom,
+ finished: frozenset[str],
+ ) -> tuple[int, list[dict[str, str]]]:
+ """Start a scan per session, as many as fit. Returns (started, per-session outcomes).
+
+ "Scan what fits": the caller works out how many NEW scans can start once, up front, and passes it
+ in so one request takes the quota snapshot once. The tighter of the in-flight caps and the
+ remaining monthly quota bounds it; the loser names the skip reason so the user knows which limit
+ they hit. Decrementing a local counter as we start models each new in-flight row without
+ re-querying (a started scan consumes exactly one slot).
+ """
+ max_starts, skip_reason = headroom.max_starts, headroom.skip_reason
results: list[dict[str, str]] = []
started = 0
for session_id in session_ids:
+ # Checked before the cap so a settled session reports what it is rather than being
+ # reported as skipped, and consumes no headroom. `start_apply_scanner_workflow` enforces the
+ # same rule for callers that don't prefetch.
+ if session_id in finished:
+ results.append({"session_id": session_id, "scan_outcome": "already_scanned"})
+ continue
if started >= max_starts:
results.append({"session_id": session_id, "scan_outcome": skip_reason})
continue
- workflow_id, outcome = start_apply_scanner_workflow(
+ _, outcome = start_apply_scanner_workflow(
scanner,
session_id,
triggered_by_user_id=user.id,
trigger=ObservationTrigger.ON_DEMAND,
# Row counts are this request's snapshot; the atomic claim inside makes racing
# requests visible to each other, which the snapshot alone cannot.
- team_in_flight_rows=team_rows,
- scanner_in_flight_rows=scanner_rows,
+ team_in_flight_rows=headroom.team_rows,
+ scanner_in_flight_rows=headroom.scanner_rows,
+ finished_sessions=finished,
)
if outcome is WorkflowStartOutcome.STARTED:
started += 1
results.append({"session_id": session_id, "scan_outcome": "started"})
+ elif outcome is WorkflowStartOutcome.ALREADY_SCANNED:
+ # The prefetched set was taken before the loop, so a session can settle mid-batch.
+ results.append({"session_id": session_id, "scan_outcome": "already_scanned"})
elif outcome is WorkflowStartOutcome.ALREADY_RUNNING:
# Already in flight — counted in the caps already, so it consumes no new headroom.
results.append({"session_id": session_id, "scan_outcome": "already_running"})
@@ -1254,64 +1534,66 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
skip_reason = "skipped_limit"
else:
results.append({"session_id": session_id, "scan_outcome": "failed"})
+ return started, results
- report_user_action(
- user,
- "replay_vision_bulk_scan_started",
- {
- "scanner_id": str(scanner.id),
- "scanner_type": scanner.scanner_type,
- "requested": len(session_ids),
- "started": started,
- },
- team=self.team,
- request=request,
- )
- # Key off the outcomes, not skip_reason: skip_reason only names the limit that would bind
- # first, and a batch that never reached the cap must not report exhaustion.
- if any(result["scan_outcome"] == "skipped_quota" for result in results):
- self._report_quota_exhausted(scanner, "bulk")
- return Response(
- BulkObserveResponseSerializer({"started": started, "results": results}).data,
- status=status.HTTP_202_ACCEPTED,
- )
+ def _report_quota_exhausted(self, scanner: ReplayScanner | None, trigger: str) -> None:
+ """A scan was blocked or capped by the org's monthly Replay vision credit limit.
- def _report_quota_exhausted(self, scanner: ReplayScanner, trigger: str) -> None:
- """A scan was blocked or capped by the org's monthly Replay vision credit limit."""
+ `scanner` is None when an inline scan was refused before it minted one.
+ """
report_user_action(
cast(User, self.request.user),
"replay_vision_quota_exhausted",
{
- "scanner_id": str(scanner.id),
- "scanner_type": scanner.scanner_type,
+ "scanner_id": str(scanner.id) if scanner is not None else None,
+ "scanner_type": scanner.scanner_type if scanner is not None else None,
"trigger": trigger,
},
team=self.team,
request=self.request,
)
- def _bulk_observe_headroom(self, scanner: ReplayScanner) -> tuple[int, str, int, int]:
- """(max_starts, skip_reason, team_rows, scanner_rows): how many new scans can start, the
- reason once that's used up, and the row counts reused by the per-start slot claims."""
+ def _scan_headroom(self, *, model: str, scanner: ReplayScanner | None) -> _Headroom:
+ """How many new scans can start, the reason once that's used up, and the row counts the
+ per-start slot claims reuse.
+
+ `scanner=None` asks the same question for a config that has no scanner yet, so an inline scan can
+ decide whether minting one is worth it. The per-scanner terms are zero by definition there, which
+ is also why the caller can pass the answer straight into `_start_observations`.
+ """
team_in_flight = ReplayObservation.in_flight_for_team(self.team_id).count()
- scanner_in_flight = ReplayObservation.in_flight_for_team(self.team_id).filter(scanner_id=scanner.id).count()
+ scanner_in_flight = 0
+ scanner_claims = 0
+ if scanner is not None:
+ scanner_in_flight = ReplayObservation.in_flight_for_team(self.team_id).filter(scanner_id=scanner.id).count()
+ scanner_claims = pending_enqueue_claims_for_scanner(scanner.id)
# Enqueued-but-not-yet-persisted scans hold claims instead of rows.
in_flight_limit = max(
0,
min(
- MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight - pending_enqueue_claims_for_scanner(scanner.id),
+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight - scanner_claims,
MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight - pending_enqueue_claims_for_team(self.team_id),
),
)
snapshot = compute_quota_snapshot(self.team.organization_id)
- cost = observation_credits_for_model(scanner.model)
+ cost = observation_credits_for_model(model)
# Uncapped org, or a free model that spends nothing: quota can't bind. Otherwise, how many of
# THIS model's cost fit.
quota_limit = in_flight_limit if snapshot.remaining is None or cost <= 0 else snapshot.remaining // cost
# Report quota as the reason only when it's the strictly tighter limit.
if quota_limit < in_flight_limit:
- return quota_limit, "skipped_quota", team_in_flight, scanner_in_flight
- return in_flight_limit, "skipped_limit", team_in_flight, scanner_in_flight
+ return _Headroom(
+ max_starts=quota_limit,
+ skip_reason="skipped_quota",
+ team_rows=team_in_flight,
+ scanner_rows=scanner_in_flight,
+ )
+ return _Headroom(
+ max_starts=in_flight_limit,
+ skip_reason="skipped_limit",
+ team_rows=team_in_flight,
+ scanner_rows=scanner_in_flight,
+ )
@extend_schema(parameters=[ScannerImpactQuerySerializer], responses={200: ScannerImpactSerializer})
@action(
diff --git a/products/replay_vision/backend/api/trigger.py b/products/replay_vision/backend/api/trigger.py
index c55d4792fcaf..285e8dab5454 100644
--- a/products/replay_vision/backend/api/trigger.py
+++ b/products/replay_vision/backend/api/trigger.py
@@ -26,7 +26,11 @@ from products.replay_vision.backend.enqueue_claims import (
release_enqueue_claim,
try_claim_enqueue_slot,
)
-from products.replay_vision.backend.models.replay_observation import ObservationTrigger, ReplayObservation
+from products.replay_vision.backend.models.replay_observation import (
+ TERMINAL_STATUSES,
+ ObservationTrigger,
+ ReplayObservation,
+)
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.quota import compute_quota_snapshot
from products.replay_vision.backend.temporal.constants import (
@@ -48,6 +52,8 @@ class WorkflowStartOutcome(enum.Enum):
STARTED = "started"
# A workflow with our deterministic id is already running — the scan is effectively in progress.
ALREADY_RUNNING = "already_running"
+ # A settled observation already holds this (scanner, session) slot, so nothing was started.
+ ALREADY_SCANNED = "already_scanned"
# The atomic enqueue-slot claim was refused: the in-flight caps have no headroom.
CAPPED = "capped"
FAILED = "failed"
@@ -117,6 +123,14 @@ def claim_apply_scanner_slot(
return workflow_id, True
+def _is_already_scanned(scanner: ReplayScanner, session_id: str, finished_sessions: frozenset[str] | None) -> bool:
+ if finished_sessions is not None:
+ return session_id in finished_sessions
+ return ReplayObservation.objects.filter(
+ scanner_id=scanner.id, session_id=session_id, status__in=TERMINAL_STATUSES
+ ).exists()
+
+
def start_apply_scanner_workflow(
scanner: ReplayScanner,
session_id: str,
@@ -125,10 +139,20 @@ def start_apply_scanner_workflow(
trigger: ObservationTrigger,
team_in_flight_rows: int | None = None,
scanner_in_flight_rows: int | None = None,
+ finished_sessions: frozenset[str] | None = None,
slot_already_claimed: bool = False,
) -> tuple[str, WorkflowStartOutcome]:
"""Start the deterministic apply-scanner workflow for one (scanner, session); never raises.
An atomic enqueue-slot claim guards the in-flight caps; pass row counts to save two queries."""
+ # A settled observation holds the (scanner, session) slot for good, so starting a workflow would
+ # burn a run only to lose the INSERT in create_observation and hand back the row we can already
+ # see. Checked here rather than in each caller so a new one gets it by default; batch callers pass
+ # `finished_sessions` to answer it for the whole batch in one query, the same way they pass row
+ # counts. Skipped when the caller pre-claimed a slot: that is retry, which deleted the settled row
+ # to free this slot and means to scan again. Returning before the claim also keeps this exit from
+ # having a claim to leak.
+ if not slot_already_claimed and _is_already_scanned(scanner, session_id, finished_sessions):
+ return build_apply_scanner_workflow_id(scanner.id, session_id), WorkflowStartOutcome.ALREADY_SCANNED
if slot_already_claimed:
workflow_id = build_apply_scanner_workflow_id(scanner.id, session_id)
else:
diff --git a/products/replay_vision/backend/facade/api.py b/products/replay_vision/backend/facade/api.py
index 4c928b2f4a88..f31ad9fec55c 100644
--- a/products/replay_vision/backend/facade/api.py
+++ b/products/replay_vision/backend/facade/api.py
@@ -6,8 +6,9 @@ from posthog.rbac.user_access_control import UserAccessControl
from products.replay_vision.backend.feature_flag import is_replay_vision_enabled
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_scanner import ScannerType
from products.replay_vision.backend.observation_formatting import format_line, read_output
+from products.replay_vision.backend.scanner_access import scanners_for_reading_observations
from ee.hogai.utils.untrusted import as_untrusted_data
@@ -49,7 +50,7 @@ def fetch_page_session_observations(
readable_scanner_ids = [
str(sid)
for sid in UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))
- .filter_queryset_by_access_level(ReplayScanner.objects.filter(team_id=team.id))
+ .filter_queryset_by_access_level(scanners_for_reading_observations(team.id))
.values_list("id", flat=True)
]
if not readable_scanner_ids:
diff --git a/products/replay_vision/backend/fingerprint.py b/products/replay_vision/backend/fingerprint.py
new file mode 100644
index 000000000000..0d2e3ad20853
--- /dev/null
+++ b/products/replay_vision/backend/fingerprint.py
@@ -0,0 +1,23 @@
+"""The config fingerprint shared by the schedule reconciler and inline scans.
+
+Both need "same config, same key", and they must agree on canonicalization: the reconciler compares its
+fingerprint against the one stamped on a live Temporal schedule, so any drift in how a config is
+serialized would re-reconcile every schedule once.
+
+The two callers want different lengths. A schedule fingerprint is a change detector, so a collision
+costs one skipped reconcile and 16 hex is plenty. An inline scan's key is an identity, so a collision
+would silently merge two unrelated questions into one result set, and it uses the full digest.
+"""
+
+import json
+import hashlib
+from typing import Any
+
+# Short enough to read in a schedule's memo, wide enough that config drift is what changes it.
+SCHEDULE_FINGERPRINT_LENGTH = 16
+
+
+def config_fingerprint(payload: dict[str, Any] | None, *, length: int | None = None) -> str:
+ canonical = json.dumps(payload or {}, sort_keys=True, separators=(",", ":"))
+ digest = hashlib.sha256(canonical.encode()).hexdigest()
+ return digest if length is None else digest[:length]
diff --git a/products/replay_vision/backend/inline_scan.py b/products/replay_vision/backend/inline_scan.py
new file mode 100644
index 000000000000..ab4a49192eb7
--- /dev/null
+++ b/products/replay_vision/backend/inline_scan.py
@@ -0,0 +1,73 @@
+"""Scanners minted from a config passed inline, for one-off questions about named sessions.
+
+An observation belongs to a scanner: that FK is its RBAC anchor, the unique `(scanner, session)` slot
+that makes a scan idempotent, and the thing its results are read back through. An inline scan has no
+saved scanner, so it needs one anyway, and it gets one keyed by a fingerprint of its config. Asking the
+same question twice resolves to the same scanner and reuses the observations it already has; asking a
+different question about the same session gets its own.
+
+These rows are not scanners in the sense the rest of the product means. They have no name, no candidate
+query, and no schedule, and `ReplayScanner.objects` excludes them so nothing lists, counts, edits, or
+sweeps them. `ReplayScanner.all_origins` is the deliberate opt-in for the two paths that must see them:
+resolving a scan id, and reading observations back.
+"""
+
+from typing import Any
+
+from posthog.models.team import Team
+
+from products.replay_vision.backend.fingerprint import config_fingerprint
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerOrigin, ScannerType
+
+
+def inline_scan_key(*, scanner_type: str, scanner_config: dict[str, Any], model: str) -> str:
+ """Fingerprint of everything that decides what an inline scan produces.
+
+ Full digest, not the schedule fingerprint's 16 chars: this key is an identity, so a collision would
+ merge two unrelated questions into one result set rather than cost a redundant reconcile.
+ """
+ return config_fingerprint(
+ {"scanner_type": ScannerType(scanner_type).value, "model": str(model), "scanner_config": scanner_config}
+ )
+
+
+def find_inline_scanner(*, team: Team, key: str) -> ReplayScanner | None:
+ """The scanner this config already resolved to, if this question has been asked before."""
+ return ReplayScanner.all_origins.filter(team=team, origin=ScannerOrigin.INLINE, inline_key=key).first()
+
+
+def create_inline_scanner(
+ *,
+ team: Team,
+ key: str,
+ scanner_type: ScannerType,
+ scanner_config: dict[str, Any],
+ model: str,
+) -> ReplayScanner:
+ """Mint the scanner for an inline config. Call only once a scan is actually going to start.
+
+ `get_or_create` rather than a plain create: two requests can ask the same question at the same
+ moment, and it wraps the losing INSERT in a savepoint so the unique violation doesn't poison an
+ enclosing transaction.
+ """
+ scanner, _ = ReplayScanner.all_origins.get_or_create(
+ team=team,
+ origin=ScannerOrigin.INLINE,
+ inline_key=key,
+ defaults={
+ # No name: inline scanners aren't addressed by one, and the team-name uniqueness index is
+ # partial on configured rows so several unnamed rows per team coexist happily.
+ "name": "",
+ "description": "Created by an inline scan. Runs only against the sessions it was pointed at.",
+ # No owner: the row is shared by everyone who asks this question, so crediting whoever got
+ # here first would misattribute it.
+ "created_by": None,
+ "scanner_type": scanner_type,
+ "scanner_config": scanner_config,
+ "model": model,
+ # Nothing to sweep: no query, and disabled, which is what actually gates scheduling.
+ "enabled": False,
+ "sampling_rate": 0.0,
+ },
+ )
+ return scanner
diff --git a/products/replay_vision/backend/max_tools.py b/products/replay_vision/backend/max_tools.py
index 6f745c400db1..d6bebb11309e 100644
--- a/products/replay_vision/backend/max_tools.py
+++ b/products/replay_vision/backend/max_tools.py
@@ -23,8 +23,12 @@ from products.replay_vision.backend.embeddings import (
)
from products.replay_vision.backend.feature_flag import is_replay_vision_enabled
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_scanner import ScannerType
from products.replay_vision.backend.observation_formatting import EVENT_ID_CITATION_RE, format_line, read_output
+from products.replay_vision.backend.scanner_access import (
+ scanner_for_reading_observations,
+ scanners_for_reading_observations,
+)
from products.replay_vision.backend.tags import clickhouse_slugify_sql, slugify_tag
from ee.hogai.tool import MaxTool
@@ -204,7 +208,7 @@ class SummarizeReplayVisionSummariesTool(MaxTool):
if not is_replay_vision_enabled(self._user, self._team):
return "Replay Vision is not enabled for this project.", {"error": "not_enabled"}
- scanner = ReplayScanner.objects.filter(team_id=self._team.id, id=scanner_id).first()
+ scanner = scanner_for_reading_observations(self._team.id, scanner_id)
if scanner is None:
return f"Scanner {scanner_id} not found.", {"error": "not_found"}
# Summaries inherit the scanner's RBAC — a team member without viewer access to this scanner
@@ -513,7 +517,7 @@ class SearchReplayVisionObservationsTool(MaxTool):
except (ValueError, TypeError):
# A model-supplied non-UUID would raise ValidationError deeper in the ORM (alert noise); treat as not-found.
return None
- scanner = ReplayScanner.objects.filter(team_id=self._team.id, id=scanner_uuid).first()
+ scanner = scanner_for_reading_observations(self._team.id, scanner_uuid)
# Observations inherit the scanner's RBAC — treat missing access as not-found.
if scanner is None or not self.user_access_control.check_access_level_for_object(scanner, "viewer"):
return None
@@ -521,7 +525,7 @@ class SearchReplayVisionObservationsTool(MaxTool):
# tool output entirely (stored-injection guard); the searcher already knows which scanner they're on.
return [str(scanner.id)], "the selected Replay Vision scanner", False
readable = self.user_access_control.filter_queryset_by_access_level(
- ReplayScanner.objects.filter(team_id=self._team.id)
+ scanners_for_reading_observations(self._team.id)
).values_list("id", flat=True)
return [str(sid) for sid in readable], "your Replay Vision scanners", True
diff --git a/products/replay_vision/backend/migrations/0059_replayscanner_origin.py b/products/replay_vision/backend/migrations/0059_replayscanner_origin.py
new file mode 100644
index 000000000000..3de847095f75
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0059_replayscanner_origin.py
@@ -0,0 +1,75 @@
+import django.db.models.manager
+from django.db import migrations, models
+
+from posthog.migration_helpers import AddConstraintNotValid
+
+
+class Migration(migrations.Migration):
+ """Columns and state. Transactional: the concurrent index builds live in 0060 so this part keeps
+ its rollback safety."""
+
+ dependencies = [
+ ("replay_vision", "0058_delete_replayquotagrant"),
+ ]
+
+ operations = [
+ # State-only: `objects` becomes configured-only and `all_origins` is the unfiltered escape
+ # hatch, with `base_manager_name` keeping FK traversal and cascades unfiltered.
+ migrations.AlterModelOptions(
+ name="replayscanner",
+ options={"base_manager_name": "all_origins"},
+ ),
+ migrations.AlterModelManagers(
+ name="replayscanner",
+ managers=[
+ ("objects", django.db.models.manager.Manager()),
+ ("all_origins", django.db.models.manager.Manager()),
+ ],
+ ),
+ # Both carry db_default, so these are metadata-only ADD COLUMNs with no table rewrite and no
+ # follow-up DROP DEFAULT. Every existing row is a configured scanner with no inline key.
+ migrations.AddField(
+ model_name="replayscanner",
+ name="origin",
+ field=models.CharField(
+ choices=[("configured", "Configured"), ("inline", "Inline")],
+ db_default="configured",
+ default="configured",
+ help_text="Whether a user saved this scanner or an inline scan minted it. See `ScannerOrigin`.",
+ max_length=16,
+ ),
+ ),
+ migrations.AddField(
+ model_name="replayscanner",
+ name="inline_key",
+ field=models.CharField(
+ blank=True,
+ db_default="",
+ default="",
+ help_text="Config fingerprint an inline scan resolves by. Empty for configured scanners.",
+ max_length=64,
+ ),
+ ),
+ # `blank` is a validation flag, so this alteration emits no SQL.
+ migrations.AlterField(
+ model_name="replayscanner",
+ name="name",
+ field=models.CharField(
+ blank=True,
+ help_text="Human-readable name, unique within the team. Empty for inline scanners, which aren't named.",
+ max_length=255,
+ ),
+ ),
+ # Every row added above already satisfies this; NOT VALID keeps the ADD off a full-table scan
+ # and 0061 validates it once the rest of the schema is in place.
+ AddConstraintNotValid(
+ model_name="replayscanner",
+ constraint=models.CheckConstraint(
+ condition=(
+ models.Q(("inline_key", ""), ("origin", "configured"))
+ | (models.Q(("origin", "inline")) & ~models.Q(("inline_key", "")))
+ ),
+ name="replay_scanner_inline_key_matches_origin",
+ ),
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0060_replayscanner_origin_indexes.py b/products/replay_vision/backend/migrations/0060_replayscanner_origin_indexes.py
new file mode 100644
index 000000000000..0052c8452192
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0060_replayscanner_origin_indexes.py
@@ -0,0 +1,85 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import CreateIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ """Index builds only. CREATE INDEX CONCURRENTLY cannot run inside a transaction, which is the one
+ reason this migration gives up atomicity; the helper is idempotent under bin/migrate retries.
+
+ A conditional UniqueConstraint is a partial unique index in Postgres, which has no NOT VALID form,
+ so the index is built here and the constraint recorded state-only (the same shape as 0030).
+ Django's RemoveConstraint emits DROP INDEX for a conditional constraint, so state and database
+ agree about what these objects are.
+ """
+
+ atomic = False
+
+ dependencies = [
+ ("replay_vision", "0059_replayscanner_origin"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddConstraint(
+ model_name="replayscanner",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("origin", "configured")),
+ fields=("team", "name"),
+ name="replay_scanner_unique_configured_team_name",
+ ),
+ ),
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="replay_scanner_unique_configured_team_name",
+ table_name="replay_vision_replayscanner",
+ columns='("team_id", "name")',
+ unique=True,
+ where="WHERE \"origin\" = 'configured'",
+ ),
+ ],
+ ),
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddConstraint(
+ model_name="replayscanner",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("origin", "inline")),
+ fields=("team", "inline_key"),
+ name="replay_scanner_unique_team_inline_key",
+ ),
+ ),
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="replay_scanner_unique_team_inline_key",
+ table_name="replay_vision_replayscanner",
+ columns='("team_id", "inline_key")',
+ unique=True,
+ where="WHERE \"origin\" = 'inline'",
+ ),
+ ],
+ ),
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddIndex(
+ model_name="replayscanner",
+ index=models.Index(
+ condition=models.Q(("origin", "inline")),
+ fields=["created_at"],
+ name="rl_inline_created_idx",
+ ),
+ ),
+ ],
+ database_operations=[
+ CreateIndexConcurrently(
+ index_name="rl_inline_created_idx",
+ table_name="replay_vision_replayscanner",
+ columns='("created_at")',
+ where="WHERE \"origin\" = 'inline'",
+ ),
+ ],
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/0061_replayscanner_drop_legacy_name_constraint.py b/products/replay_vision/backend/migrations/0061_replayscanner_drop_legacy_name_constraint.py
new file mode 100644
index 000000000000..6d824da56701
--- /dev/null
+++ b/products/replay_vision/backend/migrations/0061_replayscanner_drop_legacy_name_constraint.py
@@ -0,0 +1,25 @@
+from django.db import migrations
+
+from posthog.migration_helpers import ValidateConstraint
+
+
+class Migration(migrations.Migration):
+ """Cleanup, once the replacement indexes from 0060 exist."""
+
+ dependencies = [
+ ("replay_vision", "0060_replayscanner_origin_indexes"),
+ ]
+
+ operations = [
+ # Superseded by the partial index built in 0060. Dropped only after its replacement exists, so
+ # team name uniqueness is never unenforced.
+ migrations.RemoveConstraint(
+ model_name="replayscanner",
+ name="replay_scanner_unique_team_name",
+ ),
+ # Non-blocking: VALIDATE takes SHARE UPDATE EXCLUSIVE, so reads and writes continue.
+ ValidateConstraint(
+ model_name="replayscanner",
+ name="replay_scanner_inline_key_matches_origin",
+ ),
+ ]
diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txt
index 557b3b4cb1e5..47c39fd54ff1 100644
--- a/products/replay_vision/backend/migrations/max_migration.txt
+++ b/products/replay_vision/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0058_delete_replayquotagrant
+0061_replayscanner_drop_legacy_name_constraint
diff --git a/products/replay_vision/backend/models/replay_observation.py b/products/replay_vision/backend/models/replay_observation.py
index 47313c4009fc..0dc05c56bddc 100644
--- a/products/replay_vision/backend/models/replay_observation.py
+++ b/products/replay_vision/backend/models/replay_observation.py
@@ -18,6 +18,11 @@ class ObservationStatus(models.TextChoices):
# Not-yet-terminal statuses: what the quota meter reserves and the concurrency caps count as "in flight".
IN_FLIGHT_STATUSES = (ObservationStatus.PENDING, ObservationStatus.RUNNING)
+# Everything else, derived so the two stay exhaustive and disjoint when a status is added. These rows are
+# sticky, so the (scanner, session) slot they hold is spent: a new scan for the same pair can't be
+# started, only retried (which deletes and re-creates the row).
+TERMINAL_STATUSES = tuple(status for status in ObservationStatus if status not in IN_FLIGHT_STATUSES)
+
class ObservationTrigger(models.TextChoices):
SCHEDULE = "schedule", "Schedule"
diff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.py
index d23facc42cb8..a570f0e5115c 100644
--- a/products/replay_vision/backend/models/replay_scanner.py
+++ b/products/replay_vision/backend/models/replay_scanner.py
@@ -47,6 +47,16 @@ class ScannerModel(models.TextChoices):
GEMINI_3_6_FLASH = "gemini-3.6-flash", "Gemini 3.6 Flash"
+class ScannerOrigin(models.TextChoices):
+ """Where a scanner's config came from, and therefore what the row is allowed to do."""
+
+ # Saved by a user: named, editable, listed, and swept on a schedule.
+ CONFIGURED = "configured", "Configured"
+ # Minted from a config passed inline to a one-off scan (see `inline_scan.py`). Never swept,
+ # never listed, not editable, and reaped once it has nothing to show.
+ INLINE = "inline", "Inline"
+
+
def initial_watermark() -> "datetime":
"""A new scanner's sweep watermark, started one settle-interval back so its first sweep immediately picks up
recordings that have just cleared the settle window instead of a ~settle-interval cold start; it advances
@@ -54,11 +64,30 @@ def initial_watermark() -> "datetime":
return timezone.now() - SETTLE_INTERVAL
+class ReplayScannerManager(models.Manager["ReplayScanner"]):
+ """Fail-closed: `objects` is configured-only, so a new call site can't leak inline scanners.
+
+ Anything that presents, counts, edits, or sweeps a team's scanners wants exactly this. Reading
+ observations back is the one thing that doesn't; go through `scanner_access` for that rather than
+ naming `all_origins` yourself.
+ """
+
+ def get_queryset(self) -> "models.QuerySet[ReplayScanner]":
+ return super().get_queryset().filter(origin=ScannerOrigin.CONFIGURED)
+
+
class ReplayScanner(UUIDModel):
"""A configured probe that gets applied to completed session recordings (see README)."""
+ objects = ReplayScannerManager()
+ all_origins = models.Manager()
+
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")
- name = models.CharField(max_length=255, help_text="Human-readable name. Unique within the team.")
+ name = models.CharField(
+ max_length=255,
+ blank=True,
+ help_text="Human-readable name, unique within the team. Empty for inline scanners, which aren't named.",
+ )
description = models.TextField(
blank=True,
default="",
@@ -92,6 +121,21 @@ class ReplayScanner(UUIDModel):
)
emits_signals = models.BooleanField(default=False)
+ origin = models.CharField(
+ max_length=16,
+ choices=ScannerOrigin.choices,
+ default=ScannerOrigin.CONFIGURED,
+ db_default=ScannerOrigin.CONFIGURED,
+ help_text="Whether a user saved this scanner or an inline scan minted it. See `ScannerOrigin`.",
+ )
+ inline_key = models.CharField(
+ max_length=64,
+ blank=True,
+ default="",
+ db_default="",
+ help_text="Config fingerprint an inline scan resolves by. Empty for configured scanners.",
+ )
+
scanner_version = models.PositiveIntegerField(
default=1,
help_text="Increments on every config-changing save. Observations snapshot the version that produced them.",
@@ -132,8 +176,32 @@ class ReplayScanner(UUIDModel):
updated_at = models.DateTimeField(auto_now=True)
class Meta:
+ # FK traversal and cascades must still see inline scanners; only `objects` is fail-closed.
+ base_manager_name = "all_origins"
constraints = [
- models.UniqueConstraint(fields=["team", "name"], name="replay_scanner_unique_team_name"),
+ # Names are a configured-scanner concept; inline rows have none, and several unnamed
+ # rows per team must be allowed to coexist.
+ models.UniqueConstraint(
+ fields=["team", "name"],
+ condition=models.Q(origin=ScannerOrigin.CONFIGURED),
+ name="replay_scanner_unique_configured_team_name",
+ ),
+ # One inline scanner per team per config, so asking the same question twice reuses the
+ # observations it already has instead of minting a scanner per request.
+ models.UniqueConstraint(
+ fields=["team", "inline_key"],
+ condition=models.Q(origin=ScannerOrigin.INLINE),
+ name="replay_scanner_unique_team_inline_key",
+ ),
+ # The discriminator and the fingerprint have to agree, or `configured()` and the inline
+ # lookup would disagree about the same row.
+ models.CheckConstraint(
+ condition=(
+ models.Q(origin=ScannerOrigin.CONFIGURED, inline_key="")
+ | (models.Q(origin=ScannerOrigin.INLINE) & ~models.Q(inline_key=""))
+ ),
+ name="replay_scanner_inline_key_matches_origin",
+ ),
models.CheckConstraint(
condition=models.Q(sampling_rate__gte=0.0) & models.Q(sampling_rate__lte=1.0),
name="replay_scanner_sampling_rate_range",
@@ -141,6 +209,12 @@ class ReplayScanner(UUIDModel):
]
indexes = [
models.Index(fields=["team", "enabled"], name="rl_team_enabled_idx"),
+ # Serves the reaper's scan for inline scanners that never produced an observation.
+ models.Index(
+ fields=["created_at"],
+ name="rl_inline_created_idx",
+ condition=models.Q(origin=ScannerOrigin.INLINE),
+ ),
]
_VERSION_TRACKED_FIELDS = (
@@ -169,8 +243,9 @@ class ReplayScanner(UUIDModel):
# SELECT FOR UPDATE so concurrent saves can't both bump scanner_version from the same baseline.
with transaction.atomic():
old = (
+ # By-pk, so it must resolve whatever origin the row is; `objects` would miss inline rows.
type(self)
- .objects.select_for_update()
+ .all_origins.select_for_update()
.filter(pk=self.pk)
.only("scanner_version", "enabled", *relevant)
.first()
diff --git a/products/replay_vision/backend/scanner_access.py b/products/replay_vision/backend/scanner_access.py
index 8f41cf2a312a..0399c68f1201 100644
--- a/products/replay_vision/backend/scanner_access.py
+++ b/products/replay_vision/backend/scanner_access.py
@@ -1,6 +1,9 @@
"""Scanner-level RBAC helper shared by the vision-action engine (run-time creator gate) and the
API serializer (write-time editor gate). Lives outside `temporal/` so the API can import it without
-pulling the temporal package onto its import path."""
+pulling the temporal package onto its import path.
+
+Also home to the two queries that read observations back across scanner origins, so `all_origins`
+appears once instead of at every reading call site."""
import uuid
from typing import TYPE_CHECKING
@@ -11,6 +14,8 @@ from posthog.rbac.user_access_control import UserAccessControl
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
if TYPE_CHECKING:
+ from django.db.models import QuerySet
+
from posthog.models.user import User
@@ -22,6 +27,25 @@ def is_uuid(value: str) -> bool:
return True
+def scanners_for_reading_observations(team_id: int) -> "QuerySet[ReplayScanner]":
+ """Every scanner whose observations can be read, inline scans included.
+
+ The one place `all_origins` belongs on a read path. `ReplayScanner.objects` is configured-only so
+ that a new call site can't leak inline scans into a list or a sweep, which leaves exactly one way to
+ get this wrong: a path that reads results and forgets to opt back in, silently hiding an inline
+ scan's answers. Go through this instead of naming the manager, and still apply the caller's own
+ access-level filter on top — this widens origin, not RBAC.
+ """
+ return ReplayScanner.all_origins.filter(team_id=team_id)
+
+
+def scanner_for_reading_observations(team_id: int, scanner_id: "str | uuid.UUID") -> ReplayScanner | None:
+ """Resolve one scanner by id for reading its observations. See `scanners_for_reading_observations`."""
+ if not is_uuid(str(scanner_id)):
+ return None
+ return scanners_for_reading_observations(team_id).filter(id=scanner_id).first()
+
+
def readable_scanner_ids(user: "User", team: Team, scanner_ids: list[str]) -> list[str]:
"""Restrict an action's bound scanner ids to the ones the given user may actually read.
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index 70bfa34e05c3..0c00c34eae1b 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -24,6 +24,7 @@ from products.replay_vision.backend.temporal.activities import (
mark_observation_ineligible_activity,
mark_observation_running_activity,
mark_observation_succeeded_activity,
+ reap_childless_inline_scanners_activity,
reap_orphaned_observations_activity,
reap_stuck_vision_action_runs_activity,
record_evaluation_result_activity,
@@ -91,6 +92,7 @@ ACTIVITIES: list[Callable[..., Any]] = [
delete_scanner_schedule_activity,
list_stale_scanner_estimates_activity,
refresh_scanner_estimate_activity,
+ reap_childless_inline_scanners_activity,
reap_orphaned_observations_activity,
reap_stuck_vision_action_runs_activity,
sweep_gemini_files_activity,
@@ -142,6 +144,7 @@ __all__ = [
"mark_observation_ineligible_activity",
"mark_observation_running_activity",
"mark_observation_succeeded_activity",
+ "reap_childless_inline_scanners_activity",
"reap_orphaned_observations_activity",
"reap_stuck_vision_action_runs_activity",
"record_evaluation_result_activity",
diff --git a/products/replay_vision/backend/temporal/activities/__init__.py b/products/replay_vision/backend/temporal/activities/__init__.py
index 19505d798f68..2e9e7a8c2f27 100644
--- a/products/replay_vision/backend/temporal/activities/__init__.py
+++ b/products/replay_vision/backend/temporal/activities/__init__.py
@@ -29,6 +29,9 @@ from products.replay_vision.backend.temporal.activities.observation_state import
mark_observation_running_activity,
mark_observation_succeeded_activity,
)
+from products.replay_vision.backend.temporal.activities.reap_childless_inline_scanners import (
+ reap_childless_inline_scanners_activity,
+)
from products.replay_vision.backend.temporal.activities.reap_orphaned_observations import (
reap_orphaned_observations_activity,
)
@@ -73,6 +76,7 @@ __all__ = [
"mark_observation_ineligible_activity",
"mark_observation_running_activity",
"mark_observation_succeeded_activity",
+ "reap_childless_inline_scanners_activity",
"reap_orphaned_observations_activity",
"reap_stuck_vision_action_runs_activity",
"record_evaluation_result_activity",
diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.py
index 88706db8477c..630111ea2033 100644
--- a/products/replay_vision/backend/temporal/activities/create_observation.py
+++ b/products/replay_vision/backend/temporal/activities/create_observation.py
@@ -48,7 +48,8 @@ def create_observation_activity(inputs: CreateObservationInputs) -> CreateObserv
def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOutput:
# team__organization is prefetched for the AI-consent check below.
scanner = (
- ReplayScanner.objects.filter(pk=inputs.scanner_id, team_id=inputs.team_id)
+ # `all_origins`: this is the persistence step for every scan, inline ones included.
+ ReplayScanner.all_origins.filter(pk=inputs.scanner_id, team_id=inputs.team_id)
.select_related("team", "team__organization")
.first()
)
diff --git a/products/replay_vision/backend/temporal/activities/reap_childless_inline_scanners.py b/products/replay_vision/backend/temporal/activities/reap_childless_inline_scanners.py
new file mode 100644
index 000000000000..cb2fa08fbd65
--- /dev/null
+++ b/products/replay_vision/backend/temporal/activities/reap_childless_inline_scanners.py
@@ -0,0 +1,63 @@
+"""Deletes inline scanners that never produced an observation.
+
+An inline scan mints a scanner only once something is going to start, but a scan can still fail to
+start after that: the org runs out of quota between the check and the claim, every workflow start
+fails, or the caller retries with a config nobody ever asks about again. Those rows are permanent,
+invisible, and worthless.
+
+Only childless rows are reaped, so this can never delete a result. A row that produced observations is
+somebody's answer to a question and stays until its observations do.
+"""
+
+from django.db.models import Exists, OuterRef
+from django.utils import timezone
+
+from temporalio import activity
+
+from posthog.sync import database_sync_to_async
+
+from products.replay_vision.backend.enqueue_claims import pending_enqueue_claims_for_scanner
+from products.replay_vision.backend.models.replay_observation import ReplayObservation
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerOrigin
+from products.replay_vision.backend.temporal.constants import INLINE_SCANNER_REAP_BATCH_SIZE, INLINE_SCANNER_REAP_GRACE
+from products.replay_vision.backend.temporal.decorators import track_activity
+
+
+@database_sync_to_async
+def _reap_childless_inline_scanners() -> int:
+ # The grace period covers the gap between minting a scanner and its first observation row landing,
+ # which spans a Temporal workflow start and an activity.
+ cutoff = timezone.now() - INLINE_SCANNER_REAP_GRACE
+ candidates = list(
+ ReplayScanner.all_origins.filter(origin=ScannerOrigin.INLINE, created_at__lt=cutoff)
+ .annotate(has_observations=Exists(ReplayObservation.objects.filter(scanner_id=OuterRef("pk"))))
+ .filter(has_observations=False)
+ .values_list("id", flat=True)[:INLINE_SCANNER_REAP_BATCH_SIZE]
+ )
+ if not candidates:
+ return 0
+ # A childless scanner can still have a scan in flight: reuse resolves an old row, starts a workflow,
+ # and the observation only lands once create_observation runs. That gap is what enqueue claims
+ # cover, so a claimed scanner is off limits even though it has nothing to show yet. Without this,
+ # reaping mid-gap deletes the scanner out from under an accepted scan and the workflow fails with
+ # the scanner missing. Candidates are normally empty, so this costs no Redis calls in the common case.
+ unclaimed = [sid for sid in candidates if pending_enqueue_claims_for_scanner(sid) == 0]
+ if not unclaimed:
+ return 0
+ # Re-check emptiness in the DELETE itself: an observation can land between the two statements, and
+ # the FK cascade would take it with the scanner.
+ deleted, _ = (
+ ReplayScanner.all_origins.filter(id__in=unclaimed)
+ .exclude(id__in=ReplayObservation.objects.filter(scanner_id__in=unclaimed).values("scanner_id"))
+ .delete()
+ )
+ return deleted
+
+
+@track_activity()
+async def reap_childless_inline_scanners_activity() -> int:
+ deleted = await _reap_childless_inline_scanners()
+ if deleted:
+ activity.logger.info("Reaped childless inline scanners", extra={"deleted": deleted})
+ return deleted
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index 722420fa386c..a4f69462ca18 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -33,6 +33,12 @@ VISION_ACTION_RUN_STUCK_CUTOFF = PROCESS_VISION_ACTION_EXECUTION_TIMEOUT * 2
REAP_STUCK_VISION_ACTION_RUNS_BATCH_SIZE = 500
REAP_STUCK_VISION_ACTION_RUNS_TIMEOUT = dt.timedelta(minutes=3)
+# An inline scanner is minted just before its scans start, so anything still childless well after a
+# scan could have persisted its first observation never had one.
+INLINE_SCANNER_REAP_GRACE = APPLY_SCANNER_EXECUTION_TIMEOUT + dt.timedelta(minutes=30)
+INLINE_SCANNER_REAP_BATCH_SIZE = 500
+INLINE_SCANNER_REAP_TIMEOUT = dt.timedelta(minutes=3)
+
def build_process_vision_action_workflow_id(vision_action_id: UUID) -> str:
"""Deterministic id: a still-running action is skipped (WorkflowAlreadyStartedError), not double-fired."""
diff --git a/products/replay_vision/backend/temporal/reconciler.py b/products/replay_vision/backend/temporal/reconciler.py
index 221c8ce11e49..cb634cdcc4a8 100644
--- a/products/replay_vision/backend/temporal/reconciler.py
+++ b/products/replay_vision/backend/temporal/reconciler.py
@@ -12,6 +12,7 @@ from temporalio.exceptions import ApplicationError
from posthog.temporal.common.base import PostHogWorkflow
from products.replay_vision.backend.temporal.constants import (
+ INLINE_SCANNER_REAP_TIMEOUT,
LIST_ENABLED_SCANNERS_TIMEOUT,
LIST_SCANNER_SCHEDULES_TIMEOUT,
REAP_ORPHANED_OBSERVATIONS_HEARTBEAT_TIMEOUT,
@@ -40,6 +41,7 @@ with workflow.unsafe.imports_passed_through():
delete_scanner_schedule_activity,
list_enabled_scanners_activity,
list_scanner_schedules_activity,
+ reap_childless_inline_scanners_activity,
reap_orphaned_observations_activity,
reap_stuck_vision_action_runs_activity,
upsert_scanner_schedule_activity,
@@ -76,6 +78,16 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):
except Exception:
workflow.logger.exception("replay_vision.reap_stuck_vision_action_runs_failed")
+ if workflow.patched("reap-childless-inline-scanners-2026-08"):
+ try:
+ await workflow.execute_activity(
+ reap_childless_inline_scanners_activity,
+ start_to_close_timeout=INLINE_SCANNER_REAP_TIMEOUT,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ except Exception:
+ workflow.logger.exception("replay_vision.reap_childless_inline_scanners_failed")
+
# A scanner toggled between the two listings recovers on the next tick.
enabled_entries, existing_entries = await asyncio.gather(
workflow.execute_activity(
diff --git a/products/replay_vision/backend/temporal/schedule.py b/products/replay_vision/backend/temporal/schedule.py
index c93238474aaa..87b1b4b79b8c 100644
--- a/products/replay_vision/backend/temporal/schedule.py
+++ b/products/replay_vision/backend/temporal/schedule.py
@@ -1,7 +1,5 @@
"""Per-scanner Temporal schedule lifecycle helpers."""
-import json
-import hashlib
import datetime as dt
from typing import Any
from uuid import UUID
@@ -32,6 +30,7 @@ from posthog.temporal.common.search_attributes import (
POSTHOG_TEAM_ID_KEY,
)
+from products.replay_vision.backend.fingerprint import SCHEDULE_FINGERPRINT_LENGTH, config_fingerprint
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.temporal.constants import (
SCANNER_SCHEDULE_INTERVAL,
@@ -60,8 +59,7 @@ _FINGERPRINT_FIELDS = (
def compute_schedule_fingerprint(snapshot: dict[str, Any] | None) -> str:
# `sort_keys=True` is recursive over dicts but not lists; assumes JSONField list ordering is stable.
- canonical = json.dumps(snapshot or {}, sort_keys=True, separators=(",", ":"))
- return hashlib.sha256(canonical.encode()).hexdigest()[:16]
+ return config_fingerprint(snapshot, length=SCHEDULE_FINGERPRINT_LENGTH)
def _compute_offset(scanner_id: UUID) -> dt.timedelta:
diff --git a/products/replay_vision/backend/tests/test_access_control.py b/products/replay_vision/backend/tests/test_access_control.py
index 702967afc4d1..2d8fb3a38406 100644
--- a/products/replay_vision/backend/tests/test_access_control.py
+++ b/products/replay_vision/backend/tests/test_access_control.py
@@ -147,6 +147,31 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
allowed = self.client.post(bulk_url, data={"session_ids": ["s1"]}, format="json")
self.assertEqual(allowed.status_code, 202, allowed.json())
+ @patch("products.replay_vision.backend.api.trigger.sync_connect")
+ @patch("products.replay_vision.backend.api.trigger.async_to_sync")
+ def test_inline_scan_requires_resource_level_editor(
+ self, mock_async_to_sync: MagicMock, mock_sync_connect: MagicMock
+ ) -> None:
+ # inline_scan takes no scanner id, so an object-level grant can't narrow it the way it does for
+ # bulk_observe above. Without a resource-level check, editor on any one scanner would let a
+ # user run arbitrary configs and spend the org's credits.
+ mock_sync_connect.return_value = MagicMock()
+ mock_async_to_sync.return_value = MagicMock()
+ scanner = self._create_scanner()
+ self._set_resource_default("replay_scanner", "viewer")
+ inline_url = f"{self.scanners_url}inline_scan/"
+ body = {"session_ids": ["s1"], "prompt": "did the user rage click?"}
+
+ self.client.force_login(self.other_user)
+ self.assertEqual(self.client.post(inline_url, data=body, format="json").status_code, 403)
+
+ # Editor on one specific scanner is what gets bulk_observe through; it must not be enough here.
+ self._grant_object_access(self.other_user, "replay_scanner", str(scanner.id), "editor")
+ self.assertEqual(self.client.post(inline_url, data=body, format="json").status_code, 403)
+
+ self._set_resource_default("replay_scanner", "editor")
+ self.assertEqual(self.client.post(inline_url, data=body, format="json").status_code, 202)
+
def test_estimate_treats_denied_scanner_as_not_found(self) -> None:
# A scanner_id the caller can't view must be rejected the same way as one that doesn't exist —
# otherwise comparing responses (with/without the id) leaks whether it exists and its credit usage.
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 4537792d8259..e09f6730c6e2 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -28,6 +28,7 @@ from products.replay_vision.backend.models.replay_observation_label import Repla
from products.replay_vision.backend.models.replay_scanner import (
ReplayScanner,
ScannerModel,
+ ScannerOrigin,
ScannerProvider,
ScannerType,
)
@@ -1597,6 +1598,31 @@ class TestObserveAction(_VisionAPITestCase):
def observe_url(self, scanner_id: str) -> str:
return f"{self.scanners_url}{scanner_id}/observe/"
+ def test_a_settled_session_returns_the_existing_observation_and_starts_nothing(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # A terminal row owns the (scanner, session) slot for good, so starting a workflow would claim
+ # an enqueue slot and burn a run only to lose the INSERT and hand back this same row.
+ mock_sync_connect.return_value = MagicMock()
+ start_workflow = MagicMock()
+ mock_async_to_sync.return_value = start_workflow
+ existing = ReplayObservation.objects.create(
+ scanner=self.scanner,
+ session_id="sess-settled",
+ scanner_snapshot=_snapshot_for(self.scanner),
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ status=ObservationStatus.SUCCEEDED,
+ completed_at=timezone.now(),
+ )
+
+ resp = self.client.post(
+ self.observe_url(str(self.scanner.id)), data={"session_id": "sess-settled"}, format="json"
+ )
+
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.assertEqual(resp.json()["observation_id"], str(existing.id))
+ start_workflow.assert_not_called()
+
@parameterized.expand(
[
("row_persisted_drops_duplicate_claim", True, 0),
@@ -2643,3 +2669,146 @@ class TestCurrentPeriodBounds(SimpleTestCase):
def test_period_selection(self, _name: str, usage: dict | None, expected: tuple[datetime, datetime]) -> None:
organization = Organization(usage=usage) if usage is not None else None
self.assertEqual(_current_period_bounds(organization, self.NOW), BillingPeriod(*expected))
+
+
+@patch("products.replay_vision.backend.api.trigger.async_to_sync")
+@patch("products.replay_vision.backend.api.trigger.sync_connect")
+class TestInlineScanAction(_VisionAPITestCase):
+ @property
+ def inline_url(self) -> str:
+ return f"{self.scanners_url}inline_scan/"
+
+ def _payload(self, **overrides: Any) -> dict[str, Any]:
+ payload: dict[str, Any] = {"session_ids": ["sess-1"], "prompt": "did the user rage click?"}
+ payload.update(overrides)
+ return payload
+
+ def _scan(self, **overrides: Any):
+ return self.client.post(self.inline_url, data=self._payload(**overrides), format="json")
+
+ def _finished_observation(self, scan_id: str, session_id: str) -> ReplayObservation:
+ # The create activity runs in Temporal, which these tests mock out, so stand the row up directly.
+ scanner = ReplayScanner.all_origins.get(id=scan_id)
+ return ReplayObservation.objects.create(
+ scanner=scanner,
+ session_id=session_id,
+ scanner_snapshot=_snapshot_for(scanner),
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ status=ObservationStatus.SUCCEEDED,
+ completed_at=timezone.now(),
+ )
+
+ def test_same_prompt_reuses_one_scan_and_a_different_prompt_gets_its_own(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # The whole point of keying on the config: re-asking must not mint a second scanner (and so a
+ # second copy of every observation), while a different question must not land in the first's results.
+ mock_sync_connect.return_value = MagicMock()
+ mock_async_to_sync.return_value = MagicMock()
+
+ first = self._scan()
+ again = self._scan(session_ids=["sess-2"])
+ other = self._scan(prompt="did the user rage click twice?")
+
+ self.assertEqual(first.json()["scan_id"], again.json()["scan_id"])
+ self.assertNotEqual(first.json()["scan_id"], other.json()["scan_id"])
+ self.assertEqual(ReplayScanner.all_origins.filter(origin=ScannerOrigin.INLINE).count(), 2)
+
+ def test_a_scan_id_cannot_be_edited_as_a_scanner(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # An editable inline scanner is two bugs: PATCHing scanner_config leaves inline_key pointing at the
+ # old config, and PATCHing enabled turns a row with an empty query into a sweep over every recording.
+ mock_sync_connect.return_value = MagicMock()
+ mock_async_to_sync.return_value = MagicMock()
+ scan_id = self._scan().json()["scan_id"]
+
+ for payload in ({"scanner_config": {"prompt": "something else"}}, {"enabled": True, "sampling_rate": 0.5}):
+ resp = self.client.patch(f"{self.scanners_url}{scan_id}/", data=payload, format="json")
+ self.assertEqual(resp.status_code, 404, resp.content)
+
+ scanner = ReplayScanner.all_origins.get(id=scan_id)
+ self.assertFalse(scanner.enabled)
+ self.assertEqual(scanner.scanner_config, {"prompt": "did the user rage click?"})
+
+ def test_scans_stay_out_of_the_teams_scanner_surfaces(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # A scan is not a scanner the team configured, so it must not show up where they're presented or
+ # counted — including the usage report, which counts through the same default manager.
+ mock_sync_connect.return_value = MagicMock()
+ mock_async_to_sync.return_value = MagicMock()
+ configured = self._create_scanner()
+ scan_id = self._scan().json()["scan_id"]
+
+ listed = self.client.get(self.scanners_url).json()["results"]
+ self.assertEqual([r["id"] for r in listed], [str(configured.id)])
+ self.assertNotIn(scan_id, [r["id"] for r in listed])
+ self.assertEqual(self.client.get(f"{self.scanners_url}stats/").json()["total"], 1)
+
+ def test_a_used_up_quota_starts_nothing_and_leaves_no_scanner_behind(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # Minting before checking headroom means an org over quota accumulates a permanent row per
+ # question it was never able to answer.
+ mock_sync_connect.return_value = MagicMock()
+ start_workflow = MagicMock()
+ mock_async_to_sync.return_value = start_workflow
+
+ with patch("products.replay_vision.backend.quota.MONTHLY_CREDIT_QUOTA", 0):
+ resp = self._scan(session_ids=["sess-1", "sess-2"])
+
+ self.assertEqual(resp.status_code, 202, resp.json())
+ body = resp.json()
+ self.assertIsNone(body["scan_id"])
+ self.assertEqual(body["started"], 0)
+ self.assertEqual([r["scan_outcome"] for r in body["results"]], ["skipped_quota", "skipped_quota"])
+ self.assertFalse(ReplayScanner.all_origins.filter(origin=ScannerOrigin.INLINE).exists())
+ start_workflow.assert_not_called()
+
+ def test_a_finished_session_reports_already_scanned_without_starting_a_workflow(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # A terminal row makes (scanner, session) permanently taken, so starting a workflow would burn a
+ # run only to lose the INSERT and hand back the row we can already see.
+ mock_sync_connect.return_value = MagicMock()
+ start_workflow = MagicMock(return_value=MagicMock())
+ mock_async_to_sync.return_value = start_workflow
+ scan_id = self._scan().json()["scan_id"]
+ self._finished_observation(scan_id, "sess-1")
+ start_workflow.reset_mock()
+
+ resp = self._scan(session_ids=["sess-1", "sess-3"])
+
+ outcomes = {r["session_id"]: r["scan_outcome"] for r in resp.json()["results"]}
+ self.assertEqual(outcomes["sess-1"], "already_scanned")
+ self.assertEqual(outcomes["sess-3"], "started")
+ self.assertEqual(start_workflow.call_count, 1)
+
+ def test_results_are_readable_through_the_scan_id(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # The observations endpoint is the only way back to an inline scan's output, so it has to resolve
+ # a scanner the scanner endpoints deliberately refuse to.
+ mock_sync_connect.return_value = MagicMock()
+ mock_async_to_sync.return_value = MagicMock()
+ scan_id = self._scan().json()["scan_id"]
+ self._finished_observation(scan_id, "sess-1")
+
+ resp = self.client.get(self.observations_url(scan_id))
+ self.assertEqual(resp.status_code, 200, resp.content)
+ self.assertEqual([r["session_id"] for r in resp.json()["results"]], ["sess-1"])
+
+ def test_requires_ai_consent(self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock) -> None:
+ # New call site into the LLM path, so it needs its own consent gate rather than inheriting one.
+ mock_sync_connect.return_value = MagicMock()
+ start_workflow = MagicMock()
+ mock_async_to_sync.return_value = start_workflow
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save()
+
+ resp = self._scan()
+
+ self.assertEqual(resp.status_code, 400, resp.content)
+ self.assertFalse(ReplayScanner.all_origins.filter(origin=ScannerOrigin.INLINE).exists())
+ start_workflow.assert_not_called()
diff --git a/products/replay_vision/backend/tests/test_reconciler.py b/products/replay_vision/backend/tests/test_reconciler.py
index 91ad27e0b5df..d609a6ecfd32 100644
--- a/products/replay_vision/backend/tests/test_reconciler.py
+++ b/products/replay_vision/backend/tests/test_reconciler.py
@@ -20,12 +20,13 @@ from temporalio.testing import ActivityEnvironment
from posthog.models import Organization, Team
from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_FINGERPRINT_KEY
+from products.replay_vision.backend.enqueue_claims import try_claim_enqueue_slot
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
ObservationTrigger,
ReplayObservation,
)
-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerOrigin, ScannerType
from products.replay_vision.backend.models.replay_scanner_prompt_suggestion import (
ReplayScannerPromptSuggestion,
SuggestionStatus,
@@ -36,11 +37,13 @@ from products.replay_vision.backend.temporal.activities import (
delete_scanner_schedule_activity,
list_enabled_scanners_activity,
list_scanner_schedules_activity,
+ reap_childless_inline_scanners_activity,
reap_orphaned_observations_activity,
reap_stuck_vision_action_runs_activity,
upsert_scanner_schedule_activity,
)
from products.replay_vision.backend.temporal.constants import (
+ INLINE_SCANNER_REAP_GRACE,
OBSERVATION_ORPHAN_CUTOFF,
RECONCILER_EXECUTION_TIMEOUT,
RECONCILER_INTERVAL,
@@ -662,3 +665,70 @@ async def test_reap_stuck_vision_action_runs_activity(org_team) -> None:
for key in ("running_open", "describe_error", "too_fresh", "already_completed"):
assert statuses[key].status == rows[key].status, key
assert set(temporal.described) == {"wf-gone-1", "wf-open", "wf-err"}
+
+
+def _make_inline_scanner(team: Team, *, key: str, age: dt.timedelta) -> ReplayScanner:
+ scanner = ReplayScanner.all_origins.create(
+ team=team,
+ name="",
+ origin=ScannerOrigin.INLINE,
+ inline_key=key,
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": f"p-{key}"},
+ model=ScannerModel.GEMINI_3_6_FLASH,
+ enabled=False,
+ sampling_rate=0.0,
+ )
+ ReplayScanner.all_origins.filter(pk=scanner.pk).update(created_at=timezone.now() - age)
+ return scanner
+
+
[email protected]_db(transaction=True)
+async def test_reap_childless_inline_scanners_activity(org_team) -> None:
+ # An inline scan mints a scanner just before its scans start, so a scan that then fails to start
+ # leaves a permanent row nothing lists and nothing collects. Only childless rows go: one that
+ # produced an observation is somebody's answer.
+ _, team = org_team
+ grace = INLINE_SCANNER_REAP_GRACE + dt.timedelta(minutes=5)
+
+ def _setup() -> dict[str, ReplayScanner]:
+ rows = {
+ "childless_old": _make_inline_scanner(team, key="a", age=grace),
+ "childless_but_claimed": _make_inline_scanner(team, key="d", age=grace),
+ "childless_fresh": _make_inline_scanner(team, key="b", age=dt.timedelta(minutes=1)),
+ "has_observation": _make_inline_scanner(team, key="c", age=grace),
+ "configured": _make_scanner(team, name="kept-scanner"),
+ }
+ _make_observation(
+ rows["has_observation"],
+ session_id="s-1",
+ status=ObservationStatus.PENDING,
+ workflow_id="wf-inline",
+ age=dt.timedelta(0),
+ )
+ # A reused scanner whose scan has started but not yet persisted its row holds a claim, and
+ # nothing else distinguishes it from a dead one. Reaping it deletes the scanner out from under
+ # an accepted scan.
+ try_claim_enqueue_slot(
+ team_id=team.id,
+ scanner_id=rows["childless_but_claimed"].id,
+ workflow_id="wf-inflight",
+ team_in_flight_rows=0,
+ scanner_in_flight_rows=0,
+ )
+ # A configured scanner with no observations is not the reaper's business at any age.
+ ReplayScanner.all_origins.filter(pk=rows["configured"].pk).update(created_at=timezone.now() - grace)
+ return rows
+
+ rows = await sync_to_async(_setup)()
+
+ reaped = await ActivityEnvironment().run(reap_childless_inline_scanners_activity)
+
+ assert reaped == 1
+ surviving = await sync_to_async(
+ lambda: set(ReplayScanner.all_origins.values_list("id", flat=True)),
+ )()
+ assert rows["childless_old"].id not in surviving
+ for key in ("childless_fresh", "has_observation", "configured", "childless_but_claimed"):
+ assert rows[key].id in surviving, key
diff --git a/products/replay_vision/backend/tests/test_vision_actions_api.py b/products/replay_vision/backend/tests/test_vision_actions_api.py
index b1a9c8e15087..c3457959b2ef 100644
--- a/products/replay_vision/backend/tests/test_vision_actions_api.py
+++ b/products/replay_vision/backend/tests/test_vision_actions_api.py
@@ -19,7 +19,7 @@ from products.replay_vision.backend.api.vision_actions import (
_redact_webhook_url,
)
from products.replay_vision.backend.models.replay_observation import ReplayObservation
-from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerOrigin, ScannerType
from products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun, VisionActionRunStatus
# The webhook destination template lives in the nodejs registry (no Python source object like Slack's).
@@ -107,6 +107,26 @@ class _VisionActionAPITestCase(APIBaseTest):
class TestVisionActionViewSet(_VisionActionAPITestCase):
+ def test_create_rejects_an_inline_scan_as_the_target(self) -> None:
+ # Binding an action to an inline scan would put a scheduled digest on a row minted for one
+ # throwaway question, and keep it alive past the reaper by giving it observations forever.
+ scan = ReplayScanner.all_origins.create(
+ team=self.team,
+ name="",
+ origin=ScannerOrigin.INLINE,
+ inline_key="k",
+ scanner_type=ScannerType.MONITOR,
+ scanner_config={"prompt": "one-off"},
+ model=ScannerModel.GEMINI_3_6_FLASH,
+ enabled=False,
+ sampling_rate=0.0,
+ )
+
+ resp = self.client.post(self.actions_url, data=self._create_payload(scanner=str(scan.id)), format="json")
+
+ self.assertEqual(resp.status_code, 400, resp.content)
+ self.assertIn("scanner", resp.json()["attr"] or "")
+
def test_create_happy_path(self) -> None:
resp = self.client.post(self.actions_url, data=self._create_payload(), format="json")
self.assertEqual(resp.status_code, 201, resp.content)
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 470343ef1392..ecb18f690ea7 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -1010,8 +1010,9 @@ export interface BulkObserveRequestApi {
/**
* * `started` - Started
* * `already_running` - Already running
- * * `skipped_limit` - Skipped — in-flight limit reached
- * * `skipped_quota` - Skipped — monthly credit quota reached
+ * * `already_scanned` - Already scanned
+ * * `skipped_limit` - Skipped - in-flight limit reached
+ * * `skipped_quota` - Skipped - monthly credit quota reached
* * `failed` - Failed to start
*/
export type ScanOutcomeEnumApi = (typeof ScanOutcomeEnumApi)[keyof typeof ScanOutcomeEnumApi]
@@ -1019,6 +1020,7 @@ export type ScanOutcomeEnumApi = (typeof ScanOutcomeEnumApi)[keyof typeof ScanOu
export const ScanOutcomeEnumApi = {
Started: 'started',
AlreadyRunning: 'already_running',
+ AlreadyScanned: 'already_scanned',
SkippedLimit: 'skipped_limit',
SkippedQuota: 'skipped_quota',
Failed: 'failed',
@@ -1030,12 +1032,13 @@ export const ScanOutcomeEnumApi = {
export interface BulkObserveResultApi {
/** The session recording this outcome is for. */
session_id: string
- /** 'started' — a scan workflow was kicked off; 'already_running' — a scan for this session is already in flight (no-op, not recharged); 'skipped_limit' — the in-flight cap was reached before this session; 'skipped_quota' — the monthly credit quota would be exceeded; 'failed' — the workflow failed to start.
+ /** 'started' - a scan workflow was kicked off; 'already_running' - a scan for this session is already in flight (no-op, not recharged); 'already_scanned' - this scanner already has a finished observation for this session, so nothing was started and nothing was charged (read it back, or use the retry action to run it again); 'skipped_limit' - the in-flight cap was reached before this session; 'skipped_quota' - the monthly credit quota would be exceeded; 'failed' - the workflow failed to start.
*
* * `started` - Started
* * `already_running` - Already running
- * * `skipped_limit` - Skipped — in-flight limit reached
- * * `skipped_quota` - Skipped — monthly credit quota reached
+ * * `already_scanned` - Already scanned
+ * * `skipped_limit` - Skipped - in-flight limit reached
+ * * `skipped_quota` - Skipped - monthly credit quota reached
* * `failed` - Failed to start */
scan_outcome: ScanOutcomeEnumApi
}
@@ -1075,6 +1078,14 @@ export interface ObserveRequestApi {
session_id: string
}
+/**
+ * 200 from POST /vision/scanners/{id}/observe/ - nothing started, the answer already exists.
+ */
+export interface ObserveAlreadyScannedApi {
+ /** The settled observation this scanner already has for the session. Nothing was started and nothing was charged; read it from /vision/scanners/{id}/observations/, or use the retry action on it to scan the session again. */
+ observation_id: string
+}
+
/**
* Async-accepted response for POST /vision/scanners/{id}/observe/.
*/
@@ -1453,6 +1464,53 @@ export interface EstimateResponseApi {
sampling_rate: number
}
+/**
+ * Body of POST /vision/scanners/inline_scan/ - a prompt plus the sessions to point it at.
+ */
+export interface InlineScanRequestApi {
+ /**
+ * Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.
+ * @maxItems 200
+ * @items.maxLength 128
+ */
+ session_ids: string[]
+ /**
+ * What to look for in these sessions, in plain language. The same instruction a saved scanner carries.
+ * @maxLength 20000
+ */
+ prompt: string
+ /** What the scan produces. Defaults to monitor, an open-ended observation against the prompt.
+ *
+ * * `monitor` - Monitor
+ * * `classifier` - Classifier
+ * * `scorer` - Scorer
+ * * `summarizer` - Summarizer */
+ scanner_type?: ScannerTypeEnumApi
+ /** Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here. */
+ scanner_config?: unknown
+ /** Model to scan with. Determines what each observation costs in credits.
+ *
+ * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite
+ * * `gemini-3-flash-preview` - Gemini 3 Flash
+ * * `gemini-3.6-flash` - Gemini 3.6 Flash */
+ model?: ScannerModelEnumApi
+}
+
+/**
+ * `bulk_observe`'s partial-success shape plus the id to read the results back through.
+ */
+export interface InlineScanResponseApi {
+ /** How many new scans were started. */
+ started: number
+ /** Per-session outcomes, in request order (deduplicated). */
+ results: BulkObserveResultApi[]
+ /**
+ * Read results from `/vision/scanners/{scan_id}/observations/`. Stable for a given prompt and model, so asking the same question again returns the same id. Null when nothing was started and nothing existed to read, which happens when the quota is already used up.
+ * @nullable
+ */
+ scan_id: string | null
+}
+
/**
* Per-scanner-type count of enabled vs total scanners.
*/
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index 05911ea22eba..e6c7e7da2c86 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -19,7 +19,10 @@ import type {
EstimateRequestApi,
EstimateResponseApi,
EvaluatePromptSuggestionRequestApi,
+ InlineScanRequestApi,
+ InlineScanResponseApi,
ObservationStatsApi,
+ ObserveAlreadyScannedApi,
ObserveRequestApi,
ObserveResponseApi,
PaginatedReplayObservationListApi,
@@ -599,8 +602,8 @@ export const visionScannersObserveCreate = async (
id: string,
observeRequestApi: ObserveRequestApi,
options?: RequestInit
-): Promise<ObserveResponseApi> => {
- return apiMutator<ObserveResponseApi>(getVisionScannersObserveCreateUrl(projectId, id), {
+): Promise<ObserveAlreadyScannedApi | ObserveResponseApi> => {
+ return apiMutator<ObserveAlreadyScannedApi | ObserveResponseApi>(getVisionScannersObserveCreateUrl(projectId, id), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
@@ -1006,6 +1009,29 @@ export const visionScannersEstimateCreate = async (
})
}
+export const getVisionScannersInlineScanCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/vision/scanners/inline_scan/`
+}
+
+/**
+ * Scan named sessions against a prompt without saving a scanner first, for one-off questions.
+ *
+ * The config resolves to a scanner minted on first use, so asking the same question twice reuses
+ * the observations it already has, while a different question about the same session gets its own.
+ */
+export const visionScannersInlineScanCreate = async (
+ projectId: string,
+ inlineScanRequestApi: InlineScanRequestApi,
+ options?: RequestInit
+): Promise<InlineScanResponseApi> => {
+ return apiMutator<InlineScanResponseApi>(getVisionScannersInlineScanCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(inlineScanRequestApi),
+ })
+}
+
export const getVisionScannersStatsRetrieveUrl = (projectId: string) => {
return `/api/projects/${projectId}/vision/scanners/stats/`
}
diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.ts
index e56c5ee35690..2f5ba6864d93 100644
--- a/products/replay_vision/frontend/generated/api.zod.ts
+++ b/products/replay_vision/frontend/generated/api.zod.ts
@@ -730,6 +730,62 @@ export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
})
.describe('Body of POST \/vision\/scanners\/estimate\/ — a proposed, unsaved scanner config.')
+/**
+ * Scan named sessions against a prompt without saving a scanner first, for one-off questions.
+ *
+ * The config resolves to a scanner minted on first use, so asking the same question twice reuses
+ * the observations it already has, while a different question about the same session gets its own.
+ */
+export const visionScannersInlineScanCreateBodySessionIdsItemMax = 128
+
+export const visionScannersInlineScanCreateBodySessionIdsMax = 200
+
+export const visionScannersInlineScanCreateBodyPromptMax = 20000
+
+export const visionScannersInlineScanCreateBodyScannerTypeDefault = `monitor`
+export const visionScannersInlineScanCreateBodyModelDefault = `gemini-3-flash-preview`
+
+export const VisionScannersInlineScanCreateBody = /* @__PURE__ */ zod
+ .object({
+ session_ids: zod
+ .array(zod.string().max(visionScannersInlineScanCreateBodySessionIdsItemMax))
+ .max(visionScannersInlineScanCreateBodySessionIdsMax)
+ .describe(
+ 'Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.'
+ ),
+ prompt: zod
+ .string()
+ .max(visionScannersInlineScanCreateBodyPromptMax)
+ .describe(
+ 'What to look for in these sessions, in plain language. The same instruction a saved scanner carries.'
+ ),
+ scanner_type: zod
+ .enum(['monitor', 'classifier', 'scorer', 'summarizer'])
+ .describe(
+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ )
+ .default(visionScannersInlineScanCreateBodyScannerTypeDefault)
+ .describe(
+ 'What the scan produces. Defaults to monitor, an open-ended observation against the prompt.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ ),
+ scanner_config: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here.'
+ ),
+ model: zod
+ .enum(['gemini-3.5-flash-lite', 'gemini-3-flash-preview', 'gemini-3.6-flash'])
+ .describe(
+ '\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.6-flash` - Gemini 3.6 Flash'
+ )
+ .default(visionScannersInlineScanCreateBodyModelDefault)
+ .describe(
+ 'Model to scan with. Determines what each observation costs in credits.\n\n\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.6-flash` - Gemini 3.6 Flash'
+ ),
+ })
+ .describe('Body of POST \/vision\/scanners\/inline_scan\/ - a prompt plus the sessions to point it at.')
+
/**
* Suggest classifier tags grounded in the scanner's own observations and the org's product data.
*/
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yaml
index 0b0c6b53aea3..2a25ca689198 100644
--- a/products/replay_vision/mcp/tools.yaml
+++ b/products/replay_vision/mcp/tools.yaml
@@ -405,6 +405,32 @@ tools:
`min_score` and/or `max_score`. `sessions_without_user` reports affected sessions that carried no distinct
ID, so the user count reads honestly against the session count.
feature_flag: replay-vision
+ vision-scanners-inline-scan-create:
+ operation: vision_scanners_inline_scan_create
+ enabled: true
+ scopes:
+ - replay_scanner:write
+ - session_recording:read
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ title: Scan sessions against a prompt
+ description: >
+ Answer a one-off question about session recordings you already have in hand, without creating a scanner
+ first. Pass the `session_ids` and a `prompt`; nothing is saved and nothing runs on a schedule. Prefer this
+ over `vision-scanners-create` whenever you have specific sessions and a question about them — a scanner is
+ for a standing watch over future recordings, and creating one to answer a single question leaves a scheduled
+ sweep behind. `scanner_type` defaults to `monitor` (open-ended); pass `classifier`, `scorer`, or
+ `summarizer` with the matching `scanner_config` (`tags`, `scale`, optional `length`) when you want
+ structured output. Results are not returned inline: the response gives a `scan_id`, and you read the
+ observations from `vision-observations-list` with that scanner id, polling until each session's observation
+ leaves `pending`/`running`. Asking the same question again returns the same `scan_id` and reuses the answers
+ it already has, so re-asking is cheap and sessions already scanned come back as `already_scanned` rather
+ than being charged twice. Scans cost credits per session at the same rate a scanner does; check
+ `vision-quota-retrieve` first if the batch is large, since sessions past the monthly limit come back as
+ `skipped_quota` instead of failing the call.
+ feature_flag: replay-vision
vision-scanners-list:
operation: vision_scanners_list
enabled: true
diff --git a/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md b/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md
index ce55398001e7..b53e68248903 100644
--- a/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md
+++ b/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md
@@ -1,6 +1,6 @@
---
name: creating-replay-vision-scanners
-description: "Guides agents through creating and safely sizing a Replay Vision scanner: choosing the scanner type (monitor/classifier/scorer/summarizer), shaping the RecordingsQuery that selects sessions, and — crucially — estimating observation volume and checking the org's monthly quota before creating, so a broad scanner doesn't exhaust the budget on its first scheduled sweep.\nTRIGGER when: user asks to create, set up, or configure a Replay Vision scanner, OR when you are about to call vision-scanners-create, OR when widening an existing scanner's query or sampling_rate via vision-scanners-update.\nDO NOT TRIGGER when: only reading scanners or observations, deleting a scanner, or running an existing scanner against a single session on demand (vision-scanners-scan-session)."
+description: "Guides agents through creating and safely sizing a Replay Vision scanner: choosing the scanner type (monitor/classifier/scorer/summarizer), shaping the RecordingsQuery that selects sessions, and — crucially — estimating observation volume and checking the org's monthly quota before creating, so a broad scanner doesn't exhaust the budget on its first scheduled sweep.\nTRIGGER when: user asks to create, set up, or configure a Replay Vision scanner, OR when you are about to call vision-scanners-create, OR when widening an existing scanner's query or sampling_rate via vision-scanners-update.\nDO NOT TRIGGER when: only reading scanners or observations, deleting a scanner, or running an existing scanner against a single session on demand (vision-scanners-scan-session). For a one-off question about sessions you already have, use vision-scanners-inline-scan-create rather than creating a scanner — the skill's first section covers when that applies."
---
# Creating Replay Vision scanners
@@ -16,6 +16,22 @@ starts consuming quota automatically and can drain the whole month's budget with
Creation itself does **not** check quota — that protection only kicks in at observation time, by which point
the budget may already be gone.
+## First: is a scanner even the right thing?
+
+A scanner is a **standing watch over future recordings**. If the user has specific sessions in front of them
+and a question about those sessions, they don't want a scanner at all — they want `vision-scanners-inline-scan-create`,
+which takes `session_ids` plus a `prompt`, saves nothing, and schedules nothing.
+
+Use an inline scan when the sessions are already known: "what went wrong in these five recordings", "did any
+of yesterday's checkout sessions hit the coupon bug", anything you'd otherwise answer by creating a scanner
+and deleting it afterwards. It costs the same credits per session and reuses answers when the same question
+is asked twice, so re-asking is cheap.
+
+Create a scanner only when the user wants recordings that **haven't happened yet** to be scanned automatically.
+If you find yourself planning to create a scanner, read its results once, and delete it, stop and run an
+inline scan instead — a throwaway scanner leaves a scheduled sweep running against every future recording that
+matches its query.
+
## Core principle: size before you ship
Never create an enabled scanner blind. Estimate its monthly credit spend, check the remaining credit budget,
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index d910eeabebc4..1cf66f04bd9e 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -10559,6 +10559,21 @@
},
"feature_flag": "replay-vision"
},
+ "vision-scanners-inline-scan-create": {
+ "description": "Answer a one-off question about session recordings you already have in hand, without creating a scanner first. Pass the `session_ids` and a `prompt`; nothing is saved and nothing runs on a schedule. Prefer this over `vision-scanners-create` whenever you have specific sessions and a question about them — a scanner is for a standing watch over future recordings, and creating one to answer a single question leaves a scheduled sweep behind. `scanner_type` defaults to `monitor` (open-ended); pass `classifier`, `scorer`, or `summarizer` with the matching `scanner_config` (`tags`, `scale`, optional `length`) when you want structured output. Results are not returned inline: the response gives a `scan_id`, and you read the observations from `vision-observations-list` with that scanner id, polling until each session's observation leaves `pending`/`running`. Asking the same question again returns the same `scan_id` and reuses the answers it already has, so re-asking is cheap and sessions already scanned come back as `already_scanned` rather than being charged twice. Scans cost credits per session at the same rate a scanner does; check `vision-quota-retrieve` first if the batch is large, since sessions past the monthly limit come back as `skipped_quota` instead of failing the call.",
+ "category": "Replay vision",
+ "feature": "replay_vision",
+ "summary": "Scan sessions against a prompt",
+ "title": "Scan sessions against a prompt",
+ "required_scopes": ["replay_scanner:write", "session_recording:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "replay-vision"
+ },
"vision-scanners-list": {
"description": "List all replay vision scanners in the current project. A scanner watches a slice of session recordings (defined by its `query` and `sampling_rate`) and runs one of four LLM analyses against each matching session: `monitor` (open-ended observations), `classifier` (tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary, with facet embeddings for downstream search). Each scanner returns its current configuration, enabled state, sampling rate, and `last_swept_at` timestamp.",
"category": "Replay vision",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 4b773828e547..1983bb6829f8 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -11199,6 +11199,21 @@
},
"feature_flag": "replay-vision"
},
+ "vision-scanners-inline-scan-create": {
+ "description": "Answer a one-off question about session recordings you already have in hand, without creating a scanner first. Pass the `session_ids` and a `prompt`; nothing is saved and nothing runs on a schedule. Prefer this over `vision-scanners-create` whenever you have specific sessions and a question about them — a scanner is for a standing watch over future recordings, and creating one to answer a single question leaves a scheduled sweep behind. `scanner_type` defaults to `monitor` (open-ended); pass `classifier`, `scorer`, or `summarizer` with the matching `scanner_config` (`tags`, `scale`, optional `length`) when you want structured output. Results are not returned inline: the response gives a `scan_id`, and you read the observations from `vision-observations-list` with that scanner id, polling until each session's observation leaves `pending`/`running`. Asking the same question again returns the same `scan_id` and reuses the answers it already has, so re-asking is cheap and sessions already scanned come back as `already_scanned` rather than being charged twice. Scans cost credits per session at the same rate a scanner does; check `vision-quota-retrieve` first if the batch is large, since sessions past the monthly limit come back as `skipped_quota` instead of failing the call.",
+ "category": "Replay vision",
+ "feature": "replay_vision",
+ "summary": "Scan sessions against a prompt",
+ "title": "Scan sessions against a prompt",
+ "required_scopes": ["replay_scanner:write", "session_recording:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "replay-vision"
+ },
"vision-scanners-list": {
"description": "List all replay vision scanners in the current project. A scanner watches a slice of session recordings (defined by its `query` and `sampling_rate`) and runs one of four LLM analyses against each matching session: `monitor` (open-ended observations), `classifier` (tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary, with facet embeddings for downstream search). Each scanner returns its current configuration, enabled state, sampling rate, and `last_swept_at` timestamp.",
"category": "Replay vision",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 05fb3255c590..76a86ae52749 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -12753,8 +12753,9 @@ export namespace Schemas {
/**
* * `started` - Started
* * `already_running` - Already running
- * * `skipped_limit` - Skipped — in-flight limit reached
- * * `skipped_quota` - Skipped — monthly credit quota reached
+ * * `already_scanned` - Already scanned
+ * * `skipped_limit` - Skipped - in-flight limit reached
+ * * `skipped_quota` - Skipped - monthly credit quota reached
* * `failed` - Failed to start
*/
export type ScanOutcomeEnum = typeof ScanOutcomeEnum[keyof typeof ScanOutcomeEnum];
@@ -12763,6 +12764,7 @@ export namespace Schemas {
export const ScanOutcomeEnum = {
Started: 'started',
AlreadyRunning: 'already_running',
+ AlreadyScanned: 'already_scanned',
SkippedLimit: 'skipped_limit',
SkippedQuota: 'skipped_quota',
Failed: 'failed',
@@ -12774,12 +12776,13 @@ export namespace Schemas {
export interface BulkObserveResult {
/** The session recording this outcome is for. */
session_id: string;
- /** 'started' — a scan workflow was kicked off; 'already_running' — a scan for this session is already in flight (no-op, not recharged); 'skipped_limit' — the in-flight cap was reached before this session; 'skipped_quota' — the monthly credit quota would be exceeded; 'failed' — the workflow failed to start.
+ /** 'started' - a scan workflow was kicked off; 'already_running' - a scan for this session is already in flight (no-op, not recharged); 'already_scanned' - this scanner already has a finished observation for this session, so nothing was started and nothing was charged (read it back, or use the retry action to run it again); 'skipped_limit' - the in-flight cap was reached before this session; 'skipped_quota' - the monthly credit quota would be exceeded; 'failed' - the workflow failed to start.
*
* * `started` - Started
* * `already_running` - Already running
- * * `skipped_limit` - Skipped — in-flight limit reached
- * * `skipped_quota` - Skipped — monthly credit quota reached
+ * * `already_scanned` - Already scanned
+ * * `skipped_limit` - Skipped - in-flight limit reached
+ * * `skipped_quota` - Skipped - monthly credit quota reached
* * `failed` - Failed to start */
scan_outcome: ScanOutcomeEnum;
}
@@ -38801,6 +38804,69 @@ export namespace Schemas {
samples: IngestionWarningV2Sample[];
}
+ /**
+ * * `monitor` - Monitor
+ * * `classifier` - Classifier
+ * * `scorer` - Scorer
+ * * `summarizer` - Summarizer
+ */
+ export type ScannerTypeEnum = typeof ScannerTypeEnum[keyof typeof ScannerTypeEnum];
+
+
+ export const ScannerTypeEnum = {
+ Monitor: 'monitor',
+ Classifier: 'classifier',
+ Scorer: 'scorer',
+ Summarizer: 'summarizer',
+ } as const;
+
+ /**
+ * Body of POST /vision/scanners/inline_scan/ - a prompt plus the sessions to point it at.
+ */
+ export interface InlineScanRequest {
+ /**
+ * Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.
+ * @maxItems 200
+ * @items.maxLength 128
+ */
+ session_ids: string[];
+ /**
+ * What to look for in these sessions, in plain language. The same instruction a saved scanner carries.
+ * @maxLength 20000
+ */
+ prompt: string;
+ /** What the scan produces. Defaults to monitor, an open-ended observation against the prompt.
+ *
+ * * `monitor` - Monitor
+ * * `classifier` - Classifier
+ * * `scorer` - Scorer
+ * * `summarizer` - Summarizer */
+ scanner_type?: ScannerTypeEnum;
+ /** Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here. */
+ scanner_config?: unknown;
+ /** Model to scan with. Determines what each observation costs in credits.
+ *
+ * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite
+ * * `gemini-3-flash-preview` - Gemini 3 Flash
+ * * `gemini-3.6-flash` - Gemini 3.6 Flash */
+ model?: ScannerModelEnum;
+ }
+
+ /**
+ * `bulk_observe`'s partial-success shape plus the id to read the results back through.
+ */
+ export interface InlineScanResponse {
+ /** How many new scans were started. */
+ started: number;
+ /** Per-session outcomes, in request order (deduplicated). */
+ results: BulkObserveResult[];
+ /**
+ * Read results from `/vision/scanners/{scan_id}/observations/`. Stable for a given prompt and model, so asking the same question again returns the same id. Null when nothing was started and nothing existed to read, which happens when the quota is already used up.
+ * @nullable
+ */
+ scan_id: string | null;
+ }
+
export interface InsightBulkDeleteRequest {
/**
* Insight IDs to soft-delete (or restore). At most 1000 ids per request. Soft-deleted insights can be brought back via the bulk_restore endpoint.
@@ -44111,6 +44177,14 @@ export namespace Schemas {
Retry: 'retry',
} as const;
+ /**
+ * 200 from POST /vision/scanners/{id}/observe/ - nothing started, the answer already exists.
+ */
+ export interface ObserveAlreadyScanned {
+ /** The settled observation this scanner already has for the session. Nothing was started and nothing was charged; read it from /vision/scanners/{id}/observations/, or use the retry action on it to scan the session again. */
+ observation_id: string;
+ }
+
/**
* Body of POST /vision/scanners/{id}/observe/.
*/
@@ -46696,22 +46770,6 @@ export namespace Schemas {
results: Reminder[];
}
- /**
- * * `monitor` - Monitor
- * * `classifier` - Classifier
- * * `scorer` - Scorer
- * * `summarizer` - Summarizer
- */
- export type ScannerTypeEnum = typeof ScannerTypeEnum[keyof typeof ScannerTypeEnum];
-
-
- export const ScannerTypeEnum = {
- Monitor: 'monitor',
- Classifier: 'classifier',
- Scorer: 'scorer',
- Summarizer: 'summarizer',
- } as const;
-
/**
* Mirrors `temporal.types.ScannerSnapshot` for OpenAPI generation.
*/
diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.ts
index 2b20b8145bad..359dc25f1572 100644
--- a/services/mcp/src/generated/replay_vision/api.ts
+++ b/services/mcp/src/generated/replay_vision/api.ts
@@ -3,7 +3,7 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 28 enabled ops
+ * PostHog API - MCP 29 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
@@ -1248,3 +1248,67 @@ export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod
),
})
.describe('Body of POST \/vision\/scanners\/estimate\/ — a proposed, unsaved scanner config.')
+
+/**
+ * Scan named sessions against a prompt without saving a scanner first, for one-off questions.
+ *
+ * The config resolves to a scanner minted on first use, so asking the same question twice reuses
+ * the observations it already has, while a different question about the same session gets its own.
+ */
+export const VisionScannersInlineScanCreateParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."
+ ),
+})
+
+export const visionScannersInlineScanCreateBodySessionIdsItemMax = 128
+
+export const visionScannersInlineScanCreateBodySessionIdsMax = 200
+
+export const visionScannersInlineScanCreateBodyPromptMax = 20000
+
+export const visionScannersInlineScanCreateBodyScannerTypeDefault = `monitor`
+export const visionScannersInlineScanCreateBodyModelDefault = `gemini-3-flash-preview`
+
+export const VisionScannersInlineScanCreateBody = /* @__PURE__ */ zod
+ .object({
+ session_ids: zod
+ .array(zod.string().max(visionScannersInlineScanCreateBodySessionIdsItemMax))
+ .max(visionScannersInlineScanCreateBodySessionIdsMax)
+ .describe(
+ 'Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.'
+ ),
+ prompt: zod
+ .string()
+ .max(visionScannersInlineScanCreateBodyPromptMax)
+ .describe(
+ 'What to look for in these sessions, in plain language. The same instruction a saved scanner carries.'
+ ),
+ scanner_type: zod
+ .enum(['monitor', 'classifier', 'scorer', 'summarizer'])
+ .describe(
+ '\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ )
+ .default(visionScannersInlineScanCreateBodyScannerTypeDefault)
+ .describe(
+ 'What the scan produces. Defaults to monitor, an open-ended observation against the prompt.\n\n\* `monitor` - Monitor\n\* `classifier` - Classifier\n\* `scorer` - Scorer\n\* `summarizer` - Summarizer'
+ ),
+ scanner_config: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here.'
+ ),
+ model: zod
+ .enum(['gemini-3.5-flash-lite', 'gemini-3-flash-preview', 'gemini-3.6-flash'])
+ .describe(
+ '\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.6-flash` - Gemini 3.6 Flash'
+ )
+ .default(visionScannersInlineScanCreateBodyModelDefault)
+ .describe(
+ 'Model to scan with. Determines what each observation costs in credits.\n\n\* `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite\n\* `gemini-3-flash-preview` - Gemini 3 Flash\n\* `gemini-3.6-flash` - Gemini 3.6 Flash'
+ ),
+ })
+ .describe('Body of POST \/vision\/scanners\/inline_scan\/ - a prompt plus the sessions to point it at.')
diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.ts
index b18eb5385db0..fa96ea758096 100644
--- a/services/mcp/src/tools/generated/replay_vision.ts
+++ b/services/mcp/src/tools/generated/replay_vision.ts
@@ -25,6 +25,7 @@ import {
VisionScannersEstimateCreateBody,
VisionScannersImpactRetrieveParams,
VisionScannersImpactRetrieveQueryParams,
+ VisionScannersInlineScanCreateBody,
VisionScannersListQueryParams,
VisionScannersObservationsListParams,
VisionScannersObservationsListQueryParams,
@@ -547,6 +548,38 @@ const visionScannersImpactRetrieve = (): ToolBase<
},
})
+const VisionScannersInlineScanCreateSchema = VisionScannersInlineScanCreateBody
+
+const visionScannersInlineScanCreate = (): ToolBase<typeof VisionScannersInlineScanCreateSchema, unknown> => ({
+ name: 'vision-scanners-inline-scan-create',
+ schema: VisionScannersInlineScanCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof VisionScannersInlineScanCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.session_ids !== undefined) {
+ body['session_ids'] = params.session_ids
+ }
+ if (params.prompt !== undefined) {
+ body['prompt'] = params.prompt
+ }
+ if (params.scanner_type !== undefined) {
+ body['scanner_type'] = params.scanner_type
+ }
+ if (params.scanner_config !== undefined) {
+ body['scanner_config'] = params.scanner_config
+ }
+ if (params.model !== undefined) {
+ body['model'] = params.model
+ }
+ const result = await context.api.request<unknown>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/inline_scan/`,
+ body,
+ })
+ return result
+ },
+})
+
const VisionScannersListSchema = VisionScannersListQueryParams
const visionScannersList = (): ToolBase<
@@ -779,7 +812,10 @@ const VisionScannersScanSessionSchema = VisionScannersObserveCreateParams.omit({
VisionScannersObserveCreateBody.shape
)
-const visionScannersScanSession = (): ToolBase<typeof VisionScannersScanSessionSchema, unknown> => ({
+const visionScannersScanSession = (): ToolBase<
+ typeof VisionScannersScanSessionSchema,
+ Schemas.ObserveAlreadyScanned
+> => ({
name: 'vision-scanners-scan-session',
schema: VisionScannersScanSessionSchema,
handler: async (context: Context, params: z.infer<typeof VisionScannersScanSessionSchema>) => {
@@ -788,7 +824,7 @@ const visionScannersScanSession = (): ToolBase<typeof VisionScannersScanSessionS
if (params.session_id !== undefined) {
body['session_id'] = params.session_id
}
- const result = await context.api.request<unknown>({
+ const result = await context.api.request<Schemas.ObserveAlreadyScanned>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/vision/scanners/${encodeURIComponent(String(params.id))}/observe/`,
body,
@@ -868,6 +904,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'vision-scanners-estimate-create': visionScannersEstimateCreate,
'vision-scanners-get': visionScannersGet,
'vision-scanners-impact-retrieve': visionScannersImpactRetrieve,
+ 'vision-scanners-inline-scan-create': visionScannersInlineScanCreate,
'vision-scanners-list': visionScannersList,
'vision-scanners-observations-get': visionScannersObservationsGet,
'vision-scanners-observations-list': visionScannersObservationsList,