Skip to content

Commit fd7b378

Browse files
fix(service-storage): a chunked completion retried after it succeeded answers the same 200, and a completed upload takes no more chunks (#33249)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DU5CHkeh2msc49m4dh6kwEt)_ Fixes #33027 Area-lease pilot #33059, area A3. ## What changes Two doors in `packages/services/service-storage/src/storage-routes.ts`, both about a chunked upload session already `completed`: | Door | Before | Now | |:--|:--|:--| | `POST /storage/upload/chunked/:uploadId/complete`, sent again after it succeeded | `500 INTERNAL`; session re-stamped `failed`; file stays committed | `200` with the same body as the first completion; nothing written, backend not called; session stays `completed` | | same, the retry lists a chunk the upload does not hold | `409 RESOURCE_CONFLICT` | unchanged (the parts check still runs first) | | `PUT /storage/upload/chunked/:uploadId/chunk/:chunkIndex` on a completed session | `200` + eTag; chunk stored for no file, parts record rewritten | `409 RESOURCE_CONFLICT`, nothing stored or recorded | | either door on a session `in_progress`, `failed` or `expired` | as before | unchanged (`failed` still is not a lock: a retry after a backend blip completes) | The `200` body is built by one helper (`completedUploadBody`) for both the assembling completion and the replay, so they cannot drift. The replay answers the key the file row was committed with. No new error code: `409 RESOURCE_CONFLICT` is the code the door already uses for "the request conflicts with where the upload stands". ## Why A client that lost the `200` and retried (the SDK `resumeUpload` pattern) was told a committed, downloadable file had failed, and the session ledger said `failed`. Root cause: the completion door did not look at the session's terminal status; the adapter had already discarded its multipart, threw "Upload session not found", and the catch stamped `failed` over `completed`. ## Verification - New pins in `storage-routes.test.ts`, `describe('[#33027] a completed session')`: replay `200` deep-equals the first body, `completeChunkedUpload` and `updateSession` not called, row + progress `completed`, file `committed`; a retry with a wrong eTag still `409`, row stays `completed`; chunk PUT `409 RESOURCE_CONFLICT`, `uploadChunk` not called, `parts`/`uploaded_size` unchanged; CONTROL: a re-sent chunk on an in-flight session still `200`. - Ablation (guards replaced by `false`, fix committed first, restored with `git checkout HEAD --`): the replay pin and the chunk pin go red (`2 failed | 2 passed`); restored tree diff empty. - Local, on `d3d6b13f` + changeset: `service-storage` `storage-routes.test.ts`, `chunked-upload-integrity.test.ts`, `storage-routes.metadata-outage.test.ts`, `chunk-part-record-concurrency.test.ts`: 169/169 passed. `service-storage` typecheck, eslint on both files, `check-adr-0087-registration`, `check-changeset-no-major`, `check-empty-changeset`, `check-issue-citations`, `check:doc-authoring`, `check:route-envelope`, `check:error-status-conformance`, `check:nul-bytes`: all exit 0. Everything else: CI. Clause-②: yes (narrowing) Metadata-protocol: none Changeset `.changeset/33027-chunked-complete-retry.md`: `@objectstack/service-storage` patch, `adr-0087: not-required (no-migration-prescription)`. Narrowing = the chunk PUT on a completed session, `200` → `409`; widening = the completion replay, `500` → `200`. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4d1D3AzXvEhBbz79Pmi --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4d1D3AzXvEhBbz79Pmi)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a2be78d commit fd7b378

3 files changed

Lines changed: 133 additions & 7 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/service-storage': patch
3+
---
4+
5+
fix(service-storage): a chunked-upload completion retried after it succeeded answers the same 200, and a completed upload takes no more chunks
6+
7+
Clause-②: yes (narrowing) — widened: `POST /api/v1/storage/upload/chunked/:uploadId/complete` on an upload that has already completed answers `200` with the same body the first completion answered (file id, key, size, MIME type, URL), where it answered `500 INTERNAL` and stamped the session `failed`. Narrowed: `PUT /api/v1/storage/upload/chunked/:uploadId/chunk/:chunkIndex` on a completed upload answers `409 RESOURCE_CONFLICT`, where it stored the chunk for no file and answered `200`. A session in flight, `failed` or `expired` answers both doors as before.
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value, metadata type or export is added, removed or re-shaped. The moved answers are two storage doors' answers about a completed upload session, so there is nothing stored for a migration to rewrite and no tombstone. -->
11+
12+
A client that lost the `200` of a completion and sent it again (the SDK's `resumeUpload` retries this way) was told the upload failed, and the upload's progress read `failed`, while the file stayed committed and downloadable. The retry now writes nothing and does not reach the storage backend; it is still judged against the parts the upload holds, so a retry naming a chunk the upload does not hold is refused `409` as before. To send another file after a completed upload, start a new chunked upload.

‎packages/services/service-storage/src/storage-routes.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,74 @@ describe('Storage REST Routes', () => {
524524
expect((await store.getSession(uploadId))!.status).toBe('completed');
525525
});
526526

527+
// [#33027] A completion retried after it succeeded (a client that lost the
528+
// `200`) used to reach the backend, whose multipart the first completion
529+
// had discarded: `500 INTERNAL`, and the catch stamped `failed` over
530+
// `completed` while the file stayed committed and downloadable.
531+
describe('[#33027] a completed session', () => {
532+
async function completedUpload() {
533+
const { uploadId, resumeToken, fileId } = await initSession();
534+
const chunkRes = await putChunk(uploadId, resumeToken);
535+
const parts = [{ chunkIndex: 0, eTag: chunkRes._json.data.eTag }];
536+
const first = await complete(uploadId, parts);
537+
expect(first._status, JSON.stringify(first._json)).toBe(200);
538+
return { uploadId, resumeToken, fileId, parts, first };
539+
}
540+
541+
it('answers a completion sent again with the same 200 for the same file, and stays completed', async () => {
542+
const { uploadId, fileId, parts, first } = await completedUpload();
543+
const backend = vi.spyOn(adapter, 'completeChunkedUpload');
544+
const updateSession = vi.spyOn(store, 'updateSession');
545+
546+
const retry = await complete(uploadId, parts);
547+
548+
expect(retry._status, JSON.stringify(retry._json)).toBe(200);
549+
expect(retry._json.data).toEqual(first._json.data);
550+
expect(retry._json.data.fileId).toBe(fileId);
551+
expect(backend, 'the assembled multipart is not asked for again').not.toHaveBeenCalled();
552+
expect(updateSession, 'the retry writes no status').not.toHaveBeenCalled();
553+
expect((await store.getSession(uploadId))!.status).toBe('completed');
554+
expect((await getProgress(uploadId))._json.data.status).toBe('completed');
555+
expect((await store.getFile(fileId))!.status).toBe('committed');
556+
});
557+
558+
it('still refuses a retry naming a chunk the upload does not hold, and stays completed', async () => {
559+
const { uploadId } = await completedUpload();
560+
561+
const retry = await complete(uploadId, [{ chunkIndex: 0, eTag: 'not-the-stored-etag' }]);
562+
563+
expect(retry._status).toBe(409);
564+
expect(retry._json.error.code).toBe('RESOURCE_CONFLICT');
565+
expect((await store.getSession(uploadId))!.status).toBe('completed');
566+
});
567+
568+
it('refuses a chunk sent to it 409 RESOURCE_CONFLICT, storing and recording nothing', async () => {
569+
const { uploadId, resumeToken } = await completedUpload();
570+
const before = (await store.getSession(uploadId))!;
571+
const backend = vi.spyOn(adapter, 'uploadChunk');
572+
573+
const res = await putChunk(uploadId, resumeToken);
574+
575+
expect(res._status).toBe(409);
576+
expect(res._json.error.code).toBe('RESOURCE_CONFLICT');
577+
expect(backend, 'no byte reaches the backend').not.toHaveBeenCalled();
578+
const after = (await store.getSession(uploadId))!;
579+
expect(after.status).toBe('completed');
580+
expect(after.parts).toBe(before.parts);
581+
expect(after.uploaded_size).toBe(before.uploaded_size);
582+
});
583+
584+
it('CONTROL: a chunk sent again to a session still in flight is accepted', async () => {
585+
const { uploadId, resumeToken } = await initSession();
586+
await putChunk(uploadId, resumeToken);
587+
588+
const res = await putChunk(uploadId, resumeToken);
589+
590+
expect(res._status).toBe(200);
591+
expect((await store.getSession(uploadId))!.status).toBe('in_progress');
592+
});
593+
});
594+
527595
it('leaves a session with no declared deadline in progress', async () => {
528596
const { uploadId } = await initSession();
529597
// The route always stamps `expires_at`; a row without one carries no

‎packages/services/service-storage/src/storage-routes.ts‎

Lines changed: 53 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,19 @@ const ORGANIZATION_CHANGED_MESSAGE =
141141
const INCOMPLETE_UPLOAD_STATUS = 409;
142142
const INCOMPLETE_UPLOAD_CODE: StandardErrorCode = 'RESOURCE_CONFLICT';
143143

144+
/**
145+
* [#33027] The chunk door's answer to a chunk sent to an upload that has
146+
* already completed: the file is committed and the backend multipart is gone,
147+
* so the chunk would be stored for no file. `409` / `RESOURCE_CONFLICT`, as
148+
* for an incomplete upload above: the request conflicts with where the upload
149+
* stands. The remedy is a new upload, so the message names it.
150+
*/
151+
const COMPLETED_SESSION_STATUS = 409;
152+
const COMPLETED_SESSION_CODE: StandardErrorCode = 'RESOURCE_CONFLICT';
153+
const COMPLETED_SESSION_CHUNK_MESSAGE =
154+
'This chunked upload has already completed and its file is committed, so it takes no more chunks. ' +
155+
'To send another file, start a new chunked upload.';
156+
144157
/**
145158
* [#22470] The answer both upload-starting doors (presigned, chunked) give a
146159
* request naming a scope outside the upload-scope vocabulary — before the size
@@ -1078,6 +1091,21 @@ export function registerStorageFamily(
10781091
}
10791092
};
10801093

1094+
/**
1095+
* The chunked-completion door's `200` body. One builder for the completion
1096+
* that assembles the file and for a retry of it after it succeeded
1097+
* (#33027), so both answer the same file the same way. The key is the one
1098+
* the file row was committed with: the backend may assemble under another
1099+
* key than the session started with.
1100+
*/
1101+
const completedUploadBody = (session: UploadSessionRecord, file: Pick<FileRecord, 'key'> | null) => ({
1102+
fileId: session.file_id,
1103+
key: file?.key ?? session.key,
1104+
size: session.total_size,
1105+
mimeType: session.mime_type ?? 'application/octet-stream',
1106+
url: `${basePath}/files/${session.file_id}/url`,
1107+
});
1108+
10811109
// ---------------------------------------------------------------------------
10821110
// POST /storage/upload/presigned
10831111
// ---------------------------------------------------------------------------
@@ -1426,6 +1454,16 @@ export function registerStorageFamily(
14261454
return;
14271455
}
14281456

1457+
// [#33027] A completed upload takes no more bytes. Its backend multipart
1458+
// is already assembled and gone, so a chunk stored now belongs to no
1459+
// file, and recording it would rewrite the parts of a finished upload.
1460+
// Asked after the resume token, so only the uploader learns the status,
1461+
// and before a byte is read or stored.
1462+
if (live.status === 'completed') {
1463+
sendError(res, COMPLETED_SESSION_STATUS, COMPLETED_SESSION_CODE, COMPLETED_SESSION_CHUNK_MESSAGE);
1464+
return;
1465+
}
1466+
14291467
// [#27412] The index must name a chunk this upload declared: a whole
14301468
// number in [0, total_chunks). Judged here — after the resume token
14311469
// (a caller who cannot prove it owns the session learns nothing of its
@@ -1609,6 +1647,20 @@ export function registerStorageFamily(
16091647
return;
16101648
}
16111649

1650+
// [#33027] A completion sent again after one that succeeded (a client
1651+
// retrying after it lost the `200`, as `resumeUpload` does) answers the
1652+
// same `200` for the same file. It writes nothing and does not reach the
1653+
// backend: the multipart was assembled and discarded by the first
1654+
// completion, so the backend answered "session not found", the catch
1655+
// below stamped `failed` over `completed`, and the uploader was told a
1656+
// committed, downloadable file had failed. The request is still judged
1657+
// above against the parts the upload holds, so a retry naming a chunk
1658+
// the upload never held is refused as before.
1659+
if (live.status === 'completed') {
1660+
sendOk(res, completedUploadBody(session, file));
1661+
return;
1662+
}
1663+
16121664
await store.updateSession(uploadId, { status: 'completing' }, writeContext);
16131665

16141666
const partsForBackend = verdict.parts.map(p => ({
@@ -1640,13 +1692,7 @@ export function registerStorageFamily(
16401692
throw completionErr;
16411693
}
16421694

1643-
sendOk(res, {
1644-
fileId: session.file_id,
1645-
key: finalKey,
1646-
size: session.total_size,
1647-
mimeType: session.mime_type ?? 'application/octet-stream',
1648-
url: `${basePath}/files/${session.file_id}/url`,
1649-
});
1695+
sendOk(res, completedUploadBody(session, { key: finalKey }));
16501696
} catch (err: any) {
16511697
sendServerFault(res, 500, 'INTERNAL', 'Internal error', err);
16521698
}

0 commit comments

Comments
 (0)