Repository navigation
feat(apidocs): Require descriptions and types on new response fields - #129972
Conversation
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]>
|
🚨 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 |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
❌ 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}") |
There was a problem hiding this comment.
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.
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) |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 49a5b1b. Configure here.
…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]>
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]>
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]>


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.pyruns in the existing "api docs test" job, aftermake validate-api-docs. It walks every 2xxapplication/jsonresponse in the generated schema, nested fields included, and flags a field when it:description, orAny({}),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.src/sentry/apidocs/README.md#response-fields.python -m sentry.apidocs.response_coverage --pruneremoves fixed entries and never adds new ones, so the list can only shrink.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:DetailedProjectResponsein a new endpoint would then fail on dozens of existing fields.How the key gets into the schema:
OPENAPIGENERATE),resolve_type_hintadds anx-sentry-sourceextension to each TypedDict property inopenapi-spectacular.json. The check reads that file.api-docs/index.tsstrips the extension when it writesopenapi-derefed.json. So the published schema and thesentry-api-schemasync don't change, apart from the existing workflow-actionpriorityenum-order flake.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[].statusDetailsorcomponents/ProjectRepoLinkResponse.id. These are DRF serializers, inlineextend_schemaschemas, and the deprecated JSON docs.The check doesn't record enum values, so the
priorityenum-order flake can't trip it. I built the docs several times and got the same baseline every time.Baseline by owner
app-backendemerge-toolsdata-browsingintegration-platformalerts-monitorsagent-tracingdashboardsreplayissue-detection-backend+issues-feedowners-snubasentry-apps+integration-platformcronsteam-javascript-sdksFollow-up PRs will fill these gaps one owner team at a time and prune the baseline as they go.
Notes for review
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.tsfile.tests/sentry/apidocs/test_response_coverage.pycovers 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.--pruneremoves exactly that line.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.jsonmatches master apart from thepriorityenum order.via @BYK.
--
View Session in Sentry