Repository navigation
2026 11 26 selenium flow telemetry
History. Drafted 2026-11-26 for #65 (PR #217), from the spec Dr K approved in #65's notes. The design, finished against the code, is 2026-11-26-selenium-flow-telemetry-design.md: its "Found at plan time" list is what this plan adds to the approved draft, and its (call) marks are the calls Dr K approved. In short: with
telemetry.otelon, ametricsbus subscriber records every call onselenium_flow.call.duration; an observable gauge reports the Grid's slots;Calls.begin/endbracket each call with acall <tool>span; an ASGI middleware gives each HTTP request one span named by its route template. All of it rides kubed-mcp's OpenTelemetry. The requirements land as RUN-32 to RUN-36.At plan approval Dr K dropped
selenium_flow.grid.sessions: on a Grid 4 it always equalsselenium_flow.grid.slots{state="busy"}, so it only adds a series. One gauge is left, so nothing shares a read andREUSEand theclockwent with it; the tasks below read so.Task 3's review added two rules the route span keeps: a request that raised is ERROR whatever status it had sent, and a method outside the nine HTTP defines is
_OTHER, since the method is the caller's text.
For agentic workers: REQUIRED SUB-SKILL: Use skill://superpowers/subagent-driven-development/SKILL.md (recommended) or skill://superpowers/executing-plans/SKILL.md to implement this plan task by task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: with TELEMETRY_OTEL=true, selenium-flow's own call histogram, Grid gauge, call spans
and HTTP route spans go out through kubed-mcp's OpenTelemetry, and with it off nothing changes.
Architecture: one plain module, kubed/selenium_flow/telemetry.py, holds a Telemetry (the
tracer, the meter, the histogram, the gauge and the span helpers) on injectable providers.
workspace/calls.py asks it for a span in begin and ends it in end; http/tracing.py is the
route-span middleware over the access log's RouteTemplates; server.py builds and wires it when
settings.telemetry.otel is on, or uses the one it is handed.
Tech Stack: Python 3.11+, opentelemetry-api (from fastmcp-slim[mcp]), opentelemetry-sdk
in tests only, Starlette ASGI, pytest, ruff.
Spec: the design, and the area files Task 4
edits: runtime.md (RUN-12, RUN-25, new RUN-32 to RUN-36), workspaces-and-sessions.md (WS-28,
WS-29), grid.md (the request table, GRID-12), errors-and-logging.md (ERR-30, ERR-35).
Upstream: quick-mcp telemetry TEL-11 to
TEL-17.
-
The switch is
telemetry.otel. No new config key. Off, and with no injectedTelemetry: no subscriber, no gauge, no middleware, no span. -
Names, exactly: scope
kubed.selenium_flow;selenium_flow.call.duration(units);selenium_flow.grid.slots; attributesselenium_flow.tool,selenium_flow.surface,selenium_flow.outcome,selenium_flow.browser,selenium_flow.slot.state,selenium_flow.workspace,selenium_flow.sub_session,error.type,http.request.method,http.route,http.response.status_code; span namescall <tool>and<METHOD> <route template>; bus subscribermetrics. -
Buckets, exactly:
(0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300). -
Never on a metric: a workspace, a session key, a Grid id. Never on a span: a
sub-session's name, a Grid id, an argument, a URL, a query, a request header, an exception's
text. No
record_exception, no status description. -
Telemetry never fails a call or raises into a reader. A failure is logged by
type(exc).__name__alone (ERR-32, ERR-35). -
Imports:
telemetry.pyimports the OpenTelemetry API andmonitor.eventsonly, neveropentelemetry.sdk, nothing ofworkspace/,http/,mcp/or Starlette. The SDK appears only intests/. -
Leave
mcp/tools.py,mcp/instructions.pyand.github/alone (AGENTS.md). No README or AGENTS.md change. -
No golden moves and no integration test (CONTRIBUTING "Tests"):
git status tests/goldenstays empty. -
Spec rules (Specification.md, "Ids"): statements only, present tense, no dates or issue
numbers; RUN ids continue from 31; code cited by symbol, never by line. Examples use
example.com. -
Checks, every task:
ruff check .andpytest, both clean, astest.ymlruns them. Noui/change. -
Commits: exact paths staged, never
-a.docs/is committed by the workflow on the wiki branchissue-65.
-
Instruments made before the SDK is set. The server builds
Telemetry()at build, and kubed-mcp sets the global providers later, in the lifespan (RUN-29). The API's proxies must carry the histogram, the gauge and the tracer over. Pinned in Task 1 bytest_instruments_made_before_the_sdk_is_set_still_record, in a fresh interpreter. -
The last collection at shutdown runs on the loop. kubed-mcp shuts the meter provider down
at the lifespan's exit, which collects once more on the event loop's thread; a
GET /statusthere would block the loop for up to 5 s. Pinned in Task 1 bytest_a_collection_on_the_event_loop_reads_nothing. -
A Grid that hangs or refuses (
grid.example.comdown, credentials in its URL): one collection costs one bounded read; nothing is observed; one WARNING line a streak, by type, without the userinfo. Pinned in Task 1 bytest_one_collection_reads_the_grid_onceandtest_a_failed_read_observes_nothing_and_logs_its_type_once_a_streak. -
An app that raises under the middleware.
start_as_current_span's defaults record the exception and write its text into the status; the span must end as a 500, ERROR, with neither, and the exception must reach Starlette unchanged. Pinned in Task 3 bytest_an_app_that_raises_ends_its_span_as_a_500. -
A path no route serves (
/acme-workspace/x, a mistyped link): its first segment may be a workspace, so the span is named by its method alone with nohttp.route. Pinned in Task 3 bytest_a_path_no_route_serves_is_named_by_its_method_alone.
Files:
- Create:
kubed/selenium_flow/telemetry.py - Modify:
pyproject.toml(testextra, only if Step 1 says so) - Modify:
tests/test_packaging.py(test_the_telemetry_extra_is_kubed_mcps_and_nothing_else_carries_it, only if Step 1 says so) - Modify:
tests/fakes.py(Recorded,recorded,points),tests/conftest.py(re-export them) - Modify:
tests/test_boundaries.py(NO_PROTOCOL,NO_SELENIUM) - Test:
tests/test_telemetry.py
Interfaces:
-
Consumes:
monitor.events.CallFinished. -
Produces, in
kubed/selenium_flow/telemetry.py:- constants
SCOPE = "kubed.selenium_flow",CALL_DURATION,GRID_SLOTS(the names above),BUCKETS: tuple[float, ...]; -
grid_counts(status: dict) -> dict[tuple[str, str], int]: slots by(browser, state); -
class Telemetry:-
__init__(self, *, tracer_provider=None, meter_provider=None); -
tracer: opentelemetry.trace.Tracer,meter: opentelemetry.metrics.Meter; -
call_finished(self, event: CallFinished) -> None, the bus handler; -
grid_gauge(self, read: Callable[[], dict]) -> None, registering the slots gauge; -
start_call(self, workspace: str, *, sub_session: bool, tool: str, browser: str) -> Span | None; -
end_call(self, span: Span | None, *, surface: str, outcome: str, error: BaseException | None = None) -> None.
-
- constants
-
Produces, in
tests/fakes.py:Recorded(NamedTuple)withtelemetry,spans(InMemorySpanExporter),metrics(InMemoryMetricReader);recorded() -> Recorded;points(reader, name) -> list[tuple[dict, object]], each data point of the metricnameas(dict(point.attributes), point)from oneget_metrics_data(). -
Step 1: Find out whether the SDK is in the test install
Run: pip install -e ".[test]", then python -c "import opentelemetry.version as v; print(v.__version__)"
(the API's version) and python -c "import opentelemetry.sdk".
Expected: the second import either succeeds (the SDK comes in already: skip to Step 2, and leave
pyproject.toml and tests/test_packaging.py alone) or fails with ModuleNotFoundError. On the
error:
-
add
"opentelemetry-sdk>=<the installed opentelemetry-api version>,<2",totest, afteropenapi-spec-validator, with the comment# The in-memory span exporter and metric reader the telemetry tests read (CI installs .[test] only).; -
in
test_the_telemetry_extra_is_kubed_mcps_and_nothing_else_carries_it, replace the last two lines with: no entry ofproject["dependencies"]containstelemetryorpyroscope; and no entry of thetestextra containskubed-mcp[telemetry]orpyroscope, and every entry there containingtelemetrystarts withopentelemetry-sdk; -
reinstall and rerun the import. Say in the PR that #199's assertion was narrowed, and why (
"opentelemetry"contains"telemetry"). -
Step 2: Write the test doubles in
tests/fakes.py
recorded() builds a TracerProvider with a SimpleSpanProcessor(InMemorySpanExporter()) and a
MeterProvider(metric_readers=[InMemoryMetricReader()]), and a Telemetry on both. No global is set. conftest.py re-exports recorded, points.
- Step 3: Write the failing tests in
tests/test_telemetry.py
STATUS = {"value": {"ready": True, "nodes": [
{"availability": "UP", "maxSessions": 2, "slots": [
{"stereotype": {"browserName": "chrome"}, "session": {"sessionId": "g1"}},
{"stereotype": {"browserName": "chrome"}, "session": None}]},
{"availability": "UP", "maxSessions": 1, "slots": [
{"stereotype": {"browserName": "firefox"}, "session": {"sessionId": "g2"}}]},
{"availability": "DRAINING", "maxSessions": 1, "slots": [
{"stereotype": {"browserName": "chrome"}, "session": None}]},
{"availability": "UP", "maxSessions": 1, "slots": [
{"stereotype": {"browserName": "chrome"}, "session": {"sessionId": "g3"}},
{"stereotype": {"browserName": "firefox"}, "session": None}]},
{"slots": [{"stereotype": {"browserName": "chrome"}, "session": None}]},
]}}
FINISHED = CallFinished("ws/alice", "grid-1", "chrome", "navigate", "flow", "4xx", 0.0, 0.25)
def test_a_finished_call_is_one_point_with_exactly_four_attributes():
rec = recorded()
rec.telemetry.call_finished(FINISHED)
[(attributes, point)] = points(rec.metrics, CALL_DURATION)
assert attributes == {"selenium_flow.tool": "navigate", "selenium_flow.surface": "flow",
"selenium_flow.outcome": "4xx", "selenium_flow.browser": "chrome"}
assert (point.count, point.sum) == (1, 0.25)
def test_the_buckets_are_mcp_server_operation_durations():
rec = recorded()
rec.telemetry.call_finished(FINISHED)
[(_, point)] = points(rec.metrics, CALL_DURATION)
assert tuple(point.explicit_bounds) == BUCKETS == (
0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300)
def test_an_empty_browser_is_recorded_as_given():
rec = recorded()
rec.telemetry.call_finished(dataclasses.replace(FINISHED, browser=""))
[(attributes, _)] = points(rec.metrics, CALL_DURATION)
assert attributes["selenium_flow.browser"] == ""
def test_the_grid_counts_only_slots_that_can_take_a_session():
assert grid_counts(STATUS) == {("chrome", "busy"): 2, ("chrome", "free"): 2, ("firefox", "busy"): 1}
def test_the_gauge_reports_the_grid_by_browser_and_state():
rec = recorded()
rec.telemetry.grid_gauge(lambda: STATUS)
slots = {(a["selenium_flow.browser"], a["selenium_flow.slot.state"]): p.value
for a, p in points(rec.metrics, GRID_SLOTS)}
assert slots == {("chrome", "busy"): 2, ("chrome", "free"): 2, ("firefox", "busy"): 1}
def test_one_collection_reads_the_grid_once():
reads = []
rec = recorded()
rec.telemetry.grid_gauge(lambda: reads.append(1) or STATUS)
rec.metrics.get_metrics_data()
assert len(reads) == 1
def test_a_failed_read_observes_nothing_and_logs_its_type_once_a_streak(caplog):
rec = recorded()
answers = [ConnectionError("http://u:hunter2@grid.example.com:4444"),
ConnectionError("again"), STATUS, ConnectionError("later")]
def read():
answer = answers.pop(0)
if isinstance(answer, Exception):
raise answer
return answer
rec.telemetry.grid_gauge(read)
rounds = []
with caplog.at_level(logging.WARNING, logger="kubed.selenium_flow.telemetry"):
for _ in range(4): # each `points` is one collection, one read
rounds.append(points(rec.metrics, GRID_SLOTS))
assert [bool(s) for s in rounds] == [False, False, True, False]
assert caplog.text.count("ConnectionError") == 2
assert "hunter2" not in caplog.text and "grid.example.com" not in caplog.text
async def test_a_collection_on_the_event_loop_reads_nothing():
reads = []
rec = recorded()
rec.telemetry.grid_gauge(lambda: reads.append(1) or STATUS)
assert points(rec.metrics, GRID_SLOTS) == [] # collected on this test's running loop
assert reads == []
def test_a_span_starts_under_the_current_context_and_is_not_made_current():
rec = recorded()
with rec.telemetry.tracer.start_as_current_span("parent") as parent:
span = rec.telemetry.start_call("ws", sub_session=True, tool="navigate", browser="chrome")
assert trace.get_current_span() is parent
rec.telemetry.end_call(span, surface="mcp", outcome="ok")
call = next(s for s in rec.spans.get_finished_spans() if s.name == "call navigate")
assert call.parent.span_id == parent.get_span_context().span_id
assert call.kind is SpanKind.INTERNAL
assert dict(call.attributes) == {
"selenium_flow.workspace": "ws", "selenium_flow.sub_session": True,
"selenium_flow.tool": "navigate", "selenium_flow.browser": "chrome",
"selenium_flow.surface": "mcp", "selenium_flow.outcome": "ok"}
assert call.status.status_code is StatusCode.UNSET
def test_a_failed_call_is_an_error_with_its_type_and_none_of_its_text():
rec = recorded()
span = rec.telemetry.start_call("ws", sub_session=False, tool="write", browser="chrome")
error = ValueError("typed hunter2 on https://example.com/?q=1")
rec.telemetry.end_call(span, surface="http", outcome="4xx", error=error)
[call] = rec.spans.get_finished_spans()
assert call.status.status_code is StatusCode.ERROR and call.status.description is None
assert call.attributes["error.type"] == "ValueError"
assert len(call.events) == 0
assert "hunter2" not in repr((call.name, dict(call.attributes), call.status, call.events))
def test_the_span_helpers_never_raise(caplog):
# `Raising`: a tracer provider whose get_tracer returns itself and whose start_span raises
# RuntimeError; `BrokenSpan`: a span whose set_attribute raises RuntimeError.
telemetry = Telemetry(tracer_provider=Raising(), meter_provider=MeterProvider())
assert telemetry.start_call("ws", sub_session=False, tool="t", browser="") is None
telemetry.end_call(None, surface="mcp", outcome="ok")
telemetry.end_call(BrokenSpan(), surface="mcp", outcome="ok")
assert caplog.text.count("RuntimeError") == 2
def test_the_scope_is_kubed_selenium_flow_with_the_package_version():
rec = recorded()
rec.telemetry.call_finished(FINISHED)
[scope] = [sm.scope for rm in rec.metrics.get_metrics_data().resource_metrics
for sm in rm.scope_metrics]
assert (scope.name, scope.version) == (SCOPE, importlib.metadata.version("kubed-selenium-flow"))
def test_instruments_made_before_the_sdk_is_set_still_record():
# In a fresh interpreter (`subprocess.run([sys.executable, "-c", SCRIPT], ...)`, as
# test_boundaries does): `Telemetry()` with no providers, the gauge on `lambda: STATUS`; then
# set the global MeterProvider (an InMemoryMetricReader) and TracerProvider (an in-memory
# exporter); record FINISHED and one start_call/end_call; print the metric and span names as
# JSON.
...
assert {CALL_DURATION, GRID_SLOTS} <= set(found["metrics"])
assert found["spans"] == ["call navigate"]The ... lines are plumbing the implementer writes; the assertions are the contract.
- Step 4: Run them to see them fail
Run: pytest tests/test_telemetry.py -p no:randomly
Expected: FAIL, ModuleNotFoundError: No module named 'kubed.selenium_flow.telemetry'.
-
Step 5: Write
kubed/selenium_flow/telemetry.py -
Module docstring: why it exists (selenium-flow's own signals on kubed-mcp's OpenTelemetry; the API is a no-op until kubed-mcp sets an SDK, and the proxies carry what was made before).
-
Version:
importlib.metadata.version("kubed-selenium-flow"),NoneonPackageNotFoundError. -
__init__:trace.get_tracer(SCOPE, version, tracer_provider=...),metrics.get_meter(SCOPE, version, meter_provider=...); the histogram withunit="s", a one-sentence description,explicit_bucket_boundaries_advisory=BUCKETS. -
grid_counts: the rule of design item 10, in the order the test reads: per node, busy slots are those with a truthysession; free slots count only whenavailabilityisUPor absent and busy is belowmaxSessions(no cap when absent), and at mostmaxSessions - busyof them; the browser isslot["stereotype"].get("browserName", ""). Missing keys read as empty. -
grid_gauge: onecreate_observable_gaugewhose callback calls_counts()._counts()returnsNonewithout reading whenasyncio.get_running_loop()succeeds (the loop's thread); else callsread()andgrid_counts, storing the counts orNoneon anyException. A failure logslog.warning("telemetry: the Grid was not read for its gauge (%s)", type(exc).__name__)only when the last read succeeded (or none was made); a success ends the streak. A callback withNoneyields no observation. -
start_call:tracer.start_span(f"call {tool}", kind=SpanKind.INTERNAL, attributes=...)with the four begin attributes; anyExceptionis logged by type (log.warning("telemetry: a call span failed (%s)", ...)) and givesNone. -
end_call: no-op forNone; sets surface and outcome; witherror,Status(StatusCode.ERROR)anderror.type;span.end(). AnyExceptionis logged the same way. -
Step 6: Put
telemetrybehind the boundaries intests/test_boundaries.py
Add "telemetry" to the plain names in NO_PROTOCOL and to NO_SELENIUM.
- Step 7: Run the tests to see them pass
Run: pytest tests/test_telemetry.py tests/test_boundaries.py tests/test_packaging.py
Expected: PASS.
- Step 8: Run the checks
Run: ruff check . and pytest
Expected: both clean.
- Step 9: Commit
git add kubed/selenium_flow/telemetry.py tests/test_telemetry.py tests/fakes.py tests/conftest.py \
tests/test_boundaries.py
# and, if Step 1 changed them: pyproject.toml tests/test_packaging.py
git commit -m "Telemetry: the call histogram, the Grid gauge and the call span helpers (#65)"Files:
- Modify:
kubed/selenium_flow/workspace/calls.py(Begun,Calls.__init__,begin,end, the module docstring's list) - Test:
tests/test_call_spans.py
Interfaces:
-
Consumes: Task 1's
Telemetry.start_call,Telemetry.end_call,recorded. -
Produces:
Begun.span: object | None = None, the last field;Calls(*, monitor=None, capture=None, control=None, clock=time.time, telemetry=None)with a publictelemetryattribute, which Task 4 sets. -
Step 1: Write the failing tests in
tests/test_call_spans.py
def calls_with_spans(**kwargs):
rec = recorded()
return Calls(telemetry=rec.telemetry, **kwargs), rec
def test_a_call_has_a_span_named_by_its_tool():
calls, rec = calls_with_spans()
begun = calls.begin("ws", "grid-abc123", browser="chrome", tool="navigate")
calls.end(begun, tool="navigate", surface="http", browser="chrome")
[span] = rec.spans.get_finished_spans()
assert span.name == "call navigate"
assert span.attributes["selenium_flow.workspace"] == "ws"
assert span.attributes["selenium_flow.sub_session"] is False
assert (span.attributes["selenium_flow.surface"], span.attributes["selenium_flow.outcome"]) == ("http", "ok")
assert "grid-abc123" not in repr((span.name, dict(span.attributes)))
def test_a_sub_session_span_names_its_workspace_never_the_session():
calls, rec = calls_with_spans()
begun = calls.begin("ws/alice@example.com", "grid-1", browser="firefox", tool="extract")
calls.end(begun, tool="extract", surface="mcp", browser="firefox")
[span] = rec.spans.get_finished_spans()
assert span.attributes["selenium_flow.workspace"] == "ws"
assert span.attributes["selenium_flow.sub_session"] is True
assert "alice" not in repr((span.name, dict(span.attributes)))
def test_a_failed_call_carries_its_outcome_and_type():
calls, rec = calls_with_spans()
begun = calls.begin("ws", "grid-1", browser="chrome", tool="interact")
error = ValueError("no element at https://example.com/?token=hunter2")
calls.end(begun, tool="interact", surface="flow", browser="chrome", error=error)
[span] = rec.spans.get_finished_spans()
assert span.attributes["selenium_flow.outcome"] == outcome(error)
assert span.attributes["error.type"] == "ValueError"
assert span.status.status_code is StatusCode.ERROR
assert "hunter2" not in repr((dict(span.attributes), span.status, span.events))
def test_a_refused_call_has_no_span():
class Shut:
def refusal(self, session_id, tool):
return faults.Controlled("a person has control of this browser")
calls, rec = calls_with_spans(control=Shut())
with pytest.raises(faults.Controlled):
calls.begin("ws", "grid-1", browser="chrome", tool="navigate")
assert rec.spans.get_finished_spans() == ()
def test_without_telemetry_a_call_has_no_span():
begun = Calls().begin("ws", "grid-1", browser="chrome", tool="navigate")
assert begun.span is None
def test_a_tracer_that_raises_never_fails_the_call(monkeypatch):
monitor = FakeMonitor()
calls, rec = calls_with_spans(monitor=monitor)
monkeypatch.setattr(rec.telemetry.tracer, "start_span", refuse)
begun = calls.begin("ws", "grid-1", browser="chrome", tool="navigate")
assert begun.span is None
calls.end(begun, tool="navigate", surface="mcp", browser="chrome")
assert [e.kind for e in monitor.published] == ["call.finished"]In that last test, refuse is a plain function raising RuntimeError, set with
monkeypatch.setattr(rec.telemetry.tracer, "start_span", refuse).
- Step 2: Run them to see them fail
Run: pytest tests/test_call_spans.py -p no:randomly
Expected: FAIL, TypeError: ... unexpected keyword argument 'telemetry'.
-
Step 3: Bracket the span in
calls.py -
begin: after_resumeand the mark,span = self.telemetry.start_call(sessions.split(workspace)[0], sub_session=sessions.is_sub(workspace), tool=tool, browser=browser)whenself.telemetryis set, elseNone; it goes onBegun. The refusal stays first, so a refused call starts nothing. -
end: computeoutcome(error)once, right afterduration; end the span there, before the monitor's touch and the flush, so the span covers what the histogram does; the same outcome goes onCallFinished. -
The module docstring's list gains one bullet: with telemetry on, the call is a
call <tool>span frombegintoend, never made current, naming the workspace and never the sub-session. -
Step 4: Run the tests to see them pass
Run: pytest tests/test_call_spans.py tests/test_control_hosts.py tests/test_capture_hint.py tests/test_monitor_events.py
Expected: PASS.
- Step 5: Run the checks
Run: ruff check . and pytest
Expected: both clean.
- Step 6: Commit
git add kubed/selenium_flow/workspace/calls.py tests/test_call_spans.py
git commit -m "Calls: a span from begin to end, naming the workspace (#65)"Files:
- Create:
kubed/selenium_flow/http/tracing.py - Modify:
kubed/selenium_flow/http/access_log.py(RouteTemplates.matched;templateuses it;quietreturns its filter) - Modify:
kubed/selenium_flow/server.py(http_middlewareonly) - Test:
tests/test_http_tracing.py,tests/test_construction.py,tests/test_main.py
Interfaces:
-
Consumes: Task 1's
Telemetry.tracer,recorded. -
Produces:
-
RouteTemplates.matched(self, path: str) -> str | None: the template of the first route that matches, orNone; -
access_log.quiet(app) -> RouteTemplates: the filter it installed or reused; -
http.tracing.PROBES = ("/health", "/started", "/ready", "/info"); -
class RouteSpans(ASGI):__init__(self, app, *, tracer, templates: RouteTemplates, prefix: str = ""); -
server.http_middleware(telemetry: Telemetry | None = None, *, templates: RouteTemplates | None = None, prefix: str = "") -> list[Middleware]:[RelativeSlashRedirects]without telemetry;[RouteSpans, RelativeSlashRedirects]with it, and aValueErrorwhen telemetry comes without templates.
-
-
Step 1: Write the failing tests in
tests/test_http_tracing.py
A Starlette app built in the module: routes /workspaces/{key}/history (200, and records
trace.get_current_span().get_span_context().span_id in a list), /boom (503), /crash
(raises RuntimeError("at https://example.com/secret")), /health, /mcp, a WebSocket route
/live/{key}, and a Mount("/flow", routes=[/health, /mcp]); wrapped as
Middleware(RouteSpans, tracer=rec.telemetry.tracer, templates=RouteTemplates(routes), prefix="/flow");
driven with TestClient.
def test_a_request_span_is_named_by_its_route_template(app, rec):
TestClient(app).get("/workspaces/acme/history?workspace=acme&sig=s1gn4ture")
[span] = rec.spans.get_finished_spans()
assert span.name == "GET /workspaces/{key}/history" and span.kind is SpanKind.SERVER
assert dict(span.attributes) == {"http.request.method": "GET",
"http.route": "/workspaces/{key}/history", "http.response.status_code": 200}
assert "acme" not in repr(span.to_json()) and "s1gn4ture" not in repr(span.to_json())
def test_the_route_span_is_current_for_the_route(app, rec, seen):
TestClient(app).get("/workspaces/acme/history")
[span] = rec.spans.get_finished_spans()
assert seen == [span.context.span_id]
def test_a_path_no_route_serves_is_named_by_its_method_alone(app, rec):
TestClient(app).get("/acme-workspace/x")
[span] = rec.spans.get_finished_spans()
assert span.name == "GET" and "http.route" not in span.attributes
assert span.attributes["http.response.status_code"] == 404
def test_a_5xx_is_an_error_and_a_2xx_is_not(app, rec):
client = TestClient(app)
client.get("/boom"), client.get("/workspaces/a/history")
by_status = {s.attributes["http.response.status_code"]: s.status for s in rec.spans.get_finished_spans()}
assert by_status[503].status_code is StatusCode.ERROR
assert by_status[200].status_code is StatusCode.UNSET
def test_an_app_that_raises_ends_its_span_as_a_500(app, rec):
with pytest.raises(RuntimeError, match="example.com/secret"):
TestClient(app).get("/crash")
[span] = rec.spans.get_finished_spans()
assert span.attributes["http.response.status_code"] == 500
assert span.status.status_code is StatusCode.ERROR and span.status.description is None
assert len(span.events) == 0 and "secret" not in repr(span.to_json())
@pytest.mark.parametrize("path", ["/health", "/mcp", "/flow/health", "/flow/mcp"])
def test_the_probes_and_mcp_have_no_span(app, rec, path):
TestClient(app).get(path)
assert rec.spans.get_finished_spans() == ()
def test_a_websocket_has_no_span(app, rec):
with TestClient(app).websocket_connect("/live/acme"):
pass
assert rec.spans.get_finished_spans() == ()
def test_a_traceparent_continues_its_trace(app, rec):
TestClient(app).get("/boom", headers={
"traceparent": "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"})
[span] = rec.spans.get_finished_spans()
assert span.context.trace_id == 0x0AF7651916CD43DD8448EB211C80319C
assert span.parent.span_id == 0xB7AD6B7169203331
def test_matched_is_the_template_or_none():
templates = RouteTemplates(ROUTES)
assert templates.matched("/workspaces/acme/history") == "/workspaces/{key}/history"
assert templates.matched("/acme-workspace/x") is None
assert templates.template("/acme-workspace/x") == "/acme-workspace/…" # the log's, unchangedIn tests/test_construction.py:
def test_with_telemetry_the_route_spans_are_outermost():
rec = recorded()
built = http_middleware(rec.telemetry, templates=RouteTemplates(()), prefix="")
assert [m.cls for m in built] == [RouteSpans, RelativeSlashRedirects]
assert [m.cls for m in http_middleware()] == [RelativeSlashRedirects]
with pytest.raises(ValueError):
http_middleware(rec.telemetry)In tests/test_main.py, beside test_the_one_filter_serves_both_loggers_however_often_it_boots:
test_quiet_returns_the_filter_it_installs: quiet(app) is the RouteTemplates on
uvicorn.access, and a second quiet returns the same object.
- Step 2: Run them to see them fail
Run: pytest tests/test_http_tracing.py tests/test_construction.py tests/test_main.py -p no:randomly
Expected: FAIL, No module named 'kubed.selenium_flow.http.tracing'.
- Step 3: Write
matchedand the return ofquietinhttp/access_log.py
template becomes matched(path) or the first-segment fallback; behaviour unchanged.
-
Step 4: Write
RouteSpansinkubed/selenium_flow/http/tracing.py -
Module docstring: one SERVER span per HTTP request, named by the route template so nothing a caller chose reaches it;
/mcpis FastMCP's, the probes are noise, WebSockets are the live view's. -
Passes through untouched: a scope whose
typeis not"http"; a path equal top + probeor top + "/mcp", or starting withp + "/mcp/", forpin""andprefix. -
Parent:
opentelemetry.propagate.extractover the scope's headers decoded as latin-1. -
tracer.start_as_current_span(name, context=parent, kind=SpanKind.SERVER, attributes=..., record_exception=False, set_status_on_exception=False): both off, so neither the exception nor its text reaches the span. -
The status comes from the
http.response.startmessage, through a wrappedsend. An exception from the app with no status sent is 500; it is re-raised as it came. At the end:http.response.status_code, andStatus(StatusCode.ERROR)for 500 and above. -
Step 5: Change
http_middlewareinserver.pyto the signature above; its docstring says the route spans come first so they see every answer, redirects included.run()is Task 4's. -
Step 6: Run the tests to see them pass
Run: pytest tests/test_http_tracing.py tests/test_construction.py tests/test_main.py
Expected: PASS.
- Step 7: Run the checks
Run: ruff check . and pytest
Expected: both clean.
- Step 8: Commit
git add kubed/selenium_flow/http/tracing.py kubed/selenium_flow/http/access_log.py \
kubed/selenium_flow/server.py tests/test_http_tracing.py tests/test_construction.py tests/test_main.py
git commit -m "HTTP: one span per request, named by its route template (#65)"Files:
- Modify:
kubed/selenium_flow/server.py(SeleniumMCP.__init__,run,create_app) - Modify:
kubed/selenium_flow/core/browser.py(Grid.status) - Test:
tests/test_telemetry_wiring.py,tests/test_construction.py,tests/test_grid_connections.py,tests/test_flowapi.py - Modify:
docs/superpowers/specs/runtime.md,workspaces-and-sessions.md,grid.md,errors-and-logging.md - Modify:
CHANGELOG.md([Unreleased], one line)
Interfaces:
-
Consumes: Tasks 1 to 3:
Telemetry,Calls.telemetry,http_middleware,access_log.quiet,RouteTemplates,recorded,points. -
Produces:
SeleniumMCP(settings=None, *, sources=None, store=None, pointers=None, telemetry: Telemetry | None = None)andcreate_app(..., telemetry=None)passing it on;SeleniumMCP.telemetry: Telemetry | None;Grid.status(self, *, timeout: float = GRID_TIMEOUT, retry: bool = True) -> dict. -
Step 1: Write the failing tests
tests/test_telemetry_wiring.py:
GRID = {"url": "http://grid.invalid:4444"}
def test_with_otel_off_nothing_is_wired():
server = create_app(Settings(grid=GRID))
assert server.telemetry is None and server.workspaces.calls.telemetry is None
assert "metrics" not in [s.name for s in server.bus._subs]
def test_with_otel_on_a_telemetry_is_built_on_the_global_providers():
server = create_app(Settings(grid=GRID, telemetry={"otel": True})) # never served
assert isinstance(server.telemetry, Telemetry)
assert server.workspaces.calls.telemetry is server.telemetry
assert "metrics" in [s.name for s in server.bus._subs]
def test_an_injected_telemetry_hears_every_finished_call():
rec = recorded()
server = create_app(Settings(grid=GRID), telemetry=rec.telemetry)
server.bus.publish(CallFinished("ws", "g", "chrome", "navigate", "mcp", "ok", 0.0, 1.5))
[(attributes, point)] = points(rec.metrics, CALL_DURATION)
assert attributes["selenium_flow.surface"] == "mcp" and point.sum == 1.5
def test_the_gauge_reads_the_grid_briefly_and_once(monkeypatch):
rec = recorded()
server = create_app(Settings(grid=GRID), telemetry=rec.telemetry)
asked = []
monkeypatch.setattr(server.grid, "status", lambda **kw: asked.append(kw) or {"value": {"nodes": []}})
rec.metrics.get_metrics_data()
assert asked == [{"timeout": SHOWN_TIMEOUT, "retry": False}]tests/test_construction.py, with the ran fixture:
def test_main_serves_the_route_spans_when_otel_is_on(tmp_path, ran):
main_module.main(_config(tmp_path, "telemetry:\n otel: true\n"))
[(_serving, options)] = ran
assert [m.cls for m in options["middleware"]] == [RouteSpans, RelativeSlashRedirects]test_main_serves_http_through_run_with_the_config_s_settings stays as it is and covers otel off.
tests/test_grid_connections.py, after test_the_idle_timeout_is_asked_once_and_briefly, in
its style: test_status_can_be_asked_briefly_and_not_again — with fake.drop = 1,
grid.status(timeout=SHOWN_TIMEOUT, retry=False) raises requests.ConnectionError, one request
reached the fake, and the timeout sent was SHOWN_TIMEOUT.
tests/test_flowapi.py, beside test_verbose_false_over_http_does_not_turn_verbose_on:
def test_a_runs_steps_are_children_of_its_route_span(tmp_path, monkeypatch):
rec = recorded()
server = untabbed(SeleniumMCP(Settings(grid={"url": "http://grid.invalid:4444"},
auth={"token": TOKEN}, data={"dir": str(tmp_path)}),
telemetry=rec.telemetry))
acting_as(monkeypatch, server, NAMED)
monkeypatch.setattr(server.actions, "navigate", lambda session_id, **kw: {"url": "u", "title": "t"})
monkeypatch.setattr(server.workspaces, "resolved", lambda name: ("b", "chrome"))
templates = RouteTemplates(server.mcp.server.http_app().routes)
client = TestClient(server.mcp.server.http_app(
middleware=http_middleware(rec.telemetry, templates=templates, prefix=server.prefix)))
client.put("/flows/f", json={"steps": GOOD * 2}, headers=named("workflow"))
rec.spans.clear()
assert client.post("/flows/f/runs", headers=named("workflow")).status_code == 200
spans = rec.spans.get_finished_spans()
[route] = [s for s in spans if s.kind is SpanKind.SERVER]
steps = [s for s in spans if s.name == "call navigate"]
assert route.name.startswith("POST /flows/") and "/f/" not in route.name
assert len(steps) == 2
assert {s.parent.span_id for s in steps} == {route.context.span_id}
assert {s.attributes["selenium_flow.surface"] for s in steps} == {"flow"}- Step 2: Run them to see them fail
Run: pytest tests/test_telemetry_wiring.py tests/test_construction.py tests/test_grid_connections.py tests/test_flowapi.py -p no:randomly -k "otel or telemetry or gauges or briefly or route_span or finished"
Expected: FAIL, SeleniumMCP has no telemetry / unexpected keyword telemetry.
-
Step 3: Give
Grid.statusits two keywords, passed to_json; the docstring says the gauge asks it briefly and once (RUN-33). Every existing caller keeps the defaults. -
Step 4: Wire it in
server.py -
After the workspaces are built:
self.telemetry = telemetry, orTelemetry()when it isNoneandsettings.telemetry.otelis on, elseNone. With one: setself.workspaces.calls.telemetry;self.bus.subscribe("call.finished", self.telemetry.call_finished, name="metrics");self.telemetry.grid_gauge(lambda: grid.status(timeout=SHOWN_TIMEOUT, retry=False)). A comment says an injected one is used whateverotelsays, so the tests record without kubed-mcp starting an SDK. -
run(): over HTTP,templates = access_log.quiet(self.mcp.server.http_app(path=self.mcp_path))andmiddleware=http_middleware(self.telemetry, templates=templates, prefix=self.prefix); overstdio,http_middleware(). -
create_apppassestelemetrythrough; the class docstring is unchanged. -
Step 5: Run the tests to see them pass
Run: pytest tests/test_telemetry_wiring.py tests/test_construction.py tests/test_grid_connections.py tests/test_flowapi.py tests/test_main.py
Expected: PASS.
- Step 6: Edit the area files
runtime.md, at the end of ## Telemetry (before the link definition):
-
RUN-32. With
telemetry.otelon, every callCalls.endends is recorded onselenium_flow.call.duration, a histogram in seconds of the call's own time inside its turn (WS-28'sduration), by themetricssubscriber (WS-29). Its attributes are exactlyselenium_flow.tool,selenium_flow.surface(mcp,httporflow),selenium_flow.outcome(ok,4xxor5xx) andselenium_flow.browser; never the workspace, the session key or a Grid id. Its buckets are those ofmcp.server.operation.duration: 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120 and 300 s. Its count is the call count. A call refused because a person holds the browser is never begun and is not recorded. -
RUN-33. With
telemetry.otelon, a gauge reports the Grid:selenium_flow.grid.slotsbyselenium_flow.browserandselenium_flow.slot.state. A slot isbusywhile it holds a session, andfreewhile it holds none on a node that is up and below itsmaxSessions(GRID-12); other slots are not counted. One collection readsGET /statusonce, briefly and without a retry (GRID-2), on the metric reader's thread, and a collection on the event loop reads nothing. A read that fails observes nothing, is logged by type once a streak, and never raises. Every replica reports the same Grid, so a dashboard takes themaxof it, never thesum. -
RUN-34. With
telemetry.otelon, every begun call is a span,call <tool>, fromCalls.begintoCalls.end, a child of the context current atbegin: FastMCP'stools/callspan over MCP, the route span (RUN-35) over HTTP, and the run's context for a flow step. It is never made current. It carriesselenium_flow.workspace, the workspace and never a sub-session's name,selenium_flow.sub_session,selenium_flow.tool,selenium_flow.browser,selenium_flow.surfaceandselenium_flow.outcome. A failed call's span has status ERROR with no description anderror.type, the exception's class name, and records no exception. A span that fails is logged by type and never fails the call. -
RUN-35. With
telemetry.otelon, every HTTP request is one server span named<method> <route template>(ERR-29), withhttp.request.method,http.routeandhttp.response.status_codeand nothing else of the request. A method outside the nine HTTP defines is_OTHER. A path no route serves is named by its method alone, withouthttp.route. The span continues the trace the request'straceparentnames, and a 5xx, or a request that raised, has status ERROR./mcp, the four probes, at the root and underroute_prefix, and WebSockets have none. -
RUN-36. The instruments and spans are the scope
kubed.selenium_flowwith the package's version, and go where kubed-mcp's OpenTelemetry sends them (RUN-29): pushed over OTLP, or, withOTEL_METRICS_EXPORTER=prometheusandOTEL_EXPORTER_PROMETHEUS_HOST=0.0.0.0, scraped from the exporter's own port, 9464, not the server's. Withtelemetry.oteloff none is made.
Also in runtime.md: a RUN-12 row | The Grid gauge's read (RUN-33) | the metric reader's thread, or the scrape's; never the loop |; a RUN-25 row | Grid gauge read | 5 s, no retry | none | RUN-33 |.
workspaces-and-sessions.md: WS-28 "Nothing subscribes to it." becomes "The metrics
subscriber hears it when telemetry.otel is on (RUN-32)." WS-29 ends with "call.finished
is heard by the metrics subscriber when telemetry.otel is on."
grid.md: GRID-2's GET /status row: its use gains "the telemetry gauge (RUN-33)", its timeout "5 s
for the idle timeout and the gauge", its retry "no for the idle timeout and the gauge".
GRID-12 gains: "The gauge (RUN-33) also read each node's availability and maxSessions
and each slot's stereotype.browserName; a node without availability counts as up, and one
without maxSessions has no cap."
errors-and-logging.md: ERR-30's WARNING row gains "a Grid read for the gauge or a span
that failed, by type". ERR-35 gains the row | On a span, a sub-session's name, a Grid id, an argument, a URL, a query or an exception's text; on a metric, a workspace or a session key | RUN-32, RUN-34, RUN-35 |.
- Step 7: Add the changelog line at the top of
[Unreleased]
- **Browser metrics and traces:** with `TELEMETRY_OTEL=true`, each call's time by tool, surface, outcome and browser, the Grid's busy and free slots, and a span for every call, naming its workspace, and every HTTP request (#65).- Step 8: Run the checks
Run: ruff check . and pytest
Expected: both clean, tests/test_wiki.py included, and git status tests/golden shows
nothing.
- Step 9: Commit
git add kubed/selenium_flow/server.py kubed/selenium_flow/core/browser.py \
tests/test_telemetry_wiring.py tests/test_construction.py tests/test_grid_connections.py \
tests/test_flowapi.py CHANGELOG.md docs
git commit -m "Server: selenium-flow's telemetry behind telemetry.otel (#65)"- In the PR: whether Task 1 Step 1 added
opentelemetry-sdktotestand narrowed #199's packaging assertion. - Dr K checks in the cluster, which the runners can't reach: with
TELEMETRY_OTEL=true,selenium_flow_call_duration_secondsand the Grid gauge appear in the metrics backend, and anavigatecall's trace showscall navigateunder FastMCP'stools/call navigatewithselenium_flow.workspaceset.
The action pages are generated from the server's tool schemas, so they describe the version that shipped.
selenium-flow · MIT
Start here
Guides
Lifecycle
Going places
Doing things
Getting things out
Site data
Console and network