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): export gemini storage, cleanup sweep and in-flight backlog metrics (#113372)

Tue Haulundc8f3fb1a235d
diff --git a/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py b/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
index 3980efdf5058..421f84a80efb 100644
--- a/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
+++ b/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
@@ -4,6 +4,8 @@ from datetime import UTC, datetime
from typing import Any, cast
from uuid import UUID
+from django.db.models import Count, Min
+
import structlog
from temporalio import activity
from temporalio.client import Client
@@ -11,7 +13,11 @@ from temporalio.client import Client
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 (
+ IN_FLIGHT_STATUSES,
+ ObservationStatus,
+ ReplayObservation,
+)
from products.replay_vision.backend.temporal.activities.observation_state import mark_observation_terminal
from products.replay_vision.backend.temporal.activities.reaping import classify_stale_rows
from products.replay_vision.backend.temporal.constants import (
@@ -21,7 +27,7 @@ from products.replay_vision.backend.temporal.constants import (
)
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.errors import FailureKind
-from products.replay_vision.backend.temporal.metrics import record_failure_kind
+from products.replay_vision.backend.temporal.metrics import push_in_flight_observation_gauges, record_failure_kind
from products.replay_vision.backend.temporal.query_budget import bounded_queries
logger = structlog.get_logger(__name__)
@@ -30,6 +36,21 @@ _LIVE_STATUSES = (ObservationStatus.PENDING, ObservationStatus.RUNNING)
_ORPHANED_ERROR_REASON = f"{FailureKind.ORPHANED.value}:The analysis stopped without recording an outcome."
+def _measure_in_flight() -> None:
+ """Report how many observations are pending or running and how old the oldest is, so a growing queue
+ shows before rows reach the orphan cutoff."""
+ now = datetime.now(UTC)
+ with bounded_queries(REAP_ORPHANED_OBSERVATIONS_HEARTBEAT_TIMEOUT):
+ rows = {
+ row["status"]: (row["count"], (now - row["oldest"]).total_seconds())
+ for row in ReplayObservation.objects.filter(status__in=IN_FLIGHT_STATUSES)
+ .order_by()
+ .values("status")
+ .annotate(count=Count("id"), oldest=Min("created_at"))
+ }
+ push_in_flight_observation_gauges({status.value: rows.get(status, (0, 0.0)) for status in IN_FLIGHT_STATUSES})
+
+
def _list_stale_observations() -> list[dict[str, Any]]:
cutoff = datetime.now(UTC) - OBSERVATION_ORPHAN_CUTOFF
# The listing runs before the first heartbeat, so the heartbeat timeout ends a slow attempt.
@@ -84,6 +105,10 @@ async def reap_orphaned_observations_activity() -> int:
The describe check protects rows reclaimed by a live re-trigger of the same deterministic workflow id.
"""
+ try:
+ await database_sync_to_async(_measure_in_flight, thread_sensitive=False)()
+ except Exception:
+ logger.exception("replay_vision.reap_orphaned_observations.measure_in_flight_failed")
rows = await database_sync_to_async(_list_stale_observations, thread_sensitive=False)()
if not rows:
return 0
diff --git a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/activities.py b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/activities.py
index fbfd4ec334ff..a8964d59ff37 100644
--- a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/activities.py
+++ b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/activities.py
@@ -1,5 +1,6 @@
import asyncio
from datetime import UTC, datetime
+from itertools import islice
import structlog
from google.genai import Client as RawGenAIClient
@@ -16,6 +17,8 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep.constants impo
DELETE_CONCURRENCY,
DESCRIBE_CONCURRENCY,
MAX_FILES_PER_SWEEP,
+ MAX_STORAGE_LIST_FILES,
+ STORAGE_LIST_PAGE_SIZE,
SWEEP_MIN_AGE,
)
from products.replay_vision.backend.temporal.gemini_cleanup_sweep.tracking import (
@@ -26,12 +29,22 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep.tracking impor
from products.replay_vision.backend.temporal.gemini_cleanup_sweep.types import (
CleanupSweepInputs,
CleanupSweepResult,
+ GeminiStorageUsage,
TrackedFile,
)
-from products.replay_vision.backend.temporal.metrics import record_gemini_cleanup_backlog
+from products.replay_vision.backend.temporal.metrics import push_gemini_cleanup_gauges, record_gemini_cleanup_files
logger = structlog.get_logger(__name__)
+_FILE_RESULTS = (
+ "deleted",
+ "delete_failed",
+ "skipped_running",
+ "skipped_too_young",
+ "skipped_temporal_error",
+ "skipped_invalid_value",
+)
+
_TERMINAL_STATUSES = frozenset(
{
WorkflowExecutionStatus.COMPLETED,
@@ -74,7 +87,6 @@ async def _sweep_gemini_files(inputs: CleanupSweepInputs) -> CleanupSweepResult:
cutoff = datetime.now(UTC) - SWEEP_MIN_AGE
total_tracked = await index_size()
- record_gemini_cleanup_backlog(total_tracked)
hit_max_files_cap = total_tracked > MAX_FILES_PER_SWEEP
scanned = 0
@@ -132,7 +144,11 @@ async def _sweep_gemini_files(inputs: CleanupSweepInputs) -> CleanupSweepResult:
deleted = sum(1 for r in delete_results if r)
delete_failed = sum(1 for r in delete_results if not r)
- result = base_result.model_copy(update={"deleted": deleted, "delete_failed": delete_failed})
+ storage = await _measure_storage(raw_client)
+ result = base_result.model_copy(update={"deleted": deleted, "delete_failed": delete_failed, "storage": storage})
+ for name in _FILE_RESULTS:
+ record_gemini_cleanup_files(name, getattr(result, name))
+ await asyncio.to_thread(push_gemini_cleanup_gauges, total_tracked, storage)
logger.info(
"replay_vision.cleanup_sweep.cycle_complete",
scanned=result.scanned,
@@ -143,6 +159,46 @@ async def _sweep_gemini_files(inputs: CleanupSweepInputs) -> CleanupSweepResult:
skipped_temporal_error=result.skipped_temporal_error,
delete_failed=result.delete_failed,
hit_max_files_cap=result.hit_max_files_cap,
+ storage=storage.model_dump() if storage else None,
signals_type="cleanup-sweep",
)
return result
+
+
+def _list_storage(raw_client: RawGenAIClient) -> GeminiStorageUsage:
+ now = datetime.now(UTC)
+ files = 0
+ total_bytes = 0
+ oldest_created_at = now
+ for file in islice(raw_client.files.list(config={"page_size": STORAGE_LIST_PAGE_SIZE}), MAX_STORAGE_LIST_FILES):
+ files += 1
+ total_bytes += file.size_bytes or 0
+ if file.create_time and file.create_time < oldest_created_at:
+ oldest_created_at = file.create_time
+ return GeminiStorageUsage(
+ files=files,
+ total_bytes=total_bytes,
+ oldest_age_seconds=(now - oldest_created_at).total_seconds(),
+ truncated=files == MAX_STORAGE_LIST_FILES,
+ )
+
+
+async def _measure_storage(raw_client: RawGenAIClient) -> GeminiStorageUsage | None:
+ """Lists every file in the Gemini project, which is what counts against its storage quota.
+
+ The Redis index only knows files whose tracking write succeeded, so this listing also sees the files
+ the sweep can never reach. A failed listing returns None and never fails the sweep.
+ """
+ try:
+ storage = await asyncio.to_thread(_list_storage, raw_client)
+ except Exception:
+ logger.exception("replay_vision.cleanup_sweep.storage_list_failed", signals_type="cleanup-sweep")
+ return None
+ activity.heartbeat({"phase": "storage_listed", "files": storage.files})
+ if storage.truncated:
+ logger.warning(
+ "replay_vision.cleanup_sweep.storage_list_truncated",
+ max_files=MAX_STORAGE_LIST_FILES,
+ signals_type="cleanup-sweep",
+ )
+ return storage
diff --git a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/constants.py b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/constants.py
index 0eeaa51bff1e..0d0a3d5b083c 100644
--- a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/constants.py
+++ b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/constants.py
@@ -19,6 +19,10 @@ SWEEP_MIN_AGE = timedelta(seconds=60)
MAX_FILES_PER_SWEEP = 1500
MGET_BATCH_SIZE = 200
+# The Files API caps a page at 100 files. The cap bounds a listing when files leak and pile up.
+STORAGE_LIST_PAGE_SIZE = 100
+MAX_STORAGE_LIST_FILES = 5000
+
DESCRIBE_CONCURRENCY = 20
DELETE_CONCURRENCY = 10
diff --git a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/types.py b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/types.py
index 568b04d9b095..99f2f2c73768 100644
--- a/products/replay_vision/backend/temporal/gemini_cleanup_sweep/types.py
+++ b/products/replay_vision/backend/temporal/gemini_cleanup_sweep/types.py
@@ -7,6 +7,13 @@ class CleanupSweepInputs(BaseModel, frozen=True):
pass
+class GeminiStorageUsage(BaseModel, frozen=True):
+ files: int
+ total_bytes: int
+ oldest_age_seconds: float
+ truncated: bool
+
+
class CleanupSweepResult(BaseModel, frozen=True):
scanned: int = 0
deleted: int = 0
@@ -16,6 +23,7 @@ class CleanupSweepResult(BaseModel, frozen=True):
skipped_invalid_value: int = 0
delete_failed: int = 0
hit_max_files_cap: bool = False
+ storage: GeminiStorageUsage | None = None
class TrackedFile(BaseModel, frozen=True):
diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.py
index 06499fccb1ed..b5ac60f44a4c 100644
--- a/products/replay_vision/backend/temporal/metrics.py
+++ b/products/replay_vision/backend/temporal/metrics.py
@@ -8,10 +8,17 @@ The twin derives its name and description from the prom instrument, and its reco
is swallowed so telemetry can never fail an activity.
"""
+import time
+from typing import TYPE_CHECKING
+
from prometheus_client import Counter, Gauge, Histogram
+from posthog.metrics import pushed_metrics_registry
from posthog.otel_metrics import OtelInstrumentFactory
+if TYPE_CHECKING:
+ from products.replay_vision.backend.temporal.gemini_cleanup_sweep.types import GeminiStorageUsage
+
_otel = OtelInstrumentFactory("replay-vision")
REPLAY_VISION_OBSERVATIONS = Counter(
@@ -198,9 +205,10 @@ REPLAY_VISION_ESTIMATE_OUTCOMES = Counter(
["outcome"],
)
-REPLAY_VISION_GEMINI_CLEANUP_BACKLOG = Gauge(
- "replay_vision_gemini_cleanup_backlog",
- "Tracked Gemini files awaiting cleanup (a growing backlog means the sweep is losing)",
+REPLAY_VISION_GEMINI_CLEANUP_FILES = Counter(
+ "replay_vision_gemini_cleanup_files_total",
+ "Tracked Gemini files the cleanup sweep looked at, by result",
+ ["result"],
)
@@ -358,9 +366,73 @@ def record_enqueue_claim_failure(operation: str) -> None:
_otel.record_counter_twin(REPLAY_VISION_ENQUEUE_CLAIM_FAILURES, 1, {"operation": operation})
-def record_gemini_cleanup_backlog(count: int) -> None:
- REPLAY_VISION_GEMINI_CLEANUP_BACKLOG.set(count)
- _otel.record_gauge_twin(REPLAY_VISION_GEMINI_CLEANUP_BACKLOG, count)
+def record_gemini_cleanup_files(result: str, count: int) -> None:
+ if count <= 0:
+ return
+ REPLAY_VISION_GEMINI_CLEANUP_FILES.labels(result=result).inc(count)
+ _otel.record_counter_twin(REPLAY_VISION_GEMINI_CLEANUP_FILES, count, {"result": result})
+
+
+# Singleton schedules push their gauges, so each region holds one series per gauge. A scraped gauge would keep
+# exporting, from every pod that ever ran the job, the value that pod last saw. The Pushgateway takes only
+# Prometheus metrics, so these gauges have no OTLP twin.
+
+
+def push_gemini_cleanup_gauges(tracked_files: int, storage: "GeminiStorageUsage | None") -> None:
+ """Each push replaces the job's previous gauges, so a failed listing leaves a gap in the storage series."""
+ with pushed_metrics_registry("replay_vision_gemini_cleanup_sweep") as registry:
+ Gauge(
+ "replay_vision_gemini_cleanup_backlog",
+ "Tracked Gemini files awaiting cleanup (a growing backlog means the sweep is losing)",
+ registry=registry,
+ ).set(tracked_files)
+ if storage is not None:
+ Gauge(
+ "replay_vision_gemini_storage_files",
+ "Files in the Gemini project from a full Files API listing, including files the Redis index "
+ "lost; a flat line at the listing cap means the real count is higher",
+ registry=registry,
+ ).set(storage.files)
+ Gauge(
+ "replay_vision_gemini_storage_bytes",
+ "Bytes the listed Gemini files hold against the project's Files API storage quota",
+ registry=registry,
+ ).set(storage.total_bytes)
+ Gauge(
+ "replay_vision_gemini_oldest_file_age_seconds",
+ "Age of the oldest listed Gemini file; a file older than any scan's run time is one cleanup missed",
+ registry=registry,
+ ).set(storage.oldest_age_seconds)
+ Gauge(
+ "replay_vision_gemini_cleanup_last_run_timestamp_seconds",
+ "Unix time the Gemini cleanup sweep last finished",
+ registry=registry,
+ ).set(time.time())
+
+
+def push_in_flight_observation_gauges(by_status: dict[str, tuple[int, float]]) -> None:
+ """Takes `(count, oldest age in seconds)` per not-yet-terminal status."""
+ with pushed_metrics_registry("replay_vision_observation_backlog") as registry:
+ counts = Gauge(
+ "replay_vision_in_flight_observations",
+ "Observations not yet terminal, by status",
+ ["status"],
+ registry=registry,
+ )
+ ages = Gauge(
+ "replay_vision_oldest_in_flight_observation_age_seconds",
+ "Time since the oldest not-yet-terminal observation was created, by status; 0 when there is none",
+ ["status"],
+ registry=registry,
+ )
+ for status, (count, oldest_age_seconds) in by_status.items():
+ counts.labels(status=status).set(count)
+ ages.labels(status=status).set(oldest_age_seconds)
+ Gauge(
+ "replay_vision_observation_backlog_last_run_timestamp_seconds",
+ "Unix time the in-flight observation backlog was last measured",
+ registry=registry,
+ ).set(time.time())
def record_search_rerank(outcome: str, seconds: float) -> None:
diff --git a/products/replay_vision/backend/tests/test_gemini_cleanup_activities.py b/products/replay_vision/backend/tests/test_gemini_cleanup_activities.py
index 609971a0c935..0a638dc9b2b6 100644
--- a/products/replay_vision/backend/tests/test_gemini_cleanup_activities.py
+++ b/products/replay_vision/backend/tests/test_gemini_cleanup_activities.py
@@ -1,11 +1,14 @@
import json
import datetime as dt
+from contextlib import nullcontext
from dataclasses import dataclass
import pytest
from unittest.mock import AsyncMock, patch
+from google.genai import types
from google.genai.errors import APIError
+from prometheus_client import CollectorRegistry
from temporalio.client import WorkflowExecutionStatus
from temporalio.service import RPCError, RPCStatusCode
@@ -17,8 +20,13 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep.constants impo
REDIS_KEY_TTL,
SWEEP_MIN_AGE,
)
-from products.replay_vision.backend.temporal.gemini_cleanup_sweep.types import CleanupSweepInputs, CleanupSweepResult
+from products.replay_vision.backend.temporal.gemini_cleanup_sweep.types import (
+ CleanupSweepInputs,
+ CleanupSweepResult,
+ GeminiStorageUsage,
+)
+_PUSHED_REGISTRY = "products.replay_vision.backend.temporal.metrics.pushed_metrics_registry"
_NOW = dt.datetime(2026, 6, 12, 12, 0, 0, tzinfo=dt.UTC)
@@ -57,6 +65,13 @@ class _StubFiles:
def __init__(self) -> None:
self.deleted: list[str] = []
self.delete_raises_for: dict[str, BaseException] = {}
+ self.listed: list[types.File] = []
+ self.list_raises: BaseException | None = None
+
+ def list(self, *, config: dict) -> list[types.File]:
+ if self.list_raises is not None:
+ raise self.list_raises
+ return self.listed
def delete(self, *, name: str) -> None:
if name in self.delete_raises_for:
@@ -117,7 +132,9 @@ async def test_no_keys_returns_zeros(activity_environment, fixed_now, gemini_red
p1, p2 = _patch_clients(raw, tmp)
with p1, p2:
result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
- assert result == CleanupSweepResult()
+ assert result == CleanupSweepResult(
+ storage=GeminiStorageUsage(files=0, total_bytes=0, oldest_age_seconds=0.0, truncated=False)
+ )
assert raw.files.deleted == []
@@ -333,3 +350,39 @@ async def test_mixed_cycle_aggregates_correctly(activity_environment, fixed_now,
assert result.skipped_invalid_value == 1
assert result.deleted == 2
assert sorted(raw.files.deleted) == ["files/done", "files/orphan"]
+
+
+async def test_reports_storage_from_the_full_gemini_listing(activity_environment, fixed_now, gemini_redis):
+ raw, tmp = _StubRawClient(), _StubTemporal({})
+ raw.files.listed = [
+ types.File(name="files/tracked", size_bytes=300, create_time=_NOW - dt.timedelta(minutes=5)),
+ types.File(name="files/untracked", size_bytes=700, create_time=_NOW - dt.timedelta(hours=30)),
+ types.File(name="files/no-metadata"),
+ ]
+ p1, p2 = _patch_clients(raw, tmp)
+ pushed = CollectorRegistry()
+ with p1, p2, patch(_PUSHED_REGISTRY, lambda _job: nullcontext(pushed)):
+ result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
+ assert result.storage == GeminiStorageUsage(
+ files=3, total_bytes=1000, oldest_age_seconds=30 * 3600, truncated=False
+ )
+ assert pushed.get_sample_value("replay_vision_gemini_storage_bytes") == 1000
+ assert pushed.get_sample_value("replay_vision_gemini_cleanup_backlog") == 0
+
+
+async def test_storage_listing_failure_still_deletes_and_drops_storage_gauges(
+ activity_environment, fixed_now, gemini_redis
+):
+ await _track(gemini_redis, file_name="files/old", workflow_id="wf-1", age=SWEEP_MIN_AGE * 10)
+ raw, tmp = _StubRawClient(), _StubTemporal({"wf-1": _Outcome(status=WorkflowExecutionStatus.COMPLETED)})
+ raw.files.list_raises = RuntimeError("simulated")
+ p1, p2 = _patch_clients(raw, tmp)
+ pushed = CollectorRegistry()
+ with p1, p2, patch(_PUSHED_REGISTRY, lambda _job: nullcontext(pushed)):
+ result = await activity_environment.run(sweep_gemini_files_activity, CleanupSweepInputs())
+ assert result.deleted == 1
+ assert result.storage is None
+ assert pushed.get_sample_value("replay_vision_gemini_cleanup_backlog") == 1
+ assert pushed.get_sample_value("replay_vision_gemini_storage_bytes") is None
diff --git a/products/replay_vision/backend/tests/test_gemini_cleanup_workflow.py b/products/replay_vision/backend/tests/test_gemini_cleanup_workflow.py
index 3307a0427ed1..fef79a015da2 100644
--- a/products/replay_vision/backend/tests/test_gemini_cleanup_workflow.py
+++ b/products/replay_vision/backend/tests/test_gemini_cleanup_workflow.py
@@ -8,7 +8,11 @@ from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker
from products.replay_vision.backend.temporal.gemini_cleanup_sweep.constants import WORKFLOW_NAME
-from products.replay_vision.backend.temporal.gemini_cleanup_sweep.types import CleanupSweepInputs, CleanupSweepResult
+from products.replay_vision.backend.temporal.gemini_cleanup_sweep.types import (
+ CleanupSweepInputs,
+ CleanupSweepResult,
+ GeminiStorageUsage,
+)
from products.replay_vision.backend.temporal.gemini_cleanup_sweep.workflow import ReplayVisionGeminiCleanupSweepWorkflow
@@ -25,6 +29,7 @@ async def test_workflow_returns_activity_result_as_dict():
skipped_invalid_value=2,
delete_failed=1,
hit_max_files_cap=True,
+ storage=GeminiStorageUsage(files=7, total_bytes=2048, oldest_age_seconds=60.0, truncated=False),
)
task_queue = str(uuid.uuid4())
@@ -52,4 +57,5 @@ async def test_workflow_returns_activity_result_as_dict():
"skipped_invalid_value": 2,
"delete_failed": 1,
"hit_max_files_cap": True,
+ "storage": {"files": 7, "total_bytes": 2048, "oldest_age_seconds": 60.0, "truncated": False},
}
diff --git a/products/replay_vision/backend/tests/test_metrics.py b/products/replay_vision/backend/tests/test_metrics.py
index d5efd313f8bb..91c995d4f612 100644
--- a/products/replay_vision/backend/tests/test_metrics.py
+++ b/products/replay_vision/backend/tests/test_metrics.py
@@ -10,7 +10,7 @@ from products.replay_vision.backend.temporal.metrics import (
record_credits_consumed,
record_estimate_outcome,
record_failure_kind,
- record_gemini_cleanup_backlog,
+ record_gemini_cleanup_files,
record_ineligible_kind,
record_observation,
record_observation_e2e,
@@ -107,6 +107,13 @@ class TestRecordHelpers(SimpleTestCase):
{"scanner_type": "monitor"},
1.0,
),
+ (
+ "gemini_cleanup_files",
+ lambda: record_gemini_cleanup_files("delete_failed", 4),
+ "replay_vision_gemini_cleanup_files_total",
+ {"result": "delete_failed"},
+ 4.0,
+ ),
(
"side_effect_failure",
lambda: record_side_effect_failure("signal"),
@@ -127,9 +134,3 @@ class TestRecordHelpers(SimpleTestCase):
before = _sample(sample_name, labels)
record()
assert _sample(sample_name, labels) == before + expected_delta
-
- def test_gemini_cleanup_backlog_is_a_gauge(self) -> None:
- record_gemini_cleanup_backlog(7)
- assert _sample("replay_vision_gemini_cleanup_backlog", {}) == 7.0
- record_gemini_cleanup_backlog(2)
- assert _sample("replay_vision_gemini_cleanup_backlog", {}) == 2.0
diff --git a/products/replay_vision/backend/tests/test_reconciler.py b/products/replay_vision/backend/tests/test_reconciler.py
index a351ad9072f2..7f1bd2b294c4 100644
--- a/products/replay_vision/backend/tests/test_reconciler.py
+++ b/products/replay_vision/backend/tests/test_reconciler.py
@@ -2,6 +2,7 @@ import uuid
import datetime as dt
import dataclasses
from collections.abc import Callable
+from contextlib import nullcontext
from typing import Any
import pytest
@@ -12,6 +13,7 @@ from django.utils import timezone
from asgiref.sync import sync_to_async
from parameterized import parameterized
+from prometheus_client import CollectorRegistry
from temporalio.client import ScheduleOverlapPolicy, WorkflowExecutionStatus
from temporalio.common import SearchAttributePair, TypedSearchAttributes
from temporalio.exceptions import ApplicationError
@@ -543,6 +545,7 @@ async def test_reap_orphaned_observations_activity(org_team) -> None:
}
rows = await sync_to_async(_setup)()
+ pushed = CollectorRegistry()
temporal = _StubReapTemporal(
{"wf-gone-1": "not_found", "wf-timed-out": "closed", "wf-open": "open", "wf-err": "rpc_error"}
)
@@ -551,7 +554,11 @@ async def test_reap_orphaned_observations_activity(org_team) -> None:
"products.replay_vision.backend.temporal.activities.reap_orphaned_observations.async_connect",
AsyncMock(return_value=temporal),
):
- reaped = await _live_activity_env().run(reap_orphaned_observations_activity)
+ with patch(
+ "products.replay_vision.backend.temporal.metrics.pushed_metrics_registry",
+ lambda _job: nullcontext(pushed),
+ ):
+ reaped = await _live_activity_env().run(reap_orphaned_observations_activity)
assert reaped == 3
statuses = {
@@ -566,6 +573,13 @@ async def test_reap_orphaned_observations_activity(org_team) -> None:
assert statuses[key].completed_at is None, key
# The fresh row never reaches Temporal; the empty-workflow-id row is reaped without a describe.
assert set(temporal.described) == {"wf-gone-1", "wf-timed-out", "wf-open", "wf-err"}
+ # The backlog is measured before reaping, so it counts every row the setup left in flight.
+ for status in ("pending", "running"):
+ assert pushed.get_sample_value("replay_vision_in_flight_observations", {"status": status}) == 3, status
+ oldest_pending = pushed.get_sample_value(
+ "replay_vision_oldest_in_flight_observation_age_seconds", {"status": "pending"}
+ )
+ assert oldest_pending is not None and oldest_pending >= stale.total_seconds()
def _make_inline_scanner(team: Team, *, key: str, age: dt.timedelta) -> ReplayScanner: