[PR #5103] [MERGED] feat(image): global media-generation concurrency ceiling with priority, bounded waits, and live tuning #6629

Closed
opened 2026-10-23 04:12:13 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/5103
Author: @kolacheee
Created: 8/15/2026
Status: ✅ Merged
Merged: 8/16/2026
Merged by: @kolacheee

Base: staging ← Head: feat/5097-generation-concurrency-cap


📝 Commits (9)

  • 2fafe73 feat(image): global media-generation concurrency ceiling (#5097)
  • 6a3eeb7 Merge branch 'staging' into feat/5097-generation-concurrency-cap
  • d865da9 Merge remote-tracking branch 'origin/staging' into feat/5097-generation-concurrency-cap
  • c5db679 fix(image): warn once on an invalid media-generation wait-timeout env
  • 3f66af2 Merge remote-tracking branch 'origin/staging' into feat/5097-generation-concurrency-cap
  • b3ea4d9 Merge remote-tracking branch 'origin/staging' into feat/5097-generation-concurrency-cap
  • f774d59 Merge remote-tracking branch 'origin/staging' into feat/5097-generation-concurrency-cap
  • b987b70 docs(changelog): qualify the no-stampede claim to when the ceiling is enabled (#5097)
  • c2ab98b docs(changelog): qualify the bounded-wait claim (WAIT_TIMEOUT_MS=0 waits indefinitely) (#5097)

📊 Changes

8 files changed (+593 additions, -3 deletions)

View changed files

📝 .env.example (+5 -0)
📝 CHANGELOG.md (+1 -0)
📝 docs/CONFIGURATION.md (+2 -0)
📝 package.json (+2 -1)
📝 packages/server/src/services/image/image-generation-queue.ts (+217 -2)
📝 packages/server/src/services/image/image-generation.ts (+27 -0)
📝 packages/shared/src/constants/defaults.ts (+7 -0)
➕ scripts/regressions/media-generation-cap.regression.ts (+332 -0)

📄 Description

Closes #5097

Why

Media generation has no process-wide limit: the per-connection FIFO is opt-in and per-key, so a batch that fans out (a zone's worth of tiles, storyboard frames, gallery bulk) can stampede a local ComfyUI/SwarmUI GPU into OOM or fan out unbounded concurrent calls against a paid provider.

What changed

A two-tier permit semaphore in image-generation-queue.ts, enforced at the generators themselves: generateImage now self-wraps exactly the way generateVideo already did, so every image path — game assets, sprites, avatars, storyboards, Mari images, previously all uncapped — is covered at a single point with no per-caller wiring. Default ceiling 4, MARINARA_MEDIA_GENERATION_CONCURRENCY to tune, 0 to disable.

This PR went through a pre-submission adversarial review that reshaped it substantially; the design properties below are each regression-pinned:

  • Re-entrancy (review blocker). The video fallback hop re-enters the queue while holding a permit — with the naive semaphore that self-deadlocks at limit 1 (and at 4 under a storyboard batch failing into fallback), hanging all generation until restart. An AsyncLocalStorage guard makes nested acquisitions reuse the held permit — which is also what makes generateImage's self-wrap safe under the existing per-connection wrappers and its own fallback recursion.
  • Live tunability. .env changes are hot-reloaded in this app, and the docs tell users to lower the cap exactly when a batch is thrashing VRAM — so lowering must converge while waiters exist (the naive direct-handoff pinned the old width), and raising must wake parked waiters. Pump-based accounting does both.
  • Bounded waits. A permit wait times out with an actionable error (MARINARA_MEDIA_GENERATION_WAIT_TIMEOUT_MS, default 10 min, 0 = forever) instead of parking forever behind a hung provider call — saturation now fails loudly, never silently.
  • Priority. Background/automatic work (the existing admissionMode marker from connection-admission) never occupies the last permit, so batches cannot fully starve interactive generation. Foreground waiters drain first.
  • Strict config parsing. 0 = unlimited (the explicit opt-out), invalid values warn once and use the default; a would-be negative permit count logs an accounting-bug warning instead of hiding in a clamp.

Acquisition ordering keeps the two queues cycle-free (global permit strictly after the per-connection turn), and release is idempotent and in finally on every path.

New tracked lane regression:generation-cap (in regression:issues), 10 deterministic cases: cap enforcement for non-queued callers, throw/abort/grant-then-abort permit recovery, nested-at-limit-1 no-deadlock, live lower convergence and raise wake-up, wait timeout, 0-unlimited, background-reserve + foreground-first draining, per-key FIFO with cross-queue no-deadlock, and pre-aborted rejection.

Known limitations, stated plainly: video requests don't carry admissionMode yet, so the priority split currently differentiates image work only (video defaults to foreground); and several signal-less call sites (sprite animation loop, connection tests) rely on the wait timeout rather than true cancellation — threading signals there is a natural follow-up.

Validation

  • pnpm check
  • pnpm regression:generation-cap (new)
  • pnpm regression:docs and pnpm version:check (defaults.ts gains a constant only)
  • Manual soak: generate a storyboard and a batch of gallery images concurrently against a local provider — throughput degrades gracefully, nothing stalls, and lowering MARINARA_MEDIA_GENERATION_CONCURRENCY in .env mid-batch visibly reduces in-flight requests.
  • Manually verify a single interactive avatar/selfie generation stays responsive while a batch runs.

Summary by CodeRabbit

  • New Features

    • Added configurable process-wide limits for concurrent image and video generation requests.
    • Foreground requests are prioritized, with bounded wait times and cancellation support.
    • Added unlimited-concurrency mode when configured.
    • Improved reliability during fallback retries and provider failures.
  • Documentation

    • Documented concurrency settings, defaults, validation, reservation behavior, and timeout handling.
  • Tests

    • Added regression coverage for limits, prioritization, failures, cancellations, timeouts, and queue recovery.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/5103 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/15/2026 **Status:** ✅ Merged **Merged:** 8/16/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `feat/5097-generation-concurrency-cap` --- ### 📝 Commits (9) - [`2fafe73`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2fafe7311114f39d4c667326a82784dc9ce3e114) feat(image): global media-generation concurrency ceiling (#5097) - [`6a3eeb7`](https://github.com/Pasta-Devs/Marinara-Engine/commit/6a3eeb734145734c259499c3e7632dfb6b208471) Merge branch 'staging' into feat/5097-generation-concurrency-cap - [`d865da9`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d865da9444e482da69dac359007fc71d995c2869) Merge remote-tracking branch 'origin/staging' into feat/5097-generation-concurrency-cap - [`c5db679`](https://github.com/Pasta-Devs/Marinara-Engine/commit/c5db6799558c17a81e3928dab833a156f2cba502) fix(image): warn once on an invalid media-generation wait-timeout env - [`3f66af2`](https://github.com/Pasta-Devs/Marinara-Engine/commit/3f66af2d61c9af39e38a0f1bd4246d9419fd1da1) Merge remote-tracking branch 'origin/staging' into feat/5097-generation-concurrency-cap - [`b3ea4d9`](https://github.com/Pasta-Devs/Marinara-Engine/commit/b3ea4d9d5fae0577003ed1d531916122bab11685) Merge remote-tracking branch 'origin/staging' into feat/5097-generation-concurrency-cap - [`f774d59`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f774d594e9fdce2e25a4b08b811195bc072786ea) Merge remote-tracking branch 'origin/staging' into feat/5097-generation-concurrency-cap - [`b987b70`](https://github.com/Pasta-Devs/Marinara-Engine/commit/b987b70027fa0ba773b6146ce4d77c46565cb739) docs(changelog): qualify the no-stampede claim to when the ceiling is enabled (#5097) - [`c2ab98b`](https://github.com/Pasta-Devs/Marinara-Engine/commit/c2ab98b45c5d218a1fa882f482f1dc799e7efa20) docs(changelog): qualify the bounded-wait claim (WAIT_TIMEOUT_MS=0 waits indefinitely) (#5097) ### 📊 Changes **8 files changed** (+593 additions, -3 deletions) <details> <summary>View changed files</summary> 📝 `.env.example` (+5 -0) 📝 `CHANGELOG.md` (+1 -0) 📝 `docs/CONFIGURATION.md` (+2 -0) 📝 `package.json` (+2 -1) 📝 `packages/server/src/services/image/image-generation-queue.ts` (+217 -2) 📝 `packages/server/src/services/image/image-generation.ts` (+27 -0) 📝 `packages/shared/src/constants/defaults.ts` (+7 -0) ➕ `scripts/regressions/media-generation-cap.regression.ts` (+332 -0) </details> ### 📄 Description Closes #5097 ## Why Media generation has no process-wide limit: the per-connection FIFO is opt-in and per-key, so a batch that fans out (a zone's worth of tiles, storyboard frames, gallery bulk) can stampede a local ComfyUI/SwarmUI GPU into OOM or fan out unbounded concurrent calls against a paid provider. ## What changed A two-tier permit semaphore in `image-generation-queue.ts`, **enforced at the generators themselves**: `generateImage` now self-wraps exactly the way `generateVideo` already did, so every image path — game assets, sprites, avatars, storyboards, Mari images, previously all uncapped — is covered at a single point with no per-caller wiring. Default ceiling 4, `MARINARA_MEDIA_GENERATION_CONCURRENCY` to tune, `0` to disable. This PR went through a pre-submission adversarial review that reshaped it substantially; the design properties below are each regression-pinned: - **Re-entrancy (review blocker).** The video fallback hop re-enters the queue while holding a permit — with the naive semaphore that self-deadlocks at limit 1 (and at 4 under a storyboard batch failing into fallback), hanging all generation until restart. An `AsyncLocalStorage` guard makes nested acquisitions reuse the held permit — which is also what makes `generateImage`'s self-wrap safe under the existing per-connection wrappers and its own fallback recursion. - **Live tunability.** `.env` changes are hot-reloaded in this app, and the docs tell users to lower the cap exactly when a batch is thrashing VRAM — so lowering must converge while waiters exist (the naive direct-handoff pinned the old width), and raising must wake parked waiters. Pump-based accounting does both. - **Bounded waits.** A permit wait times out with an actionable error (`MARINARA_MEDIA_GENERATION_WAIT_TIMEOUT_MS`, default 10 min, `0` = forever) instead of parking forever behind a hung provider call — saturation now fails loudly, never silently. - **Priority.** Background/automatic work (the existing `admissionMode` marker from connection-admission) never occupies the last permit, so batches cannot fully starve interactive generation. Foreground waiters drain first. - **Strict config parsing.** `0` = unlimited (the explicit opt-out), invalid values warn once and use the default; a would-be negative permit count logs an accounting-bug warning instead of hiding in a clamp. Acquisition ordering keeps the two queues cycle-free (global permit strictly after the per-connection turn), and release is idempotent and in `finally` on every path. **New tracked lane** `regression:generation-cap` (in `regression:issues`), 10 deterministic cases: cap enforcement for non-queued callers, throw/abort/grant-then-abort permit recovery, nested-at-limit-1 no-deadlock, live lower convergence and raise wake-up, wait timeout, 0-unlimited, background-reserve + foreground-first draining, per-key FIFO with cross-queue no-deadlock, and pre-aborted rejection. Known limitations, stated plainly: video requests don't carry `admissionMode` yet, so the priority split currently differentiates image work only (video defaults to foreground); and several signal-less call sites (sprite animation loop, connection tests) rely on the wait timeout rather than true cancellation — threading signals there is a natural follow-up. ## Validation - [x] `pnpm check` - [x] `pnpm regression:generation-cap` (new) - [x] `pnpm regression:docs` and `pnpm version:check` (defaults.ts gains a constant only) - [x] Manual soak: generate a storyboard and a batch of gallery images concurrently against a local provider — throughput degrades gracefully, nothing stalls, and lowering `MARINARA_MEDIA_GENERATION_CONCURRENCY` in `.env` mid-batch visibly reduces in-flight requests. - [x] Manually verify a single interactive avatar/selfie generation stays responsive while a batch runs. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added configurable process-wide limits for concurrent image and video generation requests. * Foreground requests are prioritized, with bounded wait times and cancellation support. * Added unlimited-concurrency mode when configured. * Improved reliability during fallback retries and provider failures. * **Documentation** * Documented concurrency settings, defaults, validation, reservation behavior, and timeout handling. * **Tests** * Added regression coverage for limits, prioritization, failures, cancellations, timeouts, and queue recovery. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:12:13 +07:00
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#6629
No description provided.