[GH-ISSUE #3063] [Issue]: Chat-gallery and global-gallery uploads orphan a partial file when the upload stream is truncated or aborted #1629

Closed
opened 2026-10-21 05:41:06 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @kolacheee on GitHub (Jun 29, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3063

Originally assigned to: @SpicyMarinara on GitHub.

What's wrong

Both the chat-gallery upload (POST /api/gallery/:chatId/upload) and the global-gallery upload (POST /api/global-gallery/upload) stream the request body to a file with await pipeline(data.file, createWriteStream(filePath)) and do NOT wrap that pipeline in a try/catch that deletes the partial file on failure. If the upload stream errors mid-write — the client aborts the connection, or the file exceeds the 256 MB @fastify/multipart fileSize limit so the stream is truncated — the pipeline rejects, the request 500s, and a partially-written file is left stranded on disk with no DB row. For the chat-gallery case, gallery-recovery re-adopts it as a full image only if the chat still exists (and even then writes a corrupt "valid" image); otherwise it is a permanent orphan the API cannot delete. The sibling routes custom-emojis.routes.ts:103-114 and custom-stickers.routes.ts:107-118 DO wrap the same pipeline in try/catch + cleanup, confirming this is an inconsistency.

How to reproduce (try it yourself)

  1. Start the server.
  2. POST a multipart upload to /api/gallery/<existingChatId>/upload with a .png file part whose body is larger than 256 MB (or simply close the TCP connection partway through sending the body).
  3. Inspect data/gallery/<chatId>/.

You'll see: the request fails (500 or aborted) and a truncated <id>.png remains on disk with no corresponding chat_images record. The same applies to /api/global-gallery/upload, leaving a stray file in data/gallery/global/.

Expected: a failed/aborted upload deletes the partial file and returns 400 (or 413 when the multipart layer truncated an oversize stream).

Where it is

  • packages/server/src/routes/gallery.routes.ts:396 — await pipeline(...) with no cleanup anywhere in the handler.
  • packages/server/src/routes/global-gallery.routes.ts:112 — await pipeline(...) sits OUTSIDE the DB-only rollback try (lines 121-141), which only unlinks on a createImage failure, not a pipeline rejection.
  • Multipart cap: app.ts:45,67-71 (MAX_UPLOAD_BYTES = 256 MB). Recovery: gallery-recovery.ts:29-31,47-64.

What's happening

The await pipeline(...) that writes the uploaded bytes is not guarded by a try/catch that unlinks the just-created file on stream error. createWriteStream creates the file before bytes flow, so a mid-stream error strands a partial file. global-gallery rolls back only on a DB failure; gallery has no rollback at all.

Suggested fix

Wrap the pipeline call in its OWN try/catch in BOTH routes, unlinking the partial file and returning 413 on truncation else 400. Do NOT reuse the global-gallery DB-rollback try.

gallery.routes.ts, replace line 396:

try {
  await pipeline(data.file, createWriteStream(filePath));
} catch (err) {
  if (existsSync(filePath)) unlinkSync(filePath);
  const truncated = (data.file as typeof data.file & { truncated?: boolean }).truncated === true;
  logger.warn(err, "Failed to receive chat gallery upload %s", filename);
  return reply
    .status(truncated ? 413 : 400)
    .send({ error: truncated ? "Uploaded image exceeds the upload size limit." : "Failed to read uploaded image." });
}

global-gallery.routes.ts, replace line 112 with the same block (using a "global gallery" log message). existsSync, unlinkSync, and logger are already imported in both files. Leave the existing DB-rollback try/catch (global-gallery lines 121-141) exactly as-is.

Regression avoided: the original suggestion offered moving the pipeline INTO the global-gallery DB-rollback try, but that catch returns a hardcoded 500 'Failed to save image metadata', which would mislabel a 413/400 transport failure. A dedicated pipeline try/catch keeps the two failure modes distinct. The happy path is unchanged (pipeline resolves -> falls through), and the client hook already treats any non-2xx upload as a failure via Promise.allSettled, so returning 400/413 instead of an uncaught 500 is strictly better. A plainer variant that always returns 400 (matching custom-emojis verbatim) is also acceptable; the .truncated check just gives the more accurate 413.


AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.

Originally created by @kolacheee on GitHub (Jun 29, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3063 Originally assigned to: @SpicyMarinara on GitHub. **What's wrong** Both the chat-gallery upload (`POST /api/gallery/:chatId/upload`) and the global-gallery upload (`POST /api/global-gallery/upload`) stream the request body to a file with `await pipeline(data.file, createWriteStream(filePath))` and do NOT wrap that pipeline in a try/catch that deletes the partial file on failure. If the upload stream errors mid-write — the client aborts the connection, or the file exceeds the 256 MB `@fastify/multipart` `fileSize` limit so the stream is truncated — the pipeline rejects, the request 500s, and a partially-written file is left stranded on disk with no DB row. For the chat-gallery case, gallery-recovery re-adopts it as a full image only if the chat still exists (and even then writes a corrupt "valid" image); otherwise it is a permanent orphan the API cannot delete. The sibling routes `custom-emojis.routes.ts:103-114` and `custom-stickers.routes.ts:107-118` DO wrap the same pipeline in try/catch + cleanup, confirming this is an inconsistency. **How to reproduce (try it yourself)** 1. Start the server. 2. `POST` a multipart upload to `/api/gallery/<existingChatId>/upload` with a `.png` file part whose body is larger than 256 MB (or simply close the TCP connection partway through sending the body). 3. Inspect `data/gallery/<chatId>/`. You'll see: the request fails (500 or aborted) and a truncated `<id>.png` remains on disk with no corresponding `chat_images` record. The same applies to `/api/global-gallery/upload`, leaving a stray file in `data/gallery/global/`. Expected: a failed/aborted upload deletes the partial file and returns 400 (or 413 when the multipart layer truncated an oversize stream). **Where it is** - `packages/server/src/routes/gallery.routes.ts:396` — `await pipeline(...)` with no cleanup anywhere in the handler. - `packages/server/src/routes/global-gallery.routes.ts:112` — `await pipeline(...)` sits OUTSIDE the DB-only rollback try (lines 121-141), which only unlinks on a `createImage` failure, not a pipeline rejection. - Multipart cap: `app.ts:45,67-71` (`MAX_UPLOAD_BYTES = 256 MB`). Recovery: `gallery-recovery.ts:29-31,47-64`. **What's happening** The `await pipeline(...)` that writes the uploaded bytes is not guarded by a try/catch that unlinks the just-created file on stream error. `createWriteStream` creates the file before bytes flow, so a mid-stream error strands a partial file. global-gallery rolls back only on a DB failure; gallery has no rollback at all. **Suggested fix** Wrap the pipeline call in its OWN try/catch in BOTH routes, unlinking the partial file and returning 413 on truncation else 400. Do NOT reuse the global-gallery DB-rollback try. gallery.routes.ts, replace line 396: ```ts try { await pipeline(data.file, createWriteStream(filePath)); } catch (err) { if (existsSync(filePath)) unlinkSync(filePath); const truncated = (data.file as typeof data.file & { truncated?: boolean }).truncated === true; logger.warn(err, "Failed to receive chat gallery upload %s", filename); return reply .status(truncated ? 413 : 400) .send({ error: truncated ? "Uploaded image exceeds the upload size limit." : "Failed to read uploaded image." }); } ``` global-gallery.routes.ts, replace line 112 with the same block (using a "global gallery" log message). `existsSync`, `unlinkSync`, and `logger` are already imported in both files. Leave the existing DB-rollback try/catch (global-gallery lines 121-141) exactly as-is. Regression avoided: the original suggestion offered moving the pipeline INTO the global-gallery DB-rollback try, but that catch returns a hardcoded 500 'Failed to save image metadata', which would mislabel a 413/400 transport failure. A dedicated pipeline try/catch keeps the two failure modes distinct. The happy path is unchanged (pipeline resolves -> falls through), and the client hook already treats any non-2xx upload as a failure via `Promise.allSettled`, so returning 400/413 instead of an uncaught 500 is strictly better. A plainer variant that always returns 400 (matching custom-emojis verbatim) is also acceptable; the `.truncated` check just gives the more accurate 413. --- *AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.*
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Claiming this for the current staging sweep in draft PR #3064: https://github.com/Pasta-Devs/Marinara-Engine/pull/3064

<!-- gh-comment-id:4835430061 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Claiming this for the current staging sweep in draft PR #3064: https://github.com/Pasta-Devs/Marinara-Engine/pull/3064
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Fixed in PR #3064 on branch codex/issue-sweep-3054-3063 (commit 3ae8ca37). Closing this issue as addressed; the PR remains open for staging review/merge.

<!-- gh-comment-id:4835580128 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Fixed in PR #3064 on branch `codex/issue-sweep-3054-3063` (commit 3ae8ca37). Closing this issue as addressed; the PR remains open for staging review/merge.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1629
No description provided.