@animastor/orchestration 0.3.5 → 1.1.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 +101 -0
  2. package/README.md +37 -0
  3. package/package.json +11 -8
  4. package/src/gen/accept.js +425 -0
  5. package/src/gen/claim.js +155 -0
  6. package/src/gen/commands.js +367 -0
  7. package/src/gen/index.js +110 -0
  8. package/src/gen/local-runner.js +80 -0
  9. package/src/gen/ports.js +169 -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 +368 -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 +17 -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,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
- });
@@ -1,164 +0,0 @@
1
- // ======================================================
2
- // Counter Reconciliation Tests (B10 verification)
3
- // ======================================================
4
-
5
- const { expect } = require('chai');
6
- const { createMockRedis } = require('./mocks/redis-mock');
7
- const counterReconciliation = require('../src/runtime/counter-reconciliation');
8
-
9
- describe('Counter Reconciliation', () => {
10
- let redis;
11
-
12
- beforeEach(() => {
13
- redis = createMockRedis();
14
- });
15
-
16
- // ── correctCounterWithLua ─────────────────────────
17
- describe('correctCounterWithLua (B10 regression)', () => {
18
- it('corrects a drifted counter value', async () => {
19
- // Simulate drift: counter says 5, but only 3 leases exist
20
- await redis.set('animastor:runtime:active-audio', '5');
21
-
22
- const result = await counterReconciliation.correctCounterWithLua(redis, 'audio', 3);
23
- expect(result.success).to.equal(true);
24
- expect(result.action).to.equal('corrected');
25
- expect(result.old).to.equal('5');
26
- expect(result.new).to.equal('3');
27
-
28
- // Verify the counter was actually corrected
29
- const val = await redis.get('animastor:runtime:active-audio');
30
- expect(val).to.equal('3');
31
- });
32
-
33
- it('corrects when counter is zero but leases exist', async () => {
34
- // Drift: counter is 0, but lease scan finds 2
35
- // Actually the correct behavior is: counter is too LOW
36
- await redis.set('animastor:runtime:active-image', '0');
37
-
38
- const result = await counterReconciliation.correctCounterWithLua(redis, 'image', 2);
39
- expect(result.success).to.equal(true);
40
- expect(result.old).to.equal('0');
41
- expect(result.new).to.equal('2');
42
-
43
- const val = await redis.get('animastor:runtime:active-image');
44
- expect(val).to.equal('2');
45
- });
46
-
47
- it('corrects when counter key does not exist', async () => {
48
- const result = await counterReconciliation.correctCounterWithLua(redis, 'video', 1);
49
- expect(result.success).to.equal(true);
50
- expect(result.old).to.equal(null);
51
-
52
- const val = await redis.get('animastor:runtime:active-video');
53
- expect(val).to.equal('1');
54
- });
55
-
56
- it('B10 bug: ioredis null → "" no longer causes silent no-op', async () => {
57
- // This test verifies that the fix for B10 works:
58
- // Previously, correctCounterWithLua passed `null` as an "expected" guard arg,
59
- // which ioredis serialized to "" (truthy in Lua), causing the guard to
60
- // always fire and skip the SET. The guard was removed.
61
- await redis.set('animastor:runtime:active-audio', '10');
62
-
63
- const result = await counterReconciliation.correctCounterWithLua(redis, 'audio', 7);
64
- expect(result.success).to.equal(true);
65
- expect(result.old).to.equal('10');
66
- expect(result.new).to.equal('7');
67
- });
68
- });
69
-
70
- // ── getCounterWithDriftCheck ──────────────────────
71
- describe('getCounterWithDriftCheck', () => {
72
- it('reports no drift when counter matches lease count', async () => {
73
- const result = await counterReconciliation.getCounterWithDriftCheck(redis, 'audio');
74
- expect(result.stage).to.equal('audio');
75
- expect(result.leaseCount).to.equal(0);
76
- expect(result.counterValue).to.equal(0);
77
- expect(result.drift).to.equal(0);
78
- expect(result.correct).to.equal(true);
79
- });
80
-
81
- it('detects positive drift (counter > actual leases)', async () => {
82
- // Set counter higher with no leases
83
- await redis.set('animastor:runtime:active-audio', '3');
84
-
85
- const result = await counterReconciliation.getCounterWithDriftCheck(redis, 'audio');
86
- expect(result.drift).to.equal(3);
87
- expect(result.correct).to.equal(false);
88
- expect(result.counterValue).to.equal(3);
89
- expect(result.leaseCount).to.equal(0);
90
- });
91
- });
92
-
93
- // ── reconcileCounters ─────────────────────────────
94
- describe('reconcileCounters', () => {
95
- it('reports no corrections when counters are balanced', async () => {
96
- const report = await counterReconciliation.reconcileCounters(redis);
97
-
98
- expect(report.summary.correctedCount).to.equal(0);
99
- expect(report.summary.totalDrift).to.equal(0);
100
- for (const stage of ['audio', 'image', 'video']) {
101
- expect(report.stages[stage].corrected).to.equal(false);
102
- expect(report.stages[stage].drift).to.equal(0);
103
- }
104
- });
105
-
106
- it('corrects drifted counters across all stages', async () => {
107
- // Create drift: audio=2, image=3, video=1
108
- await redis.set('animastor:runtime:active-audio', '2');
109
- await redis.set('animastor:runtime:active-image', '3');
110
- await redis.set('animastor:runtime:active-video', '1');
111
-
112
- const report = await counterReconciliation.reconcileCounters(redis);
113
-
114
- // All 3 should be corrected to 0 (no leases in mock)
115
- expect(report.summary.correctedCount).to.equal(3);
116
-
117
- // Verify counters are corrected
118
- expect(await redis.get('animastor:runtime:active-audio')).to.equal('0');
119
- expect(await redis.get('animastor:runtime:active-image')).to.equal('0');
120
- expect(await redis.get('animastor:runtime:active-video')).to.equal('0');
121
- });
122
-
123
- it('corrects counter even with non-numeric initial value', async () => {
124
- await redis.set('animastor:runtime:active-audio', 'not-a-number');
125
-
126
- const report = await counterReconciliation.reconcileCounters(redis);
127
- // Counter should be corrected to 0 (no leases in mock)
128
- expect(report.stages.audio.corrected).to.equal(true);
129
- expect(await redis.get('animastor:runtime:active-audio')).to.equal('0');
130
- });
131
- });
132
-
133
- // ── countActiveLeasesByStage ──────────────────────
134
- describe('countActiveLeasesByStage', () => {
135
- it('returns 0 when no leases exist', async () => {
136
- const count = await counterReconciliation.countActiveLeasesByStage(redis, 'audio');
137
- expect(count).to.equal(0);
138
- });
139
- });
140
-
141
- // ── getCurrentCounter ────────────────────────────
142
- describe('getCurrentCounter', () => {
143
- it('returns 0 for missing key', async () => {
144
- const val = await counterReconciliation.getCurrentCounter(redis, 'audio');
145
- expect(val).to.equal(0);
146
- });
147
-
148
- it('returns stored integer value', async () => {
149
- await redis.set('animastor:runtime:active-audio', '42');
150
- const val = await counterReconciliation.getCurrentCounter(redis, 'audio');
151
- expect(val).to.equal(42);
152
- });
153
- });
154
-
155
- // ── manualCounterCorrection ───────────────────────
156
- describe('manualCounterCorrection', () => {
157
- it('sets counter to exact value', async () => {
158
- await redis.set('animastor:runtime:active-audio', '99');
159
- const result = await counterReconciliation.manualCounterCorrection(redis, 'audio', 5);
160
- expect(result.success).to.equal(true);
161
- expect(await redis.get('animastor:runtime:active-audio')).to.equal('5');
162
- });
163
- });
164
- });
@@ -1,231 +0,0 @@
1
- // In-memory Redis mock for tests.
2
- // Operations are internally consistent: hset/hget/hgetall use flat `key:field` storage,
3
- // scan filters the store by glob pattern, lrange handles stop=-1.
4
-
5
- function globToRegex(pattern) {
6
- let regexStr = '^';
7
- for (const ch of pattern) {
8
- if (ch === '*') regexStr += '.*';
9
- else if (ch === '?') regexStr += '.';
10
- else if ('[](){}+.^$|\\'.includes(ch)) regexStr += '\\' + ch;
11
- else regexStr += ch;
12
- }
13
- regexStr += '$';
14
- return new RegExp(regexStr);
15
- }
16
-
17
- function createMockRedis() {
18
- const store = new Map();
19
- // Recorded TTLs (seconds) so ttl() can report them. Keys are NOT
20
- // auto-expired — existing tests rely on keys persisting. Tests simulate
21
- // renewal / decay by calling set(...,'EX',n) or expire(key, n).
22
- const expiries = new Map();
23
- const recordExpiry = (key, args) => {
24
- const i = args.indexOf('EX');
25
- if (i !== -1 && args[i + 1] !== undefined) expiries.set(key, Number(args[i + 1]));
26
- };
27
- return {
28
- hset: async (key, field, value) => {
29
- if (field && typeof field === 'object' && !Array.isArray(field)) {
30
- for (const [name, fieldValue] of Object.entries(field)) {
31
- store.set(`${key}:${name}`, fieldValue);
32
- }
33
- return Object.keys(field).length;
34
- }
35
- store.set(`${key}:${field}`, value);
36
- return 1;
37
- },
38
- hget: async (key, field) => store.get(`${key}:${field}`) || null,
39
- hgetall: async (key) => {
40
- const result = {};
41
- const prefix = key + ':';
42
- for (const [k, v] of store) {
43
- if (k.startsWith(prefix)) {
44
- result[k.slice(prefix.length)] = v;
45
- }
46
- }
47
- return Object.keys(result).length > 0 ? result : null;
48
- },
49
- hdel: async (key, ...fields) => {
50
- let n = 0;
51
- for (const field of fields) {
52
- if (store.delete(`${key}:${field}`)) n++;
53
- }
54
- return n;
55
- },
56
- hlen: async (key) => {
57
- const prefix = key + ':';
58
- let n = 0;
59
- for (const k of store.keys()) if (k.startsWith(prefix)) n++;
60
- return n;
61
- },
62
- hexists: async (key, field) => store.has(`${key}:${field}`) ? 1 : 0,
63
- get: async (key) => store.get(key) || null,
64
- set: async (key, value, ...args) => {
65
- const nx = args.includes('NX');
66
- if (nx && store.has(key)) return null;
67
- store.set(key, value);
68
- recordExpiry(key, args);
69
- return 'OK';
70
- },
71
- del: async (...keys) => { let n = 0; for (const k of keys) { expiries.delete(k); if (store.delete(k)) n++; } return n; },
72
- expire: async (key, ttl) => {
73
- if (!store.has(key)) return 0;
74
- expiries.set(key, Number(ttl));
75
- return 1;
76
- },
77
- // Mirrors ioredis: -2 if key missing, -1 if no expiry, else seconds.
78
- ttl: async (key) => {
79
- if (!store.has(key)) return -2;
80
- return expiries.has(key) ? expiries.get(key) : -1;
81
- },
82
- incr: async (key) => { const v = (parseInt(store.get(key) || '0', 10)) + 1; store.set(key, String(v)); return v; },
83
- incrby: async (key, increment) => { const v = (parseInt(store.get(key) || '0', 10)) + Number(increment || 0); store.set(key, String(v)); return v; },
84
- decr: async (key) => { const v = Math.max(0, (parseInt(store.get(key) || '0', 10)) - 1); store.set(key, String(v)); return v; },
85
- exists: async (key) => store.has(key) ? 1 : 0,
86
- scan: async (cursor, ...args) => {
87
- let pattern = null;
88
- for (let i = 0; i < args.length; i++) {
89
- if (args[i] === 'MATCH') pattern = args[i + 1];
90
- }
91
- if (!pattern) return ['0', []];
92
- const regex = globToRegex(pattern);
93
- const matched = [...store.keys()].filter(k => regex.test(k));
94
- return ['0', matched];
95
- },
96
- hscan: async (key, cursor, ...args) => {
97
- const prefix = key + ':';
98
- const entries = [];
99
- for (const [k, v] of store) {
100
- if (k.startsWith(prefix)) {
101
- entries.push(k.slice(prefix.length), v);
102
- }
103
- }
104
- return ['0', entries];
105
- },
106
- eval: async (script, keysCount, ...args) => {
107
- // reconcile-quota-leak: dispatch-engine.markDispatchJobsEnqueued
108
- // compare-and-set (KEYS=[metaKey], ARGV=[expectedRaw, newRaw]).
109
- if (script.includes('KEEPTTL') && script.includes('raw ~= ARGV[1]')) {
110
- const key = args[0];
111
- const [expected, next] = args.slice(keysCount);
112
- const raw = store.get(key);
113
- if (raw === undefined || raw !== expected) return 0;
114
- store.set(key, next);
115
- return 1;
116
- }
117
- if (script.includes('local metadata') && script.includes("ARGV[5] == '1'")) {
118
- const [metadataKey, completedKey, leaseKey, quotaKey] = args.slice(0, keysCount);
119
- const [
120
- expectedMetadata,
121
- markerValue,
122
- markerTtl,
123
- expectedLease,
124
- quotaOwned,
125
- ] = args.slice(keysCount);
126
- const metadata = store.get(metadataKey);
127
- if (metadata === undefined) return store.has(completedKey) ? 2 : 0;
128
- if (metadata !== expectedMetadata) return -1;
129
- const lease = store.get(leaseKey);
130
- if (lease !== undefined && (!expectedLease || lease !== expectedLease)) return -2;
131
- if (store.has(completedKey)) return 2;
132
-
133
- store.set(completedKey, markerValue);
134
- store.delete(metadataKey);
135
- expiries.delete(metadataKey);
136
- if (lease !== undefined && expectedLease) {
137
- store.delete(leaseKey);
138
- expiries.delete(leaseKey);
139
- }
140
- if (quotaOwned === '1') {
141
- const current = Number(store.get(quotaKey) || 0);
142
- if (current > 0) store.set(quotaKey, String(current - 1));
143
- }
144
- void markerTtl;
145
- return 1;
146
- }
147
- // Lease renewal (lease-manager.renewLeaseIfOwner): compare-and-EXPIRE.
148
- // KEYS=[leaseKey, metadataKey], ARGV=[expectedToken, ttl, now].
149
- if (script.includes('ttl_add') && script.includes('EXPIRE')) {
150
- const leaseKey = args[0];
151
- const metadataKey = args[1];
152
- const expected = args[keysCount];
153
- const ttlAdd = Number(args[keysCount + 1]);
154
- const now = args[keysCount + 2];
155
- const current = store.get(leaseKey);
156
- if (current === undefined) return ['false', 'no_lease'];
157
- if (current !== expected) return ['false', 'token_mismatch', current];
158
- expiries.set(leaseKey, ttlAdd);
159
- if (store.has(metadataKey)) expiries.set(metadataKey, ttlAdd);
160
- return ['true', 'renewed', String(now)];
161
- }
162
- if (script.includes("current ~= ARGV[1]") && script.includes("redis.call('DEL', KEYS[1])")) {
163
- const key = args[0];
164
- const expected = args[keysCount];
165
- const current = store.get(key);
166
- if (current === undefined) return 0;
167
- if (current !== expected) return -1;
168
- store.delete(key);
169
- expiries.delete(key);
170
- return 1;
171
- }
172
- if (script.includes("return redis.call('INCR', key)")) {
173
- const key = args[0];
174
- const max = Number(args[keysCount]);
175
- const current = Number(store.get(key) || 0);
176
- if (current >= max) return 0;
177
- const next = current + 1;
178
- store.set(key, String(next));
179
- return next;
180
- }
181
- // Return array mimicking Lua return: {true, 'corrected', old, new}
182
- // Callers (e.g. correctCounterWithLua) destructure result[0]..result[3]
183
- const key = args[0];
184
- const target = args[keysCount] || args[1];
185
- let current = store.get(key);
186
- if (current === undefined) current = null;
187
- store.set(key, target);
188
- return ['true', 'corrected', current, target];
189
- },
190
- rpush: async (key, ...values) => { const arr = store.get(key) || []; arr.push(...values); store.set(key, arr); return arr.length; },
191
- lpush: async (key, ...values) => { const arr = store.get(key) || []; arr.unshift(...values); store.set(key, arr); return arr.length; },
192
- rpoplpush: async (source, destination) => {
193
- const arr = store.get(source);
194
- if (!arr || arr.length === 0) return null;
195
- const value = arr.pop();
196
- if (arr.length === 0) store.delete(source);
197
- const dest = store.get(destination) || [];
198
- dest.unshift(value);
199
- store.set(destination, dest);
200
- return value;
201
- },
202
- llen: async (key) => { const arr = store.get(key); return arr ? arr.length : 0; },
203
- lrange: async (key, start, stop) => {
204
- const arr = store.get(key) || [];
205
- if (stop === -1 || stop === undefined) return arr.slice(start);
206
- return arr.slice(start, stop + 1);
207
- },
208
- lrem: async (key, count, value) => {
209
- const arr = store.get(key) || [];
210
- const index = arr.indexOf(value);
211
- if (index === -1) return 0;
212
- arr.splice(index, 1);
213
- return 1;
214
- },
215
- sadd: async (key, member) => { const s = store.get(key) || new Set(); s.add(member); store.set(key, s); return 1; },
216
- srem: async (key, member) => { const s = store.get(key); if (s) { s.delete(member); return 1; } return 0; },
217
- smembers: async (key) => { const s = store.get(key); return s ? [...s] : []; },
218
- scard: async (key) => { const s = store.get(key); return s ? s.size : 0; },
219
- zrem: async (key, member) => {
220
- const s = store.get(key);
221
- if (s && s instanceof Set) { return s.delete(member) ? 1 : 0; }
222
- return 0;
223
- },
224
- multi: () => ({ exec: async () => [] }),
225
- quit: async () => 'OK',
226
- disconnect: () => {},
227
- duplicate: () => createMockRedis(),
228
- };
229
- }
230
-
231
- module.exports = { createMockRedis };