Observability

Every state change in a run becomes a RunEvent. From that single event stream the playground derives four views: a live SSE feed, a human-readable narration, Prometheus metrics, and a web dashboard. This page covers all four and the optional run persistence behind them.

Source: src/aitp_playground/runner/{context,store}.py, src/aitp_playground/observability/{metrics,narrator}.py, src/aitp_playground/api/{runs,metrics,dashboard}.py.

The event log is the source of truth

RunContext.emit() is the single choke point. Every emit does three things:

  1. Appends the RunEvent to ctx.events (returned in RunResult and the GET /runs/{id} record).
  2. Mirrors it to RunStore.append_event, which powers GET /runs/{id} and wakes every SSE subscriber.
  3. Feeds observability.metrics.record_event, which increments the relevant counters/gauge.

Agents also emit events — they POST /internal/telemetry, which appends to the same run log. So handshake.started, llm.started, etc. (emitted inside an agent subprocess) interleave with runner-emitted events in one ordered stream.

Event types

Runner-emitted

Lifecycle & setup

TypeCarriesWhen
run.startedscenario_refAfter scenario load + input validation.
agent.spawningagent_id, portJust before the agent subprocess is launched.
agent.readyagent_id, aid, portAfter the agent signals ready.
oidc.issuer_mintedissuer url, kidWhen a scenario has any identity_type: oidc agent.
trust.peers_resolvedpeers: {agent_id: manifest_url}After peer discovery resolves.
run.complete—Workflow finished cleanly.
run.failederror, codeRefused before start (unknown scenario, missing SDK feature) or an exception inside spawn / step. code is a lowercase playground code: scenario_not_found, sdk_feature_unavailable, inputs_invalid, a PlaygroundError code such as internal_error, or null.

Trust, delegation, revocation, identity

TypeCarriesWhen
trust.peers_pinnedpeers: {agent_id: aid}After the runner pushed every launched agent's AID into its peers' trust stores, before any handshake (and again after rotate_keys).
trust.establishinginitiator, targetBefore the handshake is initiated.
trust.establishedinitiator, target, grants, jtiAfter successful handshake.
manifest.verify_failedstep_id, agent_id, cause, source_urlA trust-anchor step: the agent's own manifest failed verification before its key could be pinned.
delegation.issuinginitiator, target, grantsdelegate step.
delegation.redeeminginitiator, targetredeem_delegation step.
revocation.publishedjti, to_cprevoke_tct with via_cp.
tct.renewednew jti, expires_atrenew_tct step.
tct.cache.statshits, misses, sizetct_cache_stats step.
identity.key.rotatedold_aid, new_aidrotate_keys step.
session.bundle.exportedsession_id, participant_aidsexport_session_bundle.
session.bundle.verifiedkind, active_aids, dropped_aidsverify_session_bundle.
spki.pin.checkedcomputed_hash_b64, is_pinnedspki_pin_check.

Steps & faults

TypeCarriesWhen
step.startedstep_id, agent, capabilityWorkflow step about to run.
step.completestep_id, resultStep succeeded.
step.skippedstep_id, notesmeta step, or a CP step with no CP configured.
step.probing_no_trustinitiator, target, capabilitycapability_call_no_trust step.
step.probing_with_held_tct…capability_probe step.
step.access_deniedtarget, capability, result.status_codeProbe matched expected non-2xx.
step.unexpected_status…Probe got a status that didn't match expect_status.
step.fault_injectedtarget, notesFault overlay activated.
step.fault_completefault details, captured errorFault step finished without raising.

Control plane

TypeWhen
cp.enroll_started / cp.enroll_completeenroll_with_cp step.
cp.webhook.subscribed / cp.webhook.subscribe_failedcp_subscribe_webhook step.
cp.webhook.deliveredA verified CP webhook delivery arrived (POST /webhooks/cp/{run_id}).
cp.trust_anchor.provisionedcp_provision_trust_anchor step.
cp.delegation.treecp_delegation_tree step.

code casing. The same code key carries two vocabularies, by producer: runner events use lowercase playground codes (sdk_feature_unavailable), agent telemetry and agent HTTP error bodies use uppercase AITP wire codes (REVOCATION_UNAVAILABLE).

Agent-emitted

Agents POST /internal/telemetry directly (best-effort — failures are swallowed rather than failing the run):

TypeCarriesWhen
handshake.started—A responder accepts a hello.
handshake.complete—Initiator or responder closes the 4-message exchange.
handshake.failederrorBad hello or commit.
delegation.issued / delegation.rejected / delegation.redeemed—RFC-AITP-0006 flow milestones. A delegation.rejected caused by a revoked source TCT carries cause revoked_local or revoked_cp_snapshot.
trust.peers_pinnedadded, total/admin/trust-peers changed this agent's handshake trust store.
tct.revoked—/admin/revoke-tct adds a jti.
identity.key.rotatedold_aid, new_aid/admin/rotate-keys replaces this agent's keypair.
capability.self_execute—/admin/self-execute runs.
llm.started / llm.completenotes (only when the quota refused)Wraps the LLM call — the clearest signal in the log that real work happened, not a stub. When the LLM quota refused the call, both carry notes: "mock LLM: quota refused real calls" and the capability ran on its stub.
llm.quota_exceededcode (quota_exceeded, quota_store_unavailable, quota_check_failed), quota, limit, resets_at, capability, agent_id, callsThe first time in a run that the LLM quota refused real calls. Emitted once per run, by the playground (see LLM quota); later refusals only add to the run's llm_calls_on_mock.
llm.failedtask, detail (research tasks also carry topic)The real provider call was attempted (a key was configured) but failed — bad/expired key, quota, unreachable. Surfaces as a 502 from the capability route, detail is the provider's own error text.
manifest.verify_failedcause (the SDK's .code: pop_failed, signature_invalid, expired, aid_mismatch, malformed, …; unknown when it has none), source_urlA fetched peer manifest failed verification. The SDK checks the proof of possession before the signature (RFC-AITP-0003 §5 steps 4–5), so pop_failed says nothing about the signature: it was never assessed.
tct.renewal.requested / tct.renewal.issuedjti, plus TCT identifying fieldsHolder requests a fresh TCT before the held one expires / issuer mints it.
session.bundle.exportedsession_id, participant_countRFC-AITP-0010 coordinator built a session bundle.
session.bundle.verifiedkind, active_countRFC-AITP-0010 verifier checked one.
session.bundle.rejectederrorThe bundle failed verification against the coordinator Manifest (a 403).
tct.renewal.rejectederrorThe issuer refused a renewal request (revoked, expired, or bad proof).
cp.enroll_succeededaid, registered_at/admin/enroll-with-cp completed.
cp.enroll_failedstage (enroll/register), plus status_code/body or transport or decodeEither step of /admin/enroll-with-cp failed.
revocation.list_fetchedjti_count, added, verified, issuerA revocation snapshot verified and was applied.
revocation.refresh_failederrorThe snapshot fetch itself failed (transport, not verification).
revocation.verify_failedcause, detailA fetched snapshot did not verify (forged, wrong issuer, expired, malformed).
revocation.pollhealthy, changed, posture (unchecked | current | degraded)The background revocation-poll loop's own heartbeat.
revocation.degraded_servereason, serves, fail_modeA capability call was served in soft_fail degraded posture (no fresh verified snapshot).

run.cancelled is emitted by the runner, not an agent worker.

Live stream (SSE)

curl -N -H "Authorization: Bearer $PLAYGROUND_API_KEY" http://localhost:8000/runs/<id>/events

GET /runs/{id}/events is a Server-Sent Events stream. On connect it replays the existing backlog from the store, then streams live events from a per-subscriber asyncio queue with 1s heartbeats while idle. It terminates with data: {"type":"stream.end"} once the run is terminal and the queue is drained.

Backpressure: each subscriber queue is capped at 500 events; a consumer that falls behind drops the oldest and can backfill via GET /runs/{id}.

Narration

curl -H "Authorization: Bearer $PLAYGROUND_API_KEY" http://localhost:8000/runs/<id>/narrate      # text/plain, one line per event

observability/narrator.py is a pure function — given the event log it returns one human-readable line per recognized event, e.g.:

[trust] established researcher <- writer grants=[write.content] jti=tct-…
[step]  complete write
[cp]    webhook delivered handshake.complete

Because it's pure, the same renderer drives both GET /runs/{id}/narrate and the CLI trace command — any event log (live, persisted, or replayed from the CP) narrates identically. Unrecognized event types render to an empty string and are filtered out, so the narration stays signal-dense; optional color events (llm.*, capability.self_execute) surface but never dominate.

Metrics

curl -H "Authorization: Bearer $PLAYGROUND_API_KEY" http://localhost:8000/metrics                # Prometheus text exposition (v0.0.4)

observability/metrics.py is a tiny thread-safe registry (counters + one gauge — no histograms; this is a demo). The schema is registered up front so /metrics returns a stable, complete surface even before the first run. record_event maps event types onto these:

MetricTypeLabelsIncremented on
aitp_playground_runs_totalcounterstatus = success/failed/cancelledrun reaches terminal state
aitp_playground_runs_activegauge—run.started (+1) / terminal (−1), only for a run that started
aitp_playground_runs_refused_totalcountercode = the run.failed code (unknown if none)run.failed with no run.started before it (also counted in runs_total{status="failed"})
aitp_playground_handshakes_totalcounteroutcome = established/failedtrust.established / failures
aitp_playground_tcts_issued_totalcounter—trust.established, delegation redeem
aitp_playground_delegations_totalcounteroutcome = issued/redeemed/rejecteddelegation events
aitp_playground_revocations_totalcountersource = local/cptct.revoked / revocation.published
aitp_playground_key_rotations_totalcounter—identity.key.rotated
aitp_playground_capability_calls_totalcounteroutcome = success/deniedcapability step complete/denied
aitp_playground_step_outcomes_totalcounteroutcome = complete/denied/skippedevery workflow step
aitp_playground_llm_quota_charged_totalcounter—real LLM call units the quota allowed (POST /internal/llm-quota)
aitp_playground_llm_quota_denials_totalcounterreason = quota_exceeded/quota_store_unavailable/quota_check_failedevery refused quota check, including ones an agent reports because it got no answer
aitp_playground_llm_quota_store_upgauge—1 when the quota store answered at startup or on the last check, 0 when it is unavailable (every real call is then refused)

Output is deterministically ordered (by metric name then labels) with Prometheus-spec label escaping. It needs the API key like every non-static route (Prometheus: authorization: { credentials: ... }).

LLM quota

Before a capability makes real provider calls, its agent asks POST /internal/llm-quota (loopback only, telemetry token) for the number of call units it is about to spend (calls: 1 per writer call, 2 for the analyzer, MAX_ITER + 1 per research call, the crew's ceiling). The playground charges the counters in src/aitp_playground/quota/ against the run's trusted client IP, taken from the run record, never from the agent. Keyless runs and hosted agents charge the global counters only.

A refusal sends that whole capability to its deterministic stub, so a step is never half real and half mock. It fails closed: a full quota, an unavailable quota store, or an agent that gets no clear answer (timeout, error, non-200) all refuse. The run then shows it in three places:

  • the run summary (GET /runs, GET /runs/{id}, GET /runs/{id}/status): llm_quota_exceeded: true, llm_quota: {reason, quota, limit, resets_at} for the first refusal (resets_at is the UTC reset of the counter that refused; limit and resets_at are null when the store is unavailable), and llm_calls_on_mock, the call units that ran on the mock;
  • one llm.quota_exceeded event per run;
  • notes on the capability's llm.started / llm.complete events.

A run that falls back to the mock still ends success.

Dashboard

http://localhost:8000/dashboard

api/dashboard.py serves a single self-contained HTML page (a dark "signal console") with inline CSS/vanilla JS — no build step, no external assets. It consumes the public endpoints already described: /scenarios, /runs, /metrics, /capabilities, /cp/dashboard, and the per-run SSE stream. It's a convenience viewer; everything it shows is available from the JSON APIs.

Persistence (RUN_HISTORY_DB)

By default RunStore is in-memory only — runs and their events vanish on restart. Set RUN_HISTORY_DB=<path> and the store becomes a SqliteRunStore that:

  • mirrors every upsert and append_event to a SQLite file (runs and run_events tables), and
  • rehydrates the in-memory cache from that file on startup, so GET /runs, GET /runs/{id}, and the SSE backlog survive a process restart.

Live SSE subscribers are not persisted (they're per-process asyncio queues); a new subscriber after restart simply replays the persisted backlog. The in-memory cache stays the authoritative read path — SQLite is a durable sidecar, not a query engine.

Quick reference

ViewEndpointFormat
Live eventsGET /runs/{id}/eventstext/event-stream (SSE)
Full recordGET /runs/{id}JSON (record + events)
Compact statusGET /runs/{id}/statusJSON
NarrationGET /runs/{id}/narratetext/plain
MetricsGET /metricsPrometheus text
DashboardGET /dashboardHTML