@animastor/orchestration 0.3.5 → 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 (58) hide show
  1. package/CHANGELOG.md +70 -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/{runtime → legacy/runtime}/command-gate.js +11 -2
  21. package/src/{runtime → legacy/runtime}/persistence-port.js +21 -0
  22. package/src/{runtime → legacy/runtime}/reconciliation-engine.js +15 -0
  23. package/src/{runtime → legacy/runtime}/runtime-scheduler.js +9 -0
  24. package/src/{runtime → legacy/runtime}/scene-window.js +4 -0
  25. package/test/artifact-root-binding.test.js +0 -174
  26. package/test/capacity-deferral.test.js +0 -265
  27. package/test/counter-reconciliation.test.js +0 -164
  28. package/test/mocks/redis-mock.js +0 -231
  29. package/test/reconcile-quota-leak.test.js +0 -366
  30. package/test/stage146-d1-artifact-naming.test.js +0 -103
  31. package/test/stage147-a1-null-build-gate.test.js +0 -211
  32. package/test/test-bindings.js +0 -60
  33. /package/src/{host → legacy/host}/host-bindings.js +0 -0
  34. /package/src/{orchestration → legacy/orchestration}/index.js +0 -0
  35. /package/src/{orchestration → legacy/orchestration}/orchestrator.js +0 -0
  36. /package/src/{orchestration → legacy/orchestration}/runtime-result-consumer.js +0 -0
  37. /package/src/{orchestration → legacy/orchestration}/scene-callbacks.js +0 -0
  38. /package/src/{orchestration → legacy/orchestration}/scene-orchestrator.js +0 -0
  39. /package/src/{orchestration → legacy/orchestration}/scene-restoration.js +0 -0
  40. /package/src/{orchestration → legacy/orchestration}/scene-utils.js +0 -0
  41. /package/src/{runtime → legacy/runtime}/active-scenes-index.js +0 -0
  42. /package/src/{runtime → legacy/runtime}/audio-fsm-port.js +0 -0
  43. /package/src/{runtime → legacy/runtime}/circuit-breaker.js +0 -0
  44. /package/src/{runtime → legacy/runtime}/counter-reconciliation.js +0 -0
  45. /package/src/{runtime → legacy/runtime}/dispatch-engine.js +0 -0
  46. /package/src/{runtime → legacy/runtime}/dispatch-outcomes.js +0 -0
  47. /package/src/{runtime → legacy/runtime}/failure-taxonomy.js +0 -0
  48. /package/src/{runtime → legacy/runtime}/hub-cancel-port.js +0 -0
  49. /package/src/{runtime → legacy/runtime}/layer-config-port.js +0 -0
  50. /package/src/{runtime → legacy/runtime}/lease-manager.js +0 -0
  51. /package/src/{runtime → legacy/runtime}/placeholder-audio-port.js +0 -0
  52. /package/src/{runtime → legacy/runtime}/progress-events-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
  58. /package/src/{runtime → legacy/runtime}/worker-health.js +0 -0
@@ -1,366 +0,0 @@
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
- });
@@ -1,103 +0,0 @@
1
- // ======================================================
2
- // STAGE 146 — D1 REGRESSION: artifactNaming must be visible to resetScenes
3
- // ======================================================
4
- // D1: `const artifactNaming = require('@animastor/generation').artifactNaming;`
5
- // used to live INSIDE beginStage(). resetScenes() also reads it (step 6 — the
6
- // stale-PNG/preview pre-delete branch, formerly lines 534/537/555), so on the
7
- // pre-fix code that branch threw `ReferenceError: artifactNaming is not
8
- // defined` and /regenerate returned HTTP 500.
9
- //
10
- // This test exercises EXACTLY that branch on the fresh package sources:
11
- // • resetScenes() with a dirty unit and cleanPngUnitIds reaches step 6;
12
- // • it must NOT throw;
13
- // • it must delete the old PNG AND the old preview for that unit.
14
- //
15
- // The test FAILS on the pre-fix code (the ReferenceError escapes resetScenes —
16
- // step 6 is not wrapped in try/catch) and PASSES once artifactNaming is hoisted
17
- // to module scope.
18
- // ======================================================
19
-
20
- const { expect } = require('chai');
21
- const fs = require('fs');
22
- const os = require('os');
23
- const path = require('path');
24
- const { bindHostModules } = require('../src/host/host-bindings');
25
- const { setHubCancelPort, _resetHubCancelPort } = require('../src/runtime/hub-cancel-port');
26
- const { createMockRedis } = require('./mocks/redis-mock');
27
- const artifactNaming = require('@animastor/generation').artifactNaming;
28
-
29
- const orchestrator = require('../src/orchestration/orchestrator');
30
-
31
- const BOOK = 'b1';
32
- const CHAPTER = 'ch1';
33
- const SCENE = 'sc1';
34
- const BUILD = 'build1';
35
- const UID = 'iu_001';
36
-
37
- describe('Stage 146 — D1: resetScenes reads artifactNaming at module scope', function () {
38
- this.timeout(10000);
39
-
40
- let tmpRoot;
41
- let redis;
42
-
43
- before(() => {
44
- tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'stage146-d1-'));
45
- redis = createMockRedis();
46
- // resetScenes reaches the PNG-delete branch through these two seams.
47
- bindHostModules({
48
- config: () => ({
49
- OUTPUT_DIR: tmpRoot,
50
- TIMEOUTS: { FORCE_DISPATCH_TTL_S: 3600 },
51
- }),
52
- journal: () => ({
53
- EventType: { SCENE_RESET: 'SCENE_RESET', SCENE_RESET_COMPLETED: 'SCENE_RESET_COMPLETED' },
54
- appendSceneEvent: async () => {},
55
- }),
56
- });
57
- setHubCancelPort({ clearHubDispatches: async () => ({ requested: 0, cleared: 0, failed: 0 }) });
58
- });
59
-
60
- after(() => {
61
- _resetHubCancelPort();
62
- // Restore the fail-fast default from test/test-bindings.js.
63
- bindHostModules({
64
- config: () => { throw new Error('[D1-TEST] config unwired'); },
65
- journal: () => { throw new Error('[D1-TEST] journal unwired'); },
66
- });
67
- fs.rmSync(tmpRoot, { recursive: true, force: true });
68
- });
69
-
70
- it('removes the stale PNG and preview of a dirty unit without throwing', async () => {
71
- const buildDir = path.join(tmpRoot, BUILD);
72
- fs.mkdirSync(buildDir, { recursive: true });
73
-
74
- const pngPath = path.join(buildDir, artifactNaming.sceneImageName(BOOK, CHAPTER, SCENE, UID));
75
- const previewPath = path.join(buildDir, artifactNaming.sceneImagePreviewName(BOOK, CHAPTER, SCENE, UID));
76
- fs.writeFileSync(pngPath, 'png-bytes');
77
- fs.writeFileSync(previewPath, 'preview-bytes');
78
- expect(fs.existsSync(pngPath), 'fixture PNG must exist').to.equal(true);
79
- expect(fs.existsSync(previewPath), 'fixture preview must exist').to.equal(true);
80
-
81
- const scenes = [{ chapter_id: CHAPTER, scene_id: SCENE, dirty_layers: ['image'] }];
82
- const layerCfg = { image_enabled: true };
83
- const bookDiff = { markDirtyScenes: async () => ({ marked: 1 }) };
84
-
85
- const res = await orchestrator.resetScenes(
86
- redis, BOOK, BUILD, scenes, layerCfg,
87
- {
88
- scope: 'SCENE',
89
- chapterId: CHAPTER,
90
- sceneId: SCENE,
91
- bookDiff,
92
- cleanPngUnitIds: { [`${CHAPTER}_${SCENE}`]: [UID] },
93
- }
94
- );
95
-
96
- expect(res.reset_scenes).to.equal(1);
97
- expect(res.marked).to.equal(1);
98
- // The pre-fix bug threw before this point, so these two assertions are
99
- // what the regression pins down.
100
- expect(fs.existsSync(pngPath), 'old PNG must be deleted').to.equal(false);
101
- expect(fs.existsSync(previewPath), 'old preview must be deleted').to.equal(false);
102
- });
103
- });