@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
@@ -0,0 +1,155 @@
1
+ // ======================================================
2
+ // gen/claim — hand work to a worker (ADR §8.1) + beacon (§8.3)
3
+ // ======================================================
4
+ // One SQL statement picks and takes the job: FOR UPDATE SKIP LOCKED, so two
5
+ // concurrent claims never get the same row. Order: the worker's own lane
6
+ // first (private → borrowed share lane, as gpu-hub pop), then fairness —
7
+ // the workspace with the fewest running jobs — then age.
8
+ //
9
+ // shared_limit (§10, §13.3): how many jobs of ONE workspace may run at once
10
+ // on shared GPUs (lanes system/policy). NULL = off. Private lanes: no limit.
11
+
12
+ 'use strict';
13
+
14
+ const {
15
+ GenError, withTx, requireUuid, isUuid, issueUploadToken, notifyProgress, KINDS, WORKER_TYPES,
16
+ } = require('./util');
17
+
18
+ const MODES = Object.freeze(['private', 'share', 'system']);
19
+
20
+ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, tokenGraceMs = 15 * 60_000 }) {
21
+ const timeoutsJson = JSON.stringify(Object.fromEntries(KINDS.map((k) => [k, ports.timeoutFor(k)])));
22
+
23
+ /**
24
+ * @param {object} p
25
+ * @param {string} p.workerId
26
+ * @param {'audio'|'image'|'video'} p.workerType
27
+ * @param {'private'|'share'|'system'} p.mode
28
+ * @param {string|null} [p.workspaceId] required for mode=private
29
+ * @param {string[]} [p.policyIds] users-share policies the worker serves (borrowed lane)
30
+ * @param {boolean} [p.sharePublic] private worker with a public share policy borrows the system lane
31
+ * @param {number|null} [p.sharedLimit] overrides the module setting for this call
32
+ * @returns {Promise<{task:null}|{task:object}>}
33
+ */
34
+ async function claim(p = {}) {
35
+ const workerId = requireUuid(p.workerId, 'workerId');
36
+ if (!WORKER_TYPES.includes(p.workerType)) throw new GenError('bad_request', 400, 'workerType must be audio|image|video');
37
+ if (!MODES.includes(p.mode)) throw new GenError('bad_request', 400, 'mode must be private|share|system');
38
+ const workspaceId = p.mode === 'private' ? requireUuid(p.workspaceId, 'workspaceId') : null;
39
+ const policyIds = Array.isArray(p.policyIds) ? p.policyIds.filter(isUuid) : [];
40
+ const limit = p.sharedLimit !== undefined ? p.sharedLimit : sharedLimit;
41
+ if (limit !== null && !(Number.isInteger(limit) && limit >= 0)) throw new GenError('bad_request', 400, 'sharedLimit must be NULL or an integer >= 0');
42
+ const executor = `gpu:${p.workerType}`;
43
+
44
+ // lane predicate + rank (0 = own lane, 1 = borrowed spare capacity)
45
+ let laneSql;
46
+ let rankSql;
47
+ if (p.mode === 'private') {
48
+ const borrow = [];
49
+ if (policyIds.length) borrow.push(`(j.lane->>'kind' = 'policy' AND j.lane->>'policy_id' = ANY($5::text[]))`);
50
+ if (p.sharePublic === true) borrow.push(`(j.lane->>'kind' = 'system')`);
51
+ laneSql = `((j.lane->>'kind' = 'private' AND j.lane->>'workspace_id' = $4::text)${borrow.length ? ' OR ' + borrow.join(' OR ') : ''})`;
52
+ rankSql = `(CASE WHEN j.lane->>'kind' = 'private' THEN 0 ELSE 1 END)`;
53
+ } else {
54
+ laneSql = policyIds.length
55
+ ? `(j.lane->>'kind' = 'system' OR (j.lane->>'kind' = 'policy' AND j.lane->>'policy_id' = ANY($5::text[])))`
56
+ : `(j.lane->>'kind' = 'system')`;
57
+ rankSql = '(0)::int';
58
+ }
59
+
60
+ const job = await withTx(pool, async (client) => {
61
+ // the count-then-take of shared_limit must not race with a twin claim
62
+ if (limit !== null) await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [`animastor:gen-v2:claim:${executor}`]);
63
+ const r = await client.query(
64
+ `WITH cand AS (
65
+ SELECT j.job_id
66
+ FROM gen_jobs j
67
+ WHERE j.status = 'queued'
68
+ AND j.executor = $1
69
+ AND j.not_before <= now()
70
+ AND ${laneSql}
71
+ AND ($4::text IS NULL OR $4::text IS NOT NULL) -- bind every parameter's type
72
+ AND ($5::text[] IS NULL OR $5::text[] IS NOT NULL)
73
+ AND ($3::int IS NULL OR j.lane->>'kind' = 'private' OR
74
+ (SELECT count(*) FROM gen_jobs r
75
+ WHERE r.workspace_id = j.workspace_id AND r.status = 'running'
76
+ AND r.executor = j.executor AND r.lane->>'kind' <> 'private') < $3::int)
77
+ ORDER BY ${rankSql},
78
+ (SELECT count(*) FROM gen_jobs r WHERE r.workspace_id = j.workspace_id AND r.status = 'running'),
79
+ j.created_at, j.job_id
80
+ LIMIT 1
81
+ FOR UPDATE OF j SKIP LOCKED
82
+ )
83
+ UPDATE gen_jobs j
84
+ SET status = 'running', attempt = j.attempt + 1, worker_id = $2,
85
+ claimed_at = now(),
86
+ deadline = now() + make_interval(secs => (($6::jsonb)->>j.kind)::numeric / 1000)
87
+ FROM cand
88
+ WHERE j.job_id = cand.job_id
89
+ RETURNING j.*`,
90
+ [executor, workerId, limit, workspaceId, policyIds, timeoutsJson]);
91
+ const row = r.rows[0];
92
+ if (!row) return null;
93
+ await client.query(
94
+ `UPDATE workers SET current_job_id = $2, last_seen = floor(extract(epoch from now()))::bigint
95
+ WHERE worker_id = $1 AND revoked_at IS NULL`, [workerId, row.job_id]);
96
+ await notifyProgress(client, row.book_id, row.command_id);
97
+ return row;
98
+ });
99
+ if (!job) return { task: null };
100
+
101
+ let payload;
102
+ try {
103
+ payload = await ports.buildPayload(job);
104
+ } catch (err) {
105
+ // the payload cannot be built → this attempt fails deterministically (no silent loss)
106
+ await accept.failAttempt(job.job_id, job.attempt, 'deterministic', `build_payload: ${err && err.message}`);
107
+ return { task: null };
108
+ }
109
+ const deadlineMs = new Date(job.deadline).getTime();
110
+ const exp = deadlineMs + tokenGraceMs;
111
+ return {
112
+ task: {
113
+ job_id: job.job_id,
114
+ attempt: job.attempt,
115
+ kind: job.kind,
116
+ book_id: job.book_id,
117
+ chapter_id: job.chapter_id,
118
+ scene_id: job.scene_id,
119
+ unit_key: job.unit_key,
120
+ params: payload,
121
+ timeout_ms: ports.timeoutFor(job.kind),
122
+ deadline: new Date(deadlineMs).toISOString(),
123
+ upload_token: issueUploadToken(uploadSecret, job.job_id, job.attempt, exp),
124
+ },
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Worker liveness (ADR §8.3): last_seen + current_job_id; answer = jobs to stop.
130
+ * cancel = this worker's jobs cancelled in the last hour + the reported
131
+ * current job when it is no longer running for this worker.
132
+ * @returns {Promise<{cancel:string[], known:boolean}>}
133
+ */
134
+ async function beacon(workerId, body = {}) {
135
+ requireUuid(workerId, 'workerId');
136
+ const current = isUuid(body.current_job_id) ? body.current_job_id : null;
137
+ return withTx(pool, async (client) => {
138
+ const upd = await client.query(
139
+ `UPDATE workers SET last_seen = floor(extract(epoch from now()))::bigint, status = 'online', current_job_id = $2
140
+ WHERE worker_id = $1 AND revoked_at IS NULL`, [workerId, current]);
141
+ const r = await client.query(
142
+ `SELECT job_id FROM gen_jobs
143
+ WHERE worker_id = $1 AND status = 'cancelled' AND finished_at > now() - interval '1 hour'
144
+ UNION
145
+ SELECT job_id FROM gen_jobs
146
+ WHERE job_id = $2::uuid AND NOT (status = 'running' AND worker_id = $1)`,
147
+ [workerId, current]);
148
+ return { cancel: r.rows.map((x) => x.job_id), known: upd.rowCount > 0 };
149
+ });
150
+ }
151
+
152
+ return { claim, beacon };
153
+ }
154
+
155
+ module.exports = { createClaim, MODES };
@@ -0,0 +1,367 @@
1
+ // ======================================================
2
+ // gen/commands — create / cancel a user command (ADR §6.1, §6.2, §6.4, §4.2a)
3
+ // ======================================================
4
+ // I1: gen_jobs rows are created ONLY here (first stage) and by stage
5
+ // transitions inside acceptance (§6.3). Nothing else inserts work.
6
+ // I7: every statement is filtered by book / command; there is no
7
+ // "cancel everything" operation.
8
+ // §4.2a: gen_command_jobs records every job a command waits for — the jobs it
9
+ // created AND the live jobs it joined. Progress / completion read only it.
10
+
11
+ 'use strict';
12
+
13
+ const {
14
+ GenError, withTx, requireUuid, requireText, isUuid, notifyProgress, linkJobs,
15
+ EXECUTOR_OF_KIND, LAYER_OF_KIND, FIRST_STAGE_KINDS, LAYERS,
16
+ } = require('./util');
17
+ const { checkLane } = require('./ports');
18
+
19
+ const COMMAND_KINDS = Object.freeze(['regenerate', 'generate_all']);
20
+ const SCOPE_LEVELS = Object.freeze(['book', 'chapter', 'scenes', 'scene', 'unit']);
21
+ const MAX_SCOPE_SCENES = 10_000;
22
+
23
+ function normaliseScope(scope) {
24
+ const s = scope && typeof scope === 'object' ? scope : null;
25
+ if (!s || !SCOPE_LEVELS.includes(s.level)) throw new GenError('bad_request', 400, 'scope.level must be book|chapter|scenes|scene|unit');
26
+ const out = { level: s.level };
27
+ const opt = (k) => { if (s[k] !== undefined && s[k] !== null) out[k] = requireText(s[k], `scope.${k}`); };
28
+ opt('chapter_id'); opt('scene_id'); opt('unit_id');
29
+ if (s.level === 'chapter' && !out.chapter_id) throw new GenError('bad_request', 400, 'scope.chapter_id required for level=chapter');
30
+ if ((s.level === 'scene' || s.level === 'unit') && !out.scene_id) throw new GenError('bad_request', 400, `scope.scene_id required for level=${s.level}`);
31
+ if (s.level === 'unit' && !out.unit_id) throw new GenError('bad_request', 400, 'scope.unit_id required for level=unit');
32
+ if (s.level === 'scenes') {
33
+ // ADR §11.1: an explicit, ordered list of scenes (e.g. «from the current
34
+ // scene to the end», expanded by the host in book order). Order kept,
35
+ // duplicates dropped; chapter_id / scene_id do not apply.
36
+ if (!Array.isArray(s.scene_ids) || s.scene_ids.length === 0) throw new GenError('bad_request', 400, 'scope.scene_ids (non-empty array) required for level=scenes');
37
+ if (s.scene_ids.length > MAX_SCOPE_SCENES) throw new GenError('bad_request', 400, `scope.scene_ids: at most ${MAX_SCOPE_SCENES}`);
38
+ out.scene_ids = [...new Set(s.scene_ids.map((x, i) => requireText(x, `scope.scene_ids[${i}]`)))];
39
+ delete out.chapter_id; delete out.scene_id; delete out.unit_id;
40
+ } else if (s.scene_ids !== undefined) {
41
+ throw new GenError('bad_request', 400, 'scope.scene_ids applies only to level=scenes');
42
+ }
43
+ return out;
44
+ }
45
+
46
+ /** Layers a planned unit may belong to: video work starts with its images (§6.3). */
47
+ function unitFitsLayer(kind, layer) {
48
+ if (LAYER_OF_KIND[kind] === layer) return true;
49
+ return layer === 'video' && kind === 'iu_image';
50
+ }
51
+
52
+ function checkUnit(u, layer) {
53
+ const ok = u && typeof u === 'object'
54
+ && FIRST_STAGE_KINDS.includes(u.kind) && unitFitsLayer(u.kind, layer)
55
+ && typeof u.chapter_id === 'string' && u.chapter_id
56
+ && typeof u.scene_id === 'string' && u.scene_id
57
+ && typeof u.unit_key === 'string' && u.unit_key
58
+ && typeof u.build_id === 'string' && u.build_id
59
+ && u.input && typeof u.input === 'object';
60
+ if (!ok) {
61
+ throw new GenError('bad_plan', 500,
62
+ `planUnits(${layer}) returned an invalid unit: ${JSON.stringify(u && { kind: u.kind, chapter_id: u.chapter_id, scene_id: u.scene_id, unit_key: u.unit_key, build_id: u.build_id })}`);
63
+ }
64
+ }
65
+
66
+ const unitKey = (u) => `${u.chapter_id}\u0000${u.scene_id}\u0000${u.kind}\u0000${u.unit_key}`;
67
+
68
+ /**
69
+ * Book deletion: remove every gen_* row of the book (one transaction).
70
+ * Usable without an orchestration instance (master flag off).
71
+ * @returns {Promise<{commands:number, jobs:number, links:number, build_ids:string[], job_ids:string[]}>}
72
+ */
73
+ async function purgeBookRows(pool, bookId) {
74
+ requireText(bookId, 'bookId');
75
+ return withTx(pool, async (client) => {
76
+ const jobsOf = (await client.query(
77
+ 'SELECT job_id, build_id FROM gen_jobs WHERE book_id = $1', [bookId])).rows;
78
+ const links = await client.query(
79
+ `DELETE FROM gen_command_jobs l
80
+ WHERE l.command_id IN (SELECT command_id FROM gen_commands WHERE book_id = $1)
81
+ OR l.job_id IN (SELECT job_id FROM gen_jobs WHERE book_id = $1)`, [bookId]);
82
+ const jobs = await client.query('DELETE FROM gen_jobs WHERE book_id = $1', [bookId]);
83
+ const commands = await client.query('DELETE FROM gen_commands WHERE book_id = $1', [bookId]);
84
+ return {
85
+ commands: commands.rowCount, jobs: jobs.rowCount, links: links.rowCount,
86
+ build_ids: [...new Set(jobsOf.map((r) => r.build_id))], job_ids: jobsOf.map((r) => r.job_id),
87
+ };
88
+ });
89
+ }
90
+
91
+ function createCommands({ pool, ports }) {
92
+ /**
93
+ * ADR §6.1 — one transaction.
94
+ * @returns {Promise<{command_id:string, created:boolean, existing:boolean, status:string, layers:string[],
95
+ * summary:{jobs_created:number, joined:number, skipped_ready:number}}>}
96
+ */
97
+ async function createCommand(params = {}) {
98
+ const workspaceId = requireUuid(params.workspaceId, 'workspaceId');
99
+ const userId = requireUuid(params.userId, 'userId');
100
+ const bookId = requireText(params.bookId, 'bookId');
101
+ const kind = params.kind || 'regenerate';
102
+ if (!COMMAND_KINDS.includes(kind)) throw new GenError('bad_request', 400, `kind must be ${COMMAND_KINDS.join('|')}`);
103
+ const scope = normaliseScope(params.scope);
104
+ const requested = Array.isArray(params.layers) ? [...new Set(params.layers)] : [];
105
+ if (requested.length === 0 || requested.some((l) => !LAYERS.includes(l))) {
106
+ throw new GenError('bad_request', 400, 'layers must be a non-empty subset of audio|image|video');
107
+ }
108
+ const force = params.force === true;
109
+ const clientActionId = params.clientActionId == null ? null : requireText(params.clientActionId, 'clientActionId', 200);
110
+
111
+ // §6.1 п.2: requested ∩ enabled (host layer-config passed in, or the optional port)
112
+ let effective;
113
+ if (Array.isArray(params.enabledLayers)) {
114
+ effective = requested.filter((l) => params.enabledLayers.includes(l));
115
+ } else {
116
+ effective = [];
117
+ for (const l of requested) if (await ports.isLayerEnabled(bookId, l)) effective.push(l);
118
+ }
119
+
120
+ return withTx(pool, async (client) => {
121
+ const book = (await client.query(
122
+ 'SELECT book_id, workspace_id, orchestration FROM books WHERE book_id = $1 FOR SHARE', [bookId])).rows[0];
123
+ if (!book) throw new GenError('book_not_found', 404, `book ${bookId} not found`);
124
+ if (book.workspace_id !== workspaceId) throw new GenError('forbidden', 403, 'book belongs to another workspace');
125
+ if (book.orchestration !== 'v2') throw new GenError('book_not_v2', 409, `book ${bookId} is on legacy orchestration`);
126
+
127
+ const existingOf = async () => (await client.query(
128
+ 'SELECT * FROM gen_commands WHERE book_id = $1 AND client_action_id = $2', [bookId, clientActionId])).rows[0] || null;
129
+ const existingResponse = (row) => {
130
+ if (row.workspace_id !== workspaceId) throw new GenError('conflict', 409, 'client_action_id taken');
131
+ return {
132
+ command_id: row.command_id, created: false, existing: true,
133
+ status: row.status, layers: row.layers,
134
+ summary: row.summary || { jobs_created: 0, joined: 0, skipped_ready: 0 },
135
+ };
136
+ };
137
+
138
+ // §6.1 п.1: a repeated click returns the same command (and the same summary)
139
+ if (clientActionId) {
140
+ const prev = await existingOf();
141
+ if (prev) return existingResponse(prev);
142
+ }
143
+ if (effective.length === 0) throw new GenError('layer_disabled', 409, 'all requested layers are disabled');
144
+
145
+ const ins = await client.query(
146
+ `INSERT INTO gen_commands (workspace_id, user_id, book_id, kind, scope, layers, force, client_action_id, created_at)
147
+ VALUES ($1, $2, $3, $4, $5::jsonb, $6::text[], $7, $8, clock_timestamp())
148
+ ON CONFLICT ON CONSTRAINT gen_commands_client_action_uniq DO NOTHING
149
+ RETURNING *`,
150
+ [workspaceId, userId, bookId, kind, JSON.stringify(scope), effective, force, clientActionId]);
151
+ if (ins.rowCount === 0) return existingResponse(await existingOf()); // concurrent twin committed first
152
+ const cmd = ins.rows[0];
153
+
154
+ // §6.1 п.3: plan units per layer
155
+ const bookRef = { bookId, workspaceId, userId };
156
+ const units = [];
157
+ const seen = new Set();
158
+ for (const layer of effective) {
159
+ const planned = await ports.planUnits(bookRef, scope, layer);
160
+ if (!Array.isArray(planned)) throw new GenError('bad_plan', 500, `planUnits(${layer}) must return an array`);
161
+ for (const u of planned) {
162
+ checkUnit(u, layer);
163
+ if (seen.has(unitKey(u))) continue; // video+image may both plan the same IU
164
+ seen.add(unitKey(u));
165
+ units.push(u);
166
+ }
167
+ }
168
+
169
+ // §6.1 п.3: skip units whose scene asset is ready for the current content (PG scene_assets only)
170
+ let skipped = 0;
171
+ let todo = units;
172
+ if (!force && units.length) {
173
+ const k5 = (g) => `${g.chapter_id}\u0000${g.scene_id}\u0000${g.asset_type}\u0000${g.build_id}\u0000${g.scene_hash}`;
174
+ const gkey = (u) => k5({ ...u, asset_type: LAYER_OF_KIND[u.kind] });
175
+ const groups = new Map();
176
+ for (const u of units) {
177
+ if (typeof u.scene_hash !== 'string' || !u.scene_hash) continue; // readiness unprovable → do it
178
+ if (!groups.has(gkey(u))) groups.set(gkey(u), { chapter_id: u.chapter_id, scene_id: u.scene_id, asset_type: LAYER_OF_KIND[u.kind], build_id: u.build_id, scene_hash: u.scene_hash });
179
+ }
180
+ const readyKeys = new Set();
181
+ if (groups.size) {
182
+ const list = [...groups.values()];
183
+ const r = await client.query(
184
+ `SELECT g.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[])
185
+ WITH ORDINALITY AS g(chapter_id, scene_id, asset_type, build_id, scene_hash, ord)
186
+ WHERE EXISTS (SELECT 1 FROM scene_assets a
187
+ WHERE a.book_id = $1 AND a.chapter_id = g.chapter_id AND a.scene_id = g.scene_id
188
+ AND a.asset_type = g.asset_type AND a.build_id = g.build_id
189
+ AND a.status = 'ready' AND a.scene_hash = g.scene_hash)`,
190
+ [bookId, list.map((x) => x.chapter_id), list.map((x) => x.scene_id), list.map((x) => x.asset_type),
191
+ list.map((x) => x.build_id), list.map((x) => x.scene_hash)]);
192
+ for (const row of r.rows) readyKeys.add(k5(list[Number(row.ord) - 1]));
193
+ }
194
+ todo = units.filter((u) => {
195
+ if (typeof u.scene_hash !== 'string' || !u.scene_hash) return true;
196
+ if (readyKeys.has(gkey(u))) { skipped += 1; return false; }
197
+ return true;
198
+ });
199
+ // 1.1.0 — part-level readiness (opt-in: the unit carries input.part_hash).
200
+ // A part (e.g. one IU picture) whose accepted snapshot hash is recorded in
201
+ // scene_assets.metadata.gen_parts[unit_key].part_hash for the same build is
202
+ // already done for the current content — skip it even if its scene is not
203
+ // complete («сгенерировать недостающее» = only the missing / changed parts).
204
+ // A row the host marked 'stale' proves nothing. Units without part_hash
205
+ // (audio) keep the scene-level rule above unchanged.
206
+ const parted = todo.filter((u) => typeof u.input.part_hash === 'string' && u.input.part_hash);
207
+ if (parted.length) {
208
+ const r = await client.query(
209
+ `SELECT t.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
210
+ WITH ORDINALITY AS t(chapter_id, scene_id, asset_type, build_id, unit_key, part_hash, ord)
211
+ WHERE EXISTS (SELECT 1 FROM scene_assets a
212
+ WHERE a.book_id = $1 AND a.chapter_id = t.chapter_id AND a.scene_id = t.scene_id
213
+ AND a.asset_type = t.asset_type AND a.build_id = t.build_id
214
+ AND a.status IN ('pending', 'ready')
215
+ AND jsonb_typeof(a.metadata->'gen_parts') = 'object'
216
+ AND a.metadata->'gen_parts'->t.unit_key->>'part_hash' = t.part_hash)`,
217
+ [bookId, parted.map((u) => u.chapter_id), parted.map((u) => u.scene_id), parted.map((u) => LAYER_OF_KIND[u.kind]),
218
+ parted.map((u) => u.build_id), parted.map((u) => u.unit_key), parted.map((u) => u.input.part_hash)]);
219
+ const done = new Set(r.rows.map((row) => parted[Number(row.ord) - 1]));
220
+ if (done.size) {
221
+ skipped += done.size;
222
+ todo = todo.filter((u) => !done.has(u));
223
+ }
224
+ }
225
+ }
226
+
227
+ // lanes, one lookup per worker type (§4.2: computed at creation)
228
+ const laneCache = new Map();
229
+ const laneOf = async (executor) => {
230
+ if (executor === 'local') return null;
231
+ const type = executor.slice(4);
232
+ if (!laneCache.has(type)) {
233
+ const lane = await ports.laneFor(workspaceId, type);
234
+ if (!checkLane(lane)) throw new GenError('bad_lane', 500, `laneFor(${type}) returned an invalid lane`);
235
+ if (lane.kind === 'private' && lane.workspace_id !== workspaceId) {
236
+ throw new GenError('bad_lane', 500, 'private lane must be the book workspace (I7)');
237
+ }
238
+ laneCache.set(type, lane);
239
+ }
240
+ return laneCache.get(type);
241
+ };
242
+
243
+ // §6.1 п.4: insert; a unit live under another command → joined (link to the live job)
244
+ let created = 0;
245
+ let joined = 0;
246
+ if (todo.length) {
247
+ const cols = { ch: [], sc: [], uk: [], kind: [], ex: [], layer: [], build: [], lane: [], max: [], input: [] };
248
+ for (const u of todo) {
249
+ const ex = EXECUTOR_OF_KIND[u.kind];
250
+ const lane = await laneOf(ex);
251
+ cols.ch.push(u.chapter_id); cols.sc.push(u.scene_id); cols.uk.push(u.unit_key);
252
+ cols.kind.push(u.kind); cols.ex.push(ex); cols.layer.push(LAYER_OF_KIND[u.kind]); cols.build.push(u.build_id);
253
+ cols.lane.push(lane ? JSON.stringify(lane) : null);
254
+ cols.max.push(ports.maxAttemptsFor(u.kind));
255
+ cols.input.push(JSON.stringify({ ...u.input, scene_hash: u.scene_hash ?? u.input.scene_hash ?? null }));
256
+ }
257
+ const ins2 = await client.query(
258
+ `INSERT INTO gen_jobs (command_id, workspace_id, user_id, book_id, chapter_id, scene_id, unit_key,
259
+ kind, executor, layer, build_id, lane, max_attempts, input, created_at)
260
+ SELECT $1, $2, $3, $4, t.ch, t.sc, t.uk, t.kind, t.ex, t.layer, t.build, t.lane::jsonb, t.max, t.input::jsonb,
261
+ clock_timestamp() -- strictly increasing in plan order → claim order = plan order
262
+ FROM unnest($5::text[], $6::text[], $7::text[], $8::text[], $9::text[], $10::text[], $11::text[],
263
+ $12::text[], $13::int[], $14::text[])
264
+ WITH ORDINALITY AS t(ch, sc, uk, kind, ex, layer, build, lane, max, input, ord)
265
+ ORDER BY t.ord
266
+ ON CONFLICT (book_id, chapter_id, scene_id, kind, unit_key) WHERE status IN ('queued','running')
267
+ DO NOTHING
268
+ RETURNING job_id`,
269
+ [cmd.command_id, workspaceId, userId, bookId, cols.ch, cols.sc, cols.uk, cols.kind, cols.ex,
270
+ cols.layer, cols.build, cols.lane, cols.max, cols.input]);
271
+ created = ins2.rowCount;
272
+ // live jobs of the same units (ours just inserted + other commands' → joined)
273
+ const live = await client.query(
274
+ `SELECT j.job_id, j.command_id FROM gen_jobs j
275
+ JOIN unnest($2::text[], $3::text[], $4::text[], $5::text[]) AS t(ch, sc, kind, uk)
276
+ ON j.chapter_id = t.ch AND j.scene_id = t.sc AND j.kind = t.kind AND j.unit_key = t.uk
277
+ WHERE j.book_id = $1 AND j.status IN ('queued','running')`,
278
+ [bookId, cols.ch, cols.sc, cols.kind, cols.uk]);
279
+ joined = live.rows.filter((r) => r.command_id !== cmd.command_id).length;
280
+ await linkJobs(client, [cmd.command_id], live.rows.map((r) => r.job_id));
281
+ }
282
+ const summary = { jobs_created: created, joined, skipped_ready: skipped };
283
+ await client.query('UPDATE gen_commands SET summary = $2::jsonb WHERE command_id = $1', [cmd.command_id, JSON.stringify(summary)]);
284
+ await notifyProgress(client, bookId, cmd.command_id);
285
+ return {
286
+ command_id: cmd.command_id, created: true, existing: false,
287
+ status: cmd.status, layers: cmd.layers, summary,
288
+ };
289
+ });
290
+ }
291
+
292
+ /**
293
+ * ADR §6.4. One transaction. Exactly one of:
294
+ * {bookId} — stop the book: every active command + every live job of the book
295
+ * {bookId, layer} — stop one layer of the book (audio also stops audio_merge); commands stay active
296
+ * {commandId} — stop one command; its jobs are cancelled only when no OTHER active
297
+ * command waits for them (gen_command_jobs) — shared jobs keep running
298
+ * @param {object} target
299
+ * @param {{cancelledBy?:string}} [opts]
300
+ * @returns {Promise<{commands_cancelled:number, jobs_cancelled:number, job_ids:string[], kept_shared:number, layers?:string[]}>}
301
+ * layers (1.1.0, {commandId} only): the layers of the command that was stopped
302
+ */
303
+ async function cancel(target = {}, opts = {}) {
304
+ const by = opts.cancelledBy == null ? null : String(opts.cancelledBy).slice(0, 200);
305
+ const { bookId, layer, commandId } = target;
306
+ if ('executor' in target) throw new GenError('bad_request', 400, 'cancel by executor was removed — use {bookId, layer}');
307
+ if (commandId !== undefined) {
308
+ if (!isUuid(commandId) || bookId !== undefined || layer !== undefined) {
309
+ throw new GenError('bad_request', 400, 'cancel({commandId}) takes a UUID and nothing else');
310
+ }
311
+ } else {
312
+ requireText(bookId, 'bookId');
313
+ if (layer !== undefined && !LAYERS.includes(layer)) {
314
+ throw new GenError('bad_request', 400, 'layer must be audio|image|video');
315
+ }
316
+ }
317
+ return withTx(pool, async (client) => {
318
+ let commands = [];
319
+ let jobs;
320
+ let keptShared = 0;
321
+ if (commandId !== undefined) {
322
+ commands = (await client.query(
323
+ `UPDATE gen_commands SET status = 'cancelled', finished_at = now(), cancelled_by = $2
324
+ WHERE command_id = $1 AND status = 'active' RETURNING command_id, book_id, layers`, [commandId, by])).rows;
325
+ jobs = await client.query(
326
+ `UPDATE gen_jobs j SET status = 'cancelled', finished_at = now()
327
+ FROM gen_command_jobs l
328
+ WHERE l.command_id = $1 AND l.job_id = j.job_id AND j.status IN ('queued','running')
329
+ AND NOT EXISTS (SELECT 1 FROM gen_command_jobs o JOIN gen_commands oc ON oc.command_id = o.command_id
330
+ WHERE o.job_id = j.job_id AND o.command_id <> $1 AND oc.status = 'active')
331
+ RETURNING j.job_id, j.book_id`, [commandId]);
332
+ keptShared = Number((await client.query(
333
+ `SELECT count(*)::int AS n FROM gen_command_jobs l JOIN gen_jobs j ON j.job_id = l.job_id
334
+ WHERE l.command_id = $1 AND j.status IN ('queued','running')`, [commandId])).rows[0].n);
335
+ } else if (layer !== undefined) {
336
+ jobs = await client.query(
337
+ `UPDATE gen_jobs SET status = 'cancelled', finished_at = now()
338
+ WHERE book_id = $1 AND layer = $2 AND status IN ('queued','running')
339
+ RETURNING job_id, book_id`, [bookId, layer]);
340
+ } else {
341
+ commands = (await client.query(
342
+ `UPDATE gen_commands SET status = 'cancelled', finished_at = now(), cancelled_by = $2
343
+ WHERE book_id = $1 AND status = 'active' RETURNING command_id, book_id`, [bookId, by])).rows;
344
+ jobs = await client.query(
345
+ `UPDATE gen_jobs SET status = 'cancelled', finished_at = now()
346
+ WHERE book_id = $1 AND status IN ('queued','running')
347
+ RETURNING job_id, book_id`, [bookId]);
348
+ }
349
+ const books = new Set([...commands.map((c) => c.book_id), ...jobs.rows.map((j) => j.book_id)]);
350
+ for (const b of books) await notifyProgress(client, b, commandId || null);
351
+ const out = {
352
+ commands_cancelled: commands.length,
353
+ jobs_cancelled: jobs.rowCount,
354
+ job_ids: jobs.rows.map((j) => j.job_id),
355
+ kept_shared: keptShared,
356
+ };
357
+ if (commandId !== undefined) out.layers = commands.length ? commands[0].layers : []; // 1.1.0
358
+ return out;
359
+ });
360
+ }
361
+
362
+ const purgeBook = (bookId) => purgeBookRows(pool, bookId);
363
+
364
+ return { createCommand, cancel, purgeBook };
365
+ }
366
+
367
+ module.exports = { createCommands, normaliseScope, purgeBookRows };
@@ -0,0 +1,110 @@
1
+ // ======================================================
2
+ // @animastor/orchestration · gen — orchestration v2 core (1.1.0)
3
+ // ======================================================
4
+ // ADR: animastor-docs architecture/ORCHESTRATION_V2.md. The single source of
5
+ // truth is PG (gen_commands, gen_jobs). This namespace depends ONLY on the
6
+ // pg pool handed in by the host and on the host ports (ports.js). It never
7
+ // requires src/legacy, Redis, Express or ComfyUI.
8
+ //
9
+ // const { gen } = require('@animastor/orchestration');
10
+ // await gen.migrate(pool);
11
+ // const orch = gen.createOrchestration({ pool, ports, uploadSecret, outputDir });
12
+ // orch.createCommand(...), orch.cancel(...), orch.purgeBook(bookId), orch.claim(...), orch.acceptResult(...),
13
+ // orch.acceptError(...), orch.beacon(...), orch.sweepOnce(), orch.startSweeper(ms),
14
+ // orch.stop(), orch.progress(bookId), orch.listenProgress(fn), orch.runLocalOnce()
15
+
16
+ 'use strict';
17
+
18
+ const { migrate, MIGRATIONS } = require('./sql');
19
+ const portsMod = require('./ports');
20
+ const media = require('./validate-media');
21
+ const util = require('./util');
22
+ const { createCommands, purgeBookRows } = require('./commands');
23
+ const { createClaim } = require('./claim');
24
+ const { createAccept } = require('./accept');
25
+ const { createSweeper } = require('./sweeper');
26
+ const { createProgress } = require('./progress');
27
+ const { createLocalRunner } = require('./local-runner');
28
+
29
+ /**
30
+ * @param {object} o
31
+ * @param {{connect:Function, query:Function}} o.pool pg Pool supplied by the host
32
+ * @param {object} o.ports host ports (see ports.js)
33
+ * @param {string|Buffer} o.uploadSecret HMAC secret for upload tokens (>= 32 bytes)
34
+ * @param {string} [o.outputDir] root of {build}/.incoming (sweeper cleanup)
35
+ * @param {number|null} [o.sharedLimit=null] §10; NULL = off
36
+ * @param {number} [o.offlineAfterMs=60000] §9 п.2
37
+ * @param {number} [o.incomingMaxAgeMs=3600000] §9 п.4
38
+ * @param {number} [o.tokenGraceMs=900000] upload token validity after the deadline
39
+ * @param {number} [o.maxUploadBytes]
40
+ * @param {object} [o.logger=console]
41
+ */
42
+ function createOrchestration(o = {}) {
43
+ const { pool } = o;
44
+ if (!pool || typeof pool.connect !== 'function' || typeof pool.query !== 'function') {
45
+ throw new util.GenError('bad_config', 500, 'pool (pg Pool) is required');
46
+ }
47
+ const secret = o.uploadSecret;
48
+ if (!(typeof secret === 'string' || Buffer.isBuffer(secret)) || Buffer.byteLength(secret) < 32) {
49
+ throw new util.GenError('bad_config', 500, 'uploadSecret must be at least 32 bytes');
50
+ }
51
+ if (o.sharedLimit != null && !(Number.isInteger(o.sharedLimit) && o.sharedLimit >= 0)) {
52
+ throw new util.GenError('bad_config', 500, 'sharedLimit must be null or an integer >= 0');
53
+ }
54
+ const ports = portsMod.validatePorts(o.ports);
55
+ const logger = o.logger || console;
56
+
57
+ const accept = createAccept({ pool, ports, uploadSecret: secret, maxUploadBytes: o.maxUploadBytes });
58
+ const commands = createCommands({ pool, ports });
59
+ const claim = createClaim({ pool, ports, uploadSecret: secret, accept, sharedLimit: o.sharedLimit ?? null, tokenGraceMs: o.tokenGraceMs });
60
+ const sweeper = createSweeper({ pool, accept, outputDir: o.outputDir || null, offlineAfterMs: o.offlineAfterMs, incomingMaxAgeMs: o.incomingMaxAgeMs, logger });
61
+ const progress = createProgress({ pool });
62
+ const local = createLocalRunner({ pool, ports, accept, logger });
63
+
64
+ return Object.freeze({
65
+ createCommand: commands.createCommand,
66
+ cancel: commands.cancel,
67
+ purgeBook: commands.purgeBook,
68
+ claim: claim.claim,
69
+ beacon: claim.beacon,
70
+ acceptResult: accept.acceptResult,
71
+ acceptError: accept.acceptError,
72
+ sweepOnce: sweeper.sweepOnce,
73
+ startSweeper: sweeper.startSweeper,
74
+ stopSweeper: sweeper.stopSweeper,
75
+ runLocalOnce: local.runLocalOnce,
76
+ startLocalRunner: local.startLocalRunner,
77
+ stopLocalRunner: local.stopLocalRunner,
78
+ progress: progress.progress,
79
+ listenProgress: progress.listenProgress,
80
+ /** stop every timer this instance started */
81
+ stop() { sweeper.stopSweeper(); local.stopLocalRunner(); },
82
+ });
83
+ }
84
+
85
+ module.exports = Object.freeze({
86
+ createOrchestration,
87
+ migrate,
88
+ /** purgeBook(pool, bookId) — book deletion without an instance */
89
+ purgeBook: purgeBookRows,
90
+ MIGRATIONS,
91
+ validatePorts: portsMod.validatePorts,
92
+ REQUIRED_PORTS: portsMod.REQUIRED_PORTS,
93
+ OPTIONAL_PORTS: portsMod.OPTIONAL_PORTS,
94
+ defaults: Object.freeze({
95
+ ...portsMod.defaults,
96
+ createDefaultValidateResult: media.createDefaultValidateResult,
97
+ createAudioValidator: media.createAudioValidator,
98
+ createPngValidator: media.createPngValidator,
99
+ }),
100
+ media: Object.freeze({
101
+ inspectMp3: media.inspectMp3,
102
+ rmsDbfs: media.rmsDbfs,
103
+ ffmpegDecodePcm: media.ffmpegDecodePcm,
104
+ DEFAULT_RMS_THRESHOLD_DBFS: media.DEFAULT_RMS_THRESHOLD_DBFS,
105
+ inspectPng: media.inspectPng,
106
+ DEFAULT_MIN_LUMA_STDDEV: media.DEFAULT_MIN_LUMA_STDDEV,
107
+ }),
108
+ GenError: util.GenError,
109
+ PROGRESS_CHANNEL: util.PROGRESS_CHANNEL,
110
+ });