Skip to content

feat(apidocs): Describe TypedDict response fields with ApiDescription - #129963

Merged
BYK merged 1 commit into
masterfrom
feat/apidocs-response-field-descriptions
Nov 4, 2026
Merged

BYK merged 1 commit into
masterfrom
feat/apidocs-response-field-descriptions

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

TypedDict response fields can't carry a description into the OpenAPI spec today. resolve_type_hint reads TypedDict hints without extras, and only a nested TypedDict's class docstring ever shows up (there's a TODO: figure out solution for field descriptions). As a result, only 48 of 2,890 (1.7%) top-level 2xx response properties in the public spec have a description. Request bodies and parameters are at 99.9%.

Mechanism

A new ApiDescription marker in sentry.apidocs.descriptions, used through Annotated:

class BaseTeamSerializerResponse(TypedDict):
    isMember: Annotated[bool, ApiDescription("Whether the requesting user is a member of the team")]

How it works:

  • In the TypedDict branch of resolve_type_hint, the hints are also read with include_extras=True. Each field's hint has Required/NotRequired/ReadOnly and Annotated unwrapped, and the property gets its description from the marker.
  • Field types still resolve from the stripped hints exactly as before, so __required_keys__ and other Annotated metadata are unaffected.
  • A field description replaces a nested TypedDict's docstring for that property.

What stays the same:

  • mypy only sees the inner type, so field types and runtime behavior don't change.
  • It works with from __future__ import annotations and with functional TypedDict(...) definitions.

Tests are in tests/sentry/apidocs/test_spectacular_ports.py. That's where the existing resolve_type_hint tests live; tests/apidocs/ holds endpoint doc tests.

Fields

These are the response fields the Sentry CLI documents by hand today. The wording is seeded from the CLI text and made API-neutral, e.g. "Whether you bookmarked it" became "Whether the requesting user bookmarked the project".

Owner Files Fields
@getsentry/app-backend api/serializers/models/{event,group,organization,project,team}.py, api/serializers/types.py (releases) 12 + 11 + 10 + 12 + 4 + 19 = 68
@getsentry/replay replays/post_process.py (ReplayDetailsResponse) 30
@getsentry/alerts-monitors workflow_engine/.../{workflow,detector}_serializer.py 4
no CODEOWNERS entry tagstore/types.py 2
@getsentry/owners-api apidocs/spectacular_ports.py, apidocs/descriptions.py, tests mechanism

Spec impact

I compared make build-api-docs output from master with output from this branch:

  • openapi-derefed.json gains 970 description keys. No existing value changes and nothing else differs.
    • One exception: the workflow action priority enum comes out in a different order, but that order changes from one build to the next, with or without this change.
  • 2xx response properties with a description:
    • top-level: 48/2,890 (1.7%) → 351/2,890 (12.1%)
    • nested: 62/8,288 (0.7%) → 628/8,288 (7.6%)
  • Operations with any described response property: 11 → 61.
  • validate-api-examples and build-investigation-api-docs pass.

Why

This is for getsentry/toolkit#1853. The CLI's --help field tables and skill references wrap generated @sentry/api Valibot fields in hand-written descriptions that drift from the API. The CLI has 84 such descriptions on API fields; the spec described 4 of them before this change, and it describes all 84 with it. That lets the CLI drop its copies, and the public API docs gain field descriptions too.

Paired with getsentry/sentry-api-schema#128, which emits these descriptions in the generated Valibot and Zod schemas. Once this merges and the spec syncs, @sentry/api publishes them and the toolkit can bump and remove its duplicates.

Verification

  • tests/sentry/apidocs/ (117 passed).
  • tests/sentry/replays/test_post_process.py, tests/sentry/tagstore/test_types.py and tests/sentry/api/serializers/test_team.py pass locally.
  • mypy (pre-push hook) and prek pass on the touched files.
  • The other serializer and tests/apidocs endpoint tests need Snuba, which I don't have locally, so I left those to CI.

via @BYK.

--

View Session in Sentry

TypedDict response fields had no way to carry a description into the
OpenAPI schema: resolve_type_hint read hints without extras, so only a
nested TypedDict's class docstring showed up. As a result, only about
1.7% of top-level 2xx response properties in the public spec have a
description.

Add an ApiDescription marker for Annotated field types. The TypedDict
branch of resolve_type_hint reads the hints with include_extras=True,
unwraps Required/NotRequired/ReadOnly and Annotated, and sets the
property's description from the marker. Field types still resolve from
the stripped hints, so other Annotated metadata and required keys are
unchanged.

Use it on the response fields the Sentry CLI documents by hand today
(event, issue, organization, project, team, release, issue tag,
alert/monitor and replay responses), worded for API consumers. The
generated spec only gains description keys.

Co-Authored-By: BYK <[email protected]>
@sentry-junior
sentry-junior Bot requested review from a team as code owners November 4, 2026 21:08
@github-actions github-actions Bot added the Scope: Backend Automatically applied to PRs that change backend components label Nov 4, 2026
@BYK
BYK merged commit 3a57613 into master Nov 4, 2026
94 of 95 checks passed
@BYK
BYK deleted the feat/apidocs-response-field-descriptions branch November 4, 2026 21:26
BYK added a commit to getsentry/sentry-api-schema that referenced this pull request Nov 4, 2026
…mas (#128)

> Independent of getsentry/sentry#129963, which adds the response field
descriptions: this carries through whatever descriptions the spec has,
so it can merge first. It has to land before the `@sentry/api` release
that carries them (getsentry/toolkit#1853).

The generated Valibot and Zod schemas drop every OpenAPI description, so
consumers can't read field docs at runtime. The toolkit CLI hand-writes
`pipe(field, description("…"))` for its `--help` field tables and skill
references, and those drift from the spec.

This turns on Hey API's `metadata` option for both plugins.

- **Valibot:** the plugin emits `v.metadata({ description })`, and
`v.getDescription()` doesn't read that. A new step,
`scripts/describe-valibot-schemas.mjs`, rewrites it to
`v.description(…)`. It also drops the description pipe from top-level
schemas, because `v.pick`/`v.omit`/`v.partial`/`v.required` reject piped
object schemas. Their description is already in the JSDoc, and for
responses it's mostly status text like "No Content". Every top-level
export keeps its type head. The step fails closed on any metadata shape
it doesn't expect.
- **Nullable fields:** Hey API attaches descriptions only to typed IR
schemas, not unions, so every OpenAPI 3.0 `nullable` field lost its
description in both plugins. A `plugin:handler:before` hook copies the
field's description onto its one non-null branch. `types.gen.ts` doesn't
change.
- **Zod:** used as Hey API emits it, `.register(z.globalRegistry, {
description })`. `.description` and `z.toJSONSchema()` read that. The
type is unchanged. This part is optional: drop the `zod` entry's options
if we don't want Zod descriptions yet.

```diff
 export const vDeployResponse = v.object({
-    id: v.string(),
+    id: v.pipe(v.string(), v.description('The ID of the deploy')),
-    name: v.nullable(v.string()),
+    name: v.nullable(v.pipe(v.string(), v.description('The optional name of the deploy'))),
```

### Coverage today

In `openapi-derefed.json`, 48 of 2,879 top-level 2xx response properties
have a description (1.7%), or 62 of 8,263 counting nested ones (0.8%),
across 11 operations. Request body properties and parameters are 99.9%
described at the top level. So for now this mostly surfaces request
descriptions. Response coverage has to come from the serializers in
getsentry/sentry. getsentry/sentry#129963 raises it to 351 of 2,890
(12.1%) at the top level and 628 of 8,288 (7.6%) nested. That covers
every API field the Sentry CLI describes by hand.

### Size

| | before | after |
|---|---|---|
| `dist/valibot.js` | 1.45 MB | 2.00 MB |
| `dist/zod.js` | 1.23 MB | 1.79 MB |
| `dist/valibot.gen.d.ts` | 1.88 MB | 3.11 MB (description literals are
in the action types) |
| packed `dist` (gzip) | ~0.96 MB | ~1.35 MB |
| tree-shaken, `vGetOrganizationResponse` only (min / gzip) | 951 B /
388 B | unchanged |
| tree-shaken, 7 schemas the toolkit CLI uses (min / gzip) | 16.8 KB /
3.2 KB | 19.5 KB / 4.1 KB |

The Valibot output has 2,376 descriptions. With the toolkit CLI's
typecheck on this build, `tsc` memory goes up about 2.5%, and check time
stays within noise. The CLI's npm JS and the `@sentry/mcp-server` bundle
each grow about 2 KB.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3A98eff8ed01bc8064aba01279b3ac82c3 -->

--

[View Session in
Sentry](https://sentry.sentry.io/explore/conversations/agent%3A98eff8ed01bc8064aba01279b3ac82c3/?project=4510944073809921)

<!-- junior-session-footer:end -->

---------

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: BYK <[email protected]>
BYK added a commit that referenced this pull request Nov 4, 2026
…129972)

This PR makes new fields in public API responses carry a description and
a real type. #129963 added `Annotated[T, ApiDescription("…")]` for
TypedDict response fields. Nothing required it yet, so only about 12% of
top-level 2xx response properties are described.

### The check

`tests/apidocs/test_response_coverage.py` runs in the existing "api docs
test" job, after `make validate-api-docs`. It walks every 2xx
`application/json` response in the generated schema, nested fields
included, and flags a field when it:

- has no `description`, or
- is untyped: `Any` (`{}`), `dict[str, Any]` (`{"type": "object",
"additionalProperties": {}}`), an object without properties, or a list
or union branch of those.

The 2,370 existing violations are in
`tests/apidocs/response-coverage-baseline.txt`: 2,256 missing
descriptions and 114 untyped fields. The baseline is sorted, with one
entry per line.

- **New entry:** the test fails. The message points to the convention,
which is documented in `src/sentry/apidocs/README.md#response-fields`.
- **Fixed entry still in the baseline:** the test fails and asks you to
remove it. `python -m sentry.apidocs.response_coverage --prune` removes
fixed entries and never adds new ones, so the list can only shrink.

```
E   AssertionError: 2 response fields need a description or a type. Describe a TypedDict field with `Annotated[T, ApiDescription("...")]` and a serializer field with `help_text`. Replace `Any` and `dict[str, Any]` with a TypedDict or a concrete type. See src/sentry/apidocs/README.md#response-fields.
E       missing-description sentry.new.NewThing.id
E       untyped sentry.new.NewThing.blob
```

### How entries are keyed

Each TypedDict field is keyed by the class that declares it, for example
`missing-description
sentry.api.serializers.models.team.BaseTeamSerializerResponse.slug`.
This is why:

- **Where to fix it:** the error names the class and field to edit.
- **Reuse:** an endpoint that reuses an already-listed TypedDict adds no
entries. It still fails for any field it adds.
- **Size:** keyed by spec path instead, the baseline would be about
6,000 lines, because shared TypedDicts are inlined into many components.
Reusing `DetailedProjectResponse` in a new endpoint would then fail on
dozens of existing fields.

How the key gets into the schema:

- During the docs build (`OPENAPIGENERATE`), `resolve_type_hint` adds an
`x-sentry-source` extension to each TypedDict property in
`openapi-spectacular.json`. The check reads that file.
- `api-docs/index.ts` strips the extension when it writes
`openapi-derefed.json`. So the published schema and the
`sentry-api-schema` sync don't change, apart from the existing
workflow-action `priority` enum-order flake.
- Outside the docs build, schemas don't get the tag, so existing tests
are untouched.

Fields that don't come from a TypedDict use the operation or component
plus their JSON path, e.g. `GET
/api/0/projects/{organization_id_or_slug}/{project_id_or_slug}/issues/
200[].statusDetails` or `components/ProjectRepoLinkResponse.id`. These
are DRF serializers, inline `extend_schema` schemas, and the deprecated
JSON docs.

The check doesn't record enum values, so the `priority` enum-order flake
can't trip it. I built the docs several times and got the same baseline
every time.

### Baseline by owner

| Owner (CODEOWNERS of the declaring file) | Missing description |
Untyped |
|---|---|---|
| `app-backend` | 769 | 51 |
| `emerge-tools` | 186 | 2 |
| `data-browsing` | 122 | 5 |
| `integration-platform` | 116 | 8 |
| `alerts-monitors` | 98 | 13 |
| `agent-tracing` | 89 | 3 |
| `dashboards` | 78 | 3 |
| `replay` | 73 | 3 |
| `issue-detection-backend` + `issues-feed` | 54 | 1 |
| `owners-snuba` | 51 | 5 |
| `sentry-apps` + `integration-platform` | 51 | 2 |
| `crons` | 44 | 0 |
| `team-javascript-sdks` | 34 | 2 |
| no CODEOWNERS entry | 27 | 0 |
| 9 smaller teams | 113 | 4 |
| keyed by operation or component path | 351 | 12 |

Follow-up PRs will fill these gaps one owner team at a time and prune
the baseline as they go.

### Notes for review

- **Frontend scope label:** the only non-Python file is
`api-docs/index.ts`, which is docs build tooling and isn't deployed. It
may still pick up the "Scope: Frontend" label because it's a `.ts` file.
- **Tests:**
- `tests/sentry/apidocs/test_response_coverage.py` covers source keys,
inherited fields keyed by the declaring class, path keys, each untyped
shape, component descriptions on references, and that only 2xx responses
are checked.
- I also checked the full loop locally. A new undescribed field fails
the test. Describing a listed field fails it until `--prune` removes
exactly that line.
- **Commands run:** `make validate-api-docs` (public and investigation
docs plus the examples validator), `pytest tests/sentry/apidocs
tests/apidocs/test_response_coverage.py`, prek, and mypy.
`openapi-derefed.json` matches master apart from the `priority` enum
order.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3A98eff8ed01bc8064aba01279b3ac82c3 -->

--

[View Session in
Sentry](https://sentry.sentry.io/explore/conversations/agent%3A98eff8ed01bc8064aba01279b3ac82c3/?project=4510944073809921)

<!-- junior-session-footer:end -->

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: BYK <[email protected]>
BYK added a commit to getsentry/toolkit that referenced this pull request Nov 4, 2026
Closes #1853

The CLI output schemas now take API field descriptions from
`@sentry/api` instead of repeating them by hand. getsentry/sentry#129963
added these descriptions to the OpenAPI spec, and `@sentry/api` 1.21.0
ships them in its valibot schemas.

## Changes

- **Bump `@sentry/api` from 1.7.0 to 1.21.0.** The catalog entry,
`minimumReleaseAgeExclude` and the lockfile move to 1.21.0. Dependencies
and peer dependencies are the same as in 1.7.0. Ignoring description
comments, the only type changes between the two versions are:
- Dashboard detail responses gain `queryPriority`, and dashboard
create/update requests gain an optional `query_priority`. Toolkit
doesn't use either field.
- The workflow action `priority` enum (`P1` to `P5`) is reordered again.
The set of values is the same.
- **Drop CLI descriptions the spec now covers.** These output schemas
now use the `@sentry/api/valibot` field as it is, so its OpenAPI
description is the one the docs show:
- issue and feedback: `culprit`, `count`, `userCount`, `firstSeen`,
`lastSeen`, `level`, `status`, `permalink`, `project`, `metadata`,
`assignedTo`
- event list: `groupID`, `projectID`, `message`, `title`, `location`,
`culprit`, `user`, `tags`, `platform`, `dateCreated`, `crashFile`,
`metadata`
  - org, project, team and release: every API field that had a wrapper
- deploy: `name` and `url`. `id` and `environment` now come from
`vDeployResponse` instead of hand-written `string()` fields.
- **Keep the CLI wording where it reads better for CLI users.** A
`pipe(apiField, description(…))` wrapper still wins:
- event `formatted`: the API text describes the server's `?llmFormat`
mixin. The CLI keeps its own sentence and now fills a cell that was
empty.
- alert `id`/`name`: the spec says "Monitor ID" for metric alerts, so
all alert commands keep "Alert rule ID/name".
- `issue tags` `totalValues`/`topValues`: the CLI text notes the 9-value
limit and that the count isn't a lifetime count.
- deploy `dateStarted`/`dateFinished`: the spec gives the request-side
wording ("An optional date…") and omits the ISO 8601 format.
- **`extractSchemaFields`** collapses whitespace in descriptions so that
multi-line API descriptions don't break the field tables. Its doc
comment now says a CLI wrapper wins over the API description. Tests
cover both.
- **`packages/cli/AGENTS.md`** says API fields carry the spec
description, and to wrap a field only when the spec has none or its text
doesn't suit CLI users.

## Generated output

The skill references are regenerated: `event`, `feedback`, `issue`,
`org`, `project`, `release` and `team`. All 230 changed table rows keep
the same field name and type; only the description cell changes. Every
other reference file and generated artifact is unchanged.

## Testing

All of these ran with `SENTRY_AUTH_TOKEN` unset, so the mcp-cloudflare
build doesn't try to upload sourcemaps:

- `pnpm run tsc` passes.
- `pnpm run lint` passes.
- `pnpm run test`, run one package at a time: every package passes
except 6 CLI tests out of 13,480. Those 6 are the file-permission tests
(EACCES/EPERM/read-only/unreadable files) that also fail on `main` in
the sandbox, because it runs as root (same as #1942).
`test/script/output-schema-fields.test.ts` passes.

<!-- junior-request-attribution:start -->
via @BYK.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:agent%3A98eff8ed01bc8064aba01279b3ac82c3 -->

--

[View Session in
Sentry](https://sentry.sentry.io/explore/conversations/agent%3A98eff8ed01bc8064aba01279b3ac82c3/?project=4510944073809921)

<!-- junior-session-footer:end -->

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: BYK <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Scope: Backend Automatically applied to PRs that change backend components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant