Skip to content

feat(traces): expose custom span attributes and improve agent guidance#623

Merged
BYK merged 6 commits into
mainfrom
feat/custom-span-attributes
Apr 1, 2026
Merged

feat(traces): expose custom span attributes and improve agent guidance#623
BYK merged 6 commits into
mainfrom
feat/custom-span-attributes

Conversation

@BYK

@BYK BYK commented Apr 1, 2026

Copy link
Copy Markdown
Member

Summary

Addresses feedback from an AI agent field report about Sentry CLI usability. The critical gap was that custom span attributes (like gen_ai.usage.input_tokens, pi.session.id) were completely invisible via CLI — this PR fixes that across all three span/trace commands.

Custom attribute access (critical)

  • span view: Fetches full attributes from the trace-items/{itemId}/ endpoint (same as Sentry frontend's span detail sidebar). All custom OTEL attributes now appear in both JSON and human output with no configuration needed.
  • trace view: --fields values that aren't standard output fields are forwarded as additional_attributes query params to the trace detail API.
  • span list: --fields now drives API field selection — unknown field names are requested as additional field params from the events API. Includes gen_ai group alias that expands to common AI observability fields.

Agent guidance improvements

  • Added --since as an alias for --period on all list commands (the most natural flag name for time filtering)
  • Added "Quick Reference" section to agent guidance docs covering correct patterns for time filtering, org/project scoping, trace ID usage, and valid dataset names
  • Regenerated SKILL.md

Quality of life

  • Filter zero-valued web vitals measurements from trace view JSON output (~40% size reduction for typical traces)
  • Added EVENTS_API_DATASETS shared constant and documented valid dataset names in api command docs
  • Widened TraceSpan type to include all fields the trace detail API actually returns (measurements, additional_attributes, sdk_name, errors, occurrences, etc.)

- span view: fetch full attributes from trace-items endpoint (all
  custom OTEL attributes like gen_ai.*, pi.* now visible in output)
- trace view: pass --fields as additional_attributes query param
- span list: --fields drives API field selection for custom attributes
  with gen_ai group alias for AI observability shortcuts
- Add --since as alias for --period on all list commands
- Filter zero-valued measurements from trace/span view JSON output
- Add Quick Reference section to agent guidance docs with correct
  flag patterns, positional arg usage, and valid dataset names
- Add shared EVENTS_API_DATASETS constant and document valid dataset
  names in api command docs
@github-actions

github-actions Bot commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

Semver Impact of This PR

🟡 Minor (new features)

📋 Changelog Preview

This is how your changes will appear in the changelog.
Entries from this PR are highlighted with a left border (blockquote style).


New Features ✨

  • (auth) Show token expiry in days/weeks instead of raw hours by BYK in #620
  • (ci) Add delta patch generation for stable releases by BYK in #618
  • (dashboard) Render text widget markdown content in dashboard view by BYK in #624
  • (telemetry) Upgrade Sentry SDK to 10.47.0 and enable runtime metrics by BYK in #622
  • (traces) Expose custom span attributes and improve agent guidance by BYK in #623

Bug Fixes 🐛

  • (build) Use esbuild for binary bundling to fix minifier collision bug by BYK in #619

Internal Changes 🔧

  • Regenerate skill files and command docs by github-actions[bot] in e01b2520

🤖 This preview updates automatically when you update the PR.

@github-actions

github-actions Bot commented Apr 1, 2026

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1

QR code for preview link

🚀 View preview at
https://cli.sentry.dev/pr-preview/pr-623/

Built to branch gh-pages at 2026-04-01 20:43 UTC.
Preview will be ready when the GitHub Pages deployment is complete.

@github-actions

github-actions Bot commented Apr 1, 2026

Copy link
Copy Markdown
Contributor

Codecov Results 📊

129 passed | Total: 129 | Pass Rate: 100% | Execution Time: 0ms

📊 Comparison with Base Branch

Metric Change
Total Tests
Passed Tests
Failed Tests
Skipped Tests

✨ No test changes detected

All tests are passing successfully.

✅ Patch coverage is 85.39%. Project has 1335 uncovered lines.
❌ Project coverage is 95.56%. Comparing base (base) to head (head).

Files with missing lines (3)
File Patch % Lines
src/lib/formatters/trace.ts 37.10% ⚠️ 39 Missing
src/lib/api/traces.ts 90.91% ⚠️ 5 Missing
src/lib/formatters/json.ts 93.33% ⚠️ 1 Missing
Coverage diff
@@            Coverage Diff             @@
##          main       #PR       +/-##
==========================================
- Coverage    95.65%    95.56%    -0.09%
==========================================
  Files          204       204         —
  Lines        29769     30037      +268
  Branches         0         0         —
==========================================
+ Hits         28472     28702      +230
- Misses        1297      1335       +38
- Partials         0         0         —

Generated by Codecov Action

Comment thread src/commands/span/list.ts Outdated
Comment thread src/commands/span/list.ts Outdated
Comment thread src/commands/span/list.ts Outdated
Comment thread src/commands/span/view.ts Outdated
Comment thread src/commands/span/view.ts Outdated
Comment thread src/commands/span/view.ts Outdated
Comment thread src/lib/api/traces.ts Outdated
Comment thread src/lib/formatters/trace.ts Outdated
Comment thread src/types/sentry.ts
- Replace OUTPUT_TO_API_FIELD mapping with flat KNOWN_SPAN_FIELDS set
- Use native Set operations in extractExtraApiFields instead of
  array filter + spread dedup
- Use Array.from(set) instead of spread for set-to-array conversion
- Use Object.fromEntries() in attributesToDict
- Use p-limit .map() helper in fetchSpanDetails
- Use SPAN_FIELDS.concat() instead of spread in listSpans
- Deduplicate hidden attribute sets: single REDUNDANT_DETAIL_ATTRS
  in traces.ts shared by span/view.ts and formatters/trace.ts
- Rename INTERNAL_ATTRS to REDUNDANT_DETAIL_ATTRS with clearer
  category comments (timing/storage internals vs already-shown fields)
@BYK BYK marked this pull request as ready for review April 1, 2026 19:48
Comment thread src/lib/list-command.ts Outdated
Comment thread src/lib/api/datasets.ts Outdated
Stricli AvailableAlias type is LowercaseLetter | UppercaseLetter,
so multi-character keys like "since" are silently ignored at runtime.
Updated agent guidance to only reference --period and -t.
Comment thread src/lib/api/traces.ts

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Comment thread src/commands/span/list.ts
getNestedValue now checks for the path as a literal property name
before falling back to dot-separated nested traversal. This fixes
--fields gen_ai.usage.input_tokens on span list which stores custom
attributes as flat dotted keys, not nested objects.
@BYK BYK merged commit 42c2ca8 into main Apr 1, 2026
27 checks passed
@BYK BYK deleted the feat/custom-span-attributes branch April 1, 2026 20:50
betegon added a commit that referenced this pull request May 5, 2026
TraceItemAttribute and TraceItemDetail were defined twice: as plain TS
types in traces.ts (PR #623) and as Zod schemas in sentry.ts (this
branch). Remove the plain types from traces.ts and import from the
types barrel instead, re-exporting for existing callers.

Also:
- Add .passthrough() to TraceItemDetailSchema so meta/links from the
  spans endpoint are preserved without failing validation
- Add schema validation to getSpanDetails, matching getLogItemDetail
- Rename SHOWN_IN_STANDARD_SECTIONS → REDUNDANT_LOG_DETAIL_ATTRS to
  mirror REDUNDANT_DETAIL_ATTRS naming in traces.ts

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
betegon added a commit that referenced this pull request May 5, 2026
`sentry log view` showed a fixed set of fields. Custom attributes users
attach to their logs — visible in the Sentry UI — were never fetched or
displayed.

`sentry log list` already supported custom attributes via `--fields`
before this work. No changes there.

**How it works**

The Sentry UI calls a trace-items detail endpoint when expanding a log
row:
```
GET /projects/{org}/{project}/trace-items/{itemId}/?item_type=logs&trace_id={traceId}
```
It returns every attribute on the log without needing to enumerate field
names. `log view` now does the same: after `getLogs` fetches standard
fields (including `trace`), `getLogItemDetail` is called in parallel for
each log. `formatLogDetails` renders all non-standard attributes in a
**Custom Attributes** section automatically. `--fields` filters that
section when you only want specific attributes.

The endpoint is `EXPERIMENTAL` in Sentry and not yet in `@sentry/api`
(generated from `getsentry/sentry-api-schema`), so it uses
`apiRequestToRegion` directly — same pattern as `listTraceLogs`.
Attribute types mirror `TraceItemResponseAttribute`:

https://github.com/getsentry/sentry/blob/8a4f150b21b/static/app/views/explore/hooks/useTraceItemDetails.tsx#L85-L89

If the endpoint is unavailable (no trace ID on the log, or request
fails), the formatter degrades gracefully and shows only standard
fields.

**Type consolidation**

PR #623 defined `TraceItemAttribute` and `TraceItemDetail` as plain TS
types in `traces.ts`. This PR moves them to `src/types/sentry.ts` with
Zod schemas (`.passthrough()` so `meta`/`links` from the spans endpoint
are preserved), exports them via the types barrel, and re-exports from
`traces.ts` for existing callers. `getSpanDetails` also gets schema
validation for parity with `getLogItemDetail`.

**Usage**

```bash
# Shows ALL custom attributes automatically — no config needed
sentry log view myorg/myproject <id>

# Limits the Custom Attributes section to specific fields
sentry log view myorg/myproject <id> --fields order.id,user.tier

# JSON output: unchanged
sentry log view myorg/myproject <id> --json
```

---------

Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant