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): count scanner tool use in metrics (#102269)

Tue Haulund38703af2eaf3
diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
index 05e4f5f103d5..1e147491b87b 100644
--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py
@@ -55,8 +55,13 @@ from products.replay_vision.backend.temporal.events_tool import (
)
from products.replay_vision.backend.temporal.gemini import classify_gemini_error, describe_gemini_error, gemini_api_key
from products.replay_vision.backend.temporal.metrics import (
+ record_events_tool_call,
record_mission_pass,
+ record_network_state,
+ record_network_tool_call,
record_provider_call,
+ record_tool_round,
+ record_unknown_tool_call,
record_verification_outcome,
)
from products.replay_vision.backend.temporal.network_capture import SessionNetworkPayload
@@ -540,6 +545,12 @@ async def _run_mission(
# The network tool is offered only when the recording has requests to return. Otherwise every lookup
# would be a dead call against the budget the events tool shares.
+ scanner_type = snapshot.scanner_type.value
+ record_network_state(scanner_type, network_index.state())
+ counters: dict[str, Callable[[str, str], None]] = {
+ GET_EVENTS_TOOL_NAME: record_events_tool_call,
+ GET_NETWORK_TOOL_NAME: record_network_tool_call,
+ }
handlers: dict[str, Callable[[Any], dict[str, Any]]] = {
GET_EVENTS_TOOL_NAME: lambda call: dispatch_events_tool(call, events_index),
}
@@ -549,8 +560,10 @@ async def _run_mission(
tools.append(network_tool())
def dispatch(call: Any) -> dict[str, Any]:
- name = getattr(call, "name", None)
- handler = handlers.get(name) if isinstance(name, str) else None
+ raw_name = getattr(call, "name", None)
+ name = raw_name if isinstance(raw_name, str) else ""
+ counters.get(name, record_unknown_tool_call)(scanner_type, snapshot.model)
+ handler = handlers.get(name)
if handler is None:
# An unoffered or hallucinated name must not fall through to a lookup that returns
# plausible data for a question the model did not ask.
@@ -572,6 +585,10 @@ async def _run_mission(
else step
for step in scanner.mission_steps()
]
+
+ def on_round(calls: int) -> None:
+ record_tool_round(scanner_type, snapshot.model, calls)
+
run = functools.partial(
_run_steps,
client=client,
@@ -584,6 +601,7 @@ async def _run_mission(
metric_labels=metric_labels,
trace_id=trace_id,
tools=tools,
+ on_round=on_round,
)
verification: VerificationRecord | None = None
try:
@@ -767,6 +785,7 @@ async def _run_steps(
metric_labels: dict[str, str],
trace_id: str,
tools: list[types.Tool],
+ on_round: Callable[[int], None] | None = None,
) -> dict[str, BaseModel]:
"""Run the ordered steps over one growing conversation; return the validated output keyed by step name."""
# The video + preamble lead the conversation inline unless they're already cached as the prefix.
@@ -788,6 +807,7 @@ async def _run_steps(
tools=tools,
metric_labels=metric_labels,
trace_id=trace_id,
+ on_round=on_round,
)
if result.output is None:
# Roll the failed step's half-finished exchange back so the next instruction follows the last good
@@ -829,6 +849,7 @@ async def _run_step(
metric_labels: dict[str, str],
trace_id: str,
tools: list[types.Tool],
+ on_round: Callable[[int], None] | None = None,
) -> "_StepResult":
"""Run one step's tool loop with one re-prompt on failure. Returns the validated output, or why it was exhausted.
@@ -860,7 +881,11 @@ async def _run_step(
started = time.monotonic()
try:
response = await run_tool_loop(
- generate=_generate, convo=convo, dispatch=dispatch, max_tool_iterations=_tool_budget(model)
+ generate=_generate,
+ convo=convo,
+ dispatch=dispatch,
+ max_tool_iterations=_tool_budget(model),
+ on_round=on_round,
)
if function_calls(response):
# Tool budget spent and the model still wants a lookup. Rather than hard-fail, complete the
diff --git a/products/replay_vision/backend/temporal/conversation.py b/products/replay_vision/backend/temporal/conversation.py
index 90821f599917..81a532e51c0d 100644
--- a/products/replay_vision/backend/temporal/conversation.py
+++ b/products/replay_vision/backend/temporal/conversation.py
@@ -24,6 +24,7 @@ async def run_tool_loop(
convo: list[Any],
dispatch: Callable[[Any], dict[str, Any]],
max_tool_iterations: int = DEFAULT_MAX_TOOL_ITERATIONS,
+ on_round: Callable[[int], None] | None = None,
) -> Any:
"""Run `generate` until the model answers instead of calling a tool.
@@ -34,14 +35,27 @@ async def run_tool_loop(
The final answer's content is NOT appended — the caller validates it, then appends it (on success) to
continue the conversation, or appends a correction (on failure) to re-prompt. Returns the final response;
if the tool budget runs out we return the last response and let the caller validate it.
+
+ `on_round` receives how many lookups a turn asked for, once per turn that asked for any, including the
+ turn that spends the last of the budget. A round is what the budget spends, whether it carries one
+ lookup or several.
"""
response = await generate(convo)
for _ in range(max_tool_iterations):
calls = function_calls(response)
if not calls:
return response
+ if on_round is not None:
+ on_round(len(calls))
convo.append(response.candidates[0].content) # carries thought signatures
for call in calls:
convo.append(types.Part(function_response=types.FunctionResponse(name=call.name, response=dispatch(call))))
response = await generate(convo)
+ # Budget spent. The caller answers this response's pending calls before forcing a tool-free turn, so
+ # the round happened and is counted here. Without this every budget-exhausted run under-reports, and
+ # those are the runs where batching matters most.
+ if on_round is not None:
+ terminal = function_calls(response)
+ if terminal:
+ on_round(len(terminal))
return response
diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.py
index 4f9d5174bae9..21ea777fd85b 100644
--- a/products/replay_vision/backend/temporal/metrics.py
+++ b/products/replay_vision/backend/temporal/metrics.py
@@ -58,6 +58,43 @@ REPLAY_VISION_MISSION_PASSES = Counter(
["model", "path"],
)
+# LLM analytics cannot answer this: the scanner runs with privacy mode on, so `$ai_tools_called` is
+# derived from an output the provider events never carry.
+REPLAY_VISION_EVENTS_TOOL_CALLS = Counter(
+ "replay_vision_events_tool_calls_total",
+ "Calls the scanner model made to the analytics events lookup",
+ ["scanner_type", "model"],
+)
+
+REPLAY_VISION_NETWORK_TOOL_CALLS = Counter(
+ "replay_vision_network_tool_calls_total",
+ "Calls the scanner model made to the network request lookup",
+ ["scanner_type", "model"],
+)
+
+REPLAY_VISION_UNKNOWN_TOOL_CALLS = Counter(
+ "replay_vision_unknown_tool_calls_total",
+ "Calls the scanner model made to a name no tool answers, which means it invented one",
+ ["scanner_type", "model"],
+)
+
+# A round is one provider turn that asked for at least one lookup, which is what the tool budget spends.
+# The histogram separates a model that asks for several moments at once from one that spends a round on each.
+_TOOL_CALLS_PER_ROUND_BUCKETS = (1, 2, 3, 4, 5, 6, 8, 10, 15)
+
+REPLAY_VISION_TOOL_ROUNDS = Histogram(
+ "replay_vision_tool_calls_per_round",
+ "Lookups the scanner model asked for in one provider turn",
+ ["scanner_type", "model"],
+ buckets=_TOOL_CALLS_PER_ROUND_BUCKETS,
+)
+
+REPLAY_VISION_NETWORK_STATE = Counter(
+ "replay_vision_network_state_total",
+ "How each scan described network data to the model: available, clean, or none",
+ ["scanner_type", "state"],
+)
+
REPLAY_VISION_VERIFICATION_OUTCOMES = Counter(
"replay_vision_verification_outcomes_total",
"Verify-positives results per verified monitor `yes`: agreed, flipped, no_cache, no_budget, draw_failed",
@@ -199,6 +236,36 @@ def record_provider_call(provider: str, model: str, scanner_type: str, outcome:
_otel.record_histogram_twin(REPLAY_VISION_PROVIDER_CALL, seconds, labels)
+def record_events_tool_call(scanner_type: str, model: str) -> None:
+ labels = {"scanner_type": scanner_type, "model": model}
+ REPLAY_VISION_EVENTS_TOOL_CALLS.labels(**labels).inc()
+ _otel.record_counter_twin(REPLAY_VISION_EVENTS_TOOL_CALLS, 1, labels)
+
+
+def record_network_tool_call(scanner_type: str, model: str) -> None:
+ labels = {"scanner_type": scanner_type, "model": model}
+ REPLAY_VISION_NETWORK_TOOL_CALLS.labels(**labels).inc()
+ _otel.record_counter_twin(REPLAY_VISION_NETWORK_TOOL_CALLS, 1, labels)
+
+
+def record_unknown_tool_call(scanner_type: str, model: str) -> None:
+ labels = {"scanner_type": scanner_type, "model": model}
+ REPLAY_VISION_UNKNOWN_TOOL_CALLS.labels(**labels).inc()
+ _otel.record_counter_twin(REPLAY_VISION_UNKNOWN_TOOL_CALLS, 1, labels)
+
+
+def record_tool_round(scanner_type: str, model: str, calls: int) -> None:
+ labels = {"scanner_type": scanner_type, "model": model}
+ REPLAY_VISION_TOOL_ROUNDS.labels(**labels).observe(calls)
+ _otel.record_histogram_twin(REPLAY_VISION_TOOL_ROUNDS, calls, labels)
+
+
+def record_network_state(scanner_type: str, state: str) -> None:
+ labels = {"scanner_type": scanner_type, "state": state}
+ REPLAY_VISION_NETWORK_STATE.labels(**labels).inc()
+ _otel.record_counter_twin(REPLAY_VISION_NETWORK_STATE, 1, labels)
+
+
def record_mission_pass(model: str, path: str) -> None:
labels = {"model": model, "path": path}
REPLAY_VISION_MISSION_PASSES.labels(**labels).inc()
diff --git a/products/replay_vision/backend/tests/test_call_scanner_provider.py b/products/replay_vision/backend/tests/test_call_scanner_provider.py
index b354bbe75b80..28704c2e41e4 100644
--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py
+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py
@@ -1,5 +1,6 @@
import datetime as dt
import dataclasses
+from collections.abc import Callable
from typing import Any, cast
import pytest
@@ -55,18 +56,29 @@ class _Side(BaseModel):
class _FakeContent:
- def __init__(self, function_call: Any = None) -> None:
- part = type("Part", (), {"function_call": function_call})()
- self.parts = [part]
+ def __init__(self, function_calls: list[Any]) -> None:
+ self.parts = [type("Part", (), {"function_call": fc})() for fc in function_calls] or [
+ type("Part", (), {"function_call": None})()
+ ]
class _Resp:
- """Minimal genai response: `.text`, `.candidates[0].content.parts`, and an optional finish reason."""
+ """Minimal genai response: `.text`, `.candidates[0].content.parts`, and an optional finish reason.
+
+ `function_calls` takes a list because a turn can ask for several lookups at once, which is the
+ behaviour the per-round histogram exists to measure.
+ """
def __init__(
- self, text: str = "", function_call: Any = None, finish_reason: Any = None, empty_content: bool = False
+ self,
+ text: str = "",
+ function_call: Any = None,
+ function_calls: list[Any] | None = None,
+ finish_reason: Any = None,
+ empty_content: bool = False,
) -> None:
- content = None if empty_content else _FakeContent(function_call)
+ calls = function_calls if function_calls is not None else ([function_call] if function_call else [])
+ content = None if empty_content else _FakeContent(calls)
self.candidates = [type("Cand", (), {"content": content, "finish_reason": finish_reason})()]
self.text = text
@@ -98,6 +110,7 @@ async def _run(
dispatch: Any = lambda c: {},
cache_name=None,
model: str = "models/gemini-3-flash-preview",
+ on_round: Callable[[int], None] | None = None,
):
return await _run_steps(
client=client,
@@ -111,6 +124,7 @@ async def _run(
team_id=1,
metric_labels=_LABELS,
trace_id="trace-1",
+ on_round=on_round,
)
@@ -203,6 +217,52 @@ async def test_step_runs_a_tool_call_then_answers() -> None:
assert [fc.args for fc in dispatched] == [{"rec_t": 5}]
+async def test_each_tool_turn_reports_how_many_lookups_it_asked_for() -> None:
+ # The round hook is the only measure of batching that survives privacy mode. A signature that accepts
+ # it without forwarding it leaves the metric permanently empty and raises nothing.
+ rounds: list[int] = []
+ steps = [MissionStep(name="core", instruction="c", response_model=_Core)]
+ responses = [
+ _Resp(
+ function_calls=[
+ _fc("get_events_around", {"vid_t": 5}),
+ _fc("get_network_around", {"vid_t": 5}),
+ _fc("get_events_around", {"vid_t": 40}),
+ ]
+ ),
+ _Resp(function_call=_fc("get_events_around", {"vid_t": 90})),
+ _Resp(text='{"verdict":"yes"}'),
+ ]
+ client = _FakeClient(responses)
+ out = await _run(client, steps, dispatch=lambda fc: {"events": []}, on_round=rounds.append)
+ assert out["core"].verdict == "yes"
+ # A turn asking for three lookups must report 3, not 1: telling those apart is the whole point.
+ assert rounds == [3, 1]
+
+
+async def test_the_turn_that_spends_the_last_budget_is_still_counted() -> None:
+ # The forced final turn answers that turn's pending lookups, so the round happened. Counting only
+ # the turns inside the loop under-reports exactly the budget-exhausted runs, where batching matters.
+ rounds: list[int] = []
+ budget = 3
+ steps = [MissionStep(name="core", instruction="c", response_model=_Core)]
+ responses = [_Resp(function_call=_fc("get_events_around", {"vid_t": 5})) for _ in range(budget + 1)]
+ responses.append(_Resp(text='{"verdict":"yes"}'))
+ client = _FakeClient(responses)
+ out = await _run(
+ client,
+ steps,
+ dispatch=lambda fc: {"events": []},
+ model="models/gemini-3.8-flash",
+ on_round=rounds.append,
+ )
+ assert out["core"].verdict == "yes"
+ # budget turns inside the loop, plus the turn whose calls the forced answer dispatches.
+ assert len(rounds) == budget + 1
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
"model,budget",