@animastor/orchestration 0.3.4 → 1.0.0

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.
Files changed (57) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/README.md +31 -0
  3. package/package.json +11 -8
  4. package/src/gen/accept.js +370 -0
  5. package/src/gen/claim.js +155 -0
  6. package/src/gen/commands.js +338 -0
  7. package/src/gen/index.js +107 -0
  8. package/src/gen/local-runner.js +80 -0
  9. package/src/gen/ports.js +163 -0
  10. package/src/gen/progress.js +99 -0
  11. package/src/gen/sql/001-gen-core.js +130 -0
  12. package/src/gen/sql/002-command-jobs.js +58 -0
  13. package/src/gen/sql/003-scope-scenes.js +38 -0
  14. package/src/gen/sql/index.js +35 -0
  15. package/src/gen/sweeper.js +141 -0
  16. package/src/gen/util.js +136 -0
  17. package/src/gen/validate-media.js +181 -0
  18. package/src/index.js +15 -91
  19. package/src/legacy/index.js +100 -0
  20. package/src/{orchestration → legacy/orchestration}/scene-orchestrator.js +37 -3
  21. package/src/{runtime → legacy/runtime}/command-gate.js +83 -2
  22. package/src/{runtime → legacy/runtime}/counter-reconciliation.js +119 -1
  23. package/src/{runtime → legacy/runtime}/dispatch-engine.js +61 -0
  24. package/src/{runtime → legacy/runtime}/persistence-port.js +21 -0
  25. package/src/{runtime → legacy/runtime}/progress-events-port.js +4 -0
  26. package/src/{runtime → legacy/runtime}/reconciliation-engine.js +58 -1
  27. package/src/{runtime → legacy/runtime}/runtime-scheduler.js +53 -0
  28. package/src/{runtime → legacy/runtime}/scene-window.js +4 -0
  29. package/src/{runtime → legacy/runtime}/worker-health.js +11 -0
  30. package/test/artifact-root-binding.test.js +0 -174
  31. package/test/capacity-deferral.test.js +0 -265
  32. package/test/counter-reconciliation.test.js +0 -164
  33. package/test/mocks/redis-mock.js +0 -221
  34. package/test/stage146-d1-artifact-naming.test.js +0 -103
  35. package/test/stage147-a1-null-build-gate.test.js +0 -211
  36. package/test/test-bindings.js +0 -60
  37. /package/src/{host → legacy/host}/host-bindings.js +0 -0
  38. /package/src/{orchestration → legacy/orchestration}/index.js +0 -0
  39. /package/src/{orchestration → legacy/orchestration}/orchestrator.js +0 -0
  40. /package/src/{orchestration → legacy/orchestration}/runtime-result-consumer.js +0 -0
  41. /package/src/{orchestration → legacy/orchestration}/scene-callbacks.js +0 -0
  42. /package/src/{orchestration → legacy/orchestration}/scene-restoration.js +0 -0
  43. /package/src/{orchestration → legacy/orchestration}/scene-utils.js +0 -0
  44. /package/src/{runtime → legacy/runtime}/active-scenes-index.js +0 -0
  45. /package/src/{runtime → legacy/runtime}/audio-fsm-port.js +0 -0
  46. /package/src/{runtime → legacy/runtime}/circuit-breaker.js +0 -0
  47. /package/src/{runtime → legacy/runtime}/dispatch-outcomes.js +0 -0
  48. /package/src/{runtime → legacy/runtime}/failure-taxonomy.js +0 -0
  49. /package/src/{runtime → legacy/runtime}/hub-cancel-port.js +0 -0
  50. /package/src/{runtime → legacy/runtime}/layer-config-port.js +0 -0
  51. /package/src/{runtime → legacy/runtime}/lease-manager.js +0 -0
  52. /package/src/{runtime → legacy/runtime}/placeholder-audio-port.js +0 -0
  53. /package/src/{runtime → legacy/runtime}/retry-budget-manager.js +0 -0
  54. /package/src/{runtime → legacy/runtime}/runtime-metrics.js +0 -0
  55. /package/src/{runtime → legacy/runtime}/runtime-result-emitter.js +0 -0
  56. /package/src/{runtime → legacy/runtime}/scene-data-port.js +0 -0
  57. /package/src/{runtime → legacy/runtime}/video-fsm-port.js +0 -0
@@ -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) {
@@ -33,6 +33,7 @@ const { lazyHostBinding } = require('../host/host-bindings');
33
33
  const state = lazyHostBinding('state');
34
34
  const progressEventsOp = require('./progress-events-port').progressEventsOp;
35
35
  const persist = require('./persistence-port').persist;
36
+ const { isV2Book } = require('./persistence-port');
36
37
 
37
38
  const logPrefix = '[COMMAND-GATE]';
38
39
 
@@ -95,11 +96,12 @@ async function isBookCancelled(redis, bookId) {
95
96
 
96
97
  /** Per-pass memo (one scheduler tick / one reconcile pass). */
97
98
  function createGateCache() {
98
- return { layer: new Map(), cancelled: new Map() };
99
+ return { layer: new Map(), cancelled: new Map(), v2: new Map() };
99
100
  }
100
101
 
101
102
  async function memo(cache, bucket, bookId, fn) {
102
103
  if (!cache) return fn();
104
+ if (!cache[bucket]) cache[bucket] = new Map();
103
105
  if (cache[bucket].has(bookId)) return cache[bucket].get(bookId);
104
106
  const value = await fn();
105
107
  cache[bucket].set(bookId, value);
@@ -113,9 +115,16 @@ const EMPTY_TASK_STATE = Object.freeze({ managed: false, activeTypes: new Set()
113
115
  *
114
116
  * @returns {Promise<{stages:Set<string>, denied:Object<string,string>,
115
117
  * cancelled:boolean, layerCfg:object, taskState:{managed:boolean, activeTypes:Set<string>}}>}
116
- * `denied[stage]` ∈ 'cancelled' | 'no_active_task' | 'layer_disabled'.
118
+ * `denied[stage]` ∈ 'cancelled' | 'no_active_task' | 'layer_disabled' | 'orchestration_v2'.
117
119
  */
118
120
  async function getAuthorizedStages(redis, bookId, chapterId, sceneId, cache = null) {
121
+ // Orchestration v2 (1b/E): a v2 book is never authorized for a legacy stage —
122
+ // the gen core owns it (fail-closed inside isV2Book).
123
+ if (await memo(cache, 'v2', bookId, () => isV2Book(bookId))) {
124
+ const denied = {};
125
+ for (const stage of mediaRegistry.listMediaTypes()) denied[stage] = 'orchestration_v2';
126
+ return { stages: new Set(), denied, cancelled: false, layerCfg: null, taskState: EMPTY_TASK_STATE, v2: true };
127
+ }
119
128
  const cancelled = await memo(cache, 'cancelled', bookId, () => isBookCancelled(redis, bookId));
120
129
  const layerCfg = await memo(cache, 'layer', bookId, () => getLayerConfig(redis, bookId));
121
130
 
@@ -198,6 +207,72 @@ async function blockStageNoWorker(redis, bookId, chapterId, sceneId, stage) {
198
207
  return { reason, ...result };
199
208
  }
200
209
 
210
+ // ======================================================
211
+ // NO PROGRESS → FAILED (reconcile-quota-leak, 2026-11-05)
212
+ // ======================================================
213
+ // A commanded scene×stage whose dispatches keep ending WITHOUT jobs and
214
+ // WITHOUT completion (no_jobs_generated, already_done_rejected:*, executor
215
+ // errors …) used to loop silently: the task stayed `active`, the progress
216
+ // row kept its running timer. After NO_PROGRESS_FAIL_MS of such outcomes
217
+ // (and at least NO_PROGRESS_MIN_ATTEMPTS attempts — a transient `locked`
218
+ // must not fail a command) the command becomes `failed` with the reason;
219
+ // the row stays visible with «Повторить». Any real dispatch or completion
220
+ // resets the window.
221
+
222
+ const NO_PROGRESS_KEY_PREFIX = 'animastor:dispatch-noprogress:';
223
+ const NO_PROGRESS_FAIL_MS = 5 * 60 * 1000;
224
+ const NO_PROGRESS_MIN_ATTEMPTS = 3;
225
+ const NO_PROGRESS_TTL_S = 60 * 60;
226
+
227
+ function noProgressKey(bookId, chapterId, sceneId, stage) {
228
+ return `${NO_PROGRESS_KEY_PREFIX}${bookId}:${chapterId}:${sceneId}:${stage}`;
229
+ }
230
+
231
+ async function clearNoProgress(redis, bookId, chapterId, sceneId, stage) {
232
+ try { await redis.del(noProgressKey(bookId, chapterId, sceneId, stage)); } catch (_) { /* best-effort */ }
233
+ }
234
+
235
+ /**
236
+ * Record one dispatch outcome without progress.
237
+ * @returns {Promise<{attempts:number, since:number, exceeded:boolean}>}
238
+ */
239
+ async function noteNoProgress(redis, bookId, chapterId, sceneId, stage, reason, now = Date.now()) {
240
+ const key = noProgressKey(bookId, chapterId, sceneId, stage);
241
+ let rec = null;
242
+ try { rec = JSON.parse((await redis.get(key)) || 'null'); } catch (_) { rec = null; }
243
+ if (!rec || typeof rec.since !== 'number') rec = { since: now, attempts: 0 };
244
+ rec.attempts = (rec.attempts || 0) + 1;
245
+ rec.last_reason = reason || 'unknown';
246
+ rec.last_at = now;
247
+ await redis.set(key, JSON.stringify(rec), 'EX', NO_PROGRESS_TTL_S);
248
+ const exceeded = rec.attempts >= NO_PROGRESS_MIN_ATTEMPTS && (now - rec.since) >= NO_PROGRESS_FAIL_MS;
249
+ return { attempts: rec.attempts, since: rec.since, exceeded };
250
+ }
251
+
252
+ /**
253
+ * Terminal: the command for this scene×stage made no progress — registry
254
+ * task → failed (error_class «no_progress», error_code = last reason), PG
255
+ * legs host-side (ProgressEventsPort.failSceneStage).
256
+ */
257
+ async function failStageNoProgress(redis, bookId, chapterId, sceneId, stage, reason, attempts) {
258
+ const info = {
259
+ error_class: 'no_progress',
260
+ error_code: String(reason || 'unknown').slice(0, 120),
261
+ error_message: `генерация не идёт: ${String(reason || 'unknown').slice(0, 200)}`,
262
+ attempts: attempts || null,
263
+ };
264
+ let result = { tasks: [] };
265
+ try {
266
+ result = (await progressEventsOp('failSceneStage')(redis, bookId, chapterId, sceneId, stage, info)) || result;
267
+ } catch (err) {
268
+ warn(`failSceneStage failed for ${bookId}/${chapterId}/${sceneId}:${stage}: ${err.message}`);
269
+ }
270
+ await clearNoProgress(redis, bookId, chapterId, sceneId, stage);
271
+ const ids = (result.tasks || []).map(t => t.task_id || t).join(',') || 'none';
272
+ log(`FAILED_NO_PROGRESS ${bookId}/${chapterId}/${sceneId}:${stage} — reason=${info.error_code} attempts=${attempts}; tasks=[${ids}] — a new command is required`);
273
+ return { ...info, ...result };
274
+ }
275
+
201
276
  // ======================================================
202
277
  // FORCE — only for the scene×stage pairs of the command
203
278
  // ======================================================
@@ -260,6 +335,12 @@ module.exports = {
260
335
  describeDenied,
261
336
  rollbackGeneratingToDirty,
262
337
  blockStageNoWorker,
338
+ NO_PROGRESS_FAIL_MS,
339
+ NO_PROGRESS_MIN_ATTEMPTS,
340
+ noProgressKey,
341
+ clearNoProgress,
342
+ noteNoProgress,
343
+ failStageNoProgress,
263
344
  FORCE_STAGES_KEY_PREFIX,
264
345
  forceStagesKey,
265
346
  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
 
@@ -154,6 +154,26 @@ function persist(op) {
154
154
  return fn;
155
155
  }
156
156
 
157
+ // ── Orchestration v2 isolation (ADR ORCHESTRATION_V2 §12 этап 1; задача 1b/E) ──
158
+ // A book with books.orchestration = 'v2' belongs to the v2 core (gen_*): the
159
+ // legacy contour (command gate, reconcile, scheduler, retry policy, startup
160
+ // resume) must not touch it. The ONE predicate every legacy leg asks. The host
161
+ // adapter implements the OPTIONAL op orchestration.isV2Book(bookId) (not in
162
+ // OPS: adapters/mocks without it keep the pre-v2 behaviour = "not v2").
163
+ // Fail-closed: when the op exists but cannot answer, the book is treated as v2
164
+ // (legacy keeps its hands off).
165
+ async function isV2Book(bookId) {
166
+ if (!bookId || !impl) return false;
167
+ const fn = resolveOp(impl, 'orchestration.isV2Book');
168
+ if (typeof fn !== 'function') return false;
169
+ try {
170
+ return (await fn(bookId)) === true;
171
+ } catch (err) {
172
+ console.warn(`[PERSISTENCE-PORT] orchestration.isV2Book(${bookId}) failed: ${err && err.message} — treated as v2 (fail-closed)`);
173
+ return true;
174
+ }
175
+ }
176
+
157
177
  function isPersistencePortWired() {
158
178
  return impl !== null;
159
179
  }
@@ -164,6 +184,7 @@ function _resetPersistencePort() {
164
184
  }
165
185
 
166
186
  module.exports = {
187
+ isV2Book,
167
188
  OPS,
168
189
  setPersistencePort,
169
190
  persistence,
@@ -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;
@@ -31,6 +31,8 @@ const mediaRegistry = require('@animastor/generation').mediaRegistry;
31
31
  // audio-path composition are consumed as persistence OPERATIONS through the
32
32
  // same port (their implementations stay host-side).
33
33
  const persist = require('./persistence-port').persist;
34
+ // Orchestration v2 (1b/E): every phase skips books with books.orchestration='v2'.
35
+ const { isV2Book } = require('./persistence-port');
34
36
  const config = lazyHostBinding('config');
35
37
  // S-5: the event journal is an append-only observability sink (zero requires,
36
38
  // no orchestration policy) — the ONLY runtime→Generation dependency allowed
@@ -115,6 +117,31 @@ class ReconciliationReport {
115
117
  // ORPHAN STATE CHECKS
116
118
  // ======================================================
117
119
 
120
+ /**
121
+ * reconcile-quota-leak: «stage committed by the current generation» — the
122
+ * single readiness predicate the recovery may trust: PG scene_assets row of
123
+ * the book build is `ready` (the version gate already passed when it was
124
+ * written) AND the fenced-commit probe confirms the artifact (invariant B,
125
+ * media.audio.isSceneAudioCommitted — the same predicate the dispatch uses).
126
+ * Audio only: image/video keep the historic behavior. Any probe error → false
127
+ * (fail closed: demoting is recoverable, a false READY is not).
128
+ */
129
+ async function isStageCommittedReady(bookId, chapterId, sceneId, stage) {
130
+ if (stage !== 'audio') return false;
131
+ try {
132
+ const buildId = resolveBookBuildId(bookId);
133
+ const asset = await persist('sceneAssets.getAsset')(bookId, chapterId, sceneId, stage, buildId);
134
+ if (!asset || asset.status !== 'ready') return false;
135
+ const audio = lazyHostBinding('media.audio');
136
+ if (typeof audio.isSceneAudioCommitted !== 'function') return false;
137
+ const probe = await audio.isSceneAudioCommitted(buildId, bookId, chapterId, sceneId, null);
138
+ return !!(probe && probe.ready === true);
139
+ } catch (err) {
140
+ warn(`isStageCommittedReady probe failed for ${bookId}/${chapterId}/${sceneId}:${stage}: ${err.message}`);
141
+ return false;
142
+ }
143
+ }
144
+
118
145
  /**
119
146
  * Canonical build identity of a book (audit d9d67a3): the SAME source the
120
147
  * rest of the runtime uses (rebuildWorkList, generate-next, dispatch) —
@@ -524,6 +551,7 @@ async function checkStalledAudioScenes(redis, deps) {
524
551
  let stalled = 0;
525
552
  for (const entry of allStates) {
526
553
  const { bookId, chapterId, sceneId, state: orchState } = entry;
554
+ if (await isV2Book(bookId)) continue; // orchestration v2: not legacy's
527
555
  if (orchState.phase !== PHASES.WAITING_CHUNKS) continue;
528
556
 
529
557
  const buildId = orchState.build_id || 'default';
@@ -646,6 +674,7 @@ async function checkStalledVideoScenes(redis, deps) {
646
674
  let stalled = 0;
647
675
  for (const entry of allStates) {
648
676
  const { bookId, chapterId, sceneId, state: orchState } = entry;
677
+ if (await isV2Book(bookId)) continue; // orchestration v2: not legacy's
649
678
  if (orchState.phase !== PHASES.WAITING_CHUNKS) continue;
650
679
 
651
680
  // ── ПЕРЕСМОТР ПОРОГА ЗАСТОЯ ──
@@ -1006,6 +1035,7 @@ async function checkStaleDispatchLeases(redis, bookId, chapterId, sceneId) {
1006
1035
  */
1007
1036
  async function reconcileScene(redis, bookId, chapterId, sceneId) {
1008
1037
  const report = new ReconciliationReport();
1038
+ if (await isV2Book(bookId)) return report; // orchestration v2: not legacy's
1009
1039
 
1010
1040
  try {
1011
1041
  // Check orphan states
@@ -1445,9 +1475,25 @@ async function applyFix(redis, fix) {
1445
1475
  // S-5: asset-state writer via the injected orchestration seam
1446
1476
  const markDirtyScene = orchestrationSeams.getOrchestrationSeam('markDirtyScene');
1447
1477
  const currentStates = await state.getAssetStates(redis, scene.bookId, scene.chapterId, scene.sceneId);
1448
- const redo = [...auth.stages].filter(stage =>
1478
+ const inFlight = [...auth.stages].filter(stage =>
1449
1479
  currentStates[stage] === state.AssetState.GENERATING ||
1450
1480
  currentStates[stage] === state.AssetState.PENDING);
1481
+ // reconcile-quota-leak (2026-11-05, BA): the lease of a dispatch
1482
+ // that ended WITHOUT finalization (already_done & co) looked
1483
+ // "stale in flight"; marking that stage DIRTY bumped the epoch
1484
+ // and wrote PG stale over audio committed by the CURRENT
1485
+ // generation (8 → 13 scenes demoted on BA). A stage whose
1486
+ // commit is confirmed is only re-asserted READY here — the
1487
+ // lease/quota release above stays.
1488
+ const redo = [];
1489
+ for (const stage of inFlight) {
1490
+ if (await isStageCommittedReady(scene.bookId, scene.chapterId, scene.sceneId, stage)) {
1491
+ await state.unsafeRestoreAssetState(redis, scene.bookId, scene.chapterId, scene.sceneId, stage, state.AssetState.READY);
1492
+ log(`STALE_LEASE_COMMITTED_KEEP: ${scene.bookId}/${scene.chapterId}/${scene.sceneId} ${stage} — committed + PG ready, not demoted`);
1493
+ continue;
1494
+ }
1495
+ redo.push(stage);
1496
+ }
1451
1497
  if (redo.length > 0) {
1452
1498
  await markDirtyScene(redis, scene.bookId, scene.chapterId, scene.sceneId, redo);
1453
1499
  }
@@ -2014,6 +2060,10 @@ async function recoverResultKeys(redis, deps, scope) {
2014
2060
  // marker or one from an older dispatch of the same job_id
2015
2061
  // (audio/video regeneration within the TTL) is no proof — such
2016
2062
  // a result goes through the fenced handler exactly as before.
2063
+ {
2064
+ const pj = require('@animastor/contracts').jobProtocolV2.parseJobId(job_id);
2065
+ if (pj && await isV2Book(pj.bookId)) continue; // orchestration v2: key left untouched
2066
+ }
2017
2067
  const dedup = await readResultDedup(redis, job_id, buildId);
2018
2068
  if (dedup.state === 'settled' && dedup.dispatchId === String(dispatchId)) {
2019
2069
  await redis.del(key);
@@ -2075,6 +2125,7 @@ async function recoverResultKeys(redis, deps, scope) {
2075
2125
  // Parse job_id to get stage and scene info
2076
2126
  const jobSchema = require('@animastor/contracts').jobProtocolV2;
2077
2127
  const parsed = jobSchema.parseJobId(job_id);
2128
+ if (parsed && await isV2Book(parsed.bookId)) continue; // orchestration v2: key left untouched
2078
2129
  if (parsed) {
2079
2130
  const stageMap = { audio_chunk: 'audio', iu_image: 'image', scene_image: 'image', scene_video: 'video' };
2080
2131
  const stage = stageMap[parsed.kind];
@@ -2118,6 +2169,7 @@ async function recoverAudioOrchStates(redis, deps) {
2118
2169
 
2119
2170
  for (const entry of allStates) {
2120
2171
  const { bookId, chapterId, sceneId, state: orchState } = entry;
2172
+ if (await isV2Book(bookId)) continue; // orchestration v2: not legacy's
2121
2173
  const phase = orchState.phase;
2122
2174
  const buildId = orchState.build_id || 'default';
2123
2175
  const mergedPath = syncPath.join(OUTPUT_DIR, buildId, artifactNaming.sceneAudioName(bookId, chapterId, sceneId));
@@ -2219,6 +2271,7 @@ async function recoverVideoOrchStates(redis, deps) {
2219
2271
 
2220
2272
  for (const entry of allStates) {
2221
2273
  const { bookId, chapterId, sceneId, state: orchState } = entry;
2274
+ if (await isV2Book(bookId)) continue; // orchestration v2: not legacy's
2222
2275
  const phase = orchState.phase;
2223
2276
  const buildId = orchState.build_id || 'default';
2224
2277
  const suffixes = videoOrch.groupSuffixes(orchState);
@@ -2326,6 +2379,7 @@ async function checkVersionStaleness(redis, deps) {
2326
2379
 
2327
2380
  let outdated = 0;
2328
2381
  for (const entry of sceneMap.values()) {
2382
+ if (await isV2Book(entry.bookId)) continue; // orchestration v2
2329
2383
  if (entry.staleAssets.size === 0) continue;
2330
2384
 
2331
2385
  let assetStates;
@@ -2372,6 +2426,7 @@ async function reconcileMissingSceneState(redis, deps) {
2372
2426
  const bookResult = { rows: await persist('listBooks')() };
2373
2427
  let count = 0;
2374
2428
  for (const row of bookResult.rows) {
2429
+ if (await isV2Book(row.book_id)) continue; // orchestration v2
2375
2430
  const totalKey = `animastor:book-scenes:${row.book_id}:total`;
2376
2431
  const totalRaw = await redis.get(totalKey);
2377
2432
  if (!totalRaw || parseInt(totalRaw, 10) === 0) {
@@ -2449,6 +2504,7 @@ const state = lazyHostBinding('state');
2449
2504
 
2450
2505
  let scenesAdded = 0;
2451
2506
  for (const bookId of books) {
2507
+ if (await isV2Book(bookId)) { log(`[WORKLIST] ${bookId}: skipped (orchestration v2)`); continue; }
2452
2508
  if (cancelled.has(bookId)) {
2453
2509
  log(`[WORKLIST] ${bookId}: skipped (cancellation tombstone)`);
2454
2510
  continue;
@@ -2577,6 +2633,7 @@ const state = lazyHostBinding('state');
2577
2633
  // ======================================================
2578
2634
 
2579
2635
  module.exports = {
2636
+ isStageCommittedReady,
2580
2637
  reconcileScene,
2581
2638
  reconcileBook,
2582
2639
  reconcileAll,