: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(tracing): add explore workflow and parsing scripts to apm-traces skill (#59064)
Daniel Visca83310128b950
diff --git a/products/tracing/skills/exploring-apm-traces/SKILL.md b/products/tracing/skills/exploring-apm-traces/SKILL.mdindex f62a439888ba..7a00ada0424d 100644--- a/products/tracing/skills/exploring-apm-traces/SKILL.md+++ b/products/tracing/skills/exploring-apm-traces/SKILL.md@@ -9,62 +9,206 @@ description: ># Exploring APM traces (OpenTelemetry spans)-PostHog captures distributed traces from OpenTelemetry. Each trace is a tree of spans representing a request’s path through services.+PostHog captures distributed traces from OpenTelemetry. Each trace is a tree of spans representing a request's path through services.-**Disambiguation:** This skill is for **APM / OpenTelemetry traces**. Do not confuse with **LLM analytics traces** (agent/model `$ai_*` events and LLM observability tools) or **logs** (`posthog:query-logs`, `posthog:logs-*`).+**Disambiguation:** This skill is for **APM / OpenTelemetry traces**. Do not confuse with **LLM analytics traces** (agent/model `$ai_*` events) or **logs** (`posthog:query-logs`, `posthog:logs-*`).-## MCP tools+## Available tools-| Tool | Purpose |-| ----------------------------------- | ------------------------------------------------------------------------------ |-| `posthog:query-apm-spans` | Search and filter spans (analytics-style query; parameters live under `query`) |-| `posthog:apm-trace-get` | Fetch all spans for a hex `trace_id` |-| `posthog:apm-services-list` | List distinct service names |-| `posthog:apm-attributes-list` | List span or resource attribute keys |-| `posthog:apm-attribute-values-list` | List values for a specific attribute key |+| Tool | Purpose |+| ----------------------------------- | ------------------------------------------------- |+| `posthog:query-apm-spans` | Search and filter spans (compact list view) |+| `posthog:apm-trace-get` | Get the full span list for one hex `trace_id` |+| `posthog:apm-spans-aggregate` | Per-operation aggregates (count, p50/p95, errors) |+| `posthog:apm-spans-tree` | Call-tree aggregates per `(parent, child)` edge |+| `posthog:apm-services-list` | List distinct service names |+| `posthog:apm-attributes-list` | List span or resource attribute keys |+| `posthog:apm-attribute-values-list` | List values for a specific attribute key |-For aggregates or joins not covered by these tools, `posthog:execute-sql` may be appropriate once the span schema is confirmed for the project.+See [references/spans-and-fields.md](./references/spans-and-fields.md) for the response schema and the `kind`/`status_code` enums.-## Span data model+## Workflow: debug a trace from a URL-| Field | Description |-| ---------------- | --------------------------------------------------------------------- |-| `trace_id` | Hex ID linking spans in one trace |-| `span_id` | Hex ID for this span |-| `parent_span_id` | Parent span hex ID (null for root) |-| `name` | Operation name (e.g. `HTTP GET /api/users`) |-| `kind` | 0=Unspecified, 1=Internal, 2=Server, 3=Client, 4=Producer, 5=Consumer |-| `service_name` | Emitting service |-| `status_code` | 0=Unset, 1=OK, 2=Error |-| `timestamp` | Start time (ISO 8601) |-| `end_time` | End time (ISO 8601) |-| `duration_nano` | Duration in nanoseconds |-| `is_root_span` | Whether this is the trace entry |+### Step 1 — Fetch the trace-### Property filter types (`query.filterGroup`)+```json+posthog:apm-trace-get+{+ "trace_id": "<hex_trace_id>"+}+```-- `span` — built-in fields: `trace_id`, `span_id`, `duration`, `name`, `kind`, `status_code`-- `span_attribute` — span-level attributes (e.g. `http.method`)-- `span_resource_attribute` — resource attributes (e.g. Kubernetes labels)+The response is `{ results: [span, span, …] }` — a flat list of every span in the trace.+The list can be very large for fan-out request flows; when it exceeds the inline limit, Claude Code auto-persists it to a file.-## Workflow: investigate slow requests+From the result you get:-1. Discover services: call `posthog:apm-services-list` with `{}` (or applicable filters per tool schema).-2. Find slow spans: `posthog:query-apm-spans` with a `query` that filters by service and `duration` (remember nanoseconds: 1s = 1_000_000_000).-3. Drill in: `posthog:apm-trace-get` with `{ "trace_id": "<hex from step 2>" }`.+- Every span with `name`, `service_name`, `kind`, `status_code`, `parent_span_id`, `duration_nano`, `is_root_span`+- The `_posthogUrl` — **always include this in your response** so the user can click through to the UI-## Workflow: find error traces+### Step 2 — Parse large results with scripts-Use `posthog:query-apm-spans` with `query.filterGroup` on `status_code` `exact` / numeric operators as appropriate — OpenTelemetry status **2** means error.+When the result is persisted to a file (traces with hundreds of spans across services), use the [parsing scripts](./scripts/) to explore it.-## Workflow: explore unknown attributes+**Start with the summary** to get the full picture, then drill into specifics:-1. `posthog:apm-attributes-list` — narrow keys (e.g. search `"http"`).-2. `posthog:apm-attribute-values-list` — inspect values for a chosen key.-3. Build filters in `posthog:query-apm-spans` using the discovered keys.+```bash+# 1. Overview: services, span count, slowest spans, errors+python3 scripts/print_summary.py /path/to/persisted-file.json-## Reminders+# 2. Indented chronological tree (DFS by parent_span_id)+python3 scripts/print_timeline.py /path/to/persisted-file.json-- Prefer discovering attribute keys and services before guessing filters.-- Durations in filters are in **nanoseconds**.-- `query-apm-spans` expects a **`query`** wrapper object; defaults often assume a recent time window — tighten `query.dateRange` when the question implies it.+# 3. Drill into a specific span by name+SPAN="HTTP GET /api/users" python3 scripts/extract_span.py /path/to/persisted-file.json++# 4. Search for a keyword across span names, services, IDs+SEARCH="keyword" python3 scripts/search_spans.py /path/to/persisted-file.json++# 5. When the JSON shape looks unfamiliar+python3 scripts/show_structure.py /path/to/persisted-file.json+```++All scripts support `MAX_LEN=N` env var to control truncation (`0` = unlimited).++## Tree reconstruction (parent_span_id → span_id)++The flat span list is a tree. Each span carries:++- `trace_id` — same on every span in the trace+- `span_id` — this span's unique hex ID+- `parent_span_id` — points to the parent's `span_id` (zero-padded hex `000…000` for the root)+- `is_root_span` — convenience flag for the trace entry++To rebuild the tree:++1. Spans where `is_root_span` is true (or `parent_span_id == "00000000…"`) are **root spans**.+2. Every other span is a child of the span whose `span_id` matches its `parent_span_id`.+3. Group by `parent_span_id`, walk from each root downward.++`scripts/print_timeline.py` does this for you and prints a DFS-indented tree.++## Investigation patterns++### "Where is time going?"++1. Run `print_summary.py` — it surfaces the top-5 slowest spans by `duration_nano`.+2. For a noisy trace, run `print_timeline.py` and scan the indented durations — you can see whether time is dominated by one child span or fan-out across many.+3. To dig into one slow span, `SPAN="<name>" python3 scripts/extract_span.py FILE`.++### "Where did the error happen?"++1. `print_summary.py` lists every span with `status_code == 2` (Error). Each entry shows service, span name, and parent context.+2. Walk up the tree from an error span via `parent_span_id` to see what request path led there.+3. `apm-attribute-values-list` is the only way to fetch error message attributes — they're not in the trace payload.++### "Did the request hit service X?"++1. Run `print_summary.py` — it prints the set of services involved in the trace.+2. If service X is missing, the request never reached it (or instrumentation is missing — check `apm-services-list` to confirm X has emitted spans recently at all).++### "Did the fan-out look right?"++1. `print_timeline.py` shows the indentation — wide trees mean parallel calls, deep trees mean sequential dependencies.+2. Look for spans of kind `Client` (3) followed by matching `Server` (2) spans on the called service — that's a synchronous downstream call.++### Searching by attribute (e.g. `http.method=POST`)++The trace payload **does not contain attributes** — only the span's built-in fields. To filter or search by attributes:++1. Use `apm-attributes-list` / `apm-attribute-values-list` to discover keys and values.+2. Re-issue `query-apm-spans` with a `filterGroup` entry of type `span_attribute` or `span_resource_attribute`.++## Constructing UI links++`apm-trace-get` and `query-apm-spans` return `_posthogUrl` — **always surface this to the user** so they can verify in the PostHog UI.++When presenting findings, include the relevant PostHog URL.++## Finding traces++Use `posthog:query-apm-spans` to search and filter spans. Note this returns spans, not a tree — pass `query.traceId` or grab a `trace_id` from the results and feed it to `apm-trace-get` for the tree.++### Discover before filtering++Before constructing filters, discover what's actually in the project:++1. **Confirm services exist** — call `apm-services-list` to see which services have emitted spans.+2. **Find filterable attributes** — call `apm-attributes-list` with `attribute_type: "span"` or `"resource"`.+3. **Get actual values** — call `apm-attribute-values-list` with a key to see the real values in use.++Only then construct `query-apm-spans` filters. Custom attributes vary per project and cannot be guessed.++### By filters++```json+posthog:query-apm-spans+{+ "query": {+ "serviceNames": ["api-gateway"],+ "dateRange": {"date_from": "-1h"},+ "filterGroup": [+ {"key": "http.status_code", "operator": "gt", "type": "span_attribute", "value": "499"}+ ]+ }+}+```++### By trace ID (when known)++```json+posthog:apm-trace-get+{+ "trace_id": "0123456789abcdef0123456789abcdef"+}+```++### Common gotchas++- **Durations are nanoseconds.** 1 second = `1_000_000_000`. Filter values in `query-apm-spans` for `duration` are also nanoseconds.+- **`status_code == 2` is Error.** `0` is Unset, `1` is OK. Use `OK` to match `{0, 1}` in the UI filter.+- **`kind`** is an integer 0–5: 0 Unspecified, 1 Internal, 2 Server, 3 Client, 4 Producer, 5 Consumer.+- **`parent_span_id` of a root span** is `"0000000000000000"` (16 zero hex chars, matching the 8-byte span ID width — _not_ the 16-byte trace ID width), not null.++## Parsing large trace results++Trace tool results are JSON. When too large to read inline, Claude Code persists them to a file.++### Persisted file format++```json+[{ "type": "text", "text": "{\"results\": [...], \"_posthogUrl\": \"...\"}" }]+```++Every script in `scripts/` unwraps this envelope before parsing.++### Trace JSON structure++```text+results (array of span dicts)+ └── each span:+ ├── uuid, trace_id, span_id, parent_span_id (hex strings)+ ├── name, kind (int 0–5), service_name+ ├── status_code (int 0–2), is_root_span (bool)+ ├── timestamp, end_time (ISO 8601)+ ├── duration_nano (int, nanoseconds)+ └── matched_filter (bool — only meaningful when prefetching from query-apm-spans)+```++### Available scripts++| Script | Purpose | Usage |+| -------------------------------------------------- | ---------------------------------------------------- | -------------------------------------------------- |+| [`print_summary.py`](./scripts/print_summary.py) | Trace metadata, services, slowest spans, errors | `python3 scripts/print_summary.py FILE` |+| [`print_timeline.py`](./scripts/print_timeline.py) | DFS-indented tree from `parent_span_id` walk | `python3 scripts/print_timeline.py FILE` |+| [`extract_span.py`](./scripts/extract_span.py) | Full row + parent/children for spans matching a name | `SPAN="name" python3 scripts/extract_span.py FILE` |+| [`search_spans.py`](./scripts/search_spans.py) | Find a keyword across name, service_name, IDs | `SEARCH="kw" python3 scripts/search_spans.py FILE` |+| [`show_structure.py`](./scripts/show_structure.py) | Show JSON keys and types without values | `python3 scripts/show_structure.py FILE` |++## Tips++- Always set `dateRange` on `query-apm-spans` — queries without a time range are slow. Default is `-1h`; widen only when needed.+- Always include the `_posthogUrl` in your response so the user can click through.+- Attributes are not in the `apm-trace-get` payload — use `apm-attribute-values-list` for those.+- `is_root_span` is the cheap way to find the trace entry — don't string-match `00000000…`.+- For aggregates (p95 by operation, slowest children of a span), use `apm-spans-aggregate` for a flat view or `apm-spans-tree` for parent→child edges — don't reach for SQL.diff --git a/products/tracing/skills/exploring-apm-traces/references/spans-and-fields.md b/products/tracing/skills/exploring-apm-traces/references/spans-and-fields.mdnew file mode 100644index 000000000000..7a1a4b3a8f8d--- /dev/null+++ b/products/tracing/skills/exploring-apm-traces/references/spans-and-fields.md@@ -0,0 +1,56 @@+# APM span field reference++Fields returned by `apm-trace-get` and `query-apm-spans`.++## Span fields++| Field | Type | Description |+| ---------------- | ---------- | ---------------------------------------------------------------------------- |+| `uuid` | string | Internal row UUID (rarely useful for analysis) |+| `trace_id` | hex string | 32-char hex ID linking every span in one trace |+| `span_id` | hex string | 16-char hex ID for this span |+| `parent_span_id` | hex string | Parent span's hex ID. Zero-padded `"00000000…"` for root spans |+| `name` | string | Operation name (e.g. `HTTP GET /api/users`, `db.query`) |+| `kind` | int 0–5 | OpenTelemetry span kind (see enum below) |+| `service_name` | string | Service that emitted the span |+| `status_code` | int 0–2 | OpenTelemetry status (see enum below). `2` is the only error indicator |+| `timestamp` | ISO 8601 | Start time |+| `end_time` | ISO 8601 | End time |+| `duration_nano` | int | Duration in **nanoseconds** (1s = 1_000_000_000) |+| `is_root_span` | bool | Convenience flag for the trace entry — prefer this over comparing parent ID |+| `matched_filter` | bool | Only meaningful when `query-apm-spans` prefetches children of matching spans |++**Not returned in the trace payload:** span attributes (`http.method`, `db.statement`, etc.) and resource attributes (k8s labels, deployment metadata). Discover them via `apm-attributes-list` and fetch values via `apm-attribute-values-list`.++## `kind` enum (OpenTelemetry span kind)++| Value | Label | Meaning |+| ----- | ------------- | ------------------------------------------ |+| `0` | `Unspecified` | Default when no kind is set |+| `1` | `Internal` | Internal operation, no remote boundary |+| `2` | `Server` | Inbound side of a synchronous remote call |+| `3` | `Client` | Outbound side of a synchronous remote call |+| `4` | `Producer` | Producer side of an async messaging system |+| `5` | `Consumer` | Consumer side of an async messaging system |++A synchronous downstream call typically pairs a `Client` span on the caller with a matching `Server` span on the callee.++## `status_code` enum (OpenTelemetry span status)++| Value | Label | Meaning |+| ----- | ------- | --------------------------------- |+| `0` | `Unset` | No status reported |+| `1` | `OK` | Operation completed without error |+| `2` | `Error` | Operation failed |++UI filter chips for `status_code = OK` match `{0, 1}`, but the underlying integer column only stores the raw value. When filtering programmatically, treat any span with `status_code == 2` as the error set.++## Filter property types in `query-apm-spans`++| `type` value | Filters on |+| ------------------------- | -------------------------------------------------------------------------------------- |+| `span` | Built-in span fields: `trace_id`, `span_id`, `duration`, `name`, `kind`, `status_code` |+| `span_attribute` | Span-level attributes (e.g. `http.method`, `db.statement`) |+| `span_resource_attribute` | Resource-level attributes (e.g. `k8s.pod.name`, `service.version`) |++`duration` filters take values in **nanoseconds** (the column is `duration_nano`). The frontend translates `1000ms` → `1_000_000_000` before sending.diff --git a/products/tracing/skills/exploring-apm-traces/scripts/_common.py b/products/tracing/skills/exploring-apm-traces/scripts/_common.pynew file mode 100644index 000000000000..af70241e02aa--- /dev/null+++ b/products/tracing/skills/exploring-apm-traces/scripts/_common.py@@ -0,0 +1,64 @@+"""Shared helpers for the exploring-apm-traces skill scripts.++When a script runs as `python3 scripts/foo.py FILE`, Python prepends the script's+directory to sys.path, so `from _common import ...` resolves without any setup.+"""++import json+++SPAN_KIND = {0: "Unspecified", 1: "Internal", 2: "Server", 3: "Client", 4: "Producer", 5: "Consumer"}+STATUS_CODE = {0: "Unset", 1: "OK", 2: "Error"}+++def is_zero_id(s):+ return not s or set(s) == {"0"}+++def unwrap_text_envelope(raw):+ # Claude Code persists large MCP tool results as [{"type": "text", "text": "<json>"}].+ if isinstance(raw, list) and raw and isinstance(raw[0], dict) and raw[0].get("type") == "text":+ return json.loads(raw[0]["text"])+ return raw+++def load_trace_file(path):+ with open(path) as f:+ raw = json.load(f)+ raw = unwrap_text_envelope(raw)+ if isinstance(raw, dict):+ for key in ("trace_spans", "spans", "results"):+ if key in raw and isinstance(raw[key], list):+ return raw[key]+ return [raw]+ return raw if isinstance(raw, list) else [raw]+++def fmt_duration(nanos):+ if nanos is None:+ return "?"+ try:+ n = int(nanos)+ except (TypeError, ValueError):+ return str(nanos)+ if n >= 1_000_000_000:+ return f"{n / 1_000_000_000:.2f}s"+ if n >= 1_000_000:+ return f"{n / 1_000_000:.1f}ms"+ if n >= 1_000:+ return f"{n / 1_000:.1f}\u00b5s"+ return f"{n}ns"+++def truncate(s, max_len, show_total=False):+ if max_len <= 0 or len(s) <= max_len:+ return s+ suffix = f"... [{len(s)} chars total]" if show_total else "..."+ return s[:max_len] + suffix+++def is_root(span):+ if span.get("is_root_span"):+ return True+ parent = span.get("parent_span_id") or ""+ return is_zero_id(parent)diff --git a/products/tracing/skills/exploring-apm-traces/scripts/extract_span.py b/products/tracing/skills/exploring-apm-traces/scripts/extract_span.pynew file mode 100644index 000000000000..27ce4f3cb670--- /dev/null+++ b/products/tracing/skills/exploring-apm-traces/scripts/extract_span.py@@ -0,0 +1,86 @@+"""Extract spans matching a name (case-insensitive substring) with parent/children context.++Usage:+ SPAN="HTTP GET /api" python3 scripts/extract_span.py FILE+ SPAN="db.query" python3 scripts/extract_span.py FILE++Env vars:+ SPAN — name substring to match (required)+ MAX_LEN — truncation limit (default 0 = unlimited)+"""++import json+import os+import sys++from _common import SPAN_KIND, STATUS_CODE, fmt_duration, is_zero_id, load_trace_file, truncate+++def format_span_line(span):+ name = span.get("name", "?")+ return f"[{span.get('service_name', '?')}] {name} ({fmt_duration(span.get('duration_nano'))}) <{SPAN_KIND.get(span.get('kind'), span.get('kind'))}>"+++span_filter = os.environ.get("SPAN", "").lower()+if not span_filter:+ print("Usage: SPAN='span_name' python3 extract_span.py FILE", file=sys.stderr)+ sys.exit(1)++max_len = int(os.environ.get("MAX_LEN", "0"))++spans = load_trace_file(sys.argv[1])+if not spans:+ print("No spans in payload.", file=sys.stderr)+ sys.exit(1)++by_id = {s.get("span_id"): s for s in spans if s.get("span_id")}+children = {}+for span in spans:+ pid = span.get("parent_span_id") or ""+ children.setdefault(pid, []).append(span)++matches = [s for s in spans if span_filter in (s.get("name", "") or "").lower()]++if not matches:+ print(f"No spans matching '{span_filter}' found ({len(spans)} spans scanned).", file=sys.stderr)+ sys.exit(1)++print(f"Matched {len(matches)} span(s) for '{span_filter}'.\n")++for span in matches:+ print("=" * 80)+ print(format_span_line(span))+ err = " [ERROR]" if span.get("status_code") == 2 else ""+ print(f" status: {STATUS_CODE.get(span.get('status_code'), span.get('status_code'))}{err}")+ print(f" span_id: {span.get('span_id', '?')}")+ print(f" parent_span_id: {span.get('parent_span_id', '?')}")+ print(f" trace_id: {span.get('trace_id', '?')}")+ print(f" timestamp: {span.get('timestamp', '?')}")+ print(f" end_time: {span.get('end_time', '?')}")+ print(f" is_root_span: {span.get('is_root_span', False)}")+ print("=" * 80)++ formatted = json.dumps(span, indent=2, default=str)+ print("\n--- FULL ROW ---")+ print(truncate(formatted, max_len, show_total=True))++ parent_id = span.get("parent_span_id") or ""+ parent = by_id.get(parent_id) if parent_id and not is_zero_id(parent_id) else None+ print("\n--- PARENT ---")+ if parent:+ print(f" {format_span_line(parent)}")+ print(f" span_id={parent.get('span_id', '?')}")+ elif is_zero_id(parent_id):+ print(" (this is a root span)")+ else:+ print(f" (parent {parent_id} not in payload)")++ sid = span.get("span_id")+ kids = children.get(sid, []) if sid else []+ print(f"\n--- CHILDREN ({len(kids)}) ---")+ for kid in sorted(kids, key=lambda s: s.get("timestamp", "")):+ print(f" {format_span_line(kid)}")+ print(f" span_id={kid.get('span_id', '?')}")+ if not kids:+ print(" (none)")+ print()diff --git a/products/tracing/skills/exploring-apm-traces/scripts/print_summary.py b/products/tracing/skills/exploring-apm-traces/scripts/print_summary.pynew file mode 100644index 000000000000..2604465e13fb--- /dev/null+++ b/products/tracing/skills/exploring-apm-traces/scripts/print_summary.py@@ -0,0 +1,78 @@+"""Print a concise APM trace summary: services, slowest spans, errors.++Usage:+ python3 scripts/print_summary.py FILE++Env vars:+ MAX_LEN — truncation limit for span names (default 100, 0 = unlimited)+"""++import os+import sys++from _common import SPAN_KIND, fmt_duration, is_root, load_trace_file, truncate+++max_len = int(os.environ.get("MAX_LEN", "100"))++spans = load_trace_file(sys.argv[1])+if not spans:+ print("No spans in payload.", file=sys.stderr)+ sys.exit(1)++trace_id = spans[0].get("trace_id", "?")++# Bucket spans by service and kind, find roots, slowest, errors.+services = {} # name -> count+kinds = {} # int -> count+roots = []+errors = []+for span in spans:+ svc = span.get("service_name", "?")+ services[svc] = services.get(svc, 0) + 1+ k = span.get("kind")+ kinds[k] = kinds.get(k, 0) + 1+ if is_root(span):+ roots.append(span)+ if span.get("status_code") == 2:+ errors.append(span)++slowest = sorted(spans, key=lambda s: int(s.get("duration_nano") or 0), reverse=True)[:5]++print("=" * 80)+print("APM TRACE SUMMARY")+print("=" * 80)+print(f" Trace ID: {trace_id}")+print(f" Span count: {len(spans)}")+print(f" Services: {', '.join(f'{n} ({c})' for n, c in sorted(services.items(), key=lambda x: -x[1]))}")+print(f" Span kinds: {', '.join(f'{SPAN_KIND.get(k, k)}={c}' for k, c in sorted(kinds.items()))}")+print(f" Root spans: {len(roots)}")+print(f" Errors: {len(errors)}")++if roots:+ print()+ print("--- ROOT SPAN(S) ---")+ for r in roots:+ name = truncate(r.get("name", "?"), max_len)+ print(f" [{r.get('service_name', '?')}] {name} ({fmt_duration(r.get('duration_nano'))})")+ print(f" span_id={r.get('span_id', '?')} ts={r.get('timestamp', '?')}")++print()+print("--- TOP-5 SLOWEST SPANS ---")+for span in slowest:+ name = truncate(span.get("name", "?"), max_len)+ err = " [ERROR]" if span.get("status_code") == 2 else ""+ print(f" [{span.get('service_name', '?')}] {name} ({fmt_duration(span.get('duration_nano'))}){err}")+ print(f" kind={SPAN_KIND.get(span.get('kind'), span.get('kind'))} span_id={span.get('span_id', '?')}")++if errors:+ print()+ print("!" * 80)+ print(f"ERROR SPANS ({len(errors)})")+ print("!" * 80)+ for span in errors:+ name = truncate(span.get("name", "?"), max_len)+ print(f" [{span.get('service_name', '?')}] {name} ({fmt_duration(span.get('duration_nano'))})")+ print(f" kind={SPAN_KIND.get(span.get('kind'), span.get('kind'))} span_id={span.get('span_id', '?')} parent={span.get('parent_span_id', '?')}")+ print()+ print("Attributes are not in the trace payload — use apm-attribute-values-list to fetch error.message etc.")diff --git a/products/tracing/skills/exploring-apm-traces/scripts/print_timeline.py b/products/tracing/skills/exploring-apm-traces/scripts/print_timeline.pynew file mode 100644index 000000000000..a52fa2050bbb--- /dev/null+++ b/products/tracing/skills/exploring-apm-traces/scripts/print_timeline.py@@ -0,0 +1,75 @@+"""Print a DFS-indented tree of spans, reconstructed from parent_span_id.++Usage:+ python3 scripts/print_timeline.py FILE++Env vars:+ MAX_LEN — truncation limit for span names (default 120, 0 = unlimited)+"""++import os+import sys++from _common import SPAN_KIND, fmt_duration, is_root, load_trace_file, truncate+++max_len = int(os.environ.get("MAX_LEN", "120"))++spans = load_trace_file(sys.argv[1])+if not spans:+ print("No spans in payload.", file=sys.stderr)+ sys.exit(1)++# Build span_id -> span and parent_span_id -> [children] indexes.+# Sort children by timestamp so DFS prints chronologically within each branch.+by_id = {}+children = {}+for span in spans:+ sid = span.get("span_id")+ if sid:+ by_id[sid] = span+ pid = span.get("parent_span_id") or ""+ children.setdefault(pid, []).append(span)++for kids in children.values():+ kids.sort(key=lambda s: s.get("timestamp", ""))++roots = [s for s in spans if is_root(s)]+roots.sort(key=lambda s: s.get("timestamp", ""))++trace_id = spans[0].get("trace_id", "?")+print("=" * 80)+print(f"TIMELINE — trace {trace_id} ({len(spans)} spans, {len(roots)} root(s))")+print("=" * 80)+++def render(span, depth):+ indent = " " * depth+ name = truncate(span.get("name", "?"), max_len)+ err = " [ERR]" if span.get("status_code") == 2 else ""+ kind = SPAN_KIND.get(span.get("kind"), span.get("kind"))+ print(f"{indent}- [{span.get('service_name', '?')}] {name} ({fmt_duration(span.get('duration_nano'))}) <{kind}>{err}")+ print(f"{indent} span_id={span.get('span_id', '?')}")+ sid = span.get("span_id")+ for kid in children.get(sid, []):+ render(kid, depth + 1)+++for root in roots:+ render(root, 0)++# Render orphan subtrees (their parent isn't in the payload, but the span itself is).+orphan_roots = []+for span in spans:+ if is_root(span):+ continue+ pid = span.get("parent_span_id") or ""+ if pid not in by_id:+ orphan_roots.append(span)++if orphan_roots:+ print()+ print(f"--- ORPHAN SUBTREES ({len(orphan_roots)} — parent_span_id not in payload) ---")+ orphan_roots.sort(key=lambda s: s.get("timestamp", ""))+ for span in orphan_roots:+ render(span, 0)diff --git a/products/tracing/skills/exploring-apm-traces/scripts/search_spans.py b/products/tracing/skills/exploring-apm-traces/scripts/search_spans.pynew file mode 100644index 000000000000..16e6ff39c18f--- /dev/null+++ b/products/tracing/skills/exploring-apm-traces/scripts/search_spans.py@@ -0,0 +1,80 @@+"""Search spans by keyword across name, service_name, span_id, trace_id, parent_span_id.++Usage:+ SEARCH="db.query" python3 scripts/search_spans.py FILE+ SEARCH="payment-service" python3 scripts/search_spans.py FILE++NOTE: The apm-trace-get payload does NOT include span attributes (e.g. http.method,+http.status_code, custom k8s labels). For attribute-based searches, use the MCP tools+posthog:apm-attributes-list and posthog:apm-attribute-values-list, then re-issue+posthog:query-apm-spans with a filterGroup of type 'span_attribute' or+'span_resource_attribute'.++Env vars:+ SEARCH — keyword to match (case-insensitive substring)+ MAX_LEN — truncation limit per match snippet (default 200, 0 = unlimited)+"""++import os+import sys++from _common import SPAN_KIND, fmt_duration, load_trace_file+++# Span fields scanned for the keyword. Excludes timestamp/duration/kind/status_code —+# numeric/structural fields that are better matched via filterGroup, not free text.+SEARCH_FIELDS = ("name", "service_name", "span_id", "trace_id", "parent_span_id", "uuid")+++def snippet(value, term, max_len):+ s = str(value)+ lower = s.lower()+ idx = lower.index(term)+ if max_len <= 0:+ return s+ pad = 80+ start = max(0, idx - pad)+ end = min(len(s), idx + len(term) + pad)+ out = s[start:end]+ if len(out) > max_len:+ out = out[:max_len] + "..."+ return out+++term = os.environ.get("SEARCH", "").lower()+if not term:+ print("Usage: SEARCH='keyword' python3 search_spans.py FILE", file=sys.stderr)+ sys.exit(1)++max_len = int(os.environ.get("MAX_LEN", "200"))++spans = load_trace_file(sys.argv[1])+if not spans:+ print("No spans in payload.", file=sys.stderr)+ sys.exit(1)++hits = 0+for span in spans:+ matched_fields = []+ for field in SEARCH_FIELDS:+ value = span.get(field)+ if value is None:+ continue+ if term in str(value).lower():+ matched_fields.append((field, value))++ if not matched_fields:+ continue+ hits += 1++ err = " [ERROR]" if span.get("status_code") == 2 else ""+ name = span.get("name", "?")+ print(f"\n[{span.get('service_name', '?')}] {name} ({fmt_duration(span.get('duration_nano'))}) <{SPAN_KIND.get(span.get('kind'), span.get('kind'))}>{err}")+ print(f" span_id={span.get('span_id', '?')} ts={span.get('timestamp', '?')}")+ for field, value in matched_fields:+ print(f" {field}: ...{snippet(value, term, max_len)}...")++print(f"\nMatched {hits} span(s) for '{term}' across {len(spans)} scanned.")+if hits == 0:+ print("\nReminder: span attributes (http.method, k8s labels, etc.) are NOT in this payload.")+ print("Use posthog:apm-attribute-values-list to discover them, then filter via posthog:query-apm-spans.")diff --git a/products/tracing/skills/exploring-apm-traces/scripts/show_structure.py b/products/tracing/skills/exploring-apm-traces/scripts/show_structure.pynew file mode 100644index 000000000000..d812f4be918d--- /dev/null+++ b/products/tracing/skills/exploring-apm-traces/scripts/show_structure.py@@ -0,0 +1,38 @@+"""Show JSON keys and types without values. Reads from stdin or a file argument."""++import json+import sys++from _common import unwrap_text_envelope+++def structure(obj, depth=0, max_depth=3):+ indent = " " * depth+ if depth > max_depth:+ print(f"{indent}...")+ return+ if isinstance(obj, dict):+ for k, v in obj.items():+ if isinstance(v, dict):+ print(f"{indent}{k}: {{...}} ({len(v)} keys)")+ structure(v, depth + 1, max_depth)+ elif isinstance(v, list):+ print(f"{indent}{k}: [...] ({len(v)} items)")+ if v:+ structure(v[0], depth + 1, max_depth)+ elif isinstance(v, str):+ print(f"{indent}{k}: str[{len(v)}]")+ else:+ print(f"{indent}{k}: {v}")+ elif isinstance(obj, list):+ print(f"{indent}[{len(obj)} items]")+ if obj:+ structure(obj[0], depth + 1, max_depth)+++if len(sys.argv) > 1:+ with open(sys.argv[1]) as f:+ data = unwrap_text_envelope(json.load(f))+else:+ data = unwrap_text_envelope(json.load(sys.stdin))+structure(data)diff --git a/pyproject.toml b/pyproject.tomlindex 8aa810317e1a..e39ceaadc3d7 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -407,7 +407,7 @@ warn_unreachable = truestrict_equality = trueignore_missing_imports = trueexclude_gitignore = true-exclude = ["^(bin/.*|tools/.*|gunicorn\\.config\\.py|manage\\.py)$"]+exclude = ["^(bin/.*|tools/.*|products/[^/]+/skills/[^/]+/scripts/.*|gunicorn\\.config\\.py|manage\\.py)$"][[tool.mypy.overrides]]module = "bin.*"