@animastor/orchestration 1.1.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 +47 -0
- package/README.md +19 -0
- package/package.json +2 -2
- package/src/gen/accept.js +166 -39
- package/src/gen/claim.js +62 -3
- package/src/gen/commands.js +126 -73
- package/src/gen/index.js +13 -7
- package/src/gen/local-runner.js +4 -3
- package/src/gen/log.js +63 -0
- 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/src/gen/sweeper.js +13 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
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
|
+
|
|
29
|
+
## 1.2.0 (2026-11-07) — наблюдаемость v2 (О3)
|
|
30
|
+
|
|
31
|
+
Основание: `reports/2026-11-07/orch-v2-image-scene-run.md` О3 и «мелочи». Minor: только
|
|
32
|
+
добавления, контракт портов 1.0.0 не меняется.
|
|
33
|
+
|
|
34
|
+
- **Строки `[gen-v2]`** через порт логгера (`createOrchestration({ logger })`, метод `info`,
|
|
35
|
+
иначе `log`; без логгера — молча): `command-created` (book, command, layers, scope,
|
|
36
|
+
jobs_created/joined/skipped_ready, existing для повторного клика), `claim` (job, kind,
|
|
37
|
+
unit_key, attempt/max_attempts, worker_id, ms), `accept` (sha256, bytes, width/height,
|
|
38
|
+
idempotent, stage_jobs_created, ms приёма, run_ms от claim), `error` (каждая неудачная
|
|
39
|
+
попытка: error_class, job_status, retry; 409 — `code=stale_attempt`), `requeue`
|
|
40
|
+
(возврат в очередь, delay_ms), `command-finished` (status, done/failed/cancelled, run_ms).
|
|
41
|
+
Печатаются только поля из белого списка (`gen/log.js` `FIELDS`): токены загрузки, пути
|
|
42
|
+
файлов и параметры задач в строки не попадают. Форматер — `gen.formatGenEvent`.
|
|
43
|
+
- Ядро `src/gen` больше не вызывает `console` само: `sweeper`/`local runner` пишут ошибки
|
|
44
|
+
через тот же порт (по умолчанию `createOrchestration` по-прежнему берёт `console`).
|
|
45
|
+
- **`scene_assets.width/height`** для изображений: размеры из PNG-валидатора сохраняются в
|
|
46
|
+
`gen_parts[unit_key]` и в строке сцены при `ready` (размер файла `path`, т. е. первой
|
|
47
|
+
части); для финальных видов — `COALESCE` из результата проверки, если он их знает.
|
|
48
|
+
- **Права принятых файлов 0644** (как у legacy); временный файл в `.incoming` — 0640.
|
|
49
|
+
|
|
3
50
|
## 1.1.0 (2026-11-07) — этап 2a: изображения (`iu_image`)
|
|
4
51
|
|
|
5
52
|
ADR `architecture/ORCHESTRATION_V2.md` (§4.3, §7, §12 «2a», §13 п.9). Minor: только
|
package/README.md
CHANGED
|
@@ -31,6 +31,25 @@ orch.startSweeper(10_000);
|
|
|
31
31
|
«already done» skip) and `input.scene_parts` (scene asset `ready` once every
|
|
32
32
|
listed part is accepted — for part kinds without a merge stage).
|
|
33
33
|
|
|
34
|
+
**1.2.0 (observability).** Pass `logger` (`{ info | log, error }`) to
|
|
35
|
+
`createOrchestration`: the core writes one line per step —
|
|
36
|
+
`[gen-v2] command-created | claim | accept | error | requeue | command-finished`
|
|
37
|
+
with `book_id`, `command_id`, `job_id`, `kind`, `unit_key`, `attempt`,
|
|
38
|
+
`worker_id`, `sha256`, sizes and durations (allowlisted fields only: no upload
|
|
39
|
+
tokens, paths or task params). Image acceptance records `width`/`height`;
|
|
40
|
+
accepted files are `0644`.
|
|
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
|
+
|
|
34
53
|
`gen` requires only node builtins and its own files: no `src/legacy`, Redis,
|
|
35
54
|
Express or ComfyUI. Tests: `npm run test:gen` (env `PG_*` of the animastor-test
|
|
36
55
|
stack; refuses a DB not ending in `_test` or port 5432).
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@animastor/orchestration",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "Animastor Orchestration 1.
|
|
3
|
+
"version": "1.3.0",
|
|
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",
|
|
7
7
|
"dispatch",
|
package/src/gen/accept.js
CHANGED
|
@@ -22,6 +22,15 @@ const {
|
|
|
22
22
|
EXECUTOR_OF_KIND, LAYER_OF_KIND, LIVE,
|
|
23
23
|
} = require('./util');
|
|
24
24
|
const { checkLane } = require('./ports');
|
|
25
|
+
const { msBetween } = require('./log');
|
|
26
|
+
const {
|
|
27
|
+
normalisePlan, readyParts, mergePartsOf, mergeUnitFor, linkSceneLive, recordSkips,
|
|
28
|
+
} = require('./stage');
|
|
29
|
+
|
|
30
|
+
const NOOP_LOG = Object.freeze({ event() {} });
|
|
31
|
+
/** Mode of an accepted artifact: world-readable like the legacy outputs (О3; the tmp file is 0640). */
|
|
32
|
+
const ARTIFACT_MODE = 0o644;
|
|
33
|
+
const dim = (v) => (Number.isInteger(v) && v > 0 ? v : null);
|
|
25
34
|
|
|
26
35
|
const PART_KINDS = new Set(['audio_chunk', 'iu_image', 'video_group']);
|
|
27
36
|
const FINAL_FORMAT = { audio_merge: 'mp3', video_merge: 'mp4' };
|
|
@@ -51,7 +60,7 @@ async function drain(stream) {
|
|
|
51
60
|
try { stream.resume(); } catch (_) { /* ignore */ }
|
|
52
61
|
}
|
|
53
62
|
|
|
54
|
-
function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_UPLOAD_BYTES }) {
|
|
63
|
+
function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_UPLOAD_BYTES, genLog = NOOP_LOG }) {
|
|
55
64
|
const sceneLockKey = (j) => `animastor:gen-v2:scene:${JSON.stringify([j.book_id, j.chapter_id, j.scene_id])}`;
|
|
56
65
|
|
|
57
66
|
// ── shared: a failed attempt → retry with backoff or failed (§7 «Ошибка», §9 пп.1–2)
|
|
@@ -75,7 +84,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
75
84
|
[job.worker_id, job.job_id]);
|
|
76
85
|
}
|
|
77
86
|
await notifyProgress(client, job.book_id, job.command_id);
|
|
78
|
-
return { status: r.rows[0].status, not_before: r.rows[0].not_before, retry };
|
|
87
|
+
return { status: r.rows[0].status, not_before: r.rows[0].not_before, retry, delay_ms: retry ? delay : undefined };
|
|
79
88
|
}
|
|
80
89
|
|
|
81
90
|
/**
|
|
@@ -85,13 +94,30 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
85
94
|
async function failAttempt(jobId, attempt, errorClass, reason) {
|
|
86
95
|
const cls = typeof errorClass === 'string' && errorClass ? errorClass.slice(0, 64) : 'unknown';
|
|
87
96
|
const why = reason == null ? null : String(reason).slice(0, 2000);
|
|
88
|
-
|
|
89
|
-
|
|
97
|
+
let job = null;
|
|
98
|
+
let out = null;
|
|
99
|
+
const r = await withTx(pool, async (client) => {
|
|
100
|
+
job = (await client.query('SELECT * FROM gen_jobs WHERE job_id = $1 FOR UPDATE', [jobId])).rows[0];
|
|
90
101
|
if (!job) return { status: 404, code: 'not_found' };
|
|
91
102
|
if (job.status !== 'running' || job.attempt !== attempt) return { status: 409, code: 'stale_attempt' };
|
|
92
|
-
|
|
103
|
+
out = await failAttemptTx(client, job, cls, why);
|
|
93
104
|
return { status: 200, job_status: out.status, retry: out.retry };
|
|
94
105
|
});
|
|
106
|
+
// О3, after commit: `error` for every failed attempt, `requeue` when it goes back to the queue
|
|
107
|
+
const ids = job ? {
|
|
108
|
+
book_id: job.book_id, command_id: job.command_id, job_id: job.job_id, kind: job.kind, unit_key: job.unit_key,
|
|
109
|
+
worker_id: job.worker_id,
|
|
110
|
+
} : { job_id: jobId };
|
|
111
|
+
if (r.status !== 200) {
|
|
112
|
+
genLog.event('error', { ...ids, attempt, error_class: cls, code: r.code });
|
|
113
|
+
} else {
|
|
114
|
+
genLog.event('error', {
|
|
115
|
+
...ids, attempt, max_attempts: job.max_attempts, error_class: cls, job_status: out.status, retry: out.retry,
|
|
116
|
+
run_ms: msBetween(job.claimed_at),
|
|
117
|
+
});
|
|
118
|
+
if (out.retry) genLog.event('requeue', { ...ids, attempt, max_attempts: job.max_attempts, error_class: cls, delay_ms: out.delay_ms });
|
|
119
|
+
}
|
|
120
|
+
return r;
|
|
95
121
|
}
|
|
96
122
|
|
|
97
123
|
// ── scene_assets (§4.3: written only by acceptance) ──────────────────────
|
|
@@ -102,6 +128,8 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
102
128
|
if (PART_KINDS.has(job.kind)) {
|
|
103
129
|
// a part (chunk / IU / group) is recorded, the scene asset is not ready yet
|
|
104
130
|
const entry = { kind: job.kind, path: finalPath, sha256: sha, bytes, job_id: job.job_id, attempt: job.attempt };
|
|
131
|
+
// О3: the PNG validator knows the size — keep it with the part (scene_assets.width/height below)
|
|
132
|
+
if (validation && dim(validation.width) && dim(validation.height)) { entry.width = validation.width; entry.height = validation.height; }
|
|
105
133
|
if (typeof job.input.part_hash === 'string' && job.input.part_hash) entry.part_hash = job.input.part_hash;
|
|
106
134
|
const part = { [job.unit_key]: entry };
|
|
107
135
|
const sceneParts = partsManifest(job.input.scene_parts);
|
|
@@ -132,12 +160,14 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
132
160
|
const complete = sceneParts.every((p) => parts[p.unit_key] && parts[p.unit_key].part_hash === p.part_hash);
|
|
133
161
|
if (complete) {
|
|
134
162
|
const manifest = sceneParts.map((p) => `${p.unit_key}:${parts[p.unit_key].sha256 || ''}`).join('\n');
|
|
163
|
+
const first = parts[sceneParts[0].unit_key];
|
|
164
|
+
// width/height = those of the file `path` points at (the first part)
|
|
135
165
|
await client.query(
|
|
136
166
|
`UPDATE scene_assets SET scene_hash = $2, status = 'ready', error = NULL, sha256 = $3, job_id = $4,
|
|
137
|
-
path = $5, format = $6
|
|
167
|
+
path = $5, format = $6, width = $7, height = $8
|
|
138
168
|
WHERE id = $1`,
|
|
139
169
|
[up.id, sceneHash, crypto.createHash('sha256').update(manifest).digest('hex'), job.job_id,
|
|
140
|
-
|
|
170
|
+
first.path || finalPath, PART_FORMAT[job.kind] || null, dim(first.width), dim(first.height)]);
|
|
141
171
|
} else {
|
|
142
172
|
await client.query(
|
|
143
173
|
`UPDATE scene_assets SET scene_hash = $2, status = 'pending', sha256 = NULL, job_id = NULL WHERE id = $1`,
|
|
@@ -159,17 +189,21 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
159
189
|
return;
|
|
160
190
|
}
|
|
161
191
|
const duration = validation && Number.isFinite(validation.durationSec) ? validation.durationSec : null;
|
|
192
|
+
const width = validation ? dim(validation.width) : null;
|
|
193
|
+
const height = validation ? dim(validation.height) : null;
|
|
162
194
|
await client.query(
|
|
163
195
|
`INSERT INTO scene_assets (book_id, chapter_id, scene_id, asset_type, path, build_id, scene_hash, status,
|
|
164
|
-
job_id, sha256, duration_sec, format, updated_at)
|
|
165
|
-
VALUES ($1, $2, $3, $4, $5, $6, $7, 'ready', $8, $9, $10, $11, $12)
|
|
196
|
+
job_id, sha256, duration_sec, format, updated_at, width, height)
|
|
197
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, 'ready', $8, $9, $10, $11, $12, $13, $14)
|
|
166
198
|
ON CONFLICT (book_id, chapter_id, scene_id, asset_type, build_id) DO UPDATE SET
|
|
167
199
|
path = EXCLUDED.path, scene_hash = EXCLUDED.scene_hash, status = 'ready', error = NULL,
|
|
168
200
|
job_id = EXCLUDED.job_id, sha256 = EXCLUDED.sha256,
|
|
169
201
|
duration_sec = COALESCE(EXCLUDED.duration_sec, scene_assets.duration_sec),
|
|
202
|
+
width = COALESCE(EXCLUDED.width, scene_assets.width),
|
|
203
|
+
height = COALESCE(EXCLUDED.height, scene_assets.height),
|
|
170
204
|
format = EXCLUDED.format, updated_at = EXCLUDED.updated_at`,
|
|
171
205
|
[job.book_id, job.chapter_id, job.scene_id, assetType, finalPath, build, sceneHash,
|
|
172
|
-
job.job_id, sha, duration, FINAL_FORMAT[job.kind], epochS()]);
|
|
206
|
+
job.job_id, sha, duration, FINAL_FORMAT[job.kind], epochS(), width, height]);
|
|
173
207
|
}
|
|
174
208
|
|
|
175
209
|
// ── stage transitions (§6.3) — same transaction as the finished job ─────
|
|
@@ -241,43 +275,106 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
241
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 }));
|
|
242
276
|
}
|
|
243
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
|
+
|
|
244
327
|
/**
|
|
245
328
|
* §6.3: a next stage is created only if at least one command linked to the finished job is
|
|
246
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
|
|
247
336
|
*/
|
|
248
337
|
async function transitions(client, cmds, job) {
|
|
249
|
-
const
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
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)]);
|
|
256
348
|
const mergeInput = async (kind) => ({
|
|
257
349
|
scene_hash: job.input.scene_hash ?? null,
|
|
258
350
|
parts: await doneParts(client, job, kind),
|
|
259
351
|
});
|
|
260
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 });
|
|
261
353
|
|
|
262
|
-
if (job.kind === 'audio_chunk' || job.kind === 'video_group' || job.kind === 'iu_image') {
|
|
263
|
-
await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [sceneLockKey(job)]);
|
|
264
|
-
if (!(await sceneStageComplete(client, job, job.kind, ids))) return 0;
|
|
265
|
-
}
|
|
266
354
|
if (job.kind === 'audio_chunk') {
|
|
267
|
-
|
|
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'))]);
|
|
268
360
|
}
|
|
269
361
|
if (job.kind === 'video_group') {
|
|
270
|
-
|
|
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'))]);
|
|
271
371
|
}
|
|
272
|
-
if (job.kind === 'iu_image') {
|
|
273
|
-
const
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
&& u.chapter_id === job.chapter_id && u.scene_id === job.scene_id
|
|
279
|
-
&& typeof u.unit_key === 'string' && typeof u.build_id === 'string' && u.input && typeof u.input === 'object');
|
|
280
|
-
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);
|
|
281
378
|
}
|
|
282
379
|
return 0;
|
|
283
380
|
}
|
|
@@ -286,7 +383,27 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
286
383
|
* Steps 1(validate)–5 of §7 for a file already on disk at tmpPath.
|
|
287
384
|
* @returns {Promise<{status:number, code?:string, reason?:string, idempotent?:boolean, sha256?:string, job_status?:string, stage_jobs_created?:number}>}
|
|
288
385
|
*/
|
|
289
|
-
async function finishAccept(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);
|
|
388
|
+
// О3: `accept` for a committed result (or its idempotent replay); a stale
|
|
389
|
+
// attempt is an `error` line (code stale_attempt); invalid_result is logged by failAttempt.
|
|
390
|
+
const ids = {
|
|
391
|
+
book_id: pre.book_id, command_id: pre.command_id, job_id: pre.job_id, kind: pre.kind, unit_key: pre.unit_key,
|
|
392
|
+
attempt, worker_id: pre.worker_id,
|
|
393
|
+
};
|
|
394
|
+
if (r && r.status === 200) {
|
|
395
|
+
genLog.event('accept', {
|
|
396
|
+
...ids, sha256: sha, bytes, width: r.width, height: r.height, idempotent: r.idempotent === true ? true : undefined,
|
|
397
|
+
stage_jobs_created: r.stage_jobs_created, ms: Date.now() - t0, run_ms: msBetween(pre.claimed_at),
|
|
398
|
+
});
|
|
399
|
+
} else if (r && r.code === 'stale_attempt') {
|
|
400
|
+
genLog.event('error', { ...ids, code: 'stale_attempt', sha256: sha, bytes });
|
|
401
|
+
}
|
|
402
|
+
if (r) { delete r.width; delete r.height; }
|
|
403
|
+
return r;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
async function finishAcceptInner(pre, attempt, tmpPath, sha, bytes, localMeta = null) {
|
|
290
407
|
const finalPath = ports.artifactPath(pre);
|
|
291
408
|
if (typeof finalPath !== 'string' || !path.isAbsolute(finalPath)) {
|
|
292
409
|
await unlinkQuiet(tmpPath);
|
|
@@ -324,7 +441,9 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
324
441
|
await fs.promises.mkdir(path.dirname(finalPath), { recursive: true });
|
|
325
442
|
await fs.promises.rename(tmpPath, finalPath); // §7 п.3 (atomic, same partition)
|
|
326
443
|
renamed = true;
|
|
327
|
-
|
|
444
|
+
await fs.promises.chmod(finalPath, ARTIFACT_MODE).catch(() => {}); // О3: 0644 like legacy outputs
|
|
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 });
|
|
328
447
|
await client.query(
|
|
329
448
|
`UPDATE gen_jobs SET status = 'done', result_path = $2, result_sha256 = $3, result_bytes = $4,
|
|
330
449
|
finished_at = now(), deadline = NULL
|
|
@@ -337,7 +456,10 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
337
456
|
await upsertSceneAsset(client, job, finalPath, sha, bytes, validation);
|
|
338
457
|
const stage = await transitions(client, cmds, job);
|
|
339
458
|
await notifyProgress(client, job.book_id, job.command_id);
|
|
340
|
-
return {
|
|
459
|
+
return {
|
|
460
|
+
status: 200, sha256: sha, job_status: 'done', stage_jobs_created: stage,
|
|
461
|
+
width: validation ? dim(validation.width) : null, height: validation ? dim(validation.height) : null,
|
|
462
|
+
};
|
|
341
463
|
});
|
|
342
464
|
} finally {
|
|
343
465
|
if (!renamed) await unlinkQuiet(tmpPath); // rejected / failed before rename → discard
|
|
@@ -361,6 +483,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
361
483
|
* @param {AsyncIterable<Buffer>} stream raw file body
|
|
362
484
|
*/
|
|
363
485
|
async function acceptResult(jobId, attempt, token, stream) {
|
|
486
|
+
const t0 = Date.now();
|
|
364
487
|
checkIds(jobId, attempt);
|
|
365
488
|
if (!verifyUploadToken(uploadSecret, token, jobId, attempt)) {
|
|
366
489
|
await drain(stream);
|
|
@@ -369,7 +492,11 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
369
492
|
const pre = await readJob(jobId);
|
|
370
493
|
if (!pre) { await drain(stream); throw new GenError('not_found', 404, 'unknown job'); }
|
|
371
494
|
const current = (pre.status === 'running' || pre.status === 'done') && pre.attempt === attempt;
|
|
372
|
-
if (!current) {
|
|
495
|
+
if (!current) {
|
|
496
|
+
await drain(stream);
|
|
497
|
+
genLog.event('error', { book_id: pre.book_id, command_id: pre.command_id, job_id: jobId, kind: pre.kind, unit_key: pre.unit_key, attempt, code: 'stale_attempt' });
|
|
498
|
+
return { status: 409, code: 'stale_attempt' };
|
|
499
|
+
}
|
|
373
500
|
|
|
374
501
|
const finalPath = ports.artifactPath(pre);
|
|
375
502
|
if (typeof finalPath !== 'string' || !path.isAbsolute(finalPath)) {
|
|
@@ -398,7 +525,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
398
525
|
throw err;
|
|
399
526
|
}
|
|
400
527
|
await fh.close();
|
|
401
|
-
return finishAccept(pre, attempt, tmpPath, hash.digest('hex'), bytes);
|
|
528
|
+
return finishAccept(pre, attempt, tmpPath, hash.digest('hex'), bytes, t0);
|
|
402
529
|
}
|
|
403
530
|
|
|
404
531
|
/**
|
|
@@ -412,11 +539,11 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
|
|
|
412
539
|
}
|
|
413
540
|
|
|
414
541
|
/** Accept a file produced by the backend itself (executor='local'); no token. */
|
|
415
|
-
async function acceptLocalFile(job, filePath) {
|
|
542
|
+
async function acceptLocalFile(job, filePath, meta = null) {
|
|
416
543
|
const hash = crypto.createHash('sha256');
|
|
417
544
|
let bytes = 0;
|
|
418
545
|
for await (const chunk of fs.createReadStream(filePath)) { hash.update(chunk); bytes += chunk.length; }
|
|
419
|
-
return finishAccept(job, job.attempt, filePath, hash.digest('hex'), bytes);
|
|
546
|
+
return finishAccept(job, job.attempt, filePath, hash.digest('hex'), bytes, Date.now(), meta);
|
|
420
547
|
}
|
|
421
548
|
|
|
422
549
|
return { acceptResult, acceptError, failAttempt, acceptLocalFile };
|
package/src/gen/claim.js
CHANGED
|
@@ -11,13 +11,37 @@
|
|
|
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() {} });
|
|
43
|
+
|
|
44
|
+
function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, tokenGraceMs = 15 * 60_000, genLog = NOOP_LOG }) {
|
|
21
45
|
const timeoutsJson = JSON.stringify(Object.fromEntries(KINDS.map((k) => [k, ports.timeoutFor(k)])));
|
|
22
46
|
|
|
23
47
|
/**
|
|
@@ -32,6 +56,7 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
|
|
|
32
56
|
* @returns {Promise<{task:null}|{task:object}>}
|
|
33
57
|
*/
|
|
34
58
|
async function claim(p = {}) {
|
|
59
|
+
const t0 = Date.now();
|
|
35
60
|
const workerId = requireUuid(p.workerId, 'workerId');
|
|
36
61
|
if (!WORKER_TYPES.includes(p.workerType)) throw new GenError('bad_request', 400, 'workerType must be audio|image|video');
|
|
37
62
|
if (!MODES.includes(p.mode)) throw new GenError('bad_request', 400, 'mode must be private|share|system');
|
|
@@ -99,8 +124,11 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
|
|
|
99
124
|
if (!job) return { task: null };
|
|
100
125
|
|
|
101
126
|
let payload;
|
|
127
|
+
let inputs = null;
|
|
102
128
|
try {
|
|
103
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));
|
|
104
132
|
} catch (err) {
|
|
105
133
|
// the payload cannot be built → this attempt fails deterministically (no silent loss)
|
|
106
134
|
await accept.failAttempt(job.job_id, job.attempt, 'deterministic', `build_payload: ${err && err.message}`);
|
|
@@ -108,6 +136,10 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
|
|
|
108
136
|
}
|
|
109
137
|
const deadlineMs = new Date(job.deadline).getTime();
|
|
110
138
|
const exp = deadlineMs + tokenGraceMs;
|
|
139
|
+
genLog.event('claim', {
|
|
140
|
+
book_id: job.book_id, command_id: job.command_id, job_id: job.job_id, kind: job.kind, unit_key: job.unit_key,
|
|
141
|
+
attempt: job.attempt, max_attempts: job.max_attempts, worker_id: workerId, ms: Date.now() - t0,
|
|
142
|
+
});
|
|
111
143
|
return {
|
|
112
144
|
task: {
|
|
113
145
|
job_id: job.job_id,
|
|
@@ -121,10 +153,37 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
|
|
|
121
153
|
timeout_ms: ports.timeoutFor(job.kind),
|
|
122
154
|
deadline: new Date(deadlineMs).toISOString(),
|
|
123
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 })) } : {}),
|
|
124
157
|
},
|
|
125
158
|
};
|
|
126
159
|
}
|
|
127
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
|
+
|
|
128
187
|
/**
|
|
129
188
|
* Worker liveness (ADR §8.3): last_seen + current_job_id; answer = jobs to stop.
|
|
130
189
|
* cancel = this worker's jobs cancelled in the last hour + the reported
|
|
@@ -149,7 +208,7 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
|
|
|
149
208
|
});
|
|
150
209
|
}
|
|
151
210
|
|
|
152
|
-
return { claim, beacon };
|
|
211
|
+
return { claim, beacon, openInput };
|
|
153
212
|
}
|
|
154
213
|
|
|
155
214
|
module.exports = { createClaim, MODES };
|