[GH-ISSUE #2757] [Issue]: Game asset generation — slug collisions, duplicate paid generations, and non-atomic writes #1395

Closed
opened 2026-10-21 05:33:00 +07:00 by bsakaguchi · 1 comment
Owner

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

Originally assigned to: @SpicyMarinara on GitHub.

Summary

The game-asset generation and asset-management paths have a cluster of correctness/cost/robustness defects: slug-keyed portrait files collide and cross-assign, there is no idempotency lock so concurrent requests double-bill, recursive delete bypasses native-folder protection, and several disk writes are non-atomic/unvalidated.

Sub-bug 1: Slug collision cross-assigns portraits (#28)

  • How it breaks: safeName collapses punctuation/case so e.g. 'Eldrin the Wise' and 'Eldrin, the Wise!' -> same slug -> same avatar path (450). Two concurrent workers (GAME_ASSET_PORTRAIT_CONCURRENCY=2) both pass the existsSync gate (453), both pay, both writeFileSync (490, last wins); both NPCs get the same avatarUrl -> one shows the wrong face.
  • Repro: One /generate-assets batch with two NPCs whose names differ only by punctuation/case.

Sub-bug 2: No idempotency lock -> duplicate paid gen (#29)

  • How it breaks: /game/generate-assets has no per-chat mutex; existsSync is a TOCTOU gate. Overlapping callers (scene-flow fire-and-forget, combat-prep, retry button) both pass it and double-bill backgrounds/portraits.
  • Repro: Trigger a combat-transition or retry while a scene-flow asset generation for the same chat is in flight.

Sub-bug 3: Recursive delete wipes nested native assets (#60)

  • How it breaks: The .native guard checks only the immediate target (640); native markers exist at every depth. /move has no native/dir guard, so a native folder can be relocated under a non-native folder, then DELETE ?recursive=true rmSyncs the subtree including the nested native assets. Shipped CC0 files are not restored on restart (bundle-hash gated).
  • Repro: Create non-native folder -> move a native folder into it -> recursive-delete the parent.

Sub-bug 4: Non-atomic portrait write + sticky skip (#62)

  • How it breaks: writeFileSync(avatarPath, ...) (490) writes straight to the final path; a crash mid-write leaves a truncated png, and the existsSync skip (453) reuses it forever (unless force). Recoverable via force, but sticky.

Sub-bug 5: Portrait always .png (#64)

  • How it breaks: generateNpcPortrait hardcodes ${slug}.png and writes raw provider bytes; JPEG/WebP/AVIF (e.g. Pollinations) are mislabeled, served as image/png by extname-based MIME. Browsers sniff, but extension-trusting consumers mishandle it.

Sub-bug 6: Background sharp resize unbounded vs upload guard (#63)

  • How it breaks: gameBackgroundImage calls sharp(input).resize(...) with no limitInputPixels, unlike the upload path (which uses GENERATED_BACKGROUND_MAX_INPUT_PIXELS). Bounded by sharp's 268MP default backstop, so images between 32MP and 268MP decode/resize with transient memory pressure.

Sub-bug 7: Multipart upload orphans / wasted IO (#27/#31)

  • How it breaks: The streaming branch await pipeline(file.file, createWriteStream(target)) (448) has no try/catch; on stream error/oversize the partial file is orphaned (the post-pipeline unlink never runs). It also streams up to the 256MB global cap before the route's own 50MB check, wasting IO.
  • Repro: Abort an upload mid-stream, or upload a 50-256MB file.

Suggested Fix

  • Disambiguate colliding slugs (hash/index suffix) and/or dedupe npcsNeedingAvatars by resolved slug before dispatch.
  • Add a per-chatId in-flight lock around /generate-assets (and debounce overlapping client callers).
  • Walk the subtree for nested .native markers before recursive delete; reject moving a native folder.
  • Write portraits/backgrounds to a temp file then renameSync; validate statSync(...).size > 0 (and magic bytes) before reusing.
  • Detect real format and use the correct extension for the file + URL.
  • Pass { limitInputPixels: GENERATED_BACKGROUND_MAX_INPUT_PIXELS, failOn: 'warning' } to the generated-background sharp call.
  • Wrap the multipart pipeline in try/catch + unlink on failure; set a per-route 50MB fileSize limit so the stream aborts early.

Verification checklist (all manual)

  • Verify two punctuation-only-different NPC names get distinct portraits in one batch
  • Verify overlapping /generate-assets requests for one chat don't double-bill
  • Verify a moved native folder cannot be recursively deleted (assets preserved)
  • Verify portraits/backgrounds are written atomically and broken files aren't reused
  • Verify non-PNG provider output gets the correct file extension/Content-Type
  • Verify a large generated background doesn't spike memory; verify aborted/oversize uploads leave no orphan
  • Run pnpm check and pnpm db:push

Affected files

  • packages/server/src/services/game/game-asset-generation.ts
  • packages/server/src/routes/game.routes.ts
  • packages/server/src/routes/game-assets.routes.ts

Audit provenance

Found by a multi-agent static audit of the TTS/voice + image-generation subsystems (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified) against the merged staging tree. Severity: MEDIUM.

AI-drafted from a static read; validation/test-plan boxes intentionally left UNCHECKED for a human to verify before close.

Originally created by @kolacheee on GitHub (Jun 21, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2757 Originally assigned to: @SpicyMarinara on GitHub. ## Summary The game-asset generation and asset-management paths have a cluster of correctness/cost/robustness defects: slug-keyed portrait files collide and cross-assign, there is no idempotency lock so concurrent requests double-bill, recursive delete bypasses native-folder protection, and several disk writes are non-atomic/unvalidated. ## Sub-bug 1: Slug collision cross-assigns portraits (#28) - **How it breaks:** `safeName` collapses punctuation/case so e.g. 'Eldrin the Wise' and 'Eldrin, the Wise!' -> same slug -> same avatar path (450). Two concurrent workers (GAME_ASSET_PORTRAIT_CONCURRENCY=2) both pass the `existsSync` gate (453), both pay, both writeFileSync (490, last wins); both NPCs get the same avatarUrl -> one shows the wrong face. - **Repro:** One /generate-assets batch with two NPCs whose names differ only by punctuation/case. ## Sub-bug 2: No idempotency lock -> duplicate paid gen (#29) - **How it breaks:** /game/generate-assets has no per-chat mutex; `existsSync` is a TOCTOU gate. Overlapping callers (scene-flow fire-and-forget, combat-prep, retry button) both pass it and double-bill backgrounds/portraits. - **Repro:** Trigger a combat-transition or retry while a scene-flow asset generation for the same chat is in flight. ## Sub-bug 3: Recursive delete wipes nested native assets (#60) - **How it breaks:** The `.native` guard checks only the immediate target (640); native markers exist at every depth. `/move` has no native/dir guard, so a native folder can be relocated under a non-native folder, then `DELETE ?recursive=true` `rmSync`s the subtree including the nested native assets. Shipped CC0 files are not restored on restart (bundle-hash gated). - **Repro:** Create non-native folder -> move a native folder into it -> recursive-delete the parent. ## Sub-bug 4: Non-atomic portrait write + sticky skip (#62) - **How it breaks:** `writeFileSync(avatarPath, ...)` (490) writes straight to the final path; a crash mid-write leaves a truncated png, and the `existsSync` skip (453) reuses it forever (unless force). Recoverable via force, but sticky. ## Sub-bug 5: Portrait always .png (#64) - **How it breaks:** generateNpcPortrait hardcodes `${slug}.png` and writes raw provider bytes; JPEG/WebP/AVIF (e.g. Pollinations) are mislabeled, served as image/png by extname-based MIME. Browsers sniff, but extension-trusting consumers mishandle it. ## Sub-bug 6: Background sharp resize unbounded vs upload guard (#63) - **How it breaks:** `gameBackgroundImage` calls `sharp(input).resize(...)` with no `limitInputPixels`, unlike the upload path (which uses GENERATED_BACKGROUND_MAX_INPUT_PIXELS). Bounded by sharp's 268MP default backstop, so images between 32MP and 268MP decode/resize with transient memory pressure. ## Sub-bug 7: Multipart upload orphans / wasted IO (#27/#31) - **How it breaks:** The streaming branch `await pipeline(file.file, createWriteStream(target))` (448) has no try/catch; on stream error/oversize the partial file is orphaned (the post-pipeline unlink never runs). It also streams up to the 256MB global cap before the route's own 50MB check, wasting IO. - **Repro:** Abort an upload mid-stream, or upload a 50-256MB file. ## Suggested Fix - Disambiguate colliding slugs (hash/index suffix) and/or dedupe `npcsNeedingAvatars` by resolved slug before dispatch. - Add a per-chatId in-flight lock around /generate-assets (and debounce overlapping client callers). - Walk the subtree for nested `.native` markers before recursive delete; reject moving a native folder. - Write portraits/backgrounds to a temp file then renameSync; validate `statSync(...).size > 0` (and magic bytes) before reusing. - Detect real format and use the correct extension for the file + URL. - Pass `{ limitInputPixels: GENERATED_BACKGROUND_MAX_INPUT_PIXELS, failOn: 'warning' }` to the generated-background sharp call. - Wrap the multipart pipeline in try/catch + unlink on failure; set a per-route 50MB fileSize limit so the stream aborts early. ## Verification checklist (all manual) - [ ] Verify two punctuation-only-different NPC names get distinct portraits in one batch - [ ] Verify overlapping /generate-assets requests for one chat don't double-bill - [ ] Verify a moved native folder cannot be recursively deleted (assets preserved) - [ ] Verify portraits/backgrounds are written atomically and broken files aren't reused - [ ] Verify non-PNG provider output gets the correct file extension/Content-Type - [ ] Verify a large generated background doesn't spike memory; verify aborted/oversize uploads leave no orphan - [ ] Run `pnpm check` and `pnpm db:push` --- ### Affected files - `packages/server/src/services/game/game-asset-generation.ts` - `packages/server/src/routes/game.routes.ts` - `packages/server/src/routes/game-assets.routes.ts` ### Audit provenance Found by a multi-agent static audit of the TTS/voice + image-generation subsystems (Round 1 + round-2 gap sweep + completeness critic, each finding adversarially verified) against the merged `staging` tree. Severity: **MEDIUM**. > AI-drafted from a static read; validation/test-plan boxes intentionally left UNCHECKED for a human to verify before close.
Author
Owner

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

Addressed on PR #2747. Fixed generated portrait slug collisions by adding an identity hash, preserved provider image extensions, made generated asset writes atomic, ignored broken generated image files when deciding whether to reuse, bounded generated-background sharp input pixels, serialized /game/generate-assets per chat, and hardened game asset upload/delete/move handling around temp files and native folders. Validation so far: git diff --check. Full pnpm checks are intentionally deferred until the issue sweep is complete.

<!-- gh-comment-id:4763326842 --> @SpicyMarinara commented on GitHub (Jun 21, 2026): Addressed on PR #2747. Fixed generated portrait slug collisions by adding an identity hash, preserved provider image extensions, made generated asset writes atomic, ignored broken generated image files when deciding whether to reuse, bounded generated-background sharp input pixels, serialized /game/generate-assets per chat, and hardened game asset upload/delete/move handling around temp files and native folders. Validation so far: git diff --check. Full pnpm checks are intentionally deferred until the issue sweep is complete.
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#1395
No description provided.