Skip to content

feat(apidocs): Require descriptions and types on new response fields - #129972

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

BYK merged 1 commit into
masterfrom
feat/apidocs-response-schema-ratchet

Conversation

@sentry-junior

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

Copy link
Copy Markdown
Contributor

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.

via @BYK.

--

View Session in Sentry

Add a ratchet that fails the api docs tests when a field in a public 2xx
response has no description or no real type (`Any`, `dict[str, Any]`, or an
object without properties). Existing gaps are listed in
tests/apidocs/response-coverage-baseline.txt; fixed entries must be removed
from it, so the list only shrinks.

The docs build tags each TypedDict field with its declaring class in
openapi-spectacular.json, so entries name the field to edit and reusing a
TypedDict adds none. The deref step strips the tag, leaving the published
schema unchanged.

Co-Authored-By: BYK <[email protected]>
@sentry-junior
sentry-junior Bot requested a review from a team as a code owner November 4, 2026 21:48
@github-actions github-actions Bot added Scope: Frontend Automatically applied to PRs that change frontend components Scope: Backend Automatically applied to PRs that change backend components labels Nov 4, 2026
@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

🚨 Warning: This pull request contains Frontend and Backend changes!

It's discouraged to make changes to Sentry's Frontend and Backend in a single pull request. The Frontend and Backend are not atomically deployed. If the changes are interdependent of each other, they must be separated into two pull requests and be made forward or backwards compatible, such that the Backend or Frontend can be safely deployed independently.

Have questions? Please ask in the #discuss-dev-infra channel.

@BYK
BYK enabled auto-merge (squash) November 4, 2026 21:52
@BYK
BYK merged commit 3174196 into master Nov 4, 2026
69 of 70 checks passed
@BYK
BYK deleted the feat/apidocs-response-schema-ratchet branch November 4, 2026 21:53

@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 2 potential issues.

Fix All in Cursor

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

Reviewed by Cursor Bugbot for commit 49a5b1b. Configure here.

content = response.get("content") or {}
schema = content.get("application/json", {}).get("schema")
if schema:
self._node(schema, f"{method.upper()} {path} {status}")

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.

Empty Any schemas skip the check

Medium Severity

A 2xx application/json schema of {} (Any) is skipped because if schema treats an empty dict as false. That is the untyped shape the ratchet is meant to catch, so a new untyped root response does not fail the test or appear as a new entry.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 49a5b1b. Configure here.

return True
if kind == "object":
values = schema.get("additionalProperties")
return not schema.get("properties") and not (isinstance(values, dict) and values)

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.

Cycle placeholders flagged as untyped

Low Severity

_is_untyped treats an object with no properties as untyped. Recursive TypedDicts are replaced by _cycle_placeholder, which is exactly that shape, so a described self-referential field still produces an untyped violation that cannot be fixed on the field.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 49a5b1b. Configure here.

BYK added a commit that referenced this pull request Nov 4, 2026
…e ratchet (#129984)

Follow-up to #129972. It fixes the two Cursor Bugbot findings on the
response coverage ratchet.

- **Untyped root responses were skipped.** A 2xx `application/json`
schema of `{}` (`Any`) is falsy, so `if schema:` never checked it, and a
new endpoint with an untyped root response passed. The check now walks
every schema that is present (`is not None`), and the root is reported
as `untyped <METHOD> <path> <status>`.
- **Recursive TypedDicts counted as untyped.** Where a TypedDict repeats
inside itself, `_cycle_placeholder` gives an object without properties.
`_is_untyped` flagged that, and no change to the field could fix it. In
the docs build (`OPENAPIGENERATE`), the placeholder now carries
`x-sentry-cycle`, and the check treats it as typed. `api-docs/index.ts`
strips the extension from the published spec, as it does
`x-sentry-source`.

Neither case occurs in today's spec. After `make build-api-docs`,
`--prune` reports 0 fixed and 0 new, so the baseline doesn't change.
Neither extension appears in `openapi-derefed.json`.

`api-docs/index.ts` is the deref script for the API docs build, not app
frontend code. The frontend/backend warning comment may still show up
for it, as it did on #129972.

## Testing

- New unit tests: an `Any` root response is reported as untyped, a
described recursive TypedDict has no violations, and the cycle marker is
absent outside the docs build. The new tests fail against the old code
(`CYCLE` doesn't exist there).
- `make build-api-docs`, `tests/apidocs/test_response_coverage.py` and
`tests/sentry/apidocs` pass (127 tests).
- prek and mypy pass on the changed files.

<!-- 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
First gap-fill PR for the response coverage ratchet (#129972). It adds
`ApiDescription` to the TypedDicts in
`src/sentry/api/serializers/models/organization.py` and prunes **66
entries** from `tests/apidocs/response-coverage-baseline.txt`: 65
missing descriptions and 1 untyped field.

These types back the organization details, list and summary responses
(`OrganizationWithProjectsAndTeams` in the spec), trusted relays,
onboarding tasks, and the status and links objects.

## Where the wording comes from

- **The serializer code** for computed fields. For example,
`allowSuperuserAccess` is the inverse of the `prevent_superuser_access`
flag. `pendingAccessRequests` counts `OrganizationAccessRequest`s for
the organization's teams. `isDynamicallySampled` is true when the org or
any project samples below 1.
- **The existing request field docs** of `PUT /organizations/{org}/` for
settings that the endpoint also returns, such as `openMembership`,
`attachmentsRole`, `storeCrashReports` and the data scrubbing options. I
reworded "Specify `true` to …" as "Whether …".
- **Where an option is read**, for the Seer and code review defaults:
- `defaultSeerScannerAutomation` and `defaultCodingAgent` follow
`set_default_project_seer_*` and
`get_org_default_seer_automation_handoff`.
- `autoEnableCodeReview` and `defaultCodeReviewTriggers` follow
`Repository._handle_auto_enable_code_review`, which only applies to
GitHub.
- **The model:**
  - Status IDs and labels come from `OrganizationStatus`.
- Onboarding task keys and statuses come from `TASK_CHOICES` and
`STATUS_CHOICES`.
- Trusted relay `created` and `lastModified` follow the update logic in
`organization_details.py`.

## Typing

`role` changes from `Any` to `str`. It's set from `access.role` only
when that isn't `None`, so the spec now says `type: string`. Serialized
output doesn't change.

## Left in the baseline

The code doesn't make these clear, so I didn't guess:

- `aggregatedDataConsent`: it's set from the create-organization
request, but nothing in sentry says what the consent covers.
- `planSampleRate` and `desiredSampleRate`: they come from the blended
rate or the target sample rate, depending on the sampling mode, and the
names don't settle what a client should read them as.
- `untyped` onboarding task `data`: its shape depends on the task.
- `untyped` `extraOptions{}`: the type is clear
(`traces.spansExtractionDate: int`, `traces.checkSpanExtractionDate:
bool`), but the Sentry UI no longer reads either option, so I couldn't
describe the nested fields.

## Testing

- After `make build-api-docs`, `--prune` reports 66 fixed and 0 new.
Apart from descriptions, the derefed spec's only change is `role`
gaining `type: string`.
- `tests/apidocs/test_response_coverage.py` and `tests/sentry/apidocs`
pass.
- mypy and prek pass on the changed files.
- The organization serializer and details endpoint tests need Snuba,
which isn't available in my sandbox, so CI covers them. The change only
adds `Annotated` metadata and narrows one type hint, so nothing changes
at runtime.

<!-- 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
This is a response coverage gap-fill for the ratchet added in #129972,
and it follows #129991 (organization). It adds `ApiDescription`
annotations to the response TypedDicts in:

- `src/sentry/api/serializers/models/role.py`:
`BaseRoleSerializerResponse`, `OrganizationRoleSerializerResponse`,
`TeamRoleSerializerResponse`
- `src/sentry/api/serializers/models/team.py`:
`BaseTeamSerializerResponse`, `_TeamSerializerResponseOptional`, the
team SCIM responses
- `src/sentry/users/api/serializers/user.py`: `UserSerializerResponse`,
`UserSerializerResponseOptional`, `SerializedAvatarFields`, plus the
nested email, identity and authenticator types

These fix 72 entries in `tests/apidocs/response-coverage-baseline.txt`,
and this PR prunes them all. None of these files have fields left in the
baseline.

**Where the wording comes from**
- The serializer code, for example:
- `hasAccess`: member, open membership, or an organization role with
access to all teams
  - `emails` and `identities`: when they're included
  - `canReset2fa`: true only with exactly one active organization
  - `experiments`: always `{}`
- Model help texts (`User.is_managed`, `User.is_suspended`, ...).
- How the frontend uses `isRetired`: retired roles can't be assigned to
more members.
- `allowed` and `is_global` are marked as deprecated aliases. The
serializer comments call them "backward compatibility".

There are no type changes and no runtime changes. Apart from
descriptions, the generated spec matches the published
`openapi-derefed.json`. The only other difference is the timezone enum,
which comes from the local tz database.

**Testing**
- `make build-api-docs`, then `python -m
sentry.apidocs.response_coverage --prune`: 72 fixed, 0 new.
- `pytest tests/apidocs/test_response_coverage.py tests/sentry/apidocs`:
127 passed.
- mypy (pre-push) and prek pass on the changed files.

Refs getsentry/toolkit#1853

<!-- 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 Scope: Frontend Automatically applied to PRs that change frontend components

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant