@animastor/orchestration 1.2.0 → 1.3.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 +26 -0
- package/README.md +11 -0
- package/package.json +1 -1
- package/src/gen/accept.js +95 -28
- package/src/gen/claim.js +54 -2
- package/src/gen/commands.js +109 -71
- package/src/gen/index.js +3 -2
- package/src/gen/local-runner.js +2 -1
- package/src/gen/ports.js +17 -3
- package/src/gen/progress.js +13 -1
- package/src/gen/sql/004-command-skips.js +26 -0
- package/src/gen/sql/index.js +2 -0
- package/src/gen/stage.js +185 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.3.0 (2026-11-09) — этап 3a: видео (`video_group` + `video_merge`)
|
|
4
|
+
|
|
5
|
+
Основание: ADR `ORCHESTRATION_V2.md` §6.3, §6.5, §8.1, §13 п.11. Minor: порты 1.0–1.2 не меняются,
|
|
6
|
+
новое — дополнительно (лишний аргумент `ctx`, объектная форма ответа планировщика video, порт `inputFiles`).
|
|
7
|
+
|
|
8
|
+
- **Планирование на транзакции.** `planUnits(book, scope, layer, ctx)`, `ctx.db` — клиент транзакции
|
|
9
|
+
команды или приёма. Слои audio / image планируются и вставляются первыми, video — последним, чтобы
|
|
10
|
+
планировщик видел только что созданные работы этой же команды.
|
|
11
|
+
- **Ответ video `{units, waits, skipped}`.** `waits` — сцена ждёт живые `iu_image` / `audio_chunk` /
|
|
12
|
+
`audio_merge`: команда присоединяется к ним (`gen_command_jobs`), группы появятся переходом.
|
|
13
|
+
`skipped` — `{chapter_id, scene_id, reason: 'skipped_*'}` → `summary[reason] = [scene_id…]` и таблица
|
|
14
|
+
**`gen_command_skips`** (миграция `004-command-skips`, insert-only — приём не обновляет `gen_commands`).
|
|
15
|
+
`progress().commands[].skipped`.
|
|
16
|
+
- **Переходы (§6.3).** `audio_chunk → audio_merge` также для видео-команд, ждущих это аудио;
|
|
17
|
+
`audio_merge → ступень video`; `iu_image → ступень video`; `video_group → video_merge` по
|
|
18
|
+
`input.merge_parts` (все части плана сцены `done` с тем же `part_hash`, ни одной живой), иначе прежнее
|
|
19
|
+
правило. Ступень video уважает `part_hash` готовых групп; все группы готовы, склейки для этого контента
|
|
20
|
+
нет → только `video_merge` (и при создании команды без `force`).
|
|
21
|
+
- **Хуки.** `onArtifactPlaced(job, finalPath, {db, meta})`: `db` — транзакция приёма, `meta` — то, что
|
|
22
|
+
`runLocal` вернул рядом с `{path}`.
|
|
23
|
+
- **Входные файлы (§8.1).** Необязательный порт `inputFiles(job)` → `[{name, path, sha256, bytes}]`;
|
|
24
|
+
задача выдачи несёт `input_files: [{name, sha256, bytes}]`; `orch.openInput(jobId, attempt, token, name)`
|
|
25
|
+
— тот же токен, только текущая `running`-попытка (`409 stale_attempt`), только имена из списка (`404`),
|
|
26
|
+
байты = sha256 снимка (`409 input_changed`).
|
|
27
|
+
- Тесты: `test/gen/video.test.js` (10).
|
|
28
|
+
|
|
3
29
|
## 1.2.0 (2026-11-07) — наблюдаемость v2 (О3)
|
|
4
30
|
|
|
5
31
|
Основание: `reports/2026-11-07/orch-v2-image-scene-run.md` О3 и «мелочи». Minor: только
|
package/README.md
CHANGED
|
@@ -39,6 +39,17 @@ with `book_id`, `command_id`, `job_id`, `kind`, `unit_key`, `attempt`,
|
|
|
39
39
|
tokens, paths or task params). Image acceptance records `width`/`height`;
|
|
40
40
|
accepted files are `0644`.
|
|
41
41
|
|
|
42
|
+
**1.3.0 (video, stage 3a).** `planUnits(book, scope, layer, ctx)` gets
|
|
43
|
+
`ctx.db` (the command / acceptance transaction); for `video` it may answer
|
|
44
|
+
`{units, waits, skipped}` — waits join the live images / audio of the scene,
|
|
45
|
+
skip reasons (`skipped_*`) land in the command summary and in
|
|
46
|
+
`gen_command_skips` (migration 004, `progress().commands[].skipped`). Stage
|
|
47
|
+
transitions: `audio_merge → video`, `iu_image → video`, `video_group →
|
|
48
|
+
video_merge` by `input.merge_parts`; all parts done, no merge → the merge alone.
|
|
49
|
+
`onArtifactPlaced(job, path, {db, meta})` (meta = what `runLocal` returned);
|
|
50
|
+
optional port `inputFiles(job)` → `task.input_files` + `orch.openInput(…)` for
|
|
51
|
+
`GET /internal/gen/jobs/:id/input/:name` (ADR §8.1).
|
|
52
|
+
|
|
42
53
|
`gen` requires only node builtins and its own files: no `src/legacy`, Redis,
|
|
43
54
|
Express or ComfyUI. Tests: `npm run test:gen` (env `PG_*` of the animastor-test
|
|
44
55
|
stack; refuses a DB not ending in `_test` or port 5432).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@animastor/orchestration",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "Animastor Orchestration 1.2.0 — generation orchestration v2 (ADR ORCHESTRATION_V2): `gen` namespace — PG is the single source of truth (gen_commands, gen_jobs), commands / claim (FOR UPDATE SKIP LOCKED) / one-transaction acceptance / sweeper / progress over a host-supplied pg pool and host ports; no Redis, no Express, no ComfyUI. The 0.3.x orchestration (dispatch/reconcile/lease/FSM, O-2..O-10 ports, host bindings) ships unchanged under src/legacy/ with the same root exports until migration stage 4.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"animastor",
|
package/src/gen/accept.js
CHANGED
|
@@ -23,6 +23,9 @@ const {
|
|
|
23
23
|
} = require('./util');
|
|
24
24
|
const { checkLane } = require('./ports');
|
|
25
25
|
const { msBetween } = require('./log');
|
|
26
|
+
const {
|
|
27
|
+
normalisePlan, readyParts, mergePartsOf, mergeUnitFor, linkSceneLive, recordSkips,
|
|
28
|
+
} = require('./stage');
|
|
26
29
|
|
|
27
30
|
const NOOP_LOG = Object.freeze({ event() {} });
|
|
28
31
|
/** Mode of an accepted artifact: world-readable like the legacy outputs (О3; the tmp file is 0640). */
|
|
@@ -272,43 +275,106 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
272
275
|
return r.rows.map((x) => ({ unit_key: x.unit_key, job_id: x.job_id, path: x.result_path, sha256: x.result_sha256, meta: x.meta || null }));
|
|
273
276
|
}
|
|
274
277
|
|
|
278
|
+
/** Is the scene asset of this layer already ready for exactly this content? */
|
|
279
|
+
async function sceneReady(client, job, layer, sceneHash) {
|
|
280
|
+
if (!sceneHash) return false;
|
|
281
|
+
const r = await client.query(
|
|
282
|
+
`SELECT 1 FROM scene_assets WHERE book_id = $1 AND chapter_id = $2 AND scene_id = $3 AND asset_type = $4
|
|
283
|
+
AND build_id = $5 AND status = 'ready' AND scene_hash = $6 LIMIT 1`,
|
|
284
|
+
[job.book_id, job.chapter_id, job.scene_id, layer, job.build_id, sceneHash]);
|
|
285
|
+
return r.rowCount > 0;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* 1.3.0 — the video stage of one scene (§6.3, §6.5, §13 п.11): asked after the last
|
|
290
|
+
* IU of the scene and after its audio merge. The host video planner, run on THIS
|
|
291
|
+
* transaction, decides: groups now / wait (join the live images or audio) / skip
|
|
292
|
+
* with a reason (recorded for the commands, insert-only).
|
|
293
|
+
*/
|
|
294
|
+
async function videoStage(client, qualifying, job) {
|
|
295
|
+
const owner = qualifying[0];
|
|
296
|
+
const ids = qualifying.map((c) => c.command_id);
|
|
297
|
+
const force = qualifying.some((c) => c.force === true);
|
|
298
|
+
const plan = normalisePlan(await ports.planUnits(
|
|
299
|
+
{ bookId: owner.book_id, workspaceId: owner.workspace_id, userId: owner.user_id },
|
|
300
|
+
{ level: 'scene', chapter_id: job.chapter_id, scene_id: job.scene_id }, 'video', { db: client }), 'video');
|
|
301
|
+
let units = plan.units.filter((u) => u && u.kind === 'video_group'
|
|
302
|
+
&& u.chapter_id === job.chapter_id && u.scene_id === job.scene_id
|
|
303
|
+
&& typeof u.unit_key === 'string' && u.unit_key && typeof u.build_id === 'string' && u.build_id
|
|
304
|
+
&& u.input && typeof u.input === 'object')
|
|
305
|
+
.map((u) => ({ ...u, input: { ...u.input, scene_hash: u.scene_hash ?? u.input.scene_hash ?? null } }));
|
|
306
|
+
let created = 0;
|
|
307
|
+
if (units.length && !force) {
|
|
308
|
+
const sceneHash = units[0].input.scene_hash;
|
|
309
|
+
if (await sceneReady(client, units[0], 'video', sceneHash)) {
|
|
310
|
+
units = []; // the scene video is current
|
|
311
|
+
} else {
|
|
312
|
+
const done = await readyParts(client, job.book_id, units);
|
|
313
|
+
if (done.size === units.length && mergePartsOf(units[0].input)) {
|
|
314
|
+
const merge = await mergeUnitFor(client, job.book_id, units[0]);
|
|
315
|
+
if (merge) { created += await insertStageJobs(client, qualifying, [merge]); units = []; }
|
|
316
|
+
} else if (done.size) {
|
|
317
|
+
units = units.filter((u) => !done.has(u));
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
created += await insertStageJobs(client, qualifying, units);
|
|
322
|
+
if (plan.waits.length) await linkSceneLive(client, ids, job.book_id, plan.waits);
|
|
323
|
+
if (plan.skipped.length) await recordSkips(client, ids, plan.skipped);
|
|
324
|
+
return created;
|
|
325
|
+
}
|
|
326
|
+
|
|
275
327
|
/**
|
|
276
328
|
* §6.3: a next stage is created only if at least one command linked to the finished job is
|
|
277
329
|
* active, has the layer and the layer is enabled; the new job is linked to all such commands.
|
|
330
|
+
* audio_chunk (last of the scene) → audio_merge — commands with audio, and (1.3.0) video
|
|
331
|
+
* commands waiting for this audio (§13 п.11 п.3)
|
|
332
|
+
* iu_image (last of the scene) → video stage — commands with video
|
|
333
|
+
* audio_merge → video stage — commands with video (1.3.0)
|
|
334
|
+
* video_group (last of the plan) → video_merge — by input.merge_parts (1.3.0) or, without
|
|
335
|
+
* it, every linked group of the scene
|
|
278
336
|
*/
|
|
279
337
|
async function transitions(client, cmds, job) {
|
|
280
|
-
const
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
338
|
+
const active = cmds.filter((c) => c.status === 'active');
|
|
339
|
+
if (!active.length) return 0;
|
|
340
|
+
const pick = async (layers, enabledLayer) => {
|
|
341
|
+
const out = [];
|
|
342
|
+
for (const c of active) {
|
|
343
|
+
if (layers.some((l) => c.layers.includes(l)) && await ports.isLayerEnabled(c.book_id, enabledLayer)) out.push(c);
|
|
344
|
+
}
|
|
345
|
+
return out;
|
|
346
|
+
};
|
|
347
|
+
const lockScene = () => client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [sceneLockKey(job)]);
|
|
287
348
|
const mergeInput = async (kind) => ({
|
|
288
349
|
scene_hash: job.input.scene_hash ?? null,
|
|
289
350
|
parts: await doneParts(client, job, kind),
|
|
290
351
|
});
|
|
291
352
|
const sceneUnit = (kind, input) => ({ chapter_id: job.chapter_id, scene_id: job.scene_id, kind, unit_key: 'scene', build_id: job.build_id, input });
|
|
292
353
|
|
|
293
|
-
if (job.kind === 'audio_chunk' || job.kind === 'video_group' || job.kind === 'iu_image') {
|
|
294
|
-
await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [sceneLockKey(job)]);
|
|
295
|
-
if (!(await sceneStageComplete(client, job, job.kind, ids))) return 0;
|
|
296
|
-
}
|
|
297
354
|
if (job.kind === 'audio_chunk') {
|
|
298
|
-
|
|
355
|
+
const q = await pick(['audio', 'video'], 'audio');
|
|
356
|
+
if (!q.length) return 0;
|
|
357
|
+
await lockScene();
|
|
358
|
+
if (!(await sceneStageComplete(client, job, 'audio_chunk', q.map((c) => c.command_id)))) return 0;
|
|
359
|
+
return insertStageJobs(client, q, [sceneUnit('audio_merge', await mergeInput('audio_chunk'))]);
|
|
299
360
|
}
|
|
300
361
|
if (job.kind === 'video_group') {
|
|
301
|
-
|
|
362
|
+
const q = await pick(['video'], 'video');
|
|
363
|
+
if (!q.length) return 0;
|
|
364
|
+
await lockScene();
|
|
365
|
+
if (mergePartsOf(job.input)) {
|
|
366
|
+
const merge = await mergeUnitFor(client, job.book_id, job);
|
|
367
|
+
return merge ? insertStageJobs(client, q, [merge]) : 0;
|
|
368
|
+
}
|
|
369
|
+
if (!(await sceneStageComplete(client, job, 'video_group', q.map((c) => c.command_id)))) return 0;
|
|
370
|
+
return insertStageJobs(client, q, [sceneUnit('video_merge', await mergeInput('video_group'))]);
|
|
302
371
|
}
|
|
303
|
-
if (job.kind === 'iu_image') {
|
|
304
|
-
const
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
&& u.chapter_id === job.chapter_id && u.scene_id === job.scene_id
|
|
310
|
-
&& typeof u.unit_key === 'string' && typeof u.build_id === 'string' && u.input && typeof u.input === 'object');
|
|
311
|
-
return insertStageJobs(client, qualifying, groups.map((u) => ({ ...u, input: { ...u.input, scene_hash: u.scene_hash ?? u.input.scene_hash ?? null } })));
|
|
372
|
+
if (job.kind === 'iu_image' || job.kind === 'audio_merge') {
|
|
373
|
+
const q = await pick(['video'], 'video');
|
|
374
|
+
if (!q.length) return 0;
|
|
375
|
+
await lockScene();
|
|
376
|
+
if (job.kind === 'iu_image' && !(await sceneStageComplete(client, job, 'iu_image', q.map((c) => c.command_id)))) return 0;
|
|
377
|
+
return videoStage(client, q, job);
|
|
312
378
|
}
|
|
313
379
|
return 0;
|
|
314
380
|
}
|
|
@@ -317,8 +383,8 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
317
383
|
* Steps 1(validate)–5 of §7 for a file already on disk at tmpPath.
|
|
318
384
|
* @returns {Promise<{status:number, code?:string, reason?:string, idempotent?:boolean, sha256?:string, job_status?:string, stage_jobs_created?:number}>}
|
|
319
385
|
*/
|
|
320
|
-
async function finishAccept(pre, attempt, tmpPath, sha, bytes, t0 = Date.now()) {
|
|
321
|
-
const r = await finishAcceptInner(pre, attempt, tmpPath, sha, bytes,
|
|
386
|
+
async function finishAccept(pre, attempt, tmpPath, sha, bytes, t0 = Date.now(), localMeta = null) {
|
|
387
|
+
const r = await finishAcceptInner(pre, attempt, tmpPath, sha, bytes, localMeta);
|
|
322
388
|
// О3: `accept` for a committed result (or its idempotent replay); a stale
|
|
323
389
|
// attempt is an `error` line (code stale_attempt); invalid_result is logged by failAttempt.
|
|
324
390
|
const ids = {
|
|
@@ -337,7 +403,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
337
403
|
return r;
|
|
338
404
|
}
|
|
339
405
|
|
|
340
|
-
async function finishAcceptInner(pre, attempt, tmpPath, sha, bytes) {
|
|
406
|
+
async function finishAcceptInner(pre, attempt, tmpPath, sha, bytes, localMeta = null) {
|
|
341
407
|
const finalPath = ports.artifactPath(pre);
|
|
342
408
|
if (typeof finalPath !== 'string' || !path.isAbsolute(finalPath)) {
|
|
343
409
|
await unlinkQuiet(tmpPath);
|
|
@@ -376,7 +442,8 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
376
442
|
await fs.promises.rename(tmpPath, finalPath); // §7 п.3 (atomic, same partition)
|
|
377
443
|
renamed = true;
|
|
378
444
|
await fs.promises.chmod(finalPath, ARTIFACT_MODE).catch(() => {}); // О3: 0644 like legacy outputs
|
|
379
|
-
|
|
445
|
+
// e.g. drop the placeholder sidecar; 1.3.0: ctx.db = this transaction, ctx.meta = what runLocal returned
|
|
446
|
+
if (ports.onArtifactPlaced) await ports.onArtifactPlaced(job, finalPath, { db: client, meta: localMeta });
|
|
380
447
|
await client.query(
|
|
381
448
|
`UPDATE gen_jobs SET status = 'done', result_path = $2, result_sha256 = $3, result_bytes = $4,
|
|
382
449
|
finished_at = now(), deadline = NULL
|
|
@@ -472,11 +539,11 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
472
539
|
}
|
|
473
540
|
|
|
474
541
|
/** Accept a file produced by the backend itself (executor='local'); no token. */
|
|
475
|
-
async function acceptLocalFile(job, filePath) {
|
|
542
|
+
async function acceptLocalFile(job, filePath, meta = null) {
|
|
476
543
|
const hash = crypto.createHash('sha256');
|
|
477
544
|
let bytes = 0;
|
|
478
545
|
for await (const chunk of fs.createReadStream(filePath)) { hash.update(chunk); bytes += chunk.length; }
|
|
479
|
-
return finishAccept(job, job.attempt, filePath, hash.digest('hex'), bytes);
|
|
546
|
+
return finishAccept(job, job.attempt, filePath, hash.digest('hex'), bytes, Date.now(), meta);
|
|
480
547
|
}
|
|
481
548
|
|
|
482
549
|
return { acceptResult, acceptError, failAttempt, acceptLocalFile };
|
package/src/gen/claim.js
CHANGED
|
@@ -11,10 +11,32 @@
|
|
|
11
11
|
|
|
12
12
|
'use strict';
|
|
13
13
|
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
const crypto = require('crypto');
|
|
16
|
+
|
|
14
17
|
const {
|
|
15
|
-
GenError, withTx, requireUuid, isUuid, issueUploadToken, notifyProgress, KINDS, WORKER_TYPES,
|
|
18
|
+
GenError, withTx, requireUuid, isUuid, issueUploadToken, verifyUploadToken, notifyProgress, KINDS, WORKER_TYPES,
|
|
16
19
|
} = require('./util');
|
|
17
20
|
|
|
21
|
+
const SAFE_INPUT_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,200}$/;
|
|
22
|
+
const MAX_INPUTS = 16;
|
|
23
|
+
|
|
24
|
+
/** Validate the host's inputFiles(job) answer: plain file names, absolute paths, sha256. */
|
|
25
|
+
function listInputs(list) {
|
|
26
|
+
if (list == null) return [];
|
|
27
|
+
if (!Array.isArray(list) || list.length > MAX_INPUTS) throw new GenError('bad_inputs', 500, 'inputFiles(job) must return an array (<= 16)');
|
|
28
|
+
const seen = new Set();
|
|
29
|
+
return list.map((f) => {
|
|
30
|
+
const ok = f && typeof f.name === 'string' && SAFE_INPUT_NAME.test(f.name) && !f.name.includes('..')
|
|
31
|
+
&& typeof f.path === 'string' && f.path.startsWith('/')
|
|
32
|
+
&& typeof f.sha256 === 'string' && /^[0-9a-f]{64}$/.test(f.sha256)
|
|
33
|
+
&& Number.isInteger(f.bytes) && f.bytes > 0;
|
|
34
|
+
if (!ok || seen.has(f.name)) throw new GenError('bad_inputs', 500, `inputFiles(job): invalid entry ${f && f.name}`);
|
|
35
|
+
seen.add(f.name);
|
|
36
|
+
return { name: f.name, path: f.path, sha256: f.sha256, bytes: f.bytes };
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
18
40
|
const MODES = Object.freeze(['private', 'share', 'system']);
|
|
19
41
|
|
|
20
42
|
const NOOP_LOG = Object.freeze({ event() {} });
|
|
@@ -102,8 +124,11 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
|
|
|
102
124
|
if (!job) return { task: null };
|
|
103
125
|
|
|
104
126
|
let payload;
|
|
127
|
+
let inputs = null;
|
|
105
128
|
try {
|
|
106
129
|
payload = await ports.buildPayload(job);
|
|
130
|
+
// 1.3.0 — input files (e.g. IU frames of a video group) travel by link, not base64 (§8.1)
|
|
131
|
+
if (ports.inputFiles) inputs = listInputs(await ports.inputFiles(job));
|
|
107
132
|
} catch (err) {
|
|
108
133
|
// the payload cannot be built → this attempt fails deterministically (no silent loss)
|
|
109
134
|
await accept.failAttempt(job.job_id, job.attempt, 'deterministic', `build_payload: ${err && err.message}`);
|
|
@@ -128,10 +153,37 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
|
|
|
128
153
|
timeout_ms: ports.timeoutFor(job.kind),
|
|
129
154
|
deadline: new Date(deadlineMs).toISOString(),
|
|
130
155
|
upload_token: issueUploadToken(uploadSecret, job.job_id, job.attempt, exp),
|
|
156
|
+
...(inputs && inputs.length ? { input_files: inputs.map((f) => ({ name: f.name, sha256: f.sha256, bytes: f.bytes })) } : {}),
|
|
131
157
|
},
|
|
132
158
|
};
|
|
133
159
|
}
|
|
134
160
|
|
|
161
|
+
/**
|
|
162
|
+
* GET /internal/gen/jobs/:job_id/input/:name?attempt=N (ADR §8.1, 1.3.0): the same
|
|
163
|
+
* upload token as the result; only the CURRENT running attempt; only a name the job
|
|
164
|
+
* lists; the bytes must still be the snapshot taken at planning (sha256) — a frame
|
|
165
|
+
* replaced in between → 409 input_changed (the video would not match its hash).
|
|
166
|
+
* @returns {Promise<{status:number, code?:string, body?:Buffer, name?:string, sha256?:string}>}
|
|
167
|
+
*/
|
|
168
|
+
async function openInput(jobId, attempt, token, name) {
|
|
169
|
+
if (!isUuid(jobId)) return { status: 404, code: 'not_found' };
|
|
170
|
+
if (!Number.isInteger(attempt) || attempt < 1) return { status: 400, code: 'bad_request' };
|
|
171
|
+
if (!verifyUploadToken(uploadSecret, token, jobId, attempt)) return { status: 401, code: 'unauthorized' };
|
|
172
|
+
if (!ports.inputFiles) return { status: 404, code: 'not_found' };
|
|
173
|
+
const job = (await pool.query('SELECT * FROM gen_jobs WHERE job_id = $1', [jobId])).rows[0];
|
|
174
|
+
if (!job) return { status: 404, code: 'not_found' };
|
|
175
|
+
if (job.status !== 'running' || job.attempt !== attempt) return { status: 409, code: 'stale_attempt' };
|
|
176
|
+
let list;
|
|
177
|
+
try { list = listInputs(await ports.inputFiles(job)); } catch (_) { return { status: 404, code: 'not_found' }; }
|
|
178
|
+
const f = list.find((x) => x.name === name);
|
|
179
|
+
if (!f) return { status: 404, code: 'not_found' };
|
|
180
|
+
let body;
|
|
181
|
+
try { body = await fs.promises.readFile(f.path); } catch (_) { return { status: 409, code: 'input_missing' }; }
|
|
182
|
+
const sha = crypto.createHash('sha256').update(body).digest('hex');
|
|
183
|
+
if (sha !== f.sha256) return { status: 409, code: 'input_changed' };
|
|
184
|
+
return { status: 200, body, name: f.name, sha256: sha };
|
|
185
|
+
}
|
|
186
|
+
|
|
135
187
|
/**
|
|
136
188
|
* Worker liveness (ADR §8.3): last_seen + current_job_id; answer = jobs to stop.
|
|
137
189
|
* cancel = this worker's jobs cancelled in the last hour + the reported
|
|
@@ -156,7 +208,7 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
|
|
|
156
208
|
});
|
|
157
209
|
}
|
|
158
210
|
|
|
159
|
-
return { claim, beacon };
|
|
211
|
+
return { claim, beacon, openInput };
|
|
160
212
|
}
|
|
161
213
|
|
|
162
214
|
module.exports = { createClaim, MODES };
|
package/src/gen/commands.js
CHANGED
|
@@ -17,6 +17,9 @@ const {
|
|
|
17
17
|
EXECUTOR_OF_KIND, LAYER_OF_KIND, FIRST_STAGE_KINDS, LAYERS,
|
|
18
18
|
} = require('./util');
|
|
19
19
|
const { checkLane } = require('./ports');
|
|
20
|
+
const {
|
|
21
|
+
normalisePlan, readyParts, mergePartsOf, mergeUnitFor, linkSceneLive, recordSkips, skipSummary,
|
|
22
|
+
} = require('./stage');
|
|
20
23
|
|
|
21
24
|
const COMMAND_KINDS = Object.freeze(['regenerate', 'generate_all']);
|
|
22
25
|
const SCOPE_LEVELS = Object.freeze(['book', 'chapter', 'scenes', 'scene', 'unit']);
|
|
@@ -153,78 +156,22 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
|
|
|
153
156
|
if (ins.rowCount === 0) return existingResponse(await existingOf()); // concurrent twin committed first
|
|
154
157
|
const cmd = ins.rows[0];
|
|
155
158
|
|
|
156
|
-
// §6.1 п.3: plan units per layer
|
|
159
|
+
// §6.1 п.3: plan units per layer. Audio / image first, video last: the video
|
|
160
|
+
// planner (1.3.0) runs on THIS transaction and must see the image / audio jobs
|
|
161
|
+
// this very command has just created (they are what a video scene waits for).
|
|
157
162
|
const bookRef = { bookId, workspaceId, userId };
|
|
158
|
-
const
|
|
163
|
+
const planCtx = { db: client };
|
|
159
164
|
const seen = new Set();
|
|
160
|
-
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
for (const u of planned) {
|
|
165
|
+
const takeUnits = (list, layer) => {
|
|
166
|
+
const out = [];
|
|
167
|
+
for (const u of list) {
|
|
164
168
|
checkUnit(u, layer);
|
|
165
169
|
if (seen.has(unitKey(u))) continue; // video+image may both plan the same IU
|
|
166
170
|
seen.add(unitKey(u));
|
|
167
|
-
|
|
171
|
+
out.push(u);
|
|
168
172
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
// §6.1 п.3: skip units whose scene asset is ready for the current content (PG scene_assets only)
|
|
172
|
-
let skipped = 0;
|
|
173
|
-
let todo = units;
|
|
174
|
-
if (!force && units.length) {
|
|
175
|
-
const k5 = (g) => `${g.chapter_id}\u0000${g.scene_id}\u0000${g.asset_type}\u0000${g.build_id}\u0000${g.scene_hash}`;
|
|
176
|
-
const gkey = (u) => k5({ ...u, asset_type: LAYER_OF_KIND[u.kind] });
|
|
177
|
-
const groups = new Map();
|
|
178
|
-
for (const u of units) {
|
|
179
|
-
if (typeof u.scene_hash !== 'string' || !u.scene_hash) continue; // readiness unprovable → do it
|
|
180
|
-
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 });
|
|
181
|
-
}
|
|
182
|
-
const readyKeys = new Set();
|
|
183
|
-
if (groups.size) {
|
|
184
|
-
const list = [...groups.values()];
|
|
185
|
-
const r = await client.query(
|
|
186
|
-
`SELECT g.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[])
|
|
187
|
-
WITH ORDINALITY AS g(chapter_id, scene_id, asset_type, build_id, scene_hash, ord)
|
|
188
|
-
WHERE EXISTS (SELECT 1 FROM scene_assets a
|
|
189
|
-
WHERE a.book_id = $1 AND a.chapter_id = g.chapter_id AND a.scene_id = g.scene_id
|
|
190
|
-
AND a.asset_type = g.asset_type AND a.build_id = g.build_id
|
|
191
|
-
AND a.status = 'ready' AND a.scene_hash = g.scene_hash)`,
|
|
192
|
-
[bookId, list.map((x) => x.chapter_id), list.map((x) => x.scene_id), list.map((x) => x.asset_type),
|
|
193
|
-
list.map((x) => x.build_id), list.map((x) => x.scene_hash)]);
|
|
194
|
-
for (const row of r.rows) readyKeys.add(k5(list[Number(row.ord) - 1]));
|
|
195
|
-
}
|
|
196
|
-
todo = units.filter((u) => {
|
|
197
|
-
if (typeof u.scene_hash !== 'string' || !u.scene_hash) return true;
|
|
198
|
-
if (readyKeys.has(gkey(u))) { skipped += 1; return false; }
|
|
199
|
-
return true;
|
|
200
|
-
});
|
|
201
|
-
// 1.1.0 — part-level readiness (opt-in: the unit carries input.part_hash).
|
|
202
|
-
// A part (e.g. one IU picture) whose accepted snapshot hash is recorded in
|
|
203
|
-
// scene_assets.metadata.gen_parts[unit_key].part_hash for the same build is
|
|
204
|
-
// already done for the current content — skip it even if its scene is not
|
|
205
|
-
// complete («сгенерировать недостающее» = only the missing / changed parts).
|
|
206
|
-
// A row the host marked 'stale' proves nothing. Units without part_hash
|
|
207
|
-
// (audio) keep the scene-level rule above unchanged.
|
|
208
|
-
const parted = todo.filter((u) => typeof u.input.part_hash === 'string' && u.input.part_hash);
|
|
209
|
-
if (parted.length) {
|
|
210
|
-
const r = await client.query(
|
|
211
|
-
`SELECT t.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
|
|
212
|
-
WITH ORDINALITY AS t(chapter_id, scene_id, asset_type, build_id, unit_key, part_hash, ord)
|
|
213
|
-
WHERE EXISTS (SELECT 1 FROM scene_assets a
|
|
214
|
-
WHERE a.book_id = $1 AND a.chapter_id = t.chapter_id AND a.scene_id = t.scene_id
|
|
215
|
-
AND a.asset_type = t.asset_type AND a.build_id = t.build_id
|
|
216
|
-
AND a.status IN ('pending', 'ready')
|
|
217
|
-
AND jsonb_typeof(a.metadata->'gen_parts') = 'object'
|
|
218
|
-
AND a.metadata->'gen_parts'->t.unit_key->>'part_hash' = t.part_hash)`,
|
|
219
|
-
[bookId, parted.map((u) => u.chapter_id), parted.map((u) => u.scene_id), parted.map((u) => LAYER_OF_KIND[u.kind]),
|
|
220
|
-
parted.map((u) => u.build_id), parted.map((u) => u.unit_key), parted.map((u) => u.input.part_hash)]);
|
|
221
|
-
const done = new Set(r.rows.map((row) => parted[Number(row.ord) - 1]));
|
|
222
|
-
if (done.size) {
|
|
223
|
-
skipped += done.size;
|
|
224
|
-
todo = todo.filter((u) => !done.has(u));
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
}
|
|
173
|
+
return out;
|
|
174
|
+
};
|
|
228
175
|
|
|
229
176
|
// lanes, one lookup per worker type (§4.2: computed at creation)
|
|
230
177
|
const laneCache = new Map();
|
|
@@ -242,10 +189,73 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
|
|
|
242
189
|
return laneCache.get(type);
|
|
243
190
|
};
|
|
244
191
|
|
|
245
|
-
// §6.1 п.4: insert; a unit live under another command → joined (link to the live job)
|
|
246
192
|
let created = 0;
|
|
247
193
|
let joined = 0;
|
|
248
|
-
|
|
194
|
+
let skipped = 0;
|
|
195
|
+
|
|
196
|
+
/** §6.1 пп.3–4 for one batch of planned units: skip ready, insert / join the rest. */
|
|
197
|
+
const place = async (units) => {
|
|
198
|
+
let todo = units;
|
|
199
|
+
if (!force && units.length) {
|
|
200
|
+
// scene level: the scene asset is ready for the current content (PG scene_assets only)
|
|
201
|
+
const k5 = (g) => `${g.chapter_id}\u0000${g.scene_id}\u0000${g.asset_type}\u0000${g.build_id}\u0000${g.scene_hash}`;
|
|
202
|
+
const gkey = (u) => k5({ ...u, asset_type: LAYER_OF_KIND[u.kind] });
|
|
203
|
+
const groups = new Map();
|
|
204
|
+
for (const u of units) {
|
|
205
|
+
if (typeof u.scene_hash !== 'string' || !u.scene_hash) continue; // readiness unprovable → do it
|
|
206
|
+
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 });
|
|
207
|
+
}
|
|
208
|
+
const readyKeys = new Set();
|
|
209
|
+
if (groups.size) {
|
|
210
|
+
const list = [...groups.values()];
|
|
211
|
+
const r = await client.query(
|
|
212
|
+
`SELECT g.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[])
|
|
213
|
+
WITH ORDINALITY AS g(chapter_id, scene_id, asset_type, build_id, scene_hash, ord)
|
|
214
|
+
WHERE EXISTS (SELECT 1 FROM scene_assets a
|
|
215
|
+
WHERE a.book_id = $1 AND a.chapter_id = g.chapter_id AND a.scene_id = g.scene_id
|
|
216
|
+
AND a.asset_type = g.asset_type AND a.build_id = g.build_id
|
|
217
|
+
AND a.status = 'ready' AND a.scene_hash = g.scene_hash)`,
|
|
218
|
+
[bookId, list.map((x) => x.chapter_id), list.map((x) => x.scene_id), list.map((x) => x.asset_type),
|
|
219
|
+
list.map((x) => x.build_id), list.map((x) => x.scene_hash)]);
|
|
220
|
+
for (const row of r.rows) readyKeys.add(k5(list[Number(row.ord) - 1]));
|
|
221
|
+
}
|
|
222
|
+
todo = units.filter((u) => {
|
|
223
|
+
if (typeof u.scene_hash !== 'string' || !u.scene_hash) return true;
|
|
224
|
+
if (readyKeys.has(gkey(u))) { skipped += 1; return false; }
|
|
225
|
+
return true;
|
|
226
|
+
});
|
|
227
|
+
// 1.1.0 — part-level readiness (opt-in: the unit carries input.part_hash).
|
|
228
|
+
// A part (e.g. one IU picture, one video group) whose accepted snapshot hash
|
|
229
|
+
// is recorded in scene_assets.metadata.gen_parts[unit_key].part_hash for the
|
|
230
|
+
// same build is already done for the current content — skip it even if its
|
|
231
|
+
// scene is not complete («сгенерировать недостающее» = only the missing /
|
|
232
|
+
// changed parts). A row the host marked 'stale' proves nothing. Units without
|
|
233
|
+
// part_hash (audio) keep the scene-level rule above unchanged.
|
|
234
|
+
const done = await readyParts(client, bookId, todo);
|
|
235
|
+
if (done.size) {
|
|
236
|
+
// 1.3.0 — a part kind with a merge stage (input.merge_parts: video_group):
|
|
237
|
+
// every part of the scene is already done but the scene is not ready for
|
|
238
|
+
// this content → the merge alone is created (local, no GPU). Parts whose
|
|
239
|
+
// done job cannot be found go back to the plan.
|
|
240
|
+
const byScene = new Map();
|
|
241
|
+
for (const u of todo) {
|
|
242
|
+
if (!mergePartsOf(u.input)) continue;
|
|
243
|
+
const sk = `${u.chapter_id}\u0000${u.scene_id}`;
|
|
244
|
+
if (!byScene.has(sk)) byScene.set(sk, []);
|
|
245
|
+
byScene.get(sk).push(u);
|
|
246
|
+
}
|
|
247
|
+
const extra = [];
|
|
248
|
+
for (const list of byScene.values()) {
|
|
249
|
+
if (!list.every((u) => done.has(u))) continue; // some parts run → the transition merges
|
|
250
|
+
const merge = await mergeUnitFor(client, bookId, list[0]);
|
|
251
|
+
if (merge) extra.push(merge);
|
|
252
|
+
else for (const u of list) done.delete(u);
|
|
253
|
+
}
|
|
254
|
+
skipped += done.size;
|
|
255
|
+
todo = todo.filter((u) => !done.has(u)).concat(extra);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (!todo.length) return;
|
|
249
259
|
const cols = { ch: [], sc: [], uk: [], kind: [], ex: [], layer: [], build: [], lane: [], max: [], input: [] };
|
|
250
260
|
for (const u of todo) {
|
|
251
261
|
const ex = EXECUTOR_OF_KIND[u.kind];
|
|
@@ -256,6 +266,7 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
|
|
|
256
266
|
cols.max.push(ports.maxAttemptsFor(u.kind));
|
|
257
267
|
cols.input.push(JSON.stringify({ ...u.input, scene_hash: u.scene_hash ?? u.input.scene_hash ?? null }));
|
|
258
268
|
}
|
|
269
|
+
// §6.1 п.4: insert; a unit live under another command → joined (link to the live job)
|
|
259
270
|
const ins2 = await client.query(
|
|
260
271
|
`INSERT INTO gen_jobs (command_id, workspace_id, user_id, book_id, chapter_id, scene_id, unit_key,
|
|
261
272
|
kind, executor, layer, build_id, lane, max_attempts, input, created_at)
|
|
@@ -270,7 +281,7 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
|
|
|
270
281
|
RETURNING job_id`,
|
|
271
282
|
[cmd.command_id, workspaceId, userId, bookId, cols.ch, cols.sc, cols.uk, cols.kind, cols.ex,
|
|
272
283
|
cols.layer, cols.build, cols.lane, cols.max, cols.input]);
|
|
273
|
-
created
|
|
284
|
+
created += ins2.rowCount;
|
|
274
285
|
// live jobs of the same units (ours just inserted + other commands' → joined)
|
|
275
286
|
const live = await client.query(
|
|
276
287
|
`SELECT j.job_id, j.command_id FROM gen_jobs j
|
|
@@ -278,10 +289,37 @@ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
|
|
|
278
289
|
ON j.chapter_id = t.ch AND j.scene_id = t.sc AND j.kind = t.kind AND j.unit_key = t.uk
|
|
279
290
|
WHERE j.book_id = $1 AND j.status IN ('queued','running')`,
|
|
280
291
|
[bookId, cols.ch, cols.sc, cols.kind, cols.uk]);
|
|
281
|
-
joined
|
|
292
|
+
joined += live.rows.filter((r) => r.command_id !== cmd.command_id).length;
|
|
282
293
|
await linkJobs(client, [cmd.command_id], live.rows.map((r) => r.job_id));
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
const nonVideo = [];
|
|
297
|
+
for (const layer of effective.filter((l) => l !== 'video')) {
|
|
298
|
+
const plan = normalisePlan(await ports.planUnits(bookRef, scope, layer, planCtx), layer);
|
|
299
|
+
nonVideo.push(...takeUnits(plan.units, layer));
|
|
300
|
+
}
|
|
301
|
+
await place(nonVideo);
|
|
302
|
+
|
|
303
|
+
// 1.3.0 — video (§6.5, §13 п.11): the planner decides per scene: groups now /
|
|
304
|
+
// wait for live images or audio (the command joins those jobs; the groups come
|
|
305
|
+
// from the transition of their acceptance) / skip with a reason.
|
|
306
|
+
let skips = [];
|
|
307
|
+
if (effective.includes('video')) {
|
|
308
|
+
const plan = normalisePlan(await ports.planUnits(bookRef, scope, 'video', planCtx), 'video');
|
|
309
|
+
await place(takeUnits(plan.units, 'video'));
|
|
310
|
+
if (plan.waits.length) {
|
|
311
|
+
// joined = links to live jobs another command created (our own image / audio jobs are not «joined»)
|
|
312
|
+
const foreign = async () => (await client.query(
|
|
313
|
+
`SELECT count(*)::int AS n FROM gen_command_jobs l JOIN gen_jobs j ON j.job_id = l.job_id
|
|
314
|
+
WHERE l.command_id = $1 AND j.command_id <> $1`, [cmd.command_id])).rows[0].n;
|
|
315
|
+
const before = await foreign();
|
|
316
|
+
await linkSceneLive(client, [cmd.command_id], bookId, plan.waits);
|
|
317
|
+
joined += (await foreign()) - before;
|
|
318
|
+
}
|
|
319
|
+
skips = plan.skipped;
|
|
320
|
+
await recordSkips(client, [cmd.command_id], skips);
|
|
283
321
|
}
|
|
284
|
-
const summary = { jobs_created: created, joined, skipped_ready: skipped };
|
|
322
|
+
const summary = { jobs_created: created, joined, skipped_ready: skipped, ...skipSummary(skips) };
|
|
285
323
|
await client.query('UPDATE gen_commands SET summary = $2::jsonb WHERE command_id = $1', [cmd.command_id, JSON.stringify(summary)]);
|
|
286
324
|
await notifyProgress(client, bookId, cmd.command_id);
|
|
287
325
|
return {
|
package/src/gen/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// ======================================================
|
|
2
|
-
// @animastor/orchestration · gen — orchestration v2 core (1.
|
|
2
|
+
// @animastor/orchestration · gen — orchestration v2 core (1.3.0)
|
|
3
3
|
// ======================================================
|
|
4
4
|
// ADR: animastor-docs architecture/ORCHESTRATION_V2.md. The single source of
|
|
5
5
|
// truth is PG (gen_commands, gen_jobs). This namespace depends ONLY on the
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// await gen.migrate(pool);
|
|
11
11
|
// const orch = gen.createOrchestration({ pool, ports, uploadSecret, outputDir });
|
|
12
12
|
// orch.createCommand(...), orch.cancel(...), orch.purgeBook(bookId), orch.claim(...), orch.acceptResult(...),
|
|
13
|
-
// orch.acceptError(...), orch.beacon(...), orch.sweepOnce(), orch.startSweeper(ms),
|
|
13
|
+
// orch.acceptError(...), orch.beacon(...), orch.openInput(...), orch.sweepOnce(), orch.startSweeper(ms),
|
|
14
14
|
// orch.stop(), orch.progress(bookId), orch.listenProgress(fn), orch.runLocalOnce()
|
|
15
15
|
|
|
16
16
|
'use strict';
|
|
@@ -70,6 +70,7 @@ function createOrchestration(o = {}) {
|
|
|
70
70
|
purgeBook: commands.purgeBook,
|
|
71
71
|
claim: claim.claim,
|
|
72
72
|
beacon: claim.beacon,
|
|
73
|
+
openInput: claim.openInput,
|
|
73
74
|
acceptResult: accept.acceptResult,
|
|
74
75
|
acceptError: accept.acceptError,
|
|
75
76
|
sweepOnce: sweeper.sweepOnce,
|
package/src/gen/local-runner.js
CHANGED
|
@@ -42,7 +42,8 @@ function createLocalRunner({ pool, ports, accept, logger = null }) {
|
|
|
42
42
|
const r = await accept.failAttempt(job.job_id, job.attempt, (err && err.error_class) || 'unknown', `run_local: ${err && err.message}`);
|
|
43
43
|
return { job_id: job.job_id, attempt: job.attempt, ...r };
|
|
44
44
|
}
|
|
45
|
-
|
|
45
|
+
// 1.3.0: out.meta (e.g. measured chunk durations) reaches onArtifactPlaced inside the acceptance tx
|
|
46
|
+
const r = await accept.acceptLocalFile(job, out.path, out.meta === undefined ? null : out.meta);
|
|
46
47
|
return { job_id: job.job_id, attempt: job.attempt, ...r };
|
|
47
48
|
}
|
|
48
49
|
|
package/src/gen/ports.js
CHANGED
|
@@ -28,8 +28,22 @@
|
|
|
28
28
|
// Optional:
|
|
29
29
|
// maxAttemptsFor(kind) → int ≥ 1 (default: 1 + max retries of the policy)
|
|
30
30
|
// isLayerEnabled(bookId, layer) → Promise<boolean> (§6.3 «только если слой включён»; default true)
|
|
31
|
-
// onArtifactPlaced(job, finalPath) → called inside the acceptance transaction right after the
|
|
32
|
-
// rename (§7 п.3), e.g. to drop a placeholder sidecar marker
|
|
31
|
+
// onArtifactPlaced(job, finalPath, ctx) → called inside the acceptance transaction right after the
|
|
32
|
+
// rename (§7 п.3), e.g. to drop a placeholder sidecar marker.
|
|
33
|
+
// 1.3.0: ctx = {db, meta} — db: the acceptance transaction client
|
|
34
|
+
// (writes commit or roll back with the result); meta: what runLocal
|
|
35
|
+
// returned next to {path} (local jobs), else null
|
|
36
|
+
// inputFiles(job) → [{name, path, sha256, bytes}] (1.3.0) input files of a GPU job,
|
|
37
|
+
// served by GET /internal/gen/jobs/:id/input/:name (§8.1); listed
|
|
38
|
+
// in the claimed task as input_files [{name, sha256, bytes}]
|
|
39
|
+
//
|
|
40
|
+
// 1.3.0 planUnits(book, scope, layer, ctx): ctx = {db} — the command / acceptance transaction
|
|
41
|
+
// client (read-only use). For layer 'video' the result may be {units, waits, skipped}:
|
|
42
|
+
// waits [{chapter_id, scene_id}] — the scene waits for live images / audio: the command
|
|
43
|
+
// joins those jobs, the video stage follows their acceptance (§6.3, §6.5)
|
|
44
|
+
// skipped [{chapter_id, scene_id, reason: 'skipped_*'}] — summary + gen_command_skips
|
|
45
|
+
// A part unit may carry input.merge_parts [{unit_key, part_hash}] (every part of the scene):
|
|
46
|
+
// its merge is created when all those parts are done (video_group → video_merge).
|
|
33
47
|
|
|
34
48
|
'use strict';
|
|
35
49
|
|
|
@@ -39,7 +53,7 @@ const REQUIRED = Object.freeze([
|
|
|
39
53
|
'planUnits', 'buildPayload', 'artifactPath', 'validateResult',
|
|
40
54
|
'runLocal', 'laneFor', 'timeoutFor', 'retryPolicy',
|
|
41
55
|
]);
|
|
42
|
-
const OPTIONAL = Object.freeze(['maxAttemptsFor', 'isLayerEnabled', 'onArtifactPlaced']);
|
|
56
|
+
const OPTIONAL = Object.freeze(['maxAttemptsFor', 'isLayerEnabled', 'onArtifactPlaced', 'inputFiles']);
|
|
43
57
|
|
|
44
58
|
// ── default retry policy: gpu-retry-policy.cjs:50–53 ─────────────────────
|
|
45
59
|
const RETRY_POLICY = Object.freeze({
|
package/src/gen/progress.js
CHANGED
|
@@ -40,10 +40,22 @@ function createProgress({ pool }) {
|
|
|
40
40
|
WHERE l.command_id = ANY($1::uuid[])
|
|
41
41
|
GROUP BY 1, 2, 3, 4, 5, 6`, [ids])).rows : [];
|
|
42
42
|
|
|
43
|
+
// 1.3.0 — why the command made no work for a scene (§6.5, §13 п.11 п.9): {reason: [scene_id…]}
|
|
44
|
+
const skipRows = ids.length ? (await pool.query(
|
|
45
|
+
`SELECT command_id, reason, scene_id FROM gen_command_skips WHERE command_id = ANY($1::uuid[])
|
|
46
|
+
ORDER BY created_at, chapter_id, scene_id`, [ids])).rows : [];
|
|
47
|
+
const skippedOf = new Map();
|
|
48
|
+
for (const r of skipRows) {
|
|
49
|
+
if (!skippedOf.has(r.command_id)) skippedOf.set(r.command_id, {});
|
|
50
|
+
const m = skippedOf.get(r.command_id);
|
|
51
|
+
if (!m[r.reason]) m[r.reason] = [];
|
|
52
|
+
if (!m[r.reason].includes(r.scene_id)) m[r.reason].push(r.scene_id);
|
|
53
|
+
}
|
|
54
|
+
|
|
43
55
|
const byCmd = new Map(cmds.map((c) => [c.command_id, {
|
|
44
56
|
command_id: c.command_id, kind: c.kind, scope: c.scope, layers: c.layers, force: c.force,
|
|
45
57
|
status: c.status, user_id: c.user_id, created_at: c.created_at, finished_at: c.finished_at,
|
|
46
|
-
error: c.error, summary: c.summary,
|
|
58
|
+
error: c.error, summary: c.summary, skipped: skippedOf.get(c.command_id) || {},
|
|
47
59
|
totals: zero(), by_layer: {}, merges: {}, scenes: new Map(),
|
|
48
60
|
}]));
|
|
49
61
|
const add = (row, field) => {
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// ======================================================
|
|
2
|
+
// gen/sql/004-command-skips — ADR ORCHESTRATION_V2 §6.5, §13 п.11 (stage 3, video)
|
|
3
|
+
// ======================================================
|
|
4
|
+
// gen_command_skips: why a command did NOT create work for a scene
|
|
5
|
+
// (skipped_needs_audio / skipped_image_dirty / skipped_needs_image, …).
|
|
6
|
+
// Written when the command is created (also mirrored into gen_commands.summary)
|
|
7
|
+
// and by stage transitions inside the acceptance transaction (a video command
|
|
8
|
+
// waited for images / audio and the scene turned out not ready). Insert-only:
|
|
9
|
+
// the acceptance transaction never updates gen_commands rows (it holds them
|
|
10
|
+
// FOR SHARE — an UPDATE there could deadlock two parallel acceptances).
|
|
11
|
+
// Progress reads it. Rows go with the command (ON DELETE CASCADE).
|
|
12
|
+
|
|
13
|
+
'use strict';
|
|
14
|
+
|
|
15
|
+
const GEN_COMMAND_SKIPS_SQL = Object.freeze([
|
|
16
|
+
`CREATE TABLE IF NOT EXISTS gen_command_skips (
|
|
17
|
+
command_id UUID NOT NULL REFERENCES gen_commands(command_id) ON DELETE CASCADE,
|
|
18
|
+
chapter_id TEXT NOT NULL,
|
|
19
|
+
scene_id TEXT NOT NULL,
|
|
20
|
+
reason TEXT NOT NULL CHECK (reason ~ '^skipped_[a-z_]{1,48}$'),
|
|
21
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
22
|
+
PRIMARY KEY (command_id, chapter_id, scene_id, reason)
|
|
23
|
+
)`,
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
module.exports = { GEN_COMMAND_SKIPS_SQL };
|
package/src/gen/sql/index.js
CHANGED
|
@@ -6,12 +6,14 @@
|
|
|
6
6
|
const { GEN_CORE_SQL } = require('./001-gen-core');
|
|
7
7
|
const { GEN_COMMAND_JOBS_SQL } = require('./002-command-jobs');
|
|
8
8
|
const { GEN_SCOPE_SCENES_SQL } = require('./003-scope-scenes');
|
|
9
|
+
const { GEN_COMMAND_SKIPS_SQL } = require('./004-command-skips');
|
|
9
10
|
const { withTx } = require('../util');
|
|
10
11
|
|
|
11
12
|
const MIGRATIONS = Object.freeze([
|
|
12
13
|
Object.freeze({ id: '001-gen-core', statements: GEN_CORE_SQL }),
|
|
13
14
|
Object.freeze({ id: '002-command-jobs', statements: GEN_COMMAND_JOBS_SQL }),
|
|
14
15
|
Object.freeze({ id: '003-scope-scenes', statements: GEN_SCOPE_SCENES_SQL }),
|
|
16
|
+
Object.freeze({ id: '004-command-skips', statements: GEN_COMMAND_SKIPS_SQL }),
|
|
15
17
|
]);
|
|
16
18
|
|
|
17
19
|
/**
|
package/src/gen/stage.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// ======================================================
|
|
2
|
+
// gen/stage — helpers shared by command creation and stage transitions
|
|
3
|
+
// (1.3.0: video, ADR §6.3, §6.5, §13 п.11)
|
|
4
|
+
// ======================================================
|
|
5
|
+
// Everything here runs on the caller's transaction client (command tx or
|
|
6
|
+
// acceptance tx) and never UPDATEs gen_commands (acceptance holds those rows
|
|
7
|
+
// FOR SHARE).
|
|
8
|
+
|
|
9
|
+
'use strict';
|
|
10
|
+
|
|
11
|
+
const { GenError, LAYER_OF_KIND, LIVE } = require('./util');
|
|
12
|
+
|
|
13
|
+
/** part kind → its merge kind (a part kind with input.merge_parts ends in this local job) */
|
|
14
|
+
const MERGE_OF_PART = Object.freeze({ video_group: 'video_merge', audio_chunk: 'audio_merge' });
|
|
15
|
+
/** kinds a waiting video command joins in its scene (images + audio, §6.5, §13 п.11 п.3) */
|
|
16
|
+
const VIDEO_WAIT_KINDS = Object.freeze(['iu_image', 'audio_chunk', 'audio_merge']);
|
|
17
|
+
const SKIP_REASON_RE = /^skipped_[a-z_]{1,48}$/;
|
|
18
|
+
|
|
19
|
+
/** input.merge_parts → [{unit_key, part_hash}] (non-empty, string fields) or null. */
|
|
20
|
+
function mergePartsOf(input) {
|
|
21
|
+
const v = input && input.merge_parts;
|
|
22
|
+
if (!Array.isArray(v) || v.length === 0) return null;
|
|
23
|
+
const out = [];
|
|
24
|
+
for (const p of v) {
|
|
25
|
+
if (!p || typeof p.unit_key !== 'string' || !p.unit_key || typeof p.part_hash !== 'string' || !p.part_hash) return null;
|
|
26
|
+
out.push({ unit_key: p.unit_key, part_hash: p.part_hash });
|
|
27
|
+
}
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* planUnits result → {units, waits, skipped}. A plain array (every layer before
|
|
33
|
+
* 1.3.0, audio / image now) is {units: array}. Video may return the object form:
|
|
34
|
+
* units — first-stage units (video_group)
|
|
35
|
+
* waits — [{chapter_id, scene_id}] scenes waiting for live images / audio: the
|
|
36
|
+
* command joins those live jobs; the video stage follows their acceptance
|
|
37
|
+
* skipped — [{chapter_id, scene_id, reason: 'skipped_*'}]
|
|
38
|
+
*/
|
|
39
|
+
function normalisePlan(planned, layer) {
|
|
40
|
+
if (Array.isArray(planned)) return { units: planned, waits: [], skipped: [] };
|
|
41
|
+
if (!planned || typeof planned !== 'object' || !Array.isArray(planned.units)) {
|
|
42
|
+
throw new GenError('bad_plan', 500, `planUnits(${layer}) must return an array or {units, waits?, skipped?}`);
|
|
43
|
+
}
|
|
44
|
+
const scene = (x) => x && typeof x.chapter_id === 'string' && x.chapter_id && typeof x.scene_id === 'string' && x.scene_id;
|
|
45
|
+
const waits = Array.isArray(planned.waits) ? planned.waits : [];
|
|
46
|
+
const skipped = Array.isArray(planned.skipped) ? planned.skipped : [];
|
|
47
|
+
if (!waits.every(scene)) throw new GenError('bad_plan', 500, `planUnits(${layer}): waits[] entries need chapter_id, scene_id`);
|
|
48
|
+
if (!skipped.every((s) => scene(s) && typeof s.reason === 'string' && SKIP_REASON_RE.test(s.reason))) {
|
|
49
|
+
throw new GenError('bad_plan', 500, `planUnits(${layer}): skipped[] entries need chapter_id, scene_id, reason skipped_*`);
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
units: planned.units,
|
|
53
|
+
waits: waits.map((w) => ({ chapter_id: w.chapter_id, scene_id: w.scene_id })),
|
|
54
|
+
skipped: skipped.map((s) => ({ chapter_id: s.chapter_id, scene_id: s.scene_id, reason: s.reason })),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Units whose part is already accepted for the current content: the scene asset
|
|
60
|
+
* of the same build records gen_parts[unit_key].part_hash = input.part_hash
|
|
61
|
+
* (row pending / ready — a 'stale' row proves nothing). 1.1.0 rule, shared.
|
|
62
|
+
* @returns {Promise<Set<object>>} subset of `units` (by identity)
|
|
63
|
+
*/
|
|
64
|
+
async function readyParts(client, bookId, units) {
|
|
65
|
+
const parted = units.filter((u) => u.input && typeof u.input.part_hash === 'string' && u.input.part_hash);
|
|
66
|
+
if (!parted.length) return new Set();
|
|
67
|
+
const r = await client.query(
|
|
68
|
+
`SELECT t.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
|
|
69
|
+
WITH ORDINALITY AS t(chapter_id, scene_id, asset_type, build_id, unit_key, part_hash, ord)
|
|
70
|
+
WHERE EXISTS (SELECT 1 FROM scene_assets a
|
|
71
|
+
WHERE a.book_id = $1 AND a.chapter_id = t.chapter_id AND a.scene_id = t.scene_id
|
|
72
|
+
AND a.asset_type = t.asset_type AND a.build_id = t.build_id
|
|
73
|
+
AND a.status IN ('pending', 'ready')
|
|
74
|
+
AND jsonb_typeof(a.metadata->'gen_parts') = 'object'
|
|
75
|
+
AND a.metadata->'gen_parts'->t.unit_key->>'part_hash' = t.part_hash)`,
|
|
76
|
+
[bookId, parted.map((u) => u.chapter_id), parted.map((u) => u.scene_id), parted.map((u) => LAYER_OF_KIND[u.kind]),
|
|
77
|
+
parted.map((u) => u.build_id), parted.map((u) => u.unit_key), parted.map((u) => u.input.part_hash)]);
|
|
78
|
+
return new Set(r.rows.map((row) => parted[Number(row.ord) - 1]));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* For every listed part: the latest DONE job of that unit_key with that part_hash
|
|
83
|
+
* (same build). Returned in `parts` order; `missing` = parts without such a job.
|
|
84
|
+
*/
|
|
85
|
+
async function donePartsFor(client, { bookId, chapterId, sceneId, buildId, kind }, parts) {
|
|
86
|
+
const r = await client.query(
|
|
87
|
+
`SELECT DISTINCT ON (j.unit_key) j.unit_key, j.job_id, j.result_path, j.result_sha256,
|
|
88
|
+
j.input->'part_meta' AS meta, j.input->>'part_hash' AS part_hash
|
|
89
|
+
FROM gen_jobs j
|
|
90
|
+
JOIN unnest($6::text[], $7::text[]) AS t(uk, ph) ON j.unit_key = t.uk AND j.input->>'part_hash' = t.ph
|
|
91
|
+
WHERE j.book_id = $1 AND j.chapter_id = $2 AND j.scene_id = $3 AND j.kind = $4 AND j.build_id = $5
|
|
92
|
+
AND j.status = 'done'
|
|
93
|
+
ORDER BY j.unit_key, j.finished_at DESC`,
|
|
94
|
+
[bookId, chapterId, sceneId, kind, buildId, parts.map((p) => p.unit_key), parts.map((p) => p.part_hash)]);
|
|
95
|
+
const by = new Map(r.rows.map((x) => [x.unit_key, x]));
|
|
96
|
+
const done = [];
|
|
97
|
+
const missing = [];
|
|
98
|
+
for (const p of parts) {
|
|
99
|
+
const x = by.get(p.unit_key);
|
|
100
|
+
if (!x) { missing.push(p); continue; }
|
|
101
|
+
done.push({ unit_key: x.unit_key, job_id: x.job_id, path: x.result_path, sha256: x.result_sha256, part_hash: x.part_hash, meta: x.meta || null });
|
|
102
|
+
}
|
|
103
|
+
return { done, missing };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Is any job of these unit_keys of the scene live (queued / running)? */
|
|
107
|
+
async function anyLive(client, { bookId, chapterId, sceneId, kind }, unitKeys) {
|
|
108
|
+
const r = await client.query(
|
|
109
|
+
`SELECT 1 FROM gen_jobs WHERE book_id = $1 AND chapter_id = $2 AND scene_id = $3 AND kind = $4
|
|
110
|
+
AND unit_key = ANY($5::text[]) AND status = ANY($6::text[]) LIMIT 1`,
|
|
111
|
+
[bookId, chapterId, sceneId, kind, unitKeys, LIVE]);
|
|
112
|
+
return r.rowCount > 0;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The merge unit of a scene whose parts (input.merge_parts of its part units) are
|
|
117
|
+
* all done: {kind: merge, unit_key: 'scene', input: {scene_hash, parts}} or null.
|
|
118
|
+
*/
|
|
119
|
+
async function mergeUnitFor(client, bookId, partUnit) {
|
|
120
|
+
const parts = mergePartsOf(partUnit.input);
|
|
121
|
+
const mergeKind = MERGE_OF_PART[partUnit.kind];
|
|
122
|
+
if (!parts || !mergeKind) return null;
|
|
123
|
+
const where = { bookId, chapterId: partUnit.chapter_id, sceneId: partUnit.scene_id, buildId: partUnit.build_id, kind: partUnit.kind };
|
|
124
|
+
if (await anyLive(client, where, parts.map((p) => p.unit_key))) return null;
|
|
125
|
+
const { done, missing } = await donePartsFor(client, where, parts);
|
|
126
|
+
if (missing.length) return null;
|
|
127
|
+
const sceneHash = partUnit.scene_hash ?? partUnit.input.scene_hash ?? null;
|
|
128
|
+
return {
|
|
129
|
+
chapter_id: partUnit.chapter_id, scene_id: partUnit.scene_id, kind: mergeKind, unit_key: 'scene',
|
|
130
|
+
build_id: partUnit.build_id, scene_hash: sceneHash,
|
|
131
|
+
input: { scene_hash: sceneHash, parts: done, merge_parts: parts },
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Link commands to every live job of `kinds` in the given scenes (a waiting command joins them). */
|
|
136
|
+
async function linkSceneLive(client, commandIds, bookId, scenes, kinds = VIDEO_WAIT_KINDS) {
|
|
137
|
+
if (!commandIds.length || !scenes.length) return 0;
|
|
138
|
+
const r = await client.query(
|
|
139
|
+
`INSERT INTO gen_command_jobs (command_id, job_id)
|
|
140
|
+
SELECT c, j.job_id
|
|
141
|
+
FROM gen_jobs j
|
|
142
|
+
JOIN unnest($2::text[], $3::text[]) AS s(ch, sc) ON j.chapter_id = s.ch AND j.scene_id = s.sc
|
|
143
|
+
CROSS JOIN unnest($4::uuid[]) AS c
|
|
144
|
+
WHERE j.book_id = $1 AND j.kind = ANY($5::text[]) AND j.status IN ('queued','running')
|
|
145
|
+
ON CONFLICT DO NOTHING`,
|
|
146
|
+
[bookId, scenes.map((s) => s.chapter_id), scenes.map((s) => s.scene_id), commandIds, kinds]);
|
|
147
|
+
return r.rowCount;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Record skip reasons for commands (insert-only, idempotent). */
|
|
151
|
+
async function recordSkips(client, commandIds, skipped) {
|
|
152
|
+
if (!commandIds.length || !skipped.length) return 0;
|
|
153
|
+
const rows = [];
|
|
154
|
+
for (const c of commandIds) for (const s of skipped) rows.push([c, s.chapter_id, s.scene_id, s.reason]);
|
|
155
|
+
const r = await client.query(
|
|
156
|
+
`INSERT INTO gen_command_skips (command_id, chapter_id, scene_id, reason)
|
|
157
|
+
SELECT * FROM unnest($1::uuid[], $2::text[], $3::text[], $4::text[])
|
|
158
|
+
ON CONFLICT DO NOTHING`,
|
|
159
|
+
[rows.map((x) => x[0]), rows.map((x) => x[1]), rows.map((x) => x[2]), rows.map((x) => x[3])]);
|
|
160
|
+
return r.rowCount;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** skipped[] → {skipped_x: [scene_id…]} for the command summary. */
|
|
164
|
+
function skipSummary(skipped) {
|
|
165
|
+
const out = {};
|
|
166
|
+
for (const s of skipped) {
|
|
167
|
+
if (!out[s.reason]) out[s.reason] = [];
|
|
168
|
+
if (!out[s.reason].includes(s.scene_id)) out[s.reason].push(s.scene_id);
|
|
169
|
+
}
|
|
170
|
+
return out;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
module.exports = {
|
|
174
|
+
MERGE_OF_PART,
|
|
175
|
+
VIDEO_WAIT_KINDS,
|
|
176
|
+
mergePartsOf,
|
|
177
|
+
normalisePlan,
|
|
178
|
+
readyParts,
|
|
179
|
+
donePartsFor,
|
|
180
|
+
anyLive,
|
|
181
|
+
mergeUnitFor,
|
|
182
|
+
linkSceneLive,
|
|
183
|
+
recordSkips,
|
|
184
|
+
skipSummary,
|
|
185
|
+
};
|