Backend
Detection — At the start of every invocation, before taking any action, determine which backend to use:
- If the user passed
--backend pupanywhere in their invocation → use pup mode immediately, regardless of whether MCP tools are present. Skip steps 2–4. - Check whether MCP tools are present in your active tool list. The canonical signal is whether
mcp__datadog-llmo-mcp__search_llmobs_spansappears in your available tools. - If MCP tools are present → use MCP mode throughout. Call MCP tools exactly as named in this skill's workflow sections.
- If MCP tools are absent → check whether
pupis executable: runpup --versionvia Bash. A JSON response containing"version"confirms pup is available. - If pup responds → use pup mode throughout. Translate every MCP tool call to its pup equivalent using the Tool Reference appendix at the bottom of this file.
- If neither is available → stop and tell the user:
"Neither the Datadog MCP server nor the pup CLI is available. Connect the MCP server (
claude mcp add --scope user --transport http datadog-llmo-mcp 'https://mcp.datadoghq.com/api/unstable/mcp-server/mcp?toolsets=llmobs,rum') or install pup."
--backend pup is accepted anywhere in the invocation arguments and is stripped before passing remaining args to the skill logic.
pup invocation rules:
- Invoke via Bash:
pup llm-obs <subcommand> [flags] - pup always outputs JSON. Parse directly — no content-block unwrapping (unlike MCP results, which may wrap JSON in
[{"type": "text", "text": "<json>"}]). - If pup returns an auth error, tell the user to run
pup auth loginand stop. - Parallelization: issue multiple Bash tool calls in a single message (one pup command per call).
- Time flags: pup accepts bare duration strings (
1h,7d,30m) and RFC3339 timestamps. Do not usenow--prefixed strings — strip the prefix when converting from a skill--timeframeargument:now-7d→7d,now-24h→24h,now-30d→30d. --summaryonpup llm-obs spans searchstrips payload fields to essential metadata only. Use it in bulk/search phases where content is not needed.
pup mode notes by entry mode:
session_idmode: Steps 1–3 and Step 5 work fully. Step 4 (RUM) usespup rum aggregate --user-email EMAILinstead ofanalyze_rum_events— see Tool Reference. Step 4b (audit trail) is pup-native and queries the active user's own org via OAuth.trace_idmode: Full parity with MCP mode.ml_appmode: Option A (aggregate_spans) is unavailable in pup — skip it and proceed directly to Option B.
Invocation ID: At the very start of each invocation, before any MCP tool call, generate an 8-character hex invocation ID (e.g., 3a9f1c2b). Keep it constant for the entire invocation.
Intent tagging: On every MCP tool call, prefix telemetry.intent with skill:agent-observability-session-classify[<inv_id>] — followed by a description of why the tool is being called. On the first MCP tool call only, use skill:agent-observability-session-classify:start[<inv_id>] — instead (note the :start suffix). Example first call: skill:agent-observability-session-classify:start[3a9f1c2b] — Step 1: enumerate turn root spans for session abc-123
Skill: eval-session-classify
Classification skill for Datadog Agent Observability sessions and traces. Produces a satisfaction verdict (yes / partial / no) with a brief reasoning string. Designed to be called standalone or by eval-pipeline.
Inputs
| Input | Mode | Required | Description |
|---|---|---|---|
session_id |
session_id mode | Yes | UUID of a Datadog CMD+I assistant session |
trace_id |
trace_id mode | Yes | Trace ID from Agent Observability |
ml_app |
ml_app mode | Yes | LLM app name to sample from |
timeframe |
ml_app mode | No (default: now-7d) |
How far back to sample |
sample_limit |
ml_app mode | No (default: 20, cap: 50) |
Number of sessions or traces to classify |
If none of session_id, trace_id, or ml_app is provided → stop immediately and return:
{
"error": "missing_input",
"detail": "Provide one of: session_id, trace_id, or ml_app."
}
Phase 0 — Mode Detection
session_idprovided → session_id mode → go to Session Modetrace_idprovided (nosession_id) → trace_id mode → go to Trace Modeml_appprovided (nosession_id, notrace_id) → ml_app mode → go to ML App Mode- Nothing provided → emit error (see above)
Output Format
Default (compact) — used in all modes unless the caller requests verbose:
verdict: yes | partial | no
reason: <one sentence>
Verbose — full markdown report (see end of each mode section). Request verbose by including verbose: true in input or asking for a detailed report.
In ml_app mode, a summary table is always appended after the per-trace compact blocks.
Content Retrieval Cascade
Reading conversation content follows this cascade across all modes. Run the cascade for every turn root span identified in Step 1 (session mode) or Step T1 (trace mode) before forming a verdict.
Completeness gate: do not proceed to RUM (session mode) or classification (any mode) until the cascade has run for every turn. Previews from
search_llmobs_spans(input.preview/output.preview, truncated to ~200 chars) do NOT satisfy this gate — they identify turn boundaries, nothing more. Only actual content fromget_llmobs_agent_loop,expand_llmobs_spans+get_llmobs_span_content, orget_llmobs_span_content(field="input"/"output")counts.Short sessions (≤ 20 turns): run C1/C2 for every turn — no selection, no "key turns" heuristic.
Long sessions (> 20 turns): run C1/C2 for the first 5 and last 5 turns, plus any turn whose
input.previeworoutput.previewflags an anomaly (error, correction loop, repeated intent, unexpected tool). Scan all remaining turns' previews for anomalies before skipping them.
Parallelism: issue all N get_llmobs_agent_loop calls in a single message — one call per turn, all in the same batch. For an N-turn session this means N simultaneous C1 calls. Do not process turns sequentially and do not form partial verdicts before all results are in hand. Move to C2 for a turn only when C1 returns iterations: [] for that turn.
C1 — get_llmobs_agent_loop(trace_id, agent_span_id)
The richest source: full system prompt, user message, tool call arguments + results, assistant response, and token economics per iteration. Attempt this first for every agent span.
get_llmobs_agent_loop(
trace_id = "<TRACE_ID>",
span_id = "<AGENT_SPAN_ID>",
from = "now-90d",
to = "now",
max_content_length = 2000
)
iterations: []andtimeline: null→ the app's LLM spans go through an intermediate workflow layer (e.g.get_answer_from_model_step) rather than as direct children of the agent span. Fall through to C2.- 404 → span ID does not resolve in the trace store. Fall through to C2.
- Content fields contain
<REDACTED_INPUT>or<MASKED_STREAMING_RESPONSE>→ IO tracing is disabled by a feature flag. Structure (iteration count, tool names, token usage) is still useful — note it. Fall through to C2 for actual content.
When a C1 result is too large for context and gets persisted to disk (common on long sessions): do NOT try to Read the full file — it will exceed the token limit. Run a targeted Python extraction to build a structured per-turn summary:
import json
with open('<persisted_path>') as f:
data = json.loads(json.load(f)[0]['text'])
iters = data['iterations']
for it in iters:
tcs = [tc['name'] for tc in it.get('tool_calls', [])]
content = it.get('content', '') or ''
# Skip the system prompt body — it's verbose and not what we're classifying.
if len(content) > 4000 and content.lstrip().startswith('#'):
content = '[system prompt]'
print(f"iter {it['iteration']} [{it.get('status')}] tools={tcs}"
f" err={it.get('error_message','')} content={content[:300]}")
A large-but-parseable C1 result is real content; only fall through to C2 if C1 returned iterations: [].
C2 — get_llmobs_span_content(field="messages") on LLM child spans
When C1 returns iterations: [], the LLM spans typically sit 2 levels below the root agent span — under a workflow wrapper (e.g. get_answer_from_model_step) that the agent-loop API does not descend into. The concrete tree per turn:
<root agent span> ← one per turn
<workflow wrapper> ← one per LLM round-trip
<llm span, e.g. anthropic.request> ← call `field="messages"` here
Use expand_llmobs_spans to navigate to the LLM span IDs — not get_llmobs_trace, which only returns depth-1 children and cannot reach LLM spans nested under a workflow:
expand_llmobs_spans(
trace_id = "<TRACE_ID>",
span_ids = ["<ROOT_AGENT_SPAN_ID>"],
max_depth = 2, # root → workflow → llm span
from = "now-90d", # required: default is now-1d, silently returns empty for older spans
to = "now"
)
From the returned tree, collect all nodes with span_kind=llm and has_input=true (commonly named anthropic.request, openai.request, chat_completion-call, messages-call). Call get_llmobs_span_content(field="messages") on each.
JSONPath + truncation trap: path is applied after max_tokens truncation. Each LLM-call span typically starts with a multi-KB system prompt, so a low max_tokens means the JSONPath filter operates on system-prompt-only content and silently returns the wrong messages.
To extract the meaningful tail (user query, tool calls, final answer):
- Call once without
pathto readtotal_tokens_approxfrom the response. - Re-call with
path = "$.[-5:]"andmax_tokens = total_tokens_approx + 500.
get_llmobs_span_content(
trace_id = "<TRACE_ID>",
span_id = "<LLM_SPAN_ID>",
field = "messages",
path = "$.[-5:]",
max_tokens = <total_tokens_approx + 500>
)
This returns the last 5 messages: typically [user context+query, reasoning, assistant text, assistant tool_call, tool result] — enough to understand what the turn did.
- Messages are
"REDACTED"→ IO tracing disabled. Fall through to C3. content_infomap does not includemessages→ not a chat span. Fall through to C3.
C3 — get_llmobs_span_content(field="input") and field="output" on the root span
The root span often carries synthetic summaries written by the app (e.g. the raw user query as input, the final response as output, or "Investigate error for issue: <id>" / "Investigation completed with status: completed"). Minimal signal, but enough to confirm what the task was and whether it completed.
C4 — Structural signals only
When all content is inaccessible, classify from span metadata alone:
status(ok / error),stop_reason,response_truncated- Child span names (tool names, workflow step names like
classify,generate-summary,suggest-action) iterationtag count (total LLM rounds)- Duration and token counts if available
Drill-down — targeted extraction for suspicious tool results
After the summary pass, drill into any turn whose tool list includes a client-rendered tool, a write operation, or an iteration flagged with error_message. These checks surface silent failures the summary loop cannot detect.
Triggers:
Client-rendered tools (browser-handled, e.g.
show_content,create_datadog_notebook,edit_datadog_notebook) — always mandatory when present. The server fires an event; the client handles display. The result tells you whether rendering was delegated or confirmed."This tool is handled by the client application..."→ delegated to browser, no server-side confirmation the user saw anything. Check for aclient_tool_responsein the next turn's input. If absent, or if the next turn shows user confusion, treat as invisible output — strong negative signal.- Any other result → executed server-side; output was in the response stream.
Write operations (e.g.
call_datadog_api,upsert_datadog_dashboard,upsert_widget, monitor/notebook create-or-update) — the assistant often narrates "I updated X" regardless of the actual HTTP outcome. Check the result for:403/"not allowlisted"/"PUT not allowlisted"→ write blocked; the change was never applied.404→ asset not found; editing something that doesn't exist.500/"internal server error"→ write uncertain, may not have landed."Session not found"→ resource expired before the tool ran.200/201with payload → confirmed success.
Data queries returning empty (e.g.
search_datadog_metrics,get_datadog_metric,search_datadog_logs,search_datadog_spans) — when the summary shows many iterations (> 5) of the same query tool, check whether results were empty. An assistant reasoning fromNO_DATA/ empty arrays may produce plausible-sounding but fabricated analysis (hallucinationfailure mode).Error iterations — any iteration where
error_messageis set: confirm the exact error, which tool triggered it, and whether the assistant retried successfully or gave up. A transient retry is neutral; a permanent API restriction or repeated identical failure is negative.
CLIENT_TOOLS = {'show_content', 'create_datadog_notebook', 'edit_datadog_notebook'}
WRITE_TOOLS = {'call_datadog_api', 'upsert_datadog_dashboard', 'upsert_widget'}
FAIL_STRINGS = {'403', '404', '500', 'not allowlisted', 'not found', 'session not found', 'error'}
for it in iters:
if it.get('error_message'):
print(f"ERROR iter={it['iteration']}: {it['error_message'][:200]}")
for tc in it.get('tool_calls', []):
name = tc['name']
result = (tc.get('result') or '')
if name in CLIENT_TOOLS:
print(f"CLIENT iter={it['iteration']} {name}: {result[:300]}")
elif name in WRITE_TOOLS or any(s in result.lower() for s in FAIL_STRINGS):
print(f"WRITE iter={it['iteration']} {name}: {result[:300]}")
Interpretation cheat sheet:
| Result pattern | Verdict signal |
|---|---|
"This tool is handled by the client application" |
Unconfirmed rendering → check next-turn client_tool_response |
403 / "not allowlisted" |
Write blocked — core intent may be unachievable via assistant |
"Session not found" |
Resource expired — tool call had no effect |
NO_DATA / empty list on data query |
No real signal — check for hallucination in assistant's answer |
500 on write op |
Uncertain — may or may not have landed |
200 / 201 with payload |
Confirmed success |
The tool-name lists above are examples calibrated for Datadog assistant apps. For other apps, look at the tool names that appear in C1's tool_calls and reason about their semantics (client rendering vs server side-effect vs read-only query).
Session Mode
Classifies a single Datadog CMD+I assistant session. Uses RUM behavioral signals to confirm the trace-based verdict.
Step 1 — Enumerate turn root spans
search_llmobs_spans(
tags = {"session_id": "<SESSION_ID>"},
root_spans_only = True,
from = "now-90d",
to = "now",
limit = 500
)
pup mode:
pup llm-obs spans search --query "@session.id:<SESSION_ID>" --root-spans-only --limit 500 --from 90d
Use tags={...} (not the query string form). The free-form query="session_id:<id>" triggers full-text behavior that returns the entire trace bundle for every turn (5× the spans, structural filters silently ignored) and exhausts the row budget on long sessions. tags={"session_id": "<id>"} hits the indexed tag filter and respects the other parameters.
root_spans_only=True returns one span per user turn — typically the root agent span — rather than every workflow/LLM/tool descendant. Paginate via next_cursor if the session has more than 500 turns.
For each returned root span, record:
trace_id,span_idstart_ms,duration_ms- Tags:
user_handle,user_id,org_id,product_area,message_id nameandspan_kindof the root (usuallyagent/assistant, but app-dependent)input.preview,output.preview(for turn-boundary identification only — see warning below)
Sort the turns ascending by start_ms. From the first turn's tags, capture session-level identity: user_handle, user_id, org_id, product_area, session start_ms.
Preview-truncation warning:
input.previewandoutput.previeware truncated to ~200 characters. They identify turn boundaries and surface obvious anomalies — they are NOT sufficient for verdict formation. Never skip the Content Retrieval Cascade because the previews already "look conclusive."
If search_llmobs_spans returns no results → stop, return error llmobs_not_found.
Per-turn structural details (iteration count, tool names, stop_reason, mcp flag, response_truncated) are recovered later from each turn's get_llmobs_agent_loop result in Step 3 (C1).
Step 2 — Get evaluations and metadata
get_llmobs_span_details(
trace_id = "<TRACE_ID>",
span_ids = ["<AGENT_SPAN_ID>"],
from/to = <same window>
)
From the evaluations map: iterate all keys, note .value, .reasoning, .tags for each judge.
From content_info.metadata: query_string, referrer_path, referrer_url, entities_json, user_info_json.
If get_llmobs_span_details fails or returns empty → skip silently, proceed to step 3.
If content_info shows metadata is present, fetch it via get_llmobs_span_content(field="metadata") to get the actual query_string and referrer_path — these give the user's question and the page they were on without needing the agent loop.
Step 3 — Read the full conversation
For every turn root span enumerated in Step 1, follow the Content Retrieval Cascade. Issue all per-turn C1 calls (get_llmobs_agent_loop) in a single parallel batch per the cascade's parallelism rule, then fall through to C2 for any turns where C1 returns iterations: [].
For apps where LLM spans sit under a workflow wrapper (e.g. assistant_api, where anthropic.request is a grandchild via get_answer_from_model_step), C1 will routinely return empty iterations — this is expected and the cascade handles it by routing those turns through C2's expand_llmobs_spans navigation. C3 (metadata + output on the root span) is the last resort when no LLM-call content is available.
Step 4a — Resolve RUM session ID(s)
Before the main RUM queries, run a narrow ±2min lookup around the first turn's start_ms to find the exact browser session(s) the user was on. This isolates the RUM session_id(s) and avoids cross-session bleed that occurs when filtering only by @usr.email over a wide time window (a user with multiple tabs across the day will return events from all of them).
analyze_rum_events(
event_type = "action",
filter = "@usr.email:<user_handle> @action.type:custom",
from = <start_ms - 120000>, # 2 minutes before first turn's start_ms (epoch ms)
to = <start_ms + 120000>, # 2 minutes after
sql_query = 'SELECT DISTINCT session_id FROM rum LIMIT 10'
)
Extract all distinct session_id values → store as rum_session_ids. The RUM filter for all subsequent queries (<rum_filter> below) is determined by the result:
- 0 results →
<rum_filter>=@usr.email:<user_handle>(fallback to email + time window). - 1 result →
<rum_filter>=@session.id:<rum_session_id>. - Multiple results →
<rum_filter>=@session.id:(<id1> OR <id2>).
pup mode:
pup rum aggregate --user-email <user_handle> --query "@action.type:custom" --from <start_ms - 120000> --to <start_ms + 120000> --compute count --group-by @session.id. Confirm the--group-byflag name withpup rum aggregate --help.
Step 4 — Get RUM behavioral signals
pup mode: Replace
analyze_rum_eventscalls withpup rum aggregatecalls (see Tool Reference). Page views:pup rum aggregate --user-email USER_HANDLE --from START_MS --to END_MS --compute count --group-by @session.id. Custom actions:pup rum aggregate --user-email USER_HANDLE --query "@action.type:custom" --from START_MS --to END_MS --compute count --group-by @evt.name. Confirm event-type filtering flag withpup rum aggregate --helpif the API rejects the query.
With start_ms and <rum_filter> (from Step 4a), define the window:
- pre:
[start_ms − 30min, start_ms] - during:
[start_ms, start_ms + session_duration_ms] - post:
[start_ms + session_duration_ms, start_ms + session_duration_ms + 60min]
Run in parallel:
RUM Query A — Page view timeline:
analyze_rum_events(
event_type = "view",
filter = "<rum_filter>",
from/to = <pre to post>,
sql_query = "SELECT timestamp, view_url, \"@view.time_spent\" FROM rum ORDER BY timestamp LIMIT 200",
extra_columns = [{"name": "@view.time_spent", "type": "int64"}]
)
@view.time_spent is in nanoseconds.
RUM Query B — Custom actions (product-area narrowed):
analyze_rum_events(
event_type = "action",
filter = "@action.type:custom <rum_filter>",
from/to = <pre to post>,
sql_query = """
SELECT timestamp, "@action.name", view_url FROM rum
WHERE (
"@action.name" LIKE 'command-assistant%'
OR "@action.name" LIKE 'workbench%'
OR "@action.name" LIKE 'ai-experiences%'
OR "@action.name" = 'click on Bad response'
OR "@action.name" = 'click on Incorrect result'
OR "@action.name" = 'click on Submit'
)
ORDER BY timestamp LIMIT 200
""",
extra_columns = [{"name": "@action.name", "type": "string"}]
)
The LIKE filters above are a Datadog assistant example — narrow to whatever action-name prefix is meaningful for the app under classification, or drop the filter to read all custom actions on the session.
If either query returns 0 rows or hits a permission/auth error, do NOT abort the classification. Missing or partial RUM is a coverage gap, not behavioral evidence — treating it as negative is a documented failure mode.
| Condition | Action |
|---|---|
| 0 RUM rows on the session AND user has SOME RUM data in a wider 30-day window (web RUM gap on the session date) | Degraded. Proceed without RUM; rely on trace evidence (Step 3) and audit signals (Step 4b, if applicable). Set rum_coverage: partial — web RUM gap on session date in the output. |
analyze_rum_events / pup rum returns permission or auth errors on one or more queries (common for external orgs, SOC2-isolated tenants) |
Degraded. Use whichever RUM queries returned rows; fall back to trace + audit for the missing pieces. Set rum_coverage: partial — auth error on <query> in the output. |
| 0 RUM rows on the session AND no RUM data anywhere for the user in 30 days | Degraded. Proceed with trace + audit. Set rum_coverage: unavailable — no RUM data for user in the output. Do NOT emit rum_unavailable as a terminal error. |
Hard rule: never use the absence of RUM as evidence for a negative verdict. If trace and audit signals point to satisfaction, the absence of RUM does not override them; if trace signals are ambiguous, default to the trace-only verdict rather than penalizing for missing behavioral data.
The rum_unavailable error code is reserved for the unrecoverable case where RUM was required by the classification protocol (e.g., the trace is so content-redacted that RUM is the only remaining signal) AND no RUM exists. Otherwise, proceed in degraded mode.
Signal interpretation framework
RUM actions are not equal evidence. Stratify them into three tiers and let the tier control how much weight each carries in Step 5. The categories below are agent-agnostic — map your specific app's RUM action names onto them. Treat unrecognized actions as Ambiguous until you have evidence for how they correlate with satisfaction.
Tier-A — sufficient on its own (when present, can flip or confirm the trace verdict)
| Abstract category | Direction | Example action-name patterns |
|---|---|---|
| Stream-abort fired before the response completed | negative | *.chat-cancel, *.stream-abort, *.cancel-generation |
| Panel/window closed mid-stream with no reopen within 1s | negative | *.panel.close while the agent's LLM span is still active |
| Navigation to a URL containing an asset ID the agent explicitly named in its response | positive | View on the exact resource path the agent referenced |
| Artifact action within 60s of session end on the agent's output | positive | Export, save, modify, share targeting the produced asset |
| New session within 15 min with the same intent (retry per Step 1b classifier) | negative | Detected by neighbor-session analysis |
Wholesale rejection of the agent's plan (reject_all or equivalent) |
negative | Bulk-reject affordance, "stop" action mid-stream |
Tier-B — corroborating, never decisive on its own
| Abstract category | Direction |
|---|---|
| Short dwell on the agent's view (< 30s total) | negative |
| Post-session navigation to external help (docs, support, community) | negative |
| Repeated panel/view opens before any response | negative |
| Long dwell time (> 60s) on the agent's view | positive |
| Click on a markdown link the agent rendered | positive |
| Post-session navigation to a topic-adjacent resource (not exact-asset match) | positive |
Ambiguous — DO NOT use as sole evidence
| Abstract category | Why ambiguous | Rule |
|---|---|---|
| Reveal/expand interactions on intermediate state (tool-call panels, reasoning blocks) | Fires in both engaged-reading and pre-thumbs-down-scrutiny patterns; no principled rule discriminates | Pair with a Tier-A or matching Tier-B signal of the same direction |
Single approval of a tool call (accept on one of N proposals) |
The expected UX step — users click accept even on mediocre responses | Treat as WEAK positive; never primary evidence for yes |
Single rejection of a tool call (reject on one of N proposals) |
Could be "user redirected to a better path", not "user dissatisfied" | Count as negative ONLY if user also stopped sending messages OR all subsequent calls were rejected |
| Panel/view close without mid-stream context | "Session ended naturally" indistinguishable from "abandoned" | Need stream-active timing — see Tier-A |
For your specific agent: before classifying, build a mapping from your app's RUM action names onto these categories. A reference mapping for the Datadog CMD+I assistant is in @rum-actions-bits-assistant.md — use it as a template for what to look up in your own app's RUM event taxonomy. Unrecognized action names default to Ambiguous; promote to Tier-B or Tier-A only after you have evidence (from labeled sessions or product knowledge) for how the action correlates with satisfaction.
For interpreting Datadog assistant action names specifically, consult @rum-actions-bits-assistant.md.
Step 4b — Get audit-trail signals (when an asset was created or edited)
The audit trail surfaces server-confirmed effects of the assistant's actions (writes that landed, modifications that stuck, deletions, follow-up edits) and post-session user behavior on the same asset. For sessions where the assistant created or edited a Datadog asset (dashboard, notebook, monitor, SLO, etc.), this is the most authoritative behavioral signal — more direct than RUM clicks.
Primary tool: pup audit-logs search, which queries the active user's own org via OAuth (pup auth login).
When to run this step:
- The trace's tool calls include any write op (
upsert_*,call_datadog_apiwithPUT/POST, monitor/notebook create-or-update) → run it. - The session has a known asset ID (from a tool-call argument, the
dashboard_idtag, the session'sreferrer_path, or the user query) → run it. - The trace is pure read-only (no writes, no asset ID) → skip; nothing for audit to add over Step 4.
Query priority (most signal first, least noise last):
@asset.id— modification/deletion history with full diff. Most authoritative. Required when an asset ID is known.- Q3 (targeted HTTP path) — write count and timing for the same asset. Required when an asset ID is known.
- Q1 / Q2 (broad-signal HTTP audit) — fallback only. Noisy on active users.
@asset.id — modification history
pup audit-logs search \
--query '@asset.id:<asset_id>' \
--from "<session_start - 30d, ISO>" --to now --limit 50
Each row's body lives at row["attributes"]["attributes"]. Fields:
action—created/modified/deleted/accessedusr.emailasset.type(dashboard,notebook,monitor, …),asset.id,asset.nameasset.new_value/asset.prev_value— full before/after state as nested dicts (use directly; no JSON parsing needed)timestamp— ISO8601 string
Pup returns descending order by default. Sort ascending for the chronological session arc:
rows = sorted(d["data"], key=lambda r: r["attributes"]["attributes"]["timestamp"])
Signals:
Event after session_end |
Verdict signal |
|---|---|
deleted event |
Strong negative — asset was torn down |
modified by the user, fewer widgets/cells/items than prev_value |
Negative — user undid the assistant's changes |
modified by the user, more items than prev_value |
Positive — user extended what the assistant built |
modified with query / threshold change (monitor) |
Negative — user disagreed with the assistant's values |
modified with message / tag change only |
Neutral — cosmetic |
| No events | Neutral-to-positive — asset untouched |
Do not over-interpret audit signals. Audit measures backend correctness, not user satisfaction — a missing write or absent event is not by itself proof of dissatisfaction. The exception is explicit user actions: a
deletedevent, a manualmodifiedwith widget/cell removal, or a manual write that overrides what the agent produced. Those are direct user intent and can flip a verdict. Backend-symptom signals (zero writes despite acceptance, missing PUTs, etc.) should only corroborate trace + RUM, never flip them alone.
For dashboards, the most useful diff is widget count:
nv = row["attributes"]["attributes"]["asset"]["new_value"]
pv = row["attributes"]["attributes"]["asset"]["prev_value"]
delta = len(nv["dashboard_definition"]["widgets"]) - len(pv["dashboard_definition"]["widgets"])
Q3 — targeted HTTP path (write count + timing)
While @asset.id shows the diff, Q3 shows the HTTP event count for writes to the resource — useful for cross-checking the trace's tool calls and finding manual post-session edits.
# Dashboard:
pup audit-logs search \
--query '@usr.email:<user_handle> @http.url_details.path:/api/v1/dashboard/<dashboard_id>' \
--from "<session_start - 30min, ISO>" --to "<session_end + 2h, ISO>" --limit 200
# Notebook:
pup audit-logs search \
--query '@usr.email:<user_handle> @http.url_details.path:/api/v2/notebook/<notebook_id>' \
--from ... --to ... --limit 200
Phase-bucket the events to see what happened during vs after the session:
from collections import Counter
phase_method = Counter()
rows = sorted(d["data"], key=lambda r: r["attributes"]["attributes"]["timestamp"])
for r in rows:
a = r["attributes"]["attributes"]
ts = a["timestamp"]; m = a["http"]["method"]; s = a["http"]["status_code"]
if ts < session_start_iso: phase = "pre-session"
elif ts < session_end_iso: phase = "during"
elif ts < feedback_iso: phase = "session_end->feedback" # only when feedback time is known
else: phase = "post"
phase_method[(phase, m, s)] += 1
Each PUT is one write. 200/201 = confirmed success. status_code: 0 means the browser sent the request but navigated away before the response landed — server almost certainly processed it; count it alongside the 200s.
Interpretation:
during PUT 200count should match the trace's upsert tool-call count.- Writes timestamped 10–30s after
session_endand whose count matches the last turn's expected writes are async tool execution lag — not user-initiated. - Writes beyond 30s after
session_endare user manual edits. Count them post-session: a small clustered burst (e.g., 5–10 PUTs in ~1 min) = fine-tuning (mildly positive — user kept the result and improved it); zero post-session PUTs = clean acceptance. - Confirmed cancelled sessions have zero
during PUTevents.
Q1 / Q2 — broad-signal HTTP audit (fallback)
Use only when no asset ID is known, or to look for retry / support-ticket signals after the targeted queries.
# Q1: broad signal, session ± window
pup audit-logs search \
--query '@usr.email:<user_handle>' \
--from "<session_start - 15min, ISO>" --to "<session_end + 30min, ISO>" --limit 200
# Q2: post-session, strip the highest-volume noise paths
pup audit-logs search \
--query '@usr.email:<user_handle> -@http.url_details.path:/api/ui/query/scalar -@http.url_details.path:/api/ui/query/timeseries' \
--from "<session_end, ISO>" --to "<session_end + 30min, ISO>" --limit 200
Noise dominates on active users. The 200-row cap is real and there is no pagination cursor. Other high-volume paths to strip when needed:
/api/ui/frontend_telemetry/metrics,/api/v1/logs-analytics/aggregate,/api/v1/logs-analytics/list,/api/v1/logs-analytics/facet_info,/api/v2/watchdog/insights/search/*,/api/v2/notifications/notify/*,/api/v2/notifications/presence/*. If you still hit the cap after stripping, narrow the time window.
Look for: support ticket creation (POST /api/v2/cases), retry assistant calls (POST /api/v2/assistant), navigation to docs (visible in RUM Step 4, not here).
Response-extraction helper
The doubly-nested envelope (row["attributes"]["attributes"]) is verbose. Normalize once per script:
import json, subprocess
def pup_audit(query, frm, to, limit=200):
res = subprocess.run([
"pup", "audit-logs", "search",
"--query", query, "--from", frm, "--to", to, "--limit", str(limit),
], capture_output=True, text=True, check=True)
d = json.loads(res.stdout)
rows = []
for r in d.get("data", []):
a = r["attributes"]["attributes"]
rows.append({
"ts": a.get("timestamp"),
"method": a.get("http", {}).get("method"),
"path": a.get("http", {}).get("url_details", {}).get("path"),
"status": a.get("http", {}).get("status_code"),
"action": a.get("action"),
"asset": a.get("asset", {}),
"usr": a.get("usr", {}).get("email"),
})
rows.sort(key=lambda r: r["ts"])
return rows
Graceful degradation
If a query returns 0 rows and the session is in an external customer org, do not error — flag audit_unavailable in the verbose output and continue with trace + RUM. Some external customer audit trails (notably AP1 / SOC2-isolated orgs) are not reachable via pup. Trace + RUM alone is still sufficient for a verdict.
Step 4b — Get audit-trail signals (when an asset was created or edited)
The audit trail surfaces server-confirmed effects of the assistant's actions (writes that landed, modifications that stuck, deletions, follow-up edits) and post-session user behavior on the same asset. For sessions where the assistant created or edited a Datadog asset (dashboard, notebook, monitor, SLO, etc.), this is the most authoritative behavioral signal — more direct than RUM clicks.
Primary tool: pup audit-logs search, which queries the active user's own org via OAuth (pup auth login).
When to run this step:
- The trace's tool calls include any write op (
upsert_*,call_datadog_apiwithPUT/POST, monitor/notebook create-or-update) → run it. - The session has a known asset ID (from a tool-call argument, the
dashboard_idtag, the session'sreferrer_path, or the user query) → run it. - The trace is pure read-only (no writes, no asset ID) → skip; nothing for audit to add over Step 4.
Query priority (most signal first, least noise last):
@asset.id— modification/deletion history with full diff. Most authoritative. Required when an asset ID is known.- Q3 (targeted HTTP path) — write count and timing for the same asset. Required when an asset ID is known.
- Q1 / Q2 (broad-signal HTTP audit) — fallback only. Noisy on active users.
@asset.id — modification history
pup audit-logs search \
--query '@asset.id:<asset_id>' \
--from "<session_start - 30d, ISO>" --to now --limit 50
Each row's body lives at row["attributes"]["attributes"]. Fields:
action—created/modified/deleted/accessedusr.emailasset.type(dashboard,notebook,monitor, …),asset.id,asset.nameasset.new_value/asset.prev_value— full before/after state as nested dicts (use directly; no JSON parsing needed)timestamp— ISO8601 string
Pup returns descending order by default. Sort ascending for the chronological session arc:
rows = sorted(d["data"], key=lambda r: r["attributes"]["attributes"]["timestamp"])
Signals:
Event after session_end |
Verdict signal |
|---|---|
deleted event |
Strong negative — asset was torn down |
modified by the user, fewer widgets/cells/items than prev_value |
Negative — user undid the assistant's changes |
modified by the user, more items than prev_value |
Positive — user extended what the assistant built |
modified with query / threshold change (monitor) |
Negative — user disagreed with the assistant's values |
modified with message / tag change only |
Neutral — cosmetic |
| No events | Neutral-to-positive — asset untouched |
For dashboards, the most useful diff is widget count:
nv = row["attributes"]["attributes"]["asset"]["new_value"]
pv = row["attributes"]["attributes"]["asset"]["prev_value"]
delta = len(nv["dashboard_definition"]["widgets"]) - len(pv["dashboard_definition"]["widgets"])
Q3 — targeted HTTP path (write count + timing)
While @asset.id shows the diff, Q3 shows the HTTP event count for writes to the resource — useful for cross-checking the trace's tool calls and finding manual post-session edits.
# Dashboard:
pup audit-logs search \
--query '@usr.email:<user_handle> @http.url_details.path:/api/v1/dashboard/<dashboard_id>' \
--from "<session_start - 30min, ISO>" --to "<session_end + 2h, ISO>" --limit 200
# Notebook:
pup audit-logs search \
--query '@usr.email:<user_handle> @http.url_details.path:/api/v2/notebook/<notebook_id>' \
--from ... --to ... --limit 200
Phase-bucket the events to see what happened during vs after the session:
from collections import Counter
phase_method = Counter()
rows = sorted(d["data"], key=lambda r: r["attributes"]["attributes"]["timestamp"])
for r in rows:
a = r["attributes"]["attributes"]
ts = a["timestamp"]; m = a["http"]["method"]; s = a["http"]["status_code"]
if ts < session_start_iso: phase = "pre-session"
elif ts < session_end_iso: phase = "during"
elif ts < feedback_iso: phase = "session_end->feedback" # only when feedback time is known
else: phase = "post"
phase_method[(phase, m, s)] += 1
Each PUT
…(truncated)