@animastor/orchestration 0.3.4 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,55 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.5 (2026-11-05) — утечка квоты диспатча, reconcile не понижает закоммиченное
4
+
5
+ Основание: `reports/2026-11-05/live-check-A-B-C.md` §6, §10 и
6
+ `reports/2026-11-05/reconcile-quota-leak.md` (BA `ba_1788172242081`: «Вся книга» встала
7
+ после 4 сцен, `animastor:runtime:active-audio` = 8/8 без единого job, 13 сцен с
8
+ закоммиченным аудио сброшены в `stale`, строка в Генераторе пропала). Описание:
9
+ animastor-docs `02-orchestration/DISPATCH_QUOTA_AND_RECONCILE.md`.
10
+
11
+ ### Fixed
12
+
13
+ - `dispatch-engine.dispatchStage`: исход executor'а `completed` **без jobs**
14
+ (`already_done`, `recovered_via_completeChunk`, `cache_hit`, `scene_not_found`, …)
15
+ теперь финализируется (`finalizeDispatch` outcome `success`, reason
16
+ `completed_without_jobs:<reason>`) — meta + lease + занятый слот квоты снимаются одним
17
+ Lua-claim. Раньше они висели до stale-lease recovery (~31 мин). Повторная финализация
18
+ идемпотентна. Поле `completed` теперь возвращается наверх (планировщик считал такие
19
+ исходы ошибками).
20
+ - `dispatch-engine`: после `dispatched:true` meta помечается `jobs_enqueued` (CAS-скрипт,
21
+ без воскрешения уже финализированной meta).
22
+ - `scene-orchestrator`: `AUDIO_ALREADY_DONE` (DONE + коммит) завершает стадию через
23
+ `completeStage` под живым dispatch (handler → version gate → PG ready + asset READY),
24
+ а не просто «пропускает»; recovery `completeChunk` вызывается с живым `dispatchId`
25
+ (раньше литерал `'stale-recovery'` → `COMPLETE-STAGE Rejected … stale_dispatch`).
26
+ - `reconciliation-engine` `RELEASE_STALE_LEASE`: стадия с подтверждённым коммитом
27
+ текущего поколения (PG `ready` + `isSceneAudioCommitted`) не помечается DIRTY (нет bump
28
+ эпохи и PG stale) — только освобождение lease/квоты и повтор READY в Redis.
29
+ - `counter-reconciliation`: перед сверкой — поиск фантомных диспатчей (lease+meta без
30
+ `jobs_enqueued`, без job в хабе (`animastor:running` / `animastor:queue:*`), старше
31
+ 2 мин, замечен на двух прогонах подряд) → `cancelActiveDispatch` (`phantom_dispatch`);
32
+ счётчик сверяется с оставшимися живыми lease.
33
+
34
+ ### Added
35
+
36
+ - `runtime-scheduler`: backpressure при отсутствии живых воркеров типа в любом scope →
37
+ `blockStageNoWorker` (задача `blocked`, «нет воркера»); исходы без движения
38
+ (не dispatched / не completed / не capacity) копятся — ≥3 попыток и ≥5 мин →
39
+ `command-gate.failStageNoProgress` (задача `failed`, `error_class=no_progress`,
40
+ `error_code=<последняя причина>`).
41
+ - `worker-health.getAnyAliveCount`; `command-gate.noteNoProgress / clearNoProgress /
42
+ failStageNoProgress`; `counter-reconciliation.sweepPhantomDispatches`;
43
+ `reconciliation-engine.isStageCommittedReady`; `dispatch-engine.markDispatchJobsEnqueued`.
44
+
45
+ ### Host contract (ломающее для хоста: новая обязательная операция порта)
46
+
47
+ - `ProgressEventsPort.failSceneStage(redis, bookId, chapterId, sceneId, type, info)` —
48
+ объявлена в `OPS` (архитектурный guard O-5: каждая операция порта объявлена и живая);
49
+ `setProgressEventsPort` без неё падает при старте. Backend-адаптер
50
+ (`storage/progress-events-adapter.js`) её реализует в том же релизе — bump на 0.3.5
51
+ только вместе с ним.
52
+
3
53
  ## 0.3.4 (2026-11-04) — 0.3.3 + «ready» аудио только при коммите GPU
4
54
 
5
55
  Одна публикация вместо двух: 0.3.3 (уборка хаба при `/regenerate`, см. ниже) **не
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@animastor/orchestration",
3
- "version": "0.3.4",
3
+ "version": "0.3.5",
4
4
  "description": "Animastor Orchestration — the generation orchestration/runtime contour of the Animastor backend, physically extracted from the host (§32.30): the unified generation lifecycle owner (orchestrator facade, stage executor, scene callbacks/restoration), the dispatch engine and its lease/quota/retry managers, the reconciliation engine and counter reconciliation, the scene window/scheduler/worker-health, the runtime-result emitter/consumer, and the eight O-2..O-10 port contracts (Persistence, SceneData, PlaceholderAudio, ProgressEvents, AudioFsm, VideoFsm, HubCancel, LayerConfig). The package reaches the host (runtime config slices, Redis-domain state layer, media facades, the S-5 seam registry, the artifact root, the PW-2 workspace resolver) ONLY through the composition-root host-bindings seam — no backend/src require, no storage/book/routes/services, no Redis, no PG, no Express inside.",
5
5
  "keywords": [
6
6
  "animastor",
@@ -75,6 +75,36 @@ async function hasCommittedAudio(buildId, bookId, chapterId, sceneId, expectedCo
75
75
  }
76
76
  }
77
77
 
78
+ /**
79
+ * reconcile-quota-leak (2026-11-05, BA): an audio stage that is DONE with a
80
+ * fenced commit behind it must END the dispatch as a completed stage — not
81
+ * just "skip". The former `already_done` return left the asset state of a
82
+ * commanded scene in PENDING/GENERATING (the command had reset it), so the
83
+ * periodic stale-lease recovery later saw an "in-flight" stage, marked it
84
+ * DIRTY (epoch bump + PG stale) and the committed audio was demoted.
85
+ *
86
+ * completeStage runs under the LIVE dispatch identity: the audio handler
87
+ * (committed probe), the version gate (content / audio-config versions of
88
+ * the current generation) and only then PG ready + asset READY; it also
89
+ * finalizes the dispatch (lease + meta + quota) in the same call. A
90
+ * version-stale commit is NOT promoted (gate → DIRTY) — invariant B holds.
91
+ */
92
+ async function completeAlreadyDoneAudio(redis, bookId, chapterId, sceneId, buildId, dispatchId) {
93
+ let completion = { completed: false, reason: 'not_run' };
94
+ try {
95
+ completion = await completeStage(redis, bookId, chapterId, sceneId, 'audio', buildId, dispatchId);
96
+ } catch (err) {
97
+ warn(`AUDIO_ALREADY_DONE: completeStage failed for ${bookId}/${chapterId}/${sceneId}: ${err.message}`);
98
+ completion = { completed: false, reason: `completion_error:${err.message}` };
99
+ }
100
+ if (completion.completed) {
101
+ log(`AUDIO_ALREADY_DONE: ${bookId}/${chapterId}/${sceneId} — committed audio of the current generation restored to READY (no GPU)`);
102
+ return { dispatched: false, jobs: 0, completed: true, reason: 'already_done' };
103
+ }
104
+ warn(`AUDIO_ALREADY_DONE: ${bookId}/${chapterId}/${sceneId} — completion not accepted (${completion.reason})`);
105
+ return { dispatched: false, jobs: 0, completed: false, reason: `already_done_rejected:${completion.reason || 'unknown'}` };
106
+ }
107
+
78
108
  // ======================================================
79
109
  // SCENE ORCHESTRATOR
80
110
  // ======================================================
@@ -236,7 +266,7 @@ async function executeAudioDispatch(redis, scene, loadedBook, buildId, dispatchI
236
266
  // DONE is only authoritative with a committed chunk behind it.
237
267
  if (await hasCommittedAudio(buildId, bookId, chapterId, sceneId, orchState.expected_count)) {
238
268
  log(`AUDIO_ALREADY_DONE: ${bookId}/${chapterId}/${sceneId} — skipping dispatch`);
239
- return { dispatched: false, jobs: 0, completed: true, reason: 'already_done' };
269
+ return completeAlreadyDoneAudio(redis, bookId, chapterId, sceneId, buildId, dispatchId);
240
270
  }
241
271
  log(
242
272
  `AUDIO_ALREADY_DONE rejected: ${bookId}/${chapterId}/${sceneId} — DONE without a committed audio chunk ` +
@@ -266,7 +296,7 @@ async function executeAudioDispatch(redis, scene, loadedBook, buildId, dispatchI
266
296
  if (stalePhase === audioFsmPhases().DONE) {
267
297
  if (await hasCommittedAudio(buildId, bookId, chapterId, sceneId, orchState && orchState.expected_count)) {
268
298
  warn(`AUDIO_ORCH: DONE guard prevented stale reset for ${bookId}/${chapterId}/${sceneId}`);
269
- return { dispatched: false, jobs: 0, completed: true, reason: 'already_done' };
299
+ return completeAlreadyDoneAudio(redis, bookId, chapterId, sceneId, buildId, dispatchId);
270
300
  }
271
301
  warn(`AUDIO_ORCH: stale DONE without a committed chunk for ${bookId}/${chapterId}/${sceneId} — resetting to PLACEHOLDER_READY`);
272
302
  }
@@ -284,10 +314,14 @@ async function executeAudioDispatch(redis, scene, loadedBook, buildId, dispatchI
284
314
  if (presentChunks.length > 0) {
285
315
  log(` 🔧 AUDIO_ORCH: ${presentChunks.length} chunks on disk for ${bookId}/${chapterId}/${sceneId} — calling completeChunk instead of reset`);
286
316
  try {
317
+ // reconcile-quota-leak: the LIVE dispatch id. The former
318
+ // literal 'stale-recovery' made completeStage reject the
319
+ // recovery as `stale_dispatch` — chunks went `ready`, the
320
+ // asset stayed stale in PG, the lease/quota stayed held.
287
321
  await audioFsmOp('completeChunk')(redis, bookId, chapterId, sceneId, 'recovery', buildId, {
288
322
  audio,
289
323
  orchestrator: require('./orchestrator'),
290
- dispatchId: 'stale-recovery',
324
+ dispatchId,
291
325
  });
292
326
  return { dispatched: false, jobs: 0, completed: true, reason: 'recovered_via_completeChunk' };
293
327
  } catch (recoverErr) {
@@ -198,6 +198,72 @@ async function blockStageNoWorker(redis, bookId, chapterId, sceneId, stage) {
198
198
  return { reason, ...result };
199
199
  }
200
200
 
201
+ // ======================================================
202
+ // NO PROGRESS → FAILED (reconcile-quota-leak, 2026-11-05)
203
+ // ======================================================
204
+ // A commanded scene×stage whose dispatches keep ending WITHOUT jobs and
205
+ // WITHOUT completion (no_jobs_generated, already_done_rejected:*, executor
206
+ // errors …) used to loop silently: the task stayed `active`, the progress
207
+ // row kept its running timer. After NO_PROGRESS_FAIL_MS of such outcomes
208
+ // (and at least NO_PROGRESS_MIN_ATTEMPTS attempts — a transient `locked`
209
+ // must not fail a command) the command becomes `failed` with the reason;
210
+ // the row stays visible with «Повторить». Any real dispatch or completion
211
+ // resets the window.
212
+
213
+ const NO_PROGRESS_KEY_PREFIX = 'animastor:dispatch-noprogress:';
214
+ const NO_PROGRESS_FAIL_MS = 5 * 60 * 1000;
215
+ const NO_PROGRESS_MIN_ATTEMPTS = 3;
216
+ const NO_PROGRESS_TTL_S = 60 * 60;
217
+
218
+ function noProgressKey(bookId, chapterId, sceneId, stage) {
219
+ return `${NO_PROGRESS_KEY_PREFIX}${bookId}:${chapterId}:${sceneId}:${stage}`;
220
+ }
221
+
222
+ async function clearNoProgress(redis, bookId, chapterId, sceneId, stage) {
223
+ try { await redis.del(noProgressKey(bookId, chapterId, sceneId, stage)); } catch (_) { /* best-effort */ }
224
+ }
225
+
226
+ /**
227
+ * Record one dispatch outcome without progress.
228
+ * @returns {Promise<{attempts:number, since:number, exceeded:boolean}>}
229
+ */
230
+ async function noteNoProgress(redis, bookId, chapterId, sceneId, stage, reason, now = Date.now()) {
231
+ const key = noProgressKey(bookId, chapterId, sceneId, stage);
232
+ let rec = null;
233
+ try { rec = JSON.parse((await redis.get(key)) || 'null'); } catch (_) { rec = null; }
234
+ if (!rec || typeof rec.since !== 'number') rec = { since: now, attempts: 0 };
235
+ rec.attempts = (rec.attempts || 0) + 1;
236
+ rec.last_reason = reason || 'unknown';
237
+ rec.last_at = now;
238
+ await redis.set(key, JSON.stringify(rec), 'EX', NO_PROGRESS_TTL_S);
239
+ const exceeded = rec.attempts >= NO_PROGRESS_MIN_ATTEMPTS && (now - rec.since) >= NO_PROGRESS_FAIL_MS;
240
+ return { attempts: rec.attempts, since: rec.since, exceeded };
241
+ }
242
+
243
+ /**
244
+ * Terminal: the command for this scene×stage made no progress — registry
245
+ * task → failed (error_class «no_progress», error_code = last reason), PG
246
+ * legs host-side (ProgressEventsPort.failSceneStage).
247
+ */
248
+ async function failStageNoProgress(redis, bookId, chapterId, sceneId, stage, reason, attempts) {
249
+ const info = {
250
+ error_class: 'no_progress',
251
+ error_code: String(reason || 'unknown').slice(0, 120),
252
+ error_message: `генерация не идёт: ${String(reason || 'unknown').slice(0, 200)}`,
253
+ attempts: attempts || null,
254
+ };
255
+ let result = { tasks: [] };
256
+ try {
257
+ result = (await progressEventsOp('failSceneStage')(redis, bookId, chapterId, sceneId, stage, info)) || result;
258
+ } catch (err) {
259
+ warn(`failSceneStage failed for ${bookId}/${chapterId}/${sceneId}:${stage}: ${err.message}`);
260
+ }
261
+ await clearNoProgress(redis, bookId, chapterId, sceneId, stage);
262
+ const ids = (result.tasks || []).map(t => t.task_id || t).join(',') || 'none';
263
+ log(`FAILED_NO_PROGRESS ${bookId}/${chapterId}/${sceneId}:${stage} — reason=${info.error_code} attempts=${attempts}; tasks=[${ids}] — a new command is required`);
264
+ return { ...info, ...result };
265
+ }
266
+
201
267
  // ======================================================
202
268
  // FORCE — only for the scene×stage pairs of the command
203
269
  // ======================================================
@@ -260,6 +326,12 @@ module.exports = {
260
326
  describeDenied,
261
327
  rollbackGeneratingToDirty,
262
328
  blockStageNoWorker,
329
+ NO_PROGRESS_FAIL_MS,
330
+ NO_PROGRESS_MIN_ATTEMPTS,
331
+ noProgressKey,
332
+ clearNoProgress,
333
+ noteNoProgress,
334
+ failStageNoProgress,
263
335
  FORCE_STAGES_KEY_PREFIX,
264
336
  forceStagesKey,
265
337
  forceMember,
@@ -129,6 +129,113 @@ async function getCounterWithDriftCheck(redis, stage) {
129
129
  };
130
130
  }
131
131
 
132
+ // ======================================================
133
+ // PHANTOM DISPATCH SWEEP (reconcile-quota-leak, 2026-11-05)
134
+ // ======================================================
135
+ // The former check compared the counter with the NUMBER OF LEASES. On BA the
136
+ // counter leaked together with its leases: 8 dispatches that ended without
137
+ // jobs kept lease + metadata (status=dispatched, quota_owned=true), so
138
+ // counter 8 == leases 8 → "0 drift" while nothing ran on the GPU.
139
+ //
140
+ // A dispatch is LIVE when its lease is held by the metadata token AND one of:
141
+ // • the dispatch really enqueued jobs (meta.jobs_enqueued, set by
142
+ // dispatch-engine after dispatched:true) — result handling is in flight;
143
+ // • the hub holds a job of this dispatch (animastor:running or any
144
+ // animastor:queue:* lane) — legacy metadata without the flag;
145
+ // • it is younger than PHANTOM_GRACE_MS (the executor is still running).
146
+ // Otherwise it is a PHANTOM candidate. A candidate seen on two consecutive
147
+ // sweeps (marker with TTL) is cancelled through the canonical path
148
+ // (dispatch-engine.cancelActiveDispatch: meta + lease + OWNED quota in one
149
+ // claim). A lease without metadata keeps the historic semantics (counted,
150
+ // ownership unknown). The counter is then corrected to the live leases.
151
+
152
+ const META_PREFIX = 'animastor:dispatch-meta';
153
+ const PHANTOM_GRACE_MS = 2 * 60 * 1000;
154
+ const PHANTOM_SUSPECT_PREFIX = 'animastor:dispatch-phantom-suspect:';
155
+ const PHANTOM_SUSPECT_TTL_S = 15 * 60;
156
+
157
+ async function scanKeys(redis, pattern, limit = 10000) {
158
+ const keys = [];
159
+ let cursor = 0;
160
+ do {
161
+ const result = await redis.scan(cursor, 'MATCH', pattern, 'COUNT', 500);
162
+ cursor = parseInt(result[0], 10);
163
+ keys.push(...result[1]);
164
+ } while (cursor !== 0 && keys.length < limit);
165
+ return keys;
166
+ }
167
+
168
+ function collectDispatchId(set, raw) {
169
+ if (!raw || typeof raw !== 'string') return;
170
+ try {
171
+ const v = JSON.parse(raw);
172
+ if (v && typeof v.dispatch_id === 'string') set.add(v.dispatch_id);
173
+ } catch (_) {
174
+ const m = raw.match(/"dispatch_id"\s*:\s*"([^"]+)"/);
175
+ if (m) set.add(m[1]);
176
+ }
177
+ }
178
+
179
+ /** dispatch_ids that have a job in the hub (running or queued, any lane). */
180
+ async function collectHubDispatchIds(redis) {
181
+ const ids = new Set();
182
+ try {
183
+ const running = await redis.hgetall('animastor:running');
184
+ for (const v of Object.values(running || {})) collectDispatchId(ids, v);
185
+ } catch (_) { /* hash may not exist */ }
186
+ for (const qk of await scanKeys(redis, 'animastor:queue:*')) {
187
+ try {
188
+ const items = await redis.lrange(qk, 0, -1);
189
+ for (const v of items || []) collectDispatchId(ids, v);
190
+ } catch (_) { /* not a list (lane bookkeeping key) */ }
191
+ }
192
+ return ids;
193
+ }
194
+
195
+ /**
196
+ * Find and cancel phantom dispatches of `stage`.
197
+ * @returns {Promise<{scanned:number, suspects:number, cancelled:string[]}>}
198
+ */
199
+ async function sweepPhantomDispatches(redis, stage, now = Date.now()) {
200
+ const out = { scanned: 0, suspects: 0, cancelled: [] };
201
+ const leaseKeys = await scanKeys(redis, getLeaseKeyPattern(stage));
202
+ if (leaseKeys.length === 0) return out;
203
+ let hubIds = null;
204
+ for (const leaseKey of leaseKeys) {
205
+ const parts = leaseKey.split(':');
206
+ // animastor:dispatch-lease:<book>:<chapter>:<scene>:<stage>
207
+ if (parts.length !== 6 || parts[5] !== stage) continue;
208
+ const [, , bookId, chapterId, sceneId] = parts;
209
+ out.scanned++;
210
+ const metaRaw = await redis.get(`${META_PREFIX}:${bookId}:${chapterId}:${sceneId}:${stage}`);
211
+ if (!metaRaw) continue;
212
+ let meta;
213
+ try { meta = JSON.parse(metaRaw); } catch (_) { continue; }
214
+ const leaseToken = await redis.get(leaseKey);
215
+ if (!meta || !meta.dispatch_id || !leaseToken || meta.lease_token !== leaseToken) continue;
216
+ if (meta.jobs_enqueued === true) continue;
217
+ if (typeof meta.started_at === 'number' && now - meta.started_at < PHANTOM_GRACE_MS) continue;
218
+ if (hubIds === null) hubIds = await collectHubDispatchIds(redis);
219
+ if (hubIds.has(meta.dispatch_id)) continue;
220
+
221
+ out.suspects++;
222
+ const suspectKey = `${PHANTOM_SUSPECT_PREFIX}${meta.dispatch_id}`;
223
+ const seen = await redis.get(suspectKey);
224
+ if (!seen) {
225
+ await redis.set(suspectKey, String(now), 'EX', PHANTOM_SUSPECT_TTL_S);
226
+ continue;
227
+ }
228
+ const dispatchEngine = require('./dispatch-engine');
229
+ const res = await dispatchEngine.cancelActiveDispatch(redis, bookId, chapterId, sceneId, stage, 'phantom_dispatch');
230
+ await redis.del(suspectKey);
231
+ if (res && res.cancelled) {
232
+ out.cancelled.push(`${bookId}/${chapterId}/${sceneId}`);
233
+ warn(`PHANTOM_DISPATCH_CANCELLED: ${bookId}/${chapterId}/${sceneId}:${stage} dispatch=${String(meta.dispatch_id).slice(0, 24)}... (no jobs, no hub job, quota_owned=${meta.quota_owned === true}, quotaReleased=${res.quotaReleased === true})`);
234
+ }
235
+ }
236
+ return out;
237
+ }
238
+
132
239
  /**
133
240
  * Reconcile all counters.
134
241
  * Returns reconciliation report.
@@ -147,6 +254,14 @@ async function reconcileCounters(redis) {
147
254
 
148
255
  for (const stage of stages) {
149
256
  try {
257
+ try {
258
+ const sweep = await sweepPhantomDispatches(redis, stage);
259
+ if (sweep.cancelled.length > 0) {
260
+ report.summary.phantomsCancelled = (report.summary.phantomsCancelled || 0) + sweep.cancelled.length;
261
+ }
262
+ } catch (sweepErr) {
263
+ warn(`PHANTOM_SWEEP failed for ${stage}: ${sweepErr.message}`);
264
+ }
150
265
  const data = await getCounterWithDriftCheck(redis, stage);
151
266
 
152
267
  if (!data.correct) {
@@ -195,7 +310,7 @@ async function reconcileCounters(redis) {
195
310
  }
196
311
  }
197
312
 
198
- log(`COUNTER_RECONCILIATION_COMPLETE: ${report.summary.correctedCount} corrected, ${report.summary.totalDrift} total drift`);
313
+ log(`COUNTER_RECONCILIATION_COMPLETE: ${report.summary.correctedCount} corrected, ${report.summary.totalDrift} total drift${report.summary.phantomsCancelled ? `, ${report.summary.phantomsCancelled} phantom dispatch(es) cancelled` : ''}`);
199
314
 
200
315
  return report;
201
316
  }
@@ -283,6 +398,9 @@ async function incrementCounter(redis, stage) {
283
398
  // ======================================================
284
399
 
285
400
  module.exports = {
401
+ PHANTOM_GRACE_MS,
402
+ sweepPhantomDispatches,
403
+ collectHubDispatchIds,
286
404
  // Configuration
287
405
  COUNTER_PREFIX,
288
406
  LEASE_PREFIX,
@@ -307,6 +307,36 @@ async function verifyDispatchIdentity(redis, bookId, chapterId, sceneId, stage,
307
307
  return { valid: true, reason: 'current_dispatch', metadata };
308
308
  }
309
309
 
310
+ // reconcile-quota-leak: compare-and-set of the jobs flag. A plain get+set
311
+ // could resurrect the metadata of a dispatch that a fast completion already
312
+ // finalized (and the resurrected meta would hold its quota slot forever).
313
+ const MARK_JOBS_ENQUEUED_SCRIPT = `
314
+ local raw = redis.call('GET', KEYS[1])
315
+ if not raw or raw ~= ARGV[1] then
316
+ return 0
317
+ end
318
+ redis.call('SET', KEYS[1], ARGV[2], 'KEEPTTL')
319
+ return 1
320
+ `;
321
+
322
+ /**
323
+ * Flag the live dispatch metadata as "jobs really enqueued" (only while the
324
+ * metadata still belongs to `dispatchId` and was not changed meanwhile).
325
+ * @returns {Promise<boolean>} true when the flag was written.
326
+ */
327
+ async function markDispatchJobsEnqueued(redis, bookId, chapterId, sceneId, stage, dispatchId, jobs) {
328
+ const key = getDispatchMetaKey(bookId, chapterId, sceneId, stage);
329
+ const raw = await redis.get(key);
330
+ if (!raw) return false;
331
+ let meta;
332
+ try { meta = JSON.parse(raw); } catch (_) { return false; }
333
+ if (!meta || meta.dispatch_id !== dispatchId) return false;
334
+ meta.jobs_enqueued = true;
335
+ meta.jobs = Number(jobs) || null;
336
+ const res = await redis.eval(MARK_JOBS_ENQUEUED_SCRIPT, 1, key, raw, JSON.stringify(meta));
337
+ return Number(res) === 1;
338
+ }
339
+
310
340
  /**
311
341
  * Delete dispatch metadata (on completion/failure).
312
342
  */
@@ -1129,6 +1159,22 @@ async function dispatchStage(redis, bookId, chapterId, sceneId, stage, loadedBoo
1129
1159
  // The stage completed (cache hit / already done) — it is no
1130
1160
  // longer waiting for capacity.
1131
1161
  await clearStageDeferral(redis, bookId, chapterId, sceneId, stage);
1162
+ // reconcile-quota-leak (2026-11-05, BA): a completed outcome
1163
+ // WITHOUT jobs (already_done / recovered_via_completeChunk /
1164
+ // cache_hit / scene_not_found) used to return here with the
1165
+ // lease, the dispatch metadata and the owned quota slot still
1166
+ // held — nothing would ever finalize them (no job → no hub
1167
+ // result → no completion callback). 8 such dispatches held
1168
+ // animastor:runtime:active-audio at 8/8 with zero jobs.
1169
+ // Finalize atomically (one Lua claim: meta + lease + owned
1170
+ // quota). Idempotent: if the executor already completed the
1171
+ // stage through completeStage (already_ready path) the claim
1172
+ // reports already_finalized / no_active_dispatch.
1173
+ await finalizeDispatch(redis, bookId, chapterId, sceneId, stage, {
1174
+ outcome: 'success',
1175
+ dispatchId,
1176
+ reason: `completed_without_jobs:${result.reason || 'already_done'}`
1177
+ });
1132
1178
  }
1133
1179
  // Cancelled finalize does not touch the circuit breaker — release
1134
1180
  // the test permit here so a half-open circuit can keep recovering.
@@ -1137,6 +1183,10 @@ async function dispatchStage(redis, bookId, chapterId, sceneId, stage, loadedBoo
1137
1183
  dispatched: false,
1138
1184
  dispatchId,
1139
1185
  reason: result.reason || 'already_done',
1186
+ // reconcile-quota-leak: the scheduler counts a completed
1187
+ // stage (anyCompleted) by THIS flag; it was never surfaced,
1188
+ // so every already_done tick was reported as an error.
1189
+ completed: result.completed === true,
1140
1190
  retryable: isDeferrableOutcome(result.reason),
1141
1191
  // Stage 118 (M9): the caller (scheduler) must be able to
1142
1192
  // tell "nothing happened, try later" from a real error.
@@ -1153,6 +1203,16 @@ async function dispatchStage(redis, bookId, chapterId, sceneId, stage, loadedBoo
1153
1203
  // (not for cache hits, backpressure, or empty executor results)
1154
1204
  startDispatchRenewal(redis, bookId, chapterId, sceneId, stage, lease.leaseKey, lease.token);
1155
1205
 
1206
+ // reconcile-quota-leak: record that THIS dispatch really enqueued
1207
+ // jobs — counter reconciliation treats a dispatch without the flag
1208
+ // and without a hub job as a phantom (see counter-reconciliation).
1209
+ // Best-effort: only touch the meta while it is still ours.
1210
+ try {
1211
+ await markDispatchJobsEnqueued(redis, bookId, chapterId, sceneId, stage, dispatchId, result.jobs);
1212
+ } catch (metaErr) {
1213
+ warn(`DISPATCH_META_JOBS_FLAG_FAILED: ${bookId}/${chapterId}/${sceneId}:${stage}: ${metaErr.message}`);
1214
+ }
1215
+
1156
1216
  // Set 3s debounce — task actually sent to GPU hub
1157
1217
  await redis.set(`animastor:runtime:last-active:${stage}`, '1', 'EX', 3);
1158
1218
 
@@ -2029,6 +2089,7 @@ module.exports = {
2029
2089
  createDispatchMetadata,
2030
2090
  setDispatchMetadata,
2031
2091
  getDispatchMetadata,
2092
+ markDispatchJobsEnqueued,
2032
2093
  verifyDispatchIdentity,
2033
2094
  deleteDispatchMetadata,
2034
2095
 
@@ -39,6 +39,9 @@
39
39
  // pre-pass; the getAssetStates callback arrives
40
40
  // as an argument exactly as pre-O-5)
41
41
  //
42
+ // failSceneStage — reconcile-quota-leak (2026-11-05): a commanded
43
+ // scene×stage made no progress → its task is
44
+ // failed with the reason (registry + PG host-side)
42
45
  // blockSceneStage — command-only generation (2026-10-31): no live
43
46
  // worker of a stage's type → block the command
44
47
  // that asked for it (registry + PG are host-side;
@@ -59,6 +62,7 @@ const OPS = [
59
62
  'hasActiveTasks',
60
63
  'reconcileCompletedTasks',
61
64
  'blockSceneStage',
65
+ 'failSceneStage',
62
66
  ];
63
67
 
64
68
  let impl = null;
@@ -115,6 +115,31 @@ class ReconciliationReport {
115
115
  // ORPHAN STATE CHECKS
116
116
  // ======================================================
117
117
 
118
+ /**
119
+ * reconcile-quota-leak: «stage committed by the current generation» — the
120
+ * single readiness predicate the recovery may trust: PG scene_assets row of
121
+ * the book build is `ready` (the version gate already passed when it was
122
+ * written) AND the fenced-commit probe confirms the artifact (invariant B,
123
+ * media.audio.isSceneAudioCommitted — the same predicate the dispatch uses).
124
+ * Audio only: image/video keep the historic behavior. Any probe error → false
125
+ * (fail closed: demoting is recoverable, a false READY is not).
126
+ */
127
+ async function isStageCommittedReady(bookId, chapterId, sceneId, stage) {
128
+ if (stage !== 'audio') return false;
129
+ try {
130
+ const buildId = resolveBookBuildId(bookId);
131
+ const asset = await persist('sceneAssets.getAsset')(bookId, chapterId, sceneId, stage, buildId);
132
+ if (!asset || asset.status !== 'ready') return false;
133
+ const audio = lazyHostBinding('media.audio');
134
+ if (typeof audio.isSceneAudioCommitted !== 'function') return false;
135
+ const probe = await audio.isSceneAudioCommitted(buildId, bookId, chapterId, sceneId, null);
136
+ return !!(probe && probe.ready === true);
137
+ } catch (err) {
138
+ warn(`isStageCommittedReady probe failed for ${bookId}/${chapterId}/${sceneId}:${stage}: ${err.message}`);
139
+ return false;
140
+ }
141
+ }
142
+
118
143
  /**
119
144
  * Canonical build identity of a book (audit d9d67a3): the SAME source the
120
145
  * rest of the runtime uses (rebuildWorkList, generate-next, dispatch) —
@@ -1445,9 +1470,25 @@ async function applyFix(redis, fix) {
1445
1470
  // S-5: asset-state writer via the injected orchestration seam
1446
1471
  const markDirtyScene = orchestrationSeams.getOrchestrationSeam('markDirtyScene');
1447
1472
  const currentStates = await state.getAssetStates(redis, scene.bookId, scene.chapterId, scene.sceneId);
1448
- const redo = [...auth.stages].filter(stage =>
1473
+ const inFlight = [...auth.stages].filter(stage =>
1449
1474
  currentStates[stage] === state.AssetState.GENERATING ||
1450
1475
  currentStates[stage] === state.AssetState.PENDING);
1476
+ // reconcile-quota-leak (2026-11-05, BA): the lease of a dispatch
1477
+ // that ended WITHOUT finalization (already_done & co) looked
1478
+ // "stale in flight"; marking that stage DIRTY bumped the epoch
1479
+ // and wrote PG stale over audio committed by the CURRENT
1480
+ // generation (8 → 13 scenes demoted on BA). A stage whose
1481
+ // commit is confirmed is only re-asserted READY here — the
1482
+ // lease/quota release above stays.
1483
+ const redo = [];
1484
+ for (const stage of inFlight) {
1485
+ if (await isStageCommittedReady(scene.bookId, scene.chapterId, scene.sceneId, stage)) {
1486
+ await state.unsafeRestoreAssetState(redis, scene.bookId, scene.chapterId, scene.sceneId, stage, state.AssetState.READY);
1487
+ log(`STALE_LEASE_COMMITTED_KEEP: ${scene.bookId}/${scene.chapterId}/${scene.sceneId} ${stage} — committed + PG ready, not demoted`);
1488
+ continue;
1489
+ }
1490
+ redo.push(stage);
1491
+ }
1451
1492
  if (redo.length > 0) {
1452
1493
  await markDirtyScene(redis, scene.bookId, scene.chapterId, scene.sceneId, redo);
1453
1494
  }
@@ -2577,6 +2618,7 @@ const state = lazyHostBinding('state');
2577
2618
  // ======================================================
2578
2619
 
2579
2620
  module.exports = {
2621
+ isStageCommittedReady,
2580
2622
  reconcileScene,
2581
2623
  reconcileBook,
2582
2624
  reconcileAll,
@@ -607,12 +607,22 @@ async function attemptDispatch(redis, bookId, chapterId, sceneId, loadedBook, fo
607
607
  }
608
608
  if (result.dispatched) {
609
609
  dispatched++;
610
+ await commandGate.clearNoProgress(redis, bookId, chapterId, sceneId, stage);
610
611
  } else if (result.reason === 'backpressure' || result.reason === 'throttled') {
611
612
  throttled++;
613
+ // reconcile-quota-leak: a full quota with NO worker of this type
614
+ // alive anywhere can never drain by itself — the command would hang
615
+ // with a running timer. Block it like the hub-side no_worker path.
616
+ if (await noWorkerOfTypeAlive(redis, stage)) {
617
+ await commandGate.blockStageNoWorker(redis, bookId, chapterId, sceneId, stage);
618
+ failures.push(`${stage}:blocked_no_worker`);
619
+ continue;
620
+ }
612
621
  } else if (result.completed) {
613
622
  // Stage finished inside the executor (already_done / cache_hit /
614
623
  // no_segments) — not a failure, nothing to dispatch.
615
624
  anyCompleted = true;
625
+ await commandGate.clearNoProgress(redis, bookId, chapterId, sceneId, stage);
616
626
  } else if (result.deferred) {
617
627
  // Stage 118 (M9): a bounded deferral is NOT an error — nothing
618
628
  // happened, the stage is waiting for capacity (or is already
@@ -626,6 +636,25 @@ async function attemptDispatch(redis, bookId, chapterId, sceneId, loadedBook, fo
626
636
  // observability. Теперь причина всплывает в tick-сводку.
627
637
  failures.push(`${stage}:${result.reason || 'unknown'}`);
628
638
  }
639
+ // reconcile-quota-leak: «задача не висит молча» — an outcome that
640
+ // neither dispatched, completed nor waits for capacity is counted;
641
+ // a long run of them fails the command with the reason.
642
+ // A capacity outcome (duplicate_pending / ambiguous_post …) means the
643
+ // job IS waiting in the hub lane — that is progress-in-waiting, not a
644
+ // stall; no_worker_available is blocked above.
645
+ if (!result.dispatched && !result.completed
646
+ && result.reason !== 'backpressure' && result.reason !== 'throttled'
647
+ && result.reason !== 'no_worker_available'
648
+ && !require('./dispatch-outcomes').isCapacityOutcome(result.reason)) {
649
+ try {
650
+ const np = await commandGate.noteNoProgress(redis, bookId, chapterId, sceneId, stage, result.reason);
651
+ if (np.exceeded) {
652
+ await commandGate.failStageNoProgress(redis, bookId, chapterId, sceneId, stage, result.reason, np.attempts);
653
+ }
654
+ } catch (npErr) {
655
+ warn(`NO_PROGRESS bookkeeping failed for ${sceneKey}:${stage}: ${npErr.message}`);
656
+ }
657
+ }
629
658
  }
630
659
 
631
660
  if (dispatched > 0) {
@@ -643,6 +672,21 @@ async function attemptDispatch(redis, bookId, chapterId, sceneId, loadedBook, fo
643
672
  return { dispatched: 0, throttled, stages: stages.length, success: true, reason: 'no_dispatch' };
644
673
  }
645
674
 
675
+ /**
676
+ * reconcile-quota-leak: true when no fresh heartbeat of `stage`'s worker type
677
+ * exists in any scope. Fails OPEN (false) when the probe is unavailable — a
678
+ * probe error must never block a command.
679
+ */
680
+ async function noWorkerOfTypeAlive(redis, stage) {
681
+ try {
682
+ const workerHealth = require('./worker-health');
683
+ if (typeof workerHealth.getAnyAliveCount !== 'function') return false;
684
+ return (await workerHealth.getAnyAliveCount(redis, stage)) === 0;
685
+ } catch (_) {
686
+ return false;
687
+ }
688
+ }
689
+
646
690
  // ======================================================
647
691
  // EXPORTS
648
692
  // ======================================================
@@ -258,8 +258,19 @@ async function isAvailable(redis, type, workspaceId = null) {
258
258
  return countWhere(entries, (e) => isPrivateScopeOf(e, workspaceId)) > 0;
259
259
  }
260
260
 
261
+ /**
262
+ * reconcile-quota-leak: number of fresh heartbeats of `type` in ANY scope
263
+ * (system, share, private of any workspace). 0 means no worker of this type
264
+ * exists at all — nothing anywhere can run the job, whatever the lane.
265
+ */
266
+ async function getAnyAliveCount(redis, type) {
267
+ const entries = await scanFreshHeartbeats(redis, type);
268
+ return entries.filter(e => e && e.worker_id).length;
269
+ }
270
+
261
271
  module.exports = {
262
272
  reportHeartbeat,
273
+ getAnyAliveCount,
263
274
  getAliveCount,
264
275
  getPrivateAliveCount,
265
276
  getBusyCount,
@@ -104,6 +104,16 @@ function createMockRedis() {
104
104
  return ['0', entries];
105
105
  },
106
106
  eval: async (script, keysCount, ...args) => {
107
+ // reconcile-quota-leak: dispatch-engine.markDispatchJobsEnqueued
108
+ // compare-and-set (KEYS=[metaKey], ARGV=[expectedRaw, newRaw]).
109
+ if (script.includes('KEEPTTL') && script.includes('raw ~= ARGV[1]')) {
110
+ const key = args[0];
111
+ const [expected, next] = args.slice(keysCount);
112
+ const raw = store.get(key);
113
+ if (raw === undefined || raw !== expected) return 0;
114
+ store.set(key, next);
115
+ return 1;
116
+ }
107
117
  if (script.includes('local metadata') && script.includes("ARGV[5] == '1'")) {
108
118
  const [metadataKey, completedKey, leaseKey, quotaKey] = args.slice(0, keysCount);
109
119
  const [
@@ -0,0 +1,366 @@
1
+ // ======================================================
2
+ // reconcile-quota-leak (2026-11-05, BA ba_1788172242081) — regression net
3
+ // ======================================================
4
+ // Incident: «Генерировать аудио → Вся книга» stalled after 4 scenes.
5
+ // 1. dispatch outcomes WITHOUT jobs that the executor reported as
6
+ // `completed` (already_done / recovered_via_completeChunk) kept lease +
7
+ // dispatch-meta + the owned quota slot → active-audio 8/8, zero jobs;
8
+ // 2. the periodic stale-lease recovery then demoted stages committed by the
9
+ // current generation (DIRTY, epoch bump, PG stale);
10
+ // 3. the DRIFT check compared the counter with the NUMBER of leases — the
11
+ // leaked leases matched the leaked counter, "0 drift";
12
+ // 4. the stale scene with a real commit could neither be restored nor
13
+ // regenerated, the command hung silently.
14
+ //
15
+ // Isolated: in-memory Redis mock + stubbed host bindings and ports.
16
+
17
+ const { expect } = require('chai');
18
+ const { createMockRedis } = require('./mocks/redis-mock');
19
+ const { bindHostModules, clearHostBindings } = require('../src/host/host-bindings');
20
+ const persistencePort = require('../src/runtime/persistence-port');
21
+ const progressEventsPort = require('../src/runtime/progress-events-port');
22
+
23
+ const BOOK = 'ba_test_quota_leak';
24
+ const CH = 'ch-q1';
25
+ const BUILD = `build_${BOOK}`;
26
+ const COUNTER = 'animastor:runtime:active-audio';
27
+
28
+ const metaKey = (sc, stage = 'audio') => `animastor:dispatch-meta:${BOOK}:${CH}:${sc}:${stage}`;
29
+ const leaseKey = (sc, stage = 'audio') => `animastor:dispatch-lease:${BOOK}:${CH}:${sc}:${stage}`;
30
+
31
+ function makePersistence(overrides = {}) {
32
+ const adapter = {};
33
+ for (const op of persistencePort.OPS) {
34
+ const noop = async () => null;
35
+ const [ns, fn] = op.includes('.') ? op.split('.') : [null, op];
36
+ if (ns === null) adapter[fn] = overrides[op] || noop;
37
+ else {
38
+ adapter[ns] = adapter[ns] || {};
39
+ adapter[ns][fn] = overrides[op] || noop;
40
+ }
41
+ }
42
+ return adapter;
43
+ }
44
+
45
+ const AssetState = {
46
+ NEW: 'new', DIRTY: 'dirty', PENDING: 'pending',
47
+ GENERATING: 'generating', READY: 'ready', FAILED: 'failed',
48
+ };
49
+
50
+ describe('reconcile-quota-leak (BA 2026-11-05)', function () {
51
+ this.timeout(10000);
52
+
53
+ let redis;
54
+ let executorResult;
55
+ let executorCalls;
56
+ let assetStates;
57
+ let stateWrites;
58
+ let markDirtyCalls;
59
+ let pgAssets;
60
+ let committed;
61
+ let failedStages;
62
+ let blockedStages;
63
+ let aliveWorkers;
64
+
65
+ function freshModules() {
66
+ for (const rel of [
67
+ '../src/runtime/dispatch-engine',
68
+ '../src/runtime/counter-reconciliation',
69
+ '../src/runtime/reconciliation-engine',
70
+ '../src/runtime/runtime-scheduler',
71
+ '../src/runtime/command-gate',
72
+ '../src/runtime/worker-health',
73
+ ]) {
74
+ delete require.cache[require.resolve(rel)];
75
+ }
76
+ }
77
+
78
+ beforeEach(() => {
79
+ redis = createMockRedis();
80
+ executorCalls = 0;
81
+ executorResult = { dispatched: false, jobs: 0, completed: true, reason: 'already_done' };
82
+ assetStates = {};
83
+ stateWrites = [];
84
+ markDirtyCalls = [];
85
+ pgAssets = {};
86
+ committed = {};
87
+ failedStages = [];
88
+ blockedStages = [];
89
+ aliveWorkers = 1;
90
+
91
+ clearHostBindings();
92
+ bindHostModules({
93
+ config: () => ({
94
+ OUTPUT_DIR: '/data/output',
95
+ WORKER_HEARTBEAT_TYPES: ['audio', 'image', 'video'],
96
+ WORKER_HEARTBEAT_TTL: 30,
97
+ WORKER_HEARTBEAT_TYPE_PATTERN: (type) => `animastor:worker:heartbeat:${type}:*`,
98
+ }),
99
+ journal: () => ({ EventType: {}, appendSceneEvent: async () => true }),
100
+ state: () => ({
101
+ AssetState,
102
+ getAssetStates: async (r, b, c, s) => ({ ...(assetStates[s] || {}) }),
103
+ unsafeRestoreAssetState: async (r, b, c, s, asset, st) => {
104
+ stateWrites.push({ s, asset, st });
105
+ assetStates[s] = { ...(assetStates[s] || {}), [asset]: st };
106
+ },
107
+ validateAssetTransition: () => ({ valid: true }),
108
+ }),
109
+ seams: () => ({
110
+ getOrchestrationSeam: (name) => {
111
+ if (name === 'dispatchStage') {
112
+ return async () => { executorCalls++; return executorResult; };
113
+ }
114
+ if (name === 'rollbackStageToPending') return async () => ({ changed: true });
115
+ if (name === 'markDirtyScene') {
116
+ return async (r, b, c, s, assets) => { markDirtyCalls.push({ s, assets }); };
117
+ }
118
+ throw new Error(`seam not wired in test: ${name}`);
119
+ },
120
+ isOrchestrationSeamWired: () => true,
121
+ }),
122
+ media: () => ({
123
+ audio: {
124
+ isSceneAudioCommitted: async (buildId, b, c, s) => ({ ready: committed[s] === true }),
125
+ },
126
+ }),
127
+ });
128
+ persistencePort.setPersistencePort(makePersistence({
129
+ 'sceneAssets.getAsset': async (b, c, s, stage) => pgAssets[`${s}:${stage}`] || null,
130
+ }));
131
+ progressEventsPort.setProgressEventsPort({
132
+ publishProgress: async () => {},
133
+ getSceneTaskState: async () => ({ managed: true, activeTypes: new Set(['audio']) }),
134
+ hasActiveTasks: async () => true,
135
+ reconcileCompletedTasks: async () => [],
136
+ blockSceneStage: async (r, b, c, s, type, reason) => { blockedStages.push({ s, type, reason }); return { tasks: [{ task_id: 't1' }] }; },
137
+ failSceneStage: async (r, b, c, s, type, info) => { failedStages.push({ s, type, info }); return { tasks: [{ task_id: 't1' }] }; },
138
+ });
139
+ freshModules();
140
+ });
141
+
142
+ afterEach(() => {
143
+ clearHostBindings();
144
+ persistencePort._resetPersistencePort();
145
+ progressEventsPort._resetProgressEventsPort();
146
+ });
147
+
148
+ const dispatch = (sc, stage = 'audio') => require('../src/runtime/dispatch-engine')
149
+ .dispatchStage(redis, BOOK, CH, sc, stage, { book_id: BOOK }, BUILD);
150
+
151
+ // ── (а) ─────────────────────────────────────────────
152
+ describe('(а) a dispatch outcome without jobs releases slot + lease + meta', () => {
153
+ for (const reason of ['already_done', 'recovered_via_completeChunk', 'cache_hit', 'scene_not_found']) {
154
+ it(`completed outcome «${reason}» — active-audio unchanged, lease/meta removed, completed surfaced`, async () => {
155
+ executorResult = { dispatched: false, jobs: 0, completed: true, reason };
156
+ const res = await dispatch('sc-a');
157
+ expect(executorCalls).to.equal(1);
158
+ expect(res.dispatched).to.equal(false);
159
+ expect(await redis.get(COUNTER), 'quota slot leaked').to.equal('0');
160
+ expect(await redis.get(metaKey('sc-a')), 'dispatch-meta leaked').to.equal(null);
161
+ expect(await redis.get(leaseKey('sc-a')), 'dispatch-lease leaked').to.equal(null);
162
+ expect(res.completed).to.equal(true);
163
+ });
164
+ }
165
+
166
+ it('no_jobs_generated (not completed) — slot released too, not reported completed', async () => {
167
+ executorResult = { dispatched: false, jobs: 0, reason: 'no_jobs_generated', retryable: true };
168
+ const res = await dispatch('sc-b');
169
+ expect(res.completed).to.equal(false);
170
+ expect(await redis.get(COUNTER)).to.equal('0');
171
+ expect(await redis.get(metaKey('sc-b'))).to.equal(null);
172
+ expect(await redis.get(leaseKey('sc-b'))).to.equal(null);
173
+ });
174
+
175
+ it('a real dispatch keeps its slot and flags the meta jobs_enqueued', async () => {
176
+ executorResult = { dispatched: true, jobs: 7, reason: null };
177
+ const res = await dispatch('sc-c');
178
+ expect(res.dispatched).to.equal(true);
179
+ expect(await redis.get(COUNTER)).to.equal('1');
180
+ const meta = JSON.parse(await redis.get(metaKey('sc-c')));
181
+ expect(meta.jobs_enqueued).to.equal(true);
182
+ expect(meta.jobs).to.equal(7);
183
+ expect(meta.quota_owned).to.equal(true);
184
+ require('../src/runtime/dispatch-engine').stopDispatchRenewal?.(BOOK, CH, 'sc-c', 'audio');
185
+ });
186
+ });
187
+
188
+ // ── (б) ─────────────────────────────────────────────
189
+ describe('(б) N ticks in a row — the counter does not grow', () => {
190
+ it('17 scenes × 6 ticks of already_done / recovered / no_jobs ⇒ active-audio stays 0, never backpressure', async () => {
191
+ const outcomes = [
192
+ { dispatched: false, jobs: 0, completed: true, reason: 'already_done' },
193
+ { dispatched: false, jobs: 0, completed: true, reason: 'recovered_via_completeChunk' },
194
+ { dispatched: false, jobs: 0, reason: 'no_jobs_generated', retryable: true },
195
+ ];
196
+ const engine = require('../src/runtime/dispatch-engine');
197
+ let backpressure = 0;
198
+ for (let tick = 0; tick < 6; tick++) {
199
+ for (let i = 0; i < 17; i++) {
200
+ executorResult = outcomes[(tick + i) % outcomes.length];
201
+ // a deferral would hide the executor — clear it to force an attempt
202
+ await redis.del(engine.deferredStageKey(BOOK, CH, `sc-${i}`, 'audio'));
203
+ const res = await dispatch(`sc-${i}`);
204
+ if (res.reason === 'backpressure') backpressure++;
205
+ }
206
+ expect(await redis.get(COUNTER)).to.equal('0');
207
+ }
208
+ expect(backpressure).to.equal(0);
209
+ expect(executorCalls).to.equal(17 * 6);
210
+ });
211
+ });
212
+
213
+ // ── (в) ─────────────────────────────────────────────
214
+ describe('(в) stale-lease recovery never demotes a stage committed by the current generation', () => {
215
+ async function staleLeaseFor(sc) {
216
+ await redis.set(leaseKey(sc), 'tok-1');
217
+ await redis.set(metaKey(sc), JSON.stringify({
218
+ dispatch_id: `dispatch-${sc}`, stage: 'audio', started_at: Date.now() - 40 * 60 * 1000,
219
+ status: 'dispatched', lease_key: leaseKey(sc), lease_token: 'tok-1', quota_owned: true,
220
+ }));
221
+ await redis.set(COUNTER, '1');
222
+ }
223
+
224
+ it('committed + PG ready ⇒ lease/quota released, asset re-asserted READY, NO markDirtyScene', async () => {
225
+ await staleLeaseFor('sc-r');
226
+ assetStates['sc-r'] = { audio: AssetState.PENDING };
227
+ pgAssets['sc-r:audio'] = { status: 'ready' };
228
+ committed['sc-r'] = true;
229
+ const rec = require('../src/runtime/reconciliation-engine');
230
+ const out = await rec.applyFix(redis, { action: 'RELEASE_STALE_LEASE', scene: { bookId: BOOK, chapterId: CH, sceneId: 'sc-r' } });
231
+ expect(out.success).to.equal(true);
232
+ expect(markDirtyCalls).to.deep.equal([]);
233
+ expect(stateWrites).to.deep.include({ s: 'sc-r', asset: 'audio', st: AssetState.READY });
234
+ expect(await redis.get(COUNTER)).to.equal('0');
235
+ expect(await redis.get(leaseKey('sc-r'))).to.equal(null);
236
+ });
237
+
238
+ it('NOT committed ⇒ the historic recovery (markDirtyScene for the in-flight stage)', async () => {
239
+ await staleLeaseFor('sc-n');
240
+ assetStates['sc-n'] = { audio: AssetState.GENERATING };
241
+ pgAssets['sc-n:audio'] = { status: 'ready' };
242
+ committed['sc-n'] = false;
243
+ const rec = require('../src/runtime/reconciliation-engine');
244
+ await rec.applyFix(redis, { action: 'RELEASE_STALE_LEASE', scene: { bookId: BOOK, chapterId: CH, sceneId: 'sc-n' } });
245
+ expect(markDirtyCalls).to.deep.equal([{ s: 'sc-n', assets: ['audio'] }]);
246
+ });
247
+
248
+ it('committed but PG stale ⇒ not trusted here (left to the dispatch path + version gate)', async () => {
249
+ const rec = require('../src/runtime/reconciliation-engine');
250
+ pgAssets['sc-s:audio'] = { status: 'stale' };
251
+ committed['sc-s'] = true;
252
+ expect(await rec.isStageCommittedReady(BOOK, CH, 'sc-s', 'audio')).to.equal(false);
253
+ pgAssets['sc-s:audio'] = { status: 'ready' };
254
+ expect(await rec.isStageCommittedReady(BOOK, CH, 'sc-s', 'audio')).to.equal(true);
255
+ expect(await rec.isStageCommittedReady(BOOK, CH, 'sc-s', 'image')).to.equal(false);
256
+ });
257
+ });
258
+
259
+ // ── (г) ─────────────────────────────────────────────
260
+ describe('(г) DRIFT reconciliation repairs the phantom counter', () => {
261
+ async function phantom(sc, extra = {}) {
262
+ await redis.set(leaseKey(sc), `tok-${sc}`);
263
+ await redis.set(metaKey(sc), JSON.stringify({
264
+ dispatch_id: `dispatch-${sc}`, stage: 'audio', started_at: Date.now() - 10 * 60 * 1000,
265
+ worker: 'scheduler', retry_attempt: 0, status: 'dispatched',
266
+ lease_key: leaseKey(sc), lease_token: `tok-${sc}`, quota_owned: true, ...extra,
267
+ }));
268
+ }
269
+
270
+ it('BA snapshot: 8 phantom dispatches, counter 8/8 ⇒ cancelled on the 2nd sweep, counter 0', async () => {
271
+ for (let i = 0; i < 8; i++) await phantom(`sc-p${i}`);
272
+ await redis.set(COUNTER, '8');
273
+ const cr = require('../src/runtime/counter-reconciliation');
274
+
275
+ const first = await cr.reconcileCounters(redis);
276
+ // first sweep only marks suspects (no cancel on a single observation)
277
+ expect(await redis.get(COUNTER)).to.equal('8');
278
+ expect(first.summary.phantomsCancelled || 0).to.equal(0);
279
+
280
+ const second = await cr.reconcileCounters(redis);
281
+ expect(second.summary.phantomsCancelled).to.equal(8);
282
+ expect(await redis.get(COUNTER)).to.equal('0');
283
+ for (let i = 0; i < 8; i++) {
284
+ expect(await redis.get(metaKey(`sc-p${i}`))).to.equal(null);
285
+ expect(await redis.get(leaseKey(`sc-p${i}`))).to.equal(null);
286
+ }
287
+ });
288
+
289
+ it('live dispatches are kept: jobs_enqueued, a hub job (running / queue), or younger than the grace', async () => {
290
+ await phantom('sc-live-flag', { jobs_enqueued: true });
291
+ await phantom('sc-live-running');
292
+ await phantom('sc-live-queue');
293
+ await phantom('sc-young', { started_at: Date.now() });
294
+ await phantom('sc-dead');
295
+ await redis.hset('animastor:running', 'job-1', JSON.stringify({ dispatch_id: 'dispatch-sc-live-running', job_type: 'audio' }));
296
+ await redis.rpush('animastor:queue:audio', JSON.stringify({ job_id: 'job-2', dispatch_id: 'dispatch-sc-live-queue' }));
297
+ await redis.set(COUNTER, '5');
298
+ const cr = require('../src/runtime/counter-reconciliation');
299
+ await cr.reconcileCounters(redis);
300
+ await cr.reconcileCounters(redis);
301
+ expect(await redis.get(metaKey('sc-dead'))).to.equal(null);
302
+ for (const sc of ['sc-live-flag', 'sc-live-running', 'sc-live-queue', 'sc-young']) {
303
+ expect(await redis.get(metaKey(sc)), sc).to.not.equal(null);
304
+ }
305
+ expect(await redis.get(COUNTER)).to.equal('4');
306
+ });
307
+
308
+ it('a lease without metadata keeps the historic semantics (counted, never cancelled)', async () => {
309
+ await redis.set(leaseKey('sc-bare'), 'tok');
310
+ await redis.set(COUNTER, '3');
311
+ const cr = require('../src/runtime/counter-reconciliation');
312
+ await cr.reconcileCounters(redis);
313
+ await cr.reconcileCounters(redis);
314
+ expect(await redis.get(leaseKey('sc-bare'))).to.equal('tok');
315
+ expect(await redis.get(COUNTER)).to.equal('1');
316
+ });
317
+ });
318
+
319
+ // ── (е, scheduler part) ─────────────────────────────
320
+ describe('(е) a command without movement does not hang silently', () => {
321
+ it('backpressure with NO worker of the type alive anywhere ⇒ blocked no_worker', async () => {
322
+ await redis.set(COUNTER, '8'); // full quota
323
+ const gate = require('../src/runtime/command-gate');
324
+ // simulate the scheduler branch: no heartbeat keys exist in the mock
325
+ const wh = require('../src/runtime/worker-health');
326
+ expect(await wh.getAnyAliveCount(redis, 'audio')).to.equal(0);
327
+ await gate.blockStageNoWorker(redis, BOOK, CH, 'sc-x', 'audio');
328
+ expect(blockedStages).to.deep.equal([{ s: 'sc-x', type: 'audio', reason: 'no_worker:audio' }]);
329
+ });
330
+
331
+ it('a fresh heartbeat of the type (any scope) counts as alive — no block', async () => {
332
+ const wh = require('../src/runtime/worker-health');
333
+ await redis.set('animastor:worker:heartbeat:audio:w1', JSON.stringify({ worker_id: 'w1', ts: Date.now(), mode: 'private', workspace_id: 'ws-1' }));
334
+ expect(await wh.getAnyAliveCount(redis, 'audio')).to.equal(1);
335
+ await redis.set('animastor:worker:heartbeat:audio:w2', JSON.stringify({ worker_id: 'w2', ts: Date.now() - 120000 }));
336
+ expect(await wh.getAnyAliveCount(redis, 'audio')).to.equal(1);
337
+ });
338
+
339
+ it('no-progress outcomes fail the command only after the time window AND ≥3 attempts', async () => {
340
+ const gate = require('../src/runtime/command-gate');
341
+ const t0 = 1_000_000;
342
+ let np = await gate.noteNoProgress(redis, BOOK, CH, 'sc-np', 'audio', 'no_jobs_generated', t0);
343
+ expect(np.exceeded).to.equal(false);
344
+ np = await gate.noteNoProgress(redis, BOOK, CH, 'sc-np', 'audio', 'locked', t0 + 5_000);
345
+ np = await gate.noteNoProgress(redis, BOOK, CH, 'sc-np', 'audio', 'no_jobs_generated', t0 + 10_000);
346
+ expect(np.attempts).to.equal(3);
347
+ expect(np.exceeded).to.equal(false); // 3 attempts, but only 10 s
348
+ np = await gate.noteNoProgress(redis, BOOK, CH, 'sc-np', 'audio', 'no_jobs_generated', t0 + gate.NO_PROGRESS_FAIL_MS);
349
+ expect(np.exceeded).to.equal(true);
350
+ const res = await gate.failStageNoProgress(redis, BOOK, CH, 'sc-np', 'audio', 'no_jobs_generated', np.attempts);
351
+ expect(res.error_class).to.equal('no_progress');
352
+ expect(failedStages).to.have.length(1);
353
+ expect(failedStages[0].info.error_code).to.equal('no_jobs_generated');
354
+ expect(await redis.get(gate.noProgressKey(BOOK, CH, 'sc-np', 'audio'))).to.equal(null);
355
+ });
356
+
357
+ it('progress resets the window', async () => {
358
+ const gate = require('../src/runtime/command-gate');
359
+ await gate.noteNoProgress(redis, BOOK, CH, 'sc-rs', 'audio', 'no_jobs_generated', 1);
360
+ await gate.clearNoProgress(redis, BOOK, CH, 'sc-rs', 'audio');
361
+ const np = await gate.noteNoProgress(redis, BOOK, CH, 'sc-rs', 'audio', 'no_jobs_generated', 2 + gate.NO_PROGRESS_FAIL_MS);
362
+ expect(np.attempts).to.equal(1);
363
+ expect(np.exceeded).to.equal(false);
364
+ });
365
+ });
366
+ });