Repository navigation
feat(preprod): Add async resumable snapshot archive download endpoint - #116825
Conversation
|
🚨 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 |
11542a8 to
c0153d5
Compare
This stack of pull requests is managed by Graphite. Learn more about stacking. |
f39cfbd to
c0153d5
Compare
Add an endpoint that builds a ZIP archive of all snapshot images asynchronously and serves it with HTTP Range support so large downloads can be resumed. A GET enqueues a background build (guarded by a lock and a staleness window so concurrent requests don't double-enqueue) and reports live build progress as a percentage. Once ready, the archive is streamed with Accept-Ranges/Content-Range support and an ETag for resumable, cacheable downloads. Images sharing a content hash are fetched once and written under each filename. A failed image fetch aborts the build so a silently-incomplete archive is never persisted, and partially-created or stale File rows are cleaned up via the instance to release their blobs.
c8d9154 to
6d6c297
Compare
A build worker that finished after the 20-minute staleness re-enqueue could overwrite a newer build's state and delete its stored File. Stamp each enqueue with a build token (the unique enqueued_at) and pass it to the task; the worker now only writes terminal state or deletes the prior File when it is still the current build. Also reset progress to 0 on re-enqueue so polling no longer reports a stale percent for a fresh build.
Inline _build_hash_to_filenames into build_snapshot_zip and fold the single-use _stream_full into _stream_range (a full download is just a range over the whole file), removing two helpers that each had one caller.
The status endpoint treated a failed build like a missing one: it re-enqueued and reported "building", so clients never saw "failed", couldn't stop polling, and persistent failures triggered perpetual rebuilds. Report "failed" as-is and only re-enqueue when the client explicitly passes ?retry=true. Also return the real committed status (not an assumed "building") when the build lock is contended, and refresh metrics before reading progress so polls don't report a stale percent.
If the PreprodArtifact (and its cascading PreprodSnapshotMetrics row) is deleted during the up-to-900s build, the post-build refresh_from_db() raised DoesNotExist and leaked the freshly-written File. Guard that refresh and the _superseded() check, discarding the orphaned archive when the metrics row is gone. Also narrow two mypy type errors (file_id lookup and the test's optional extras dict).
The except UnableToAcquireLock branch returned the raw stored status, so a "ready" state whose File row was missing could report "ready" while ?download=true still 409s. Reuse _settled_status() there so the ready state is re-verified against an existing File, falling back to "building".
_ensure_build's refresh_from_db() calls (inside the lock and the lock fallback) and the progress refresh in get() were unguarded, so deleting the artifact between _resolve and the re-read raised DoesNotExist -> 500. Catch it at the get() boundary and return a graceful 404, matching the guards already in zip_tasks.py.
Superuser/cross-org downloads traverse the control-silo nginx path, which buffers the response to a 1GB-capped temp file and truncates anything larger — the exact >1GB failure this endpoint exists to fix. Set X-Accel-Buffering: no on the download responses, matching the existing /download/ route.
The status was set to "building" before apply_async, so a failed enqueue (e.g. broker unavailable) left an orphaned "building" state that blocked retries until the 20-minute staleness window and 500'd the request. Guard apply_async and mark the state failed on error so the client gets a clean status and can retry.
53eba13 to
601de2c
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 5afadb684287ca1dd0a05a7f3db5aaa3f830b86b. Configure here.
A status poll decides "building" from the metrics row loaded in _resolve. When a concurrent build settled between that load and the response, the handler refreshed only to fill progress, so it reported "building" plus stale progress for a row already marked "ready" or "failed" in the database, keeping clients polling past a finished or failed build. Reuse the refresh already performed in the building branch to re-check the ready File and the stored state, reporting "ready" or "failed" when the build has settled. Co-Authored-By: Claude <[email protected]>
…oncile Extract a shared BaseSnapshotArchiveTest holding the common setUp, artifact factory, and URL helper so the status and download suites stop duplicating scaffolding. Hoist scattered inline imports to module scope. Add coverage for reporting "ready" and "failed" when a build settles between resolve and the in-handler refresh. Co-Authored-By: Claude <[email protected]>
5afadb6 to
730bc82
Compare
Backend Test FailuresFailures on
|
…points (#130371) Part of the #130351 proposal to publish endpoints that the Sentry CLI (getsentry/toolkit) calls with raw requests today, so they appear in the public OpenAPI schema and in the generated `@sentry/api` SDK. This PR covers the Emerge Tools endpoints: | Endpoint | Status | | --- | --- | | `POST /api/0/projects/{org}/{project}/files/preprodartifacts/assemble/` (`ProjectPreprodArtifactAssembleEndpoint`) | `EXPERIMENTAL` → `PUBLIC` | | `GET` and `POST /api/0/organizations/{org}/preprodartifacts/snapshots/{snapshot_id}/archive/` (`OrganizationPreprodSnapshotArchiveEndpoint`) | `PRIVATE` → `PUBLIC_EXPERIMENTAL` | | `POST /api/0/projects/{org}/{project}/preprodartifacts/snapshots/` (`ProjectPreprodSnapshotEndpoint`) | already `PUBLIC`, docs-only fix | **Evidence** - The assemble endpoint was added in #92528 on 2025-06-03 and has been in use since then. It has been in use for more than 6 months, so it goes `PUBLIC`. - The archive endpoint was added in #116825 on 2026-06-03. Its current caller is the snapshot header's download action (`useSnapshotActions.tsx`). It's new, so it goes `PUBLIC_EXPERIMENTAL`. **Behavior fix: snapshot archive POST from a service account** - Before this PR, the archive POST passed `request.user.id` to the build task. For a service account that value is a `ServiceAccountId`, which msgpack can't serialize (`TypeError: can not serialize 'ServiceAccountId' object`). Those requests returned 503 "Couldn't start the build". - The POST now passes `acting_user_id(request.user)`. A service account gets the archive built but no email. Requests from users don't change. - The agent-token permission matrix found this once the endpoint was published. Its service-account row fails without the fix. **Changes** - **Assemble** (`assembleProjectPreprodArtifact`, `Mobile Builds` tag): - The request body schema now lives in one constant, `PREPROD_ARTIFACT_ASSEMBLE_REQUEST_SCHEMA`. Request validation and the OpenAPI request body both use it, so they can't drift apart. - New `PreprodArtifactAssembleResponse` TypedDict: `state`, `missingChunks`, and `artifactUrl`, which is only set when the state is `created`. - `idempotent_methods = frozenset()`: each successful request creates a build and queues the assembly and status-check tasks again, so a client must not resend it. - The chunk-upload prerequisites, `ChunkUploadEndpoint` and `DifAssembleEndpoint`, are still `PUBLIC_EXPERIMENTAL`. A client needs them to upload the chunks before it calls assemble. - **Snapshot archive**: - New `SnapshotArchiveStatusResponse` (`{ready}`) for the GET readiness check (`getOrganizationPreprodSnapshotArchiveStatus`). - New `SnapshotArchiveBuildResponse` for the POST 202 (`startOrganizationPreprodSnapshotArchive`). - `idempotent_methods = frozenset()`: every POST queues another build and sends another email. - **`?download` stays undocumented on purpose.** It streams the zip as a binary body. It's a CLI transport exception, and the published schema only describes the JSON readiness response. A code comment says so. - **Snapshot upload** (docs only): - `request=None` is replaced with a real request body built from `SNAPSHOT_POST_REQUEST_SCHEMA`. The per-image metadata that `ImageMetadata` checks is described too. - The OpenAPI copy uses the OpenAPI 3.0 boolean form of `exclusiveMaximum`. Validation still uses the JSON Schema one. - The docstring now says that the body may be sent with `Content-Encoding: zstd`, up to 256 MiB after decompression. - **Shared VCS fields:** `VCS_SCHEMA_PROPERTIES` gets descriptions. Validation doesn't change. - **Tests:** - Adds examples and apidocs tests for all four operations. The snapshot upload test also checks that the request body the endpoint accepts passes the documented request schema. - `AgentTokenPublicGetMatrixTest` gets a status-poll payload for the assemble POST and a real snapshot id for the archive rows. **Verification** - I ran `make build-api-docs` on this branch and on master (ac2d476) and diffed `openapi-derefed.json`. The only changes are the three new operations (assemble POST, archive GET and POST), the snapshot upload POST's `requestBody` and description, and the three new response components. - `python -m sentry.apidocs.response_coverage`: 0 new gaps. - `pnpm run validate-api-examples`: no errors. - `pytest tests/apidocs`: 159 passed. - Preprod assemble, snapshot and archive endpoint tests, plus the new apidocs tests: 175 passed. - `tests/sentry/seer/endpoints/test_organization_agent_token.py`: 327 passed, 23 xfailed. That's 2 more rows than on master. - prek and mypy (pre-push stage) pass on the changed files. The "(Optional) Shows the difference between the prod and dev schema" check is expected to fail because this PR changes the schema. <!-- junior-request-attribution:start --> via @BYK. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3A22c5e57fa755cece5122380dcb72ec8e --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3A22c5e57fa755cece5122380dcb72ec8e) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3A22c5e57fa755cece5122380dcb72ec8e/?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]>


Adds an additive endpoint for downloading a snapshot's images as a resumable ZIP. The existing
/snapshots/<id>/download/streaming endpoint is left untouched, so this merges with zero frontend risk — the frontend migrates in a separate PR and the old endpoint is removed in a later cleanup.Why
Large snapshot-image ZIP downloads fail partway through and can't resume. The on-the-fly streaming response sends no
Content-Lengthand noAccept-Ranges, so any mid-download connection drop is a permanent failure. Logs for a failing download confirmed the server is healthy (it pushed 2.35 GB in ~11s before the client disconnected) — the missing resume support is the problem, not the backend.What
New
OrganizationPreprodSnapshotArchiveEndpointat.../snapshots/<id>/archive/:build_snapshot_images_zip) assembles the ZIP once into a temp file on disk (memory-safe for multi-GB) and stores it as aFile. Build state lives inPreprodSnapshotMetrics.extras["images_zip"](building/ready/failed) — no new model. Any image-fetch failure fails the whole build instead of persisting a partial archive.data_exportpattern):GET .../archive/returns{status}and idempotently enqueues the build (lock-guarded, with a 20-minute staleness re-enqueue);?download=trueserves the storedFilewith full HTTP Range support (206,Content-Range,Accept-Ranges,Content-Length,ETag);HEADadvertises the same headers. WithAccept-Ranges+ a strong validator the browser resumes after a dropped connection instead of failing.File.Behind the existing
organizations:preprod-snapshotsflag.Follow-ups (not in this PR)
/download/endpoint once the frontend ships.