Files
image-workbench-desktop/docs/archive/audits/GENERATION-CONCURRENCY-AUDIT.md
T

7.9 KiB

⚠️ 历史·过程留档(已归档,2026-10-16):本文为当时记录,不代表现状;现状以 docs/standards/architecture-current-state.md 为准,规则见 docs/standards/。

Generation State and Concurrency Audit

Date: 2026-08-17 Scope: the image-workbench-web project only. Out of scope: the separate image-workbench-app project.

Current design

  • Per runNode() call, jobs are executed by a sliding worker window capped at GEN_CONCURRENCY = 4.
  • Each completed image is written immediately through liveUpsert(), so parallel results can appear in completion order.
  • Progress is keyed by nodeId::taskId for a single task and nodeId::all for all tasks.
  • Output-node batch generation uses outId::out for aggregate progress and calls runNode() for each source generator in parallel.
  • Each request is retried once after a 2-second delay.
  • Results are saved from a local genLatest snapshot in finally.

Findings

P0 — duplicate starts are not synchronously guarded

runNode() checks no synchronous in-flight registry before awaiting ensurePolished() or setting busy. Two rapid clicks, a context-menu invocation plus a task-button click, or overlapping callers can both enter the function before React state renders busy=true. They can submit duplicate requests and race while clearing/upserting the same result slots.

Affected areas: app.js around runNode() (approximately lines 4249-4390), task button handlers around lines 988-993, context menu around lines 5451-5452.

Recommended fix: add a synchronous refs.runningJobs/refs.runningRuns registry checked before the first await; release it in finally. Keep UI busy as presentation state, not as the lock.

P0 — GEN_CONCURRENCY is per run, not global

A single runNode() is capped at four requests, but runAll() starts every generator with Promise.all(), and runOutSources() starts every output source with Promise.all(). With multiple generator nodes, total in-flight requests can become 4 * number_of_generators or higher. This defeats the intended service-provider concurrency limit.

Affected areas: GEN_CONCURRENCY around line 392; runNode() worker creation around line 4360; runOutSources() around line 4420; runAll() around line 4450.

Recommended fix: introduce one shared scheduler/semaphore per Workbench instance. All image requests, regardless of source node or entry point, must acquire the same global slot.

P1 — concurrency is hard-coded

GEN_CONCURRENCY = 4 is a source constant. The settings model currently has no generation concurrency field, so users cannot adapt it to provider quotas or key-group limits.

Recommended fix: add a bounded setting, for example 1-8, defaulting to the current behavior or a conservative default chosen with the provider. Persist it in the Web config and display the meaning as “simultaneous browser requests”, not remote-task cancellation.

P1 — retry delay does not account for provider throttling

Every error is retried once after two seconds. The code does not distinguish 429, 5xx, network failure, timeout, 4xx parameter errors, or authentication errors. A bad request can be duplicated, and a rate-limited request can retry too aggressively.

Recommended fix: classify errors; retry only transient/network/429/5xx failures with bounded exponential backoff and jitter. Do not retry validation/authentication errors.

P1 — timeout parameter is not enforced in the Web API path

runNode() passes GEN_TIMEOUT_MS as a third argument to api('generate', ...), but api() accepts only (name, args) and wApi() does not use that timeout. wGenerate() calls fetch() without an AbortController timeout. The 240-second constant is therefore descriptive, not operational.

Recommended fix: implement timeout/abort in the shared API client, or remove the misleading argument until implemented. Preserve the distinction between browser-side stop-waiting and provider-side task cancellation.

P1 — aggregate output progress can be misleading under overlap

runOutSources() owns outId::out, while each source owns its own nodeId::all. If the same generator is already running, output batch generation can start another run. Aggregate done then reflects multiple overlapping runs and can exceed the intended total or show inconsistent completion.

Recommended fix: reject or coalesce a source already in flight; have the scheduler return the existing run handle to aggregate callers.

P1 — async persistence is fire-and-forget at important boundaries

wAddOutputs(groups...) and refreshOutputs() are called without awaiting wAddOutputs(). saveNow() in finally is also not awaited. The UI can clear progress before IndexedDB/local index persistence finishes, and failures are not surfaced to the user.

Recommended fix: await result persistence before reporting the run complete; expose persistence failure separately from generation failure.

P2 — progress semantics intentionally count failed requests as completed

completed++ runs for both successful and failed request attempts, so progress means “requests settled”, not “images succeeded”. This is reasonable but should be named and displayed clearly; output aggregate callbacks separately count successful images.

Recommended fix: expose settled, succeeded, failed, and total fields rather than overloading done.

P2 — retry identity and result identity are stable enough, but run identity is missing

Result slots use promptId + vi, which prevents a later completion from duplicating the same variant within one run. There is no runId, however, so an older overlapping run can still write into the same slots as a newer run.

Recommended fix: attach runId to progress/results and ignore stale completions when a newer run supersedes a task.

What is already correct

  • Parallel generation and first-completed-first-displayed behavior is intentional and should be preserved.
  • Per-run worker scheduling avoids launching the entire job list at once.
  • Results are incrementally upserted rather than waiting for the full batch.
  • The user confirmed real-browser Space + left-drag canvas panning works; the jsdom failure is not a product defect.
  1. Add synchronous duplicate-run guard and source coalescing.
  2. Introduce a shared global scheduler/semaphore.
  3. Make concurrency configurable with bounded validation.
  4. Add error classification, transient-only retry, and real request timeout.
  5. Await result/index persistence and surface storage failures.
  6. Add run IDs and richer progress fields.
  7. Add focused tests for duplicate starts, global slot count, retry classification, timeout, and first-completed result rendering.

Implemented in this pass

  • Added a shared per-Workbench request scheduler. All image requests from all generator nodes and entry points acquire the same slot; the current client cap remains 4.
  • Preserved parallel generation and first-completed-first-displayed behavior within the shared cap.
  • Added a synchronous runningRuns registry checked before the first async operation. Repeated starts for the same generator are rejected before submitting requests.
  • Awaited Web output index update and refresh in the generation completion path.

Verification after implementation

  • node --check app.js: passed.
  • node --check tests/iwb-v32-web-test.js: passed.
  • git diff --check: passed.
  • Existing jsdom test: 326 passed / 4 known behavior/test-assumption differences; no new failures introduced.
  • Local Web preview serving the current workspace: http://localhost:8788.
  • No GitHub push or Cloudflare deployment performed.

The current single-node parallel behavior is functionally aligned with the product requirement. The main reliability risk is not parallel display; it is that multiple entry points can create overlapping runs and bypass the intended global concurrency cap. No business code was changed during this audit.