@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.
- package/CHANGELOG.md +120 -0
- package/README.md +31 -0
- package/package.json +11 -8
- package/src/gen/accept.js +370 -0
- package/src/gen/claim.js +155 -0
- package/src/gen/commands.js +338 -0
- package/src/gen/index.js +107 -0
- package/src/gen/local-runner.js +80 -0
- package/src/gen/ports.js +163 -0
- package/src/gen/progress.js +99 -0
- package/src/gen/sql/001-gen-core.js +130 -0
- package/src/gen/sql/002-command-jobs.js +58 -0
- package/src/gen/sql/003-scope-scenes.js +38 -0
- package/src/gen/sql/index.js +35 -0
- package/src/gen/sweeper.js +141 -0
- package/src/gen/util.js +136 -0
- package/src/gen/validate-media.js +181 -0
- package/src/index.js +15 -91
- package/src/legacy/index.js +100 -0
- package/src/{orchestration → legacy/orchestration}/scene-orchestrator.js +37 -3
- package/src/{runtime → legacy/runtime}/command-gate.js +83 -2
- package/src/{runtime → legacy/runtime}/counter-reconciliation.js +119 -1
- package/src/{runtime → legacy/runtime}/dispatch-engine.js +61 -0
- package/src/{runtime → legacy/runtime}/persistence-port.js +21 -0
- package/src/{runtime → legacy/runtime}/progress-events-port.js +4 -0
- package/src/{runtime → legacy/runtime}/reconciliation-engine.js +58 -1
- package/src/{runtime → legacy/runtime}/runtime-scheduler.js +53 -0
- package/src/{runtime → legacy/runtime}/scene-window.js +4 -0
- package/src/{runtime → legacy/runtime}/worker-health.js +11 -0
- package/test/artifact-root-binding.test.js +0 -174
- package/test/capacity-deferral.test.js +0 -265
- package/test/counter-reconciliation.test.js +0 -164
- package/test/mocks/redis-mock.js +0 -221
- package/test/stage146-d1-artifact-naming.test.js +0 -103
- package/test/stage147-a1-null-build-gate.test.js +0 -211
- package/test/test-bindings.js +0 -60
- /package/src/{host → legacy/host}/host-bindings.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/index.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/orchestrator.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/runtime-result-consumer.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/scene-callbacks.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/scene-restoration.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/scene-utils.js +0 -0
- /package/src/{runtime → legacy/runtime}/active-scenes-index.js +0 -0
- /package/src/{runtime → legacy/runtime}/audio-fsm-port.js +0 -0
- /package/src/{runtime → legacy/runtime}/circuit-breaker.js +0 -0
- /package/src/{runtime → legacy/runtime}/dispatch-outcomes.js +0 -0
- /package/src/{runtime → legacy/runtime}/failure-taxonomy.js +0 -0
- /package/src/{runtime → legacy/runtime}/hub-cancel-port.js +0 -0
- /package/src/{runtime → legacy/runtime}/layer-config-port.js +0 -0
- /package/src/{runtime → legacy/runtime}/lease-manager.js +0 -0
- /package/src/{runtime → legacy/runtime}/placeholder-audio-port.js +0 -0
- /package/src/{runtime → legacy/runtime}/retry-budget-manager.js +0 -0
- /package/src/{runtime → legacy/runtime}/runtime-metrics.js +0 -0
- /package/src/{runtime → legacy/runtime}/runtime-result-emitter.js +0 -0
- /package/src/{runtime → legacy/runtime}/scene-data-port.js +0 -0
- /package/src/{runtime → legacy/runtime}/video-fsm-port.js +0 -0
|
@@ -386,7 +386,15 @@ async function tick(redis, loadedBooks = {}) {
|
|
|
386
386
|
const parsed = parseSceneKey(sceneKey);
|
|
387
387
|
if (parsed) activeBookIds.add(parsed.bookId);
|
|
388
388
|
}
|
|
389
|
+
// Orchestration v2 (1b/E): a v2 book is skipped entirely — no read-modify-write
|
|
390
|
+
// of any legacy key (registry, asset-state, active index, leases).
|
|
391
|
+
const v2Books = new Set();
|
|
389
392
|
for (const bookId of activeBookIds) {
|
|
393
|
+
if (await require('./persistence-port').isV2Book(bookId)) v2Books.add(bookId);
|
|
394
|
+
}
|
|
395
|
+
if (v2Books.size > 0) log(`V2_SKIP: ${[...v2Books].join(',')} (orchestration v2 — legacy scheduler keeps out)`);
|
|
396
|
+
for (const bookId of activeBookIds) {
|
|
397
|
+
if (v2Books.has(bookId)) continue;
|
|
390
398
|
const completedTasks = await progressEventsOp('reconcileCompletedTasks')(
|
|
391
399
|
redis,
|
|
392
400
|
bookId,
|
|
@@ -417,6 +425,7 @@ async function tick(redis, loadedBooks = {}) {
|
|
|
417
425
|
}
|
|
418
426
|
|
|
419
427
|
const { bookId, chapterId, sceneId } = parsed;
|
|
428
|
+
if (v2Books.has(bookId)) { summary.skipped++; continue; }
|
|
420
429
|
|
|
421
430
|
// Force applies only to the scene×stage pairs of the command.
|
|
422
431
|
let bookForce = forceCache.get(bookId);
|
|
@@ -607,12 +616,22 @@ async function attemptDispatch(redis, bookId, chapterId, sceneId, loadedBook, fo
|
|
|
607
616
|
}
|
|
608
617
|
if (result.dispatched) {
|
|
609
618
|
dispatched++;
|
|
619
|
+
await commandGate.clearNoProgress(redis, bookId, chapterId, sceneId, stage);
|
|
610
620
|
} else if (result.reason === 'backpressure' || result.reason === 'throttled') {
|
|
611
621
|
throttled++;
|
|
622
|
+
// reconcile-quota-leak: a full quota with NO worker of this type
|
|
623
|
+
// alive anywhere can never drain by itself — the command would hang
|
|
624
|
+
// with a running timer. Block it like the hub-side no_worker path.
|
|
625
|
+
if (await noWorkerOfTypeAlive(redis, stage)) {
|
|
626
|
+
await commandGate.blockStageNoWorker(redis, bookId, chapterId, sceneId, stage);
|
|
627
|
+
failures.push(`${stage}:blocked_no_worker`);
|
|
628
|
+
continue;
|
|
629
|
+
}
|
|
612
630
|
} else if (result.completed) {
|
|
613
631
|
// Stage finished inside the executor (already_done / cache_hit /
|
|
614
632
|
// no_segments) — not a failure, nothing to dispatch.
|
|
615
633
|
anyCompleted = true;
|
|
634
|
+
await commandGate.clearNoProgress(redis, bookId, chapterId, sceneId, stage);
|
|
616
635
|
} else if (result.deferred) {
|
|
617
636
|
// Stage 118 (M9): a bounded deferral is NOT an error — nothing
|
|
618
637
|
// happened, the stage is waiting for capacity (or is already
|
|
@@ -626,6 +645,25 @@ async function attemptDispatch(redis, bookId, chapterId, sceneId, loadedBook, fo
|
|
|
626
645
|
// observability. Теперь причина всплывает в tick-сводку.
|
|
627
646
|
failures.push(`${stage}:${result.reason || 'unknown'}`);
|
|
628
647
|
}
|
|
648
|
+
// reconcile-quota-leak: «задача не висит молча» — an outcome that
|
|
649
|
+
// neither dispatched, completed nor waits for capacity is counted;
|
|
650
|
+
// a long run of them fails the command with the reason.
|
|
651
|
+
// A capacity outcome (duplicate_pending / ambiguous_post …) means the
|
|
652
|
+
// job IS waiting in the hub lane — that is progress-in-waiting, not a
|
|
653
|
+
// stall; no_worker_available is blocked above.
|
|
654
|
+
if (!result.dispatched && !result.completed
|
|
655
|
+
&& result.reason !== 'backpressure' && result.reason !== 'throttled'
|
|
656
|
+
&& result.reason !== 'no_worker_available'
|
|
657
|
+
&& !require('./dispatch-outcomes').isCapacityOutcome(result.reason)) {
|
|
658
|
+
try {
|
|
659
|
+
const np = await commandGate.noteNoProgress(redis, bookId, chapterId, sceneId, stage, result.reason);
|
|
660
|
+
if (np.exceeded) {
|
|
661
|
+
await commandGate.failStageNoProgress(redis, bookId, chapterId, sceneId, stage, result.reason, np.attempts);
|
|
662
|
+
}
|
|
663
|
+
} catch (npErr) {
|
|
664
|
+
warn(`NO_PROGRESS bookkeeping failed for ${sceneKey}:${stage}: ${npErr.message}`);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
629
667
|
}
|
|
630
668
|
|
|
631
669
|
if (dispatched > 0) {
|
|
@@ -643,6 +681,21 @@ async function attemptDispatch(redis, bookId, chapterId, sceneId, loadedBook, fo
|
|
|
643
681
|
return { dispatched: 0, throttled, stages: stages.length, success: true, reason: 'no_dispatch' };
|
|
644
682
|
}
|
|
645
683
|
|
|
684
|
+
/**
|
|
685
|
+
* reconcile-quota-leak: true when no fresh heartbeat of `stage`'s worker type
|
|
686
|
+
* exists in any scope. Fails OPEN (false) when the probe is unavailable — a
|
|
687
|
+
* probe error must never block a command.
|
|
688
|
+
*/
|
|
689
|
+
async function noWorkerOfTypeAlive(redis, stage) {
|
|
690
|
+
try {
|
|
691
|
+
const workerHealth = require('./worker-health');
|
|
692
|
+
if (typeof workerHealth.getAnyAliveCount !== 'function') return false;
|
|
693
|
+
return (await workerHealth.getAnyAliveCount(redis, stage)) === 0;
|
|
694
|
+
} catch (_) {
|
|
695
|
+
return false;
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
|
|
646
699
|
// ======================================================
|
|
647
700
|
// EXPORTS
|
|
648
701
|
// ======================================================
|
|
@@ -683,6 +683,10 @@ async function reconcileWindowStatuses(redis, bookId, buildId) {
|
|
|
683
683
|
}
|
|
684
684
|
|
|
685
685
|
async function startScene(redis, s, buildId, bookId) {
|
|
686
|
+
if (await require('./persistence-port').isV2Book(bookId)) {
|
|
687
|
+
log(`startScene skipped: ${bookId} is on orchestration v2`);
|
|
688
|
+
return false;
|
|
689
|
+
}
|
|
686
690
|
if (await isCancelled(redis, bookId)) {
|
|
687
691
|
log(`startScene skipped: generation cancelled for ${bookId}`);
|
|
688
692
|
return false;
|
|
@@ -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,
|
|
@@ -1,174 +0,0 @@
|
|
|
1
|
-
// ======================================================
|
|
2
|
-
// STAGE 96 — ARTIFACT ROOT BINDING (поведение закрытых литералов)
|
|
3
|
-
// ======================================================
|
|
4
|
-
// Четыре production-литерала '/data/output' в orchestration-пакете
|
|
5
|
-
// (scene-callbacks.js:281,393 · reconciliation-engine.js:124,158)
|
|
6
|
-
// переведены на существующий шов artifactRoot (host-bindings, §32.30).
|
|
7
|
-
//
|
|
8
|
-
// Тесты проверяют ПОВЕДЕНИЕ на свежих исходниках пакета (src/, а не
|
|
9
|
-
// npm-копия в backend/node_modules):
|
|
10
|
-
// — путь строится из привязанного корня, а не из литерала;
|
|
11
|
-
// — при корне '/data/output' (контракт сохранённых данных PG/Redis)
|
|
12
|
-
// результирующая строка байт-в-байт равна прежней.
|
|
13
|
-
// ======================================================
|
|
14
|
-
|
|
15
|
-
const { expect } = require('chai');
|
|
16
|
-
const fs = require('fs');
|
|
17
|
-
const os = require('os');
|
|
18
|
-
const path = require('path');
|
|
19
|
-
const { bindHostModules } = require('../src/host/host-bindings');
|
|
20
|
-
const { createMockRedis } = require('./mocks/redis-mock');
|
|
21
|
-
|
|
22
|
-
const engine = require('../src/runtime/reconciliation-engine');
|
|
23
|
-
const callbacks = require('../src/orchestration/scene-callbacks');
|
|
24
|
-
|
|
25
|
-
const BOOK = 'b1';
|
|
26
|
-
const CHAPTER = 'ch1';
|
|
27
|
-
const SCENE = 'sc1';
|
|
28
|
-
|
|
29
|
-
let tmpRoot;
|
|
30
|
-
let redis;
|
|
31
|
-
let currentStates;
|
|
32
|
-
|
|
33
|
-
const imageStub = {
|
|
34
|
-
resolveCanonicalSceneImage: () => null,
|
|
35
|
-
getImageMetadata: async () => null,
|
|
36
|
-
};
|
|
37
|
-
const videoStub = {
|
|
38
|
-
validateVideoFile: () => ({ valid: false, duration: null, metadata: null }),
|
|
39
|
-
};
|
|
40
|
-
|
|
41
|
-
const stateStub = {
|
|
42
|
-
AssetState: {
|
|
43
|
-
NEW: 'new', DIRTY: 'dirty', PENDING: 'pending',
|
|
44
|
-
GENERATING: 'generating', READY: 'ready',
|
|
45
|
-
FAILED: 'failed', PLACEHOLDER: 'placeholder',
|
|
46
|
-
},
|
|
47
|
-
getAssetStates: async () => ({ audio: 'new', ...currentStates }),
|
|
48
|
-
};
|
|
49
|
-
|
|
50
|
-
const failFast = (name) => () => {
|
|
51
|
-
throw new Error(`[ARTIFACT-ROOT-TEST] ${name} not wired`);
|
|
52
|
-
};
|
|
53
|
-
|
|
54
|
-
function wire(artifactRootValue) {
|
|
55
|
-
bindHostModules({
|
|
56
|
-
state: () => stateStub,
|
|
57
|
-
media: () => ({ audio: {}, image: imageStub, video: videoStub }),
|
|
58
|
-
journal: () => ({ appendSceneEvent: async () => {} }),
|
|
59
|
-
artifactRoot: () => artifactRootValue,
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
describe('Stage 96 — artifactRoot-шов вместо литералов', () => {
|
|
64
|
-
before(() => {
|
|
65
|
-
tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'stage96-artifact-root-'));
|
|
66
|
-
fs.mkdirSync(path.join(tmpRoot, 'default'), { recursive: true });
|
|
67
|
-
redis = createMockRedis();
|
|
68
|
-
wire(tmpRoot);
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
after(() => {
|
|
72
|
-
// Вернуть дефолтный fail-fast, как в test/test-bindings.js
|
|
73
|
-
bindHostModules({
|
|
74
|
-
state: failFast('state'),
|
|
75
|
-
media: failFast('media'),
|
|
76
|
-
journal: failFast('journal'),
|
|
77
|
-
artifactRoot: failFast('artifactRoot'),
|
|
78
|
-
});
|
|
79
|
-
fs.rmSync(tmpRoot, { recursive: true, force: true });
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
describe('reconciliation-engine — checkOrphanVideoState', () => {
|
|
83
|
-
it('missingFile строится из привязанного корня, а не из литерала', async () => {
|
|
84
|
-
currentStates = { video: 'ready' };
|
|
85
|
-
const res = await engine.checkOrphanVideoState(redis, BOOK, CHAPTER, SCENE);
|
|
86
|
-
expect(res).to.be.an('object');
|
|
87
|
-
expect(res.missingFile).to.equal(`${tmpRoot}/default/${BOOK}_${CHAPTER}_${SCENE}.mp4`);
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
it('null, когда файл существует ПОД ПРИВЯЗАННЫМ корнем', async () => {
|
|
91
|
-
const file = path.join(tmpRoot, 'default', `${BOOK}_${CHAPTER}_${SCENE}.mp4`);
|
|
92
|
-
fs.writeFileSync(file, 'x');
|
|
93
|
-
try {
|
|
94
|
-
currentStates = { video: 'ready' };
|
|
95
|
-
expect(await engine.checkOrphanVideoState(redis, BOOK, CHAPTER, SCENE)).to.be.null;
|
|
96
|
-
} finally {
|
|
97
|
-
fs.rmSync(file, { force: true });
|
|
98
|
-
}
|
|
99
|
-
});
|
|
100
|
-
});
|
|
101
|
-
|
|
102
|
-
describe('reconciliation-engine — checkOrphanImageState', () => {
|
|
103
|
-
it('resolveCanonicalSceneImage получает привязанный корень', async () => {
|
|
104
|
-
let seenRoot = null;
|
|
105
|
-
imageStub.resolveCanonicalSceneImage = (root) => { seenRoot = root; return null; };
|
|
106
|
-
try {
|
|
107
|
-
currentStates = { image: 'ready' };
|
|
108
|
-
const res = await engine.checkOrphanImageState(redis, BOOK, CHAPTER, SCENE);
|
|
109
|
-
expect(seenRoot).to.equal(tmpRoot);
|
|
110
|
-
expect(res).to.be.an('object');
|
|
111
|
-
expect(res.type).to.equal('orphan_image_state');
|
|
112
|
-
} finally {
|
|
113
|
-
imageStub.resolveCanonicalSceneImage = () => null;
|
|
114
|
-
}
|
|
115
|
-
});
|
|
116
|
-
});
|
|
117
|
-
|
|
118
|
-
describe('scene-callbacks — handleVideoCompleted', () => {
|
|
119
|
-
it('validateVideoFile получает путь под привязанным корнем', async () => {
|
|
120
|
-
let seenPath = null;
|
|
121
|
-
videoStub.validateVideoFile = (p) => {
|
|
122
|
-
seenPath = p;
|
|
123
|
-
return { valid: false, duration: null, metadata: null };
|
|
124
|
-
};
|
|
125
|
-
try {
|
|
126
|
-
currentStates = { video: 'generating' };
|
|
127
|
-
const res = await callbacks.handleVideoCompleted(redis, BOOK, CHAPTER, SCENE, 'build1');
|
|
128
|
-
expect(seenPath).to.equal(`${tmpRoot}/build1/${BOOK}_${CHAPTER}_${SCENE}.mp4`);
|
|
129
|
-
expect(res).to.deep.include({ ok: false, retryable: true, reason: 'video_invalid' });
|
|
130
|
-
} finally {
|
|
131
|
-
videoStub.validateVideoFile = () => ({ valid: false, duration: null, metadata: null });
|
|
132
|
-
}
|
|
133
|
-
});
|
|
134
|
-
});
|
|
135
|
-
|
|
136
|
-
describe('scene-callbacks — handleImageCompleted', () => {
|
|
137
|
-
it('resolveCanonicalSceneImage получает привязанный корень', async () => {
|
|
138
|
-
let seenRoot = null;
|
|
139
|
-
imageStub.resolveCanonicalSceneImage = (root) => { seenRoot = root; return null; };
|
|
140
|
-
try {
|
|
141
|
-
currentStates = { image: 'generating' };
|
|
142
|
-
const res = await callbacks.handleImageCompleted(redis, BOOK, CHAPTER, SCENE, 'build1');
|
|
143
|
-
expect(seenRoot).to.equal(tmpRoot);
|
|
144
|
-
expect(res).to.deep.include({ ok: false, retryable: true, reason: 'image_not_found' });
|
|
145
|
-
} finally {
|
|
146
|
-
imageStub.resolveCanonicalSceneImage = () => null;
|
|
147
|
-
}
|
|
148
|
-
});
|
|
149
|
-
});
|
|
150
|
-
|
|
151
|
-
describe('обратная совместимость (контракт контейнерных путей)', () => {
|
|
152
|
-
it('при корне /data/output строка байт-в-байт равна прежнему литералу', async () => {
|
|
153
|
-
wire('/data/output');
|
|
154
|
-
try {
|
|
155
|
-
let seenPath = null;
|
|
156
|
-
videoStub.validateVideoFile = (p) => {
|
|
157
|
-
seenPath = p;
|
|
158
|
-
return { valid: false, duration: null, metadata: null };
|
|
159
|
-
};
|
|
160
|
-
currentStates = { video: 'generating' };
|
|
161
|
-
await callbacks.handleVideoCompleted(redis, BOOK, CHAPTER, SCENE, 'build1');
|
|
162
|
-
// ровно то, что до Stage 96 формировал шаблон
|
|
163
|
-
expect(seenPath).to.equal(`/data/output/build1/${BOOK}_${CHAPTER}_${SCENE}.mp4`);
|
|
164
|
-
|
|
165
|
-
currentStates = { video: 'ready' };
|
|
166
|
-
const orphan = await engine.checkOrphanVideoState(redis, BOOK, CHAPTER, SCENE);
|
|
167
|
-
expect(orphan.missingFile).to.equal(`/data/output/default/${BOOK}_${CHAPTER}_${SCENE}.mp4`);
|
|
168
|
-
} finally {
|
|
169
|
-
videoStub.validateVideoFile = () => ({ valid: false, duration: null, metadata: null });
|
|
170
|
-
wire(tmpRoot);
|
|
171
|
-
}
|
|
172
|
-
});
|
|
173
|
-
});
|
|
174
|
-
});
|
|
@@ -1,265 +0,0 @@
|
|
|
1
|
-
// ======================================================
|
|
2
|
-
// Stage 116 (D3) — CAPACITY DEFERRAL (bounded retry/backoff)
|
|
3
|
-
// ======================================================
|
|
4
|
-
// Regression net for the Stage 115 defect D3: a stage that could not enqueue
|
|
5
|
-
// anything (no live compatible worker, or every job already pending in the
|
|
6
|
-
// lane) was re-dispatched on EVERY scheduler tick (SCHEDULER_TICK_MS = 5 s).
|
|
7
|
-
// Each attempt created a lease + dispatch metadata, the executor sent
|
|
8
|
-
// nothing, the dispatch was cancelled and the FSM was rolled back — an
|
|
9
|
-
// unbounded dispatch/cancel loop with lease churn, FSM churn and unbounded
|
|
10
|
-
// event-journal growth.
|
|
11
|
-
//
|
|
12
|
-
// The fix: a bounded per-stage deferral. While the deferral window is open
|
|
13
|
-
// the dispatch engine returns WITHOUT any side effect (no lease, no metadata,
|
|
14
|
-
// no FSM write, no journal event), the stage stays PENDING and recoverable,
|
|
15
|
-
// and the deferral is cleared by a successful dispatch or an explicit cancel.
|
|
16
|
-
//
|
|
17
|
-
// Isolated: in-memory Redis mock + stubbed host bindings. No production
|
|
18
|
-
// Redis/PG, no hub, no network.
|
|
19
|
-
|
|
20
|
-
const { expect } = require('chai');
|
|
21
|
-
const { createMockRedis } = require('./mocks/redis-mock');
|
|
22
|
-
const { bindHostModules, clearHostBindings } = require('../src/host/host-bindings');
|
|
23
|
-
|
|
24
|
-
const BOOK = 'test-stage116-book';
|
|
25
|
-
const CHAPTER = 'ch-stage116';
|
|
26
|
-
const SCENE = 'sc-stage116';
|
|
27
|
-
const BUILD = 'build_test-stage116-book';
|
|
28
|
-
|
|
29
|
-
describe('Stage 116 (D3): capacity deferral (bounded retry/backoff)', () => {
|
|
30
|
-
let redis;
|
|
31
|
-
let dispatchEngine;
|
|
32
|
-
let journalEvents;
|
|
33
|
-
let executorCalls;
|
|
34
|
-
let executorResult;
|
|
35
|
-
let rollbacks;
|
|
36
|
-
|
|
37
|
-
beforeEach(async () => {
|
|
38
|
-
redis = createMockRedis();
|
|
39
|
-
journalEvents = [];
|
|
40
|
-
executorCalls = 0;
|
|
41
|
-
rollbacks = [];
|
|
42
|
-
executorResult = { dispatched: false, jobs: 0, reason: 'no_worker_available', retryable: true };
|
|
43
|
-
|
|
44
|
-
clearHostBindings();
|
|
45
|
-
bindHostModules({
|
|
46
|
-
journal: () => ({
|
|
47
|
-
appendSceneEvent: async (r, b, c, s, type, state, details) => {
|
|
48
|
-
journalEvents.push({ type, state, details });
|
|
49
|
-
return true;
|
|
50
|
-
},
|
|
51
|
-
}),
|
|
52
|
-
seams: () => ({
|
|
53
|
-
getOrchestrationSeam: (name) => {
|
|
54
|
-
if (name === 'dispatchStage') {
|
|
55
|
-
return async () => {
|
|
56
|
-
executorCalls++;
|
|
57
|
-
return executorResult;
|
|
58
|
-
};
|
|
59
|
-
}
|
|
60
|
-
if (name === 'rollbackStageToPending') {
|
|
61
|
-
return async (r, b, c, s, stage, buildId, reason) => {
|
|
62
|
-
rollbacks.push({ stage, reason });
|
|
63
|
-
return { changed: true };
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
throw new Error(`[stage116-test] seam not wired: ${name}`);
|
|
67
|
-
},
|
|
68
|
-
}),
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
dispatchEngine = require('../src/runtime/dispatch-engine');
|
|
72
|
-
});
|
|
73
|
-
|
|
74
|
-
afterEach(() => {
|
|
75
|
-
clearHostBindings();
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
const dispatch = () => dispatchEngine.dispatchStage(
|
|
79
|
-
redis, BOOK, CHAPTER, SCENE, 'image', { book_id: BOOK }, BUILD
|
|
80
|
-
);
|
|
81
|
-
|
|
82
|
-
it('a stage that enqueued nothing is deferred and reported as retryable', async () => {
|
|
83
|
-
const result = await dispatch();
|
|
84
|
-
expect(result.dispatched).to.equal(false);
|
|
85
|
-
expect(result.reason).to.equal('no_worker_available');
|
|
86
|
-
expect(result.retryable).to.equal(true);
|
|
87
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(true);
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
it('a deferred stage is NOT re-dispatched on the next tick (no side effects)', async () => {
|
|
91
|
-
await dispatch(); // attempt 1 — really attempted
|
|
92
|
-
const callsAfterFirst = executorCalls;
|
|
93
|
-
const journalAfterFirst = journalEvents.length;
|
|
94
|
-
|
|
95
|
-
// the next scheduler tick (5 s later) must be a no-op
|
|
96
|
-
const second = await dispatch();
|
|
97
|
-
expect(second.dispatched).to.equal(false);
|
|
98
|
-
expect(second.reason).to.equal('deferred_capacity');
|
|
99
|
-
expect(second.retryable).to.equal(true);
|
|
100
|
-
expect(executorCalls).to.equal(callsAfterFirst); // executor NOT called
|
|
101
|
-
expect(journalEvents.length).to.equal(journalAfterFirst); // no journal event
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
it('100 scheduler ticks inside the deferral window ⇒ ONE attempt (bounded churn)', async () => {
|
|
105
|
-
await dispatch();
|
|
106
|
-
for (let i = 0; i < 99; i++) await dispatch();
|
|
107
|
-
expect(executorCalls).to.equal(1);
|
|
108
|
-
// the journal must not grow with the tick count (bounded, not unbounded)
|
|
109
|
-
const journalAfterLoop = journalEvents.length;
|
|
110
|
-
expect(journalAfterLoop).to.be.lessThan(10);
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
it('the deferral window expires ⇒ the stage is dispatched again', async () => {
|
|
114
|
-
await dispatch();
|
|
115
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(true);
|
|
116
|
-
// simulate the TTL elapsing (the mock keeps keys until told otherwise)
|
|
117
|
-
await redis.del(dispatchEngine.deferredStageKey(BOOK, CHAPTER, SCENE, 'image'));
|
|
118
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(false);
|
|
119
|
-
|
|
120
|
-
executorResult = { dispatched: true, jobs: 2, reason: null };
|
|
121
|
-
const result = await dispatch();
|
|
122
|
-
expect(result.dispatched).to.equal(true);
|
|
123
|
-
expect(executorCalls).to.equal(2);
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
it('a successful dispatch clears the deferral', async () => {
|
|
127
|
-
await dispatch(); // deferred
|
|
128
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(true);
|
|
129
|
-
await redis.del(dispatchEngine.deferredStageKey(BOOK, CHAPTER, SCENE, 'image'));
|
|
130
|
-
executorResult = { dispatched: true, jobs: 1, reason: null };
|
|
131
|
-
await dispatch();
|
|
132
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(false);
|
|
133
|
-
});
|
|
134
|
-
|
|
135
|
-
it('an explicit cancel clears the deferral (the user asked for the work)', async () => {
|
|
136
|
-
await dispatch();
|
|
137
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(true);
|
|
138
|
-
await dispatchEngine.cancelActiveDispatch(redis, BOOK, CHAPTER, SCENE, 'image', 'user_cancel');
|
|
139
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(false);
|
|
140
|
-
});
|
|
141
|
-
|
|
142
|
-
it('a deferred attempt does NOT consume the retry budget (it is not a failure)', async () => {
|
|
143
|
-
const budgetKey = `animastor:retry-budget:${BOOK}:${CHAPTER}:${SCENE}:image`;
|
|
144
|
-
await redis.set(budgetKey, '3');
|
|
145
|
-
await dispatch();
|
|
146
|
-
const after = await redis.get(budgetKey);
|
|
147
|
-
expect(after).to.equal('3'); // unchanged — no budget consumed
|
|
148
|
-
});
|
|
149
|
-
|
|
150
|
-
it('a deferred attempt is not reported as a failure (retryable, not fatal)', async () => {
|
|
151
|
-
const result = await dispatch();
|
|
152
|
-
expect(result.dispatched).to.equal(false);
|
|
153
|
-
expect(result.reason).to.equal('no_worker_available');
|
|
154
|
-
expect(result.retryable).to.equal(true);
|
|
155
|
-
// the dispatch engine must not have marked the stage as failed
|
|
156
|
-
expect(result.result && result.result.retryable).to.equal(true);
|
|
157
|
-
});
|
|
158
|
-
|
|
159
|
-
it('the deferral is per stage — another stage of the same scene is not blocked', async () => {
|
|
160
|
-
await dispatch(); // image stage deferred
|
|
161
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(true);
|
|
162
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'video')).to.equal(false);
|
|
163
|
-
expect(await dispatchEngine.isStageDeferred(redis, 'other-book', CHAPTER, SCENE, 'image')).to.equal(false);
|
|
164
|
-
});
|
|
165
|
-
|
|
166
|
-
it('deferrable outcomes are classified explicitly (capacity only)', () => {
|
|
167
|
-
expect(dispatchEngine.isDeferrableOutcome('no_worker_available')).to.equal(true);
|
|
168
|
-
expect(dispatchEngine.isDeferrableOutcome('duplicate_pending')).to.equal(true);
|
|
169
|
-
expect(dispatchEngine.isDeferrableOutcome('ambiguous_post')).to.equal(true);
|
|
170
|
-
// Stage 118 (M4): 'already_completed' is NOT a capacity gap — the
|
|
171
|
-
// logical task is already complete. It stays deferrable (the stage
|
|
172
|
-
// must not spin) but in its OWN bucket with its own window.
|
|
173
|
-
expect(dispatchEngine.isCapacityOutcome('already_completed')).to.equal(false);
|
|
174
|
-
expect(dispatchEngine.isIdempotentOutcome('already_completed')).to.equal(true);
|
|
175
|
-
expect(dispatchEngine.isDeferrableOutcome('already_completed')).to.equal(true);
|
|
176
|
-
// the generic "sent nothing" outcomes keep their historic contract
|
|
177
|
-
// (immediate retry) — the audit-6929ba5 regressions depend on it
|
|
178
|
-
expect(dispatchEngine.isDeferrableOutcome('no_jobs_sent')).to.equal(false);
|
|
179
|
-
expect(dispatchEngine.isDeferrableOutcome('no_jobs_generated')).to.equal(false);
|
|
180
|
-
expect(dispatchEngine.isDeferrableOutcome('send_failed')).to.equal(false);
|
|
181
|
-
expect(dispatchEngine.isDeferrableOutcome('already_ready')).to.equal(false);
|
|
182
|
-
expect(dispatchEngine.isDeferrableOutcome('circuit_open')).to.equal(false);
|
|
183
|
-
});
|
|
184
|
-
|
|
185
|
-
it('the deferral window is bounded (not a permanent block)', () => {
|
|
186
|
-
expect(dispatchEngine.DEFERRED_STAGE_TTL_S).to.be.a('number');
|
|
187
|
-
expect(dispatchEngine.DEFERRED_STAGE_TTL_S).to.be.greaterThan(0);
|
|
188
|
-
expect(dispatchEngine.DEFERRED_STAGE_TTL_S).to.be.lessThanOrEqual(600);
|
|
189
|
-
// the key lives under the runtime namespace (backend-owned family)
|
|
190
|
-
expect(dispatchEngine.DEFERRED_STAGE_KEY_PREFIX).to.equal('animastor:runtime:deferred:');
|
|
191
|
-
});
|
|
192
|
-
|
|
193
|
-
// ── Stage 118 (audit 117) ─────────────────────────────────────────────
|
|
194
|
-
describe('Stage 118: audit 117 corrections', () => {
|
|
195
|
-
it('M2: force mode does NOT bypass the deferral', async () => {
|
|
196
|
-
await dispatch(); // deferred (capacity)
|
|
197
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(true);
|
|
198
|
-
const callsBefore = executorCalls;
|
|
199
|
-
// The force-dispatch flag lives for 120 s and is set for the WHOLE
|
|
200
|
-
// book by /regenerate — bypassing the backoff there reproduced the
|
|
201
|
-
// very churn D3 removes (≈24 full attempts per scene).
|
|
202
|
-
const forced = await dispatchEngine.dispatchStage(
|
|
203
|
-
redis, BOOK, CHAPTER, SCENE, 'image', { book_id: BOOK }, BUILD, { force: true }
|
|
204
|
-
);
|
|
205
|
-
expect(forced.dispatched).to.equal(false);
|
|
206
|
-
expect(forced.reason).to.equal('deferred_capacity');
|
|
207
|
-
expect(forced.deferred).to.equal(true);
|
|
208
|
-
expect(executorCalls).to.equal(callsBefore); // no side effect
|
|
209
|
-
});
|
|
210
|
-
|
|
211
|
-
it('M4: the idempotent suppression gets its OWN (longer) window', async () => {
|
|
212
|
-
executorResult = { dispatched: false, jobs: 0, reason: 'already_completed', retryable: true };
|
|
213
|
-
await dispatch();
|
|
214
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(true);
|
|
215
|
-
expect(dispatchEngine.deferralWindowFor('already_completed'))
|
|
216
|
-
.to.equal(dispatchEngine.DEFERRED_IDEMPOTENT_TTL_S);
|
|
217
|
-
expect(dispatchEngine.deferralWindowFor('no_worker_available'))
|
|
218
|
-
.to.equal(dispatchEngine.DEFERRED_STAGE_TTL_S);
|
|
219
|
-
expect(dispatchEngine.DEFERRED_IDEMPOTENT_TTL_S)
|
|
220
|
-
.to.be.greaterThan(dispatchEngine.DEFERRED_STAGE_TTL_S);
|
|
221
|
-
});
|
|
222
|
-
|
|
223
|
-
it('M1: a book_id containing ":" cannot reach into another book key space', async () => {
|
|
224
|
-
const bookA = 'a';
|
|
225
|
-
const bookB = 'a:b';
|
|
226
|
-
const chapter = 'ch';
|
|
227
|
-
const scene = 'sc';
|
|
228
|
-
// the deferral key of book 'a' / chapter 'b' must not collide
|
|
229
|
-
// with the key of book 'a:b'
|
|
230
|
-
executorResult = { dispatched: false, jobs: 0, reason: 'no_worker_available', retryable: true };
|
|
231
|
-
await dispatchEngine.dispatchStage(redis, bookA, chapter, scene, 'image', { book_id: bookA }, BUILD);
|
|
232
|
-
expect(await dispatchEngine.isStageDeferred(redis, bookA, chapter, scene, 'image')).to.equal(true);
|
|
233
|
-
expect(await dispatchEngine.isStageDeferred(redis, bookB, chapter, scene, 'image')).to.equal(false);
|
|
234
|
-
expect(dispatchEngine.deferredStageKey(bookA, chapter, scene, 'image'))
|
|
235
|
-
.to.not.equal(dispatchEngine.deferredStageKey(bookB, chapter, scene, 'image'));
|
|
236
|
-
});
|
|
237
|
-
|
|
238
|
-
it('M2: an explicit intent clears the backoff of a book / a scene', async () => {
|
|
239
|
-
await dispatch();
|
|
240
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(true);
|
|
241
|
-
const cleared = await dispatchEngine.clearDeferralsForBook(redis, BOOK);
|
|
242
|
-
expect(cleared).to.be.greaterThan(0);
|
|
243
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(false);
|
|
244
|
-
|
|
245
|
-
await dispatch();
|
|
246
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(true);
|
|
247
|
-
await dispatchEngine.clearDeferralsForScene(redis, BOOK, CHAPTER, SCENE);
|
|
248
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(false);
|
|
249
|
-
// a sibling book is untouched
|
|
250
|
-
await dispatchEngine.dispatchStage(redis, 'other-book', CHAPTER, SCENE, 'image', { book_id: 'other-book' }, BUILD);
|
|
251
|
-
await dispatchEngine.clearDeferralsForBook(redis, 'other-book');
|
|
252
|
-
expect(await dispatchEngine.isStageDeferred(redis, BOOK, CHAPTER, SCENE, 'image')).to.equal(false);
|
|
253
|
-
});
|
|
254
|
-
|
|
255
|
-
it('M3: several deferrable reasons are classified (the dominant one is reported)', () => {
|
|
256
|
-
const { classifyNotSentReasons } = require('../src/runtime/dispatch-outcomes');
|
|
257
|
-
expect(classifyNotSentReasons(new Map([['no_worker_available', 3], ['duplicate_pending', 1]])))
|
|
258
|
-
.to.equal('no_worker_available');
|
|
259
|
-
// a real failure keeps the historic semantics
|
|
260
|
-
expect(classifyNotSentReasons(new Map([['no_worker_available', 3], ['send_failed', 1]])))
|
|
261
|
-
.to.equal(null);
|
|
262
|
-
expect(classifyNotSentReasons(new Map())).to.equal(null);
|
|
263
|
-
});
|
|
264
|
-
});
|
|
265
|
-
});
|