@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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,106 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.0 (2026-11-07) — этап 2a: изображения (`iu_image`)
4
+
5
+ ADR `architecture/ORCHESTRATION_V2.md` (§4.3, §7, §12 «2a», §13 п.9). Minor: только
6
+ добавления, контракт портов 1.0.0 не меняется (новые поля юнита опциональны).
7
+
8
+ - **Проверка PNG** (`media.inspectPng`, `defaults.createPngValidator`; порт по умолчанию
9
+ для `iu_image`): сигнатура, IHDR первым, CRC каждого чанка, IDAT, IEND; ширина и высота
10
+ в 1…16384; поток пикселей распаковывается ровно в размер из IHDR; **не пустой кадр** —
11
+ стандартное отклонение яркости по выборке пикселей ≥ `minLumaStddev` (по умолчанию
12
+ `2.0` по шкале 0…255; чёрный / однотонный кадр = 0). Причины отказа: `not_png`,
13
+ `truncated`, `bad_crc`, `no_ihdr`, `bad_dimensions`, `bad_header`, `no_idat`, `no_iend`,
14
+ `corrupt_data`, `blank_frame` → `invalid_result` (один повтор, затем failed — как
15
+ тишина у аудио). Чересстрочные и < 8 бит — только структурная проверка
16
+ (`flat_check: 'skipped'`). 1.0.0 проверяла только сигнатуру.
17
+ - **Пропуск готового по части** (`input.part_hash`): без `force` юнит пропускается, если в
18
+ `scene_assets.metadata.gen_parts[unit_key].part_hash` той же сборки записан тот же хэш
19
+ (строка не `stale`). Приём сохраняет `part_hash` в запись части. Юниты без `part_hash`
20
+ (аудио) — прежнее правило по `scene_hash` сцены.
21
+ - **Готовность сцены без склейки** (`input.scene_parts = [{unit_key, part_hash}]`): приём
22
+ части, закрывающий набор, ставит строке сцены `ready` + `sha256` (манифест
23
+ «unit_key:sha256» по порядку) + `job_id` + `path` (файл первой части) + `format`
24
+ (`png`); незакрытый набор → `pending`, `sha256`/`job_id` = NULL. Параллельный приём
25
+ двух частей одной сцены сериализуется блокировкой строки.
26
+ - `cancel({commandId})` дополнительно возвращает `layers` остановленной команды.
27
+ - `src/gen` может использовать встроенный `zlib` (граница зависимостей).
28
+ - **legacy** (`src/legacy/runtime/scene-window`): `initSceneWindow`, `slideWindow`,
29
+ `trySlideWindowOnComplete`, `reconcileWindowStatuses`, `restoreChunkStatusForScene` для
30
+ v2-книги ничего не делают (тот же предикат `isV2Book`, fail-closed) — read-repair
31
+ chunk-статусов по файлам и сдвиг окна больше не пишут legacy-ключи v2-книги
32
+ (`POST /book/:id/generate-next`).
33
+
34
+ ## 1.0.0 (2026-11-06) — первая публикация: оркестрация v2, ядро `gen` (этапы 1a–1c)
35
+
36
+ Опубликованный пакет: `src/` (`src/gen` с миграциями `sql/001–003`, `src/legacy` — код 0.3.x),
37
+ README, LICENSE, CHANGELOG; `test/` и фикстуры в пакет не входят. Ниже — по этапам.
38
+
39
+ ### Этап 1c: scope `scenes`
40
+
41
+ ADR `architecture/ORCHESTRATION_V2.md` (редакция 06.11, §11.1, §13 п.8).
42
+
43
+ - `scope.level = 'scenes'` — `{level:'scenes', scene_ids:[…]}` (непустой список, порядок
44
+ сохраняется, дубли отбрасываются; `chapter_id` / `scene_id` к нему не применяются).
45
+ Так хост передаёт «с текущей сцены до конца», развёрнутое в порядке книги.
46
+ - `sql/003-scope-scenes`: CHECK `gen_commands_scope_check` пересоздаётся под тем же именем
47
+ с уровнем `scenes` (NULL-безопасно); `ADD_CHECK` из 001 старое определение не возвращает.
48
+
49
+ ### Этап 1b: gen_command_jobs, build_id/layer, отмена по слою
50
+
51
+ ADR `architecture/ORCHESTRATION_V2.md` (редакция 06.11, §4.2a, §6.3–6.4, §7, §13.6).
52
+
53
+ - `sql/002-command-jobs` (поверх 001, идемпотентно): `gen_jobs.build_id` NOT NULL (из
54
+ `input.build_id`), `gen_jobs.layer` NOT NULL + CHECK, `gen_commands.summary`, таблица
55
+ `gen_command_jobs` (PK, FK, бэкфилл).
56
+ - Присоединение — явной связью; прогресс и завершение команды — только по `gen_command_jobs`.
57
+ - `cancel({bookId, layer})` (аудио снимает и `audio_merge`); отмена по executor удалена;
58
+ `cancel({commandId})` не трогает работы, нужные другой активной команде.
59
+ - Ступени §6.3 — только при связанной активной команде со слоем; новая работа связывается со всеми такими.
60
+ - `invalid_result` — один повтор на работу (считается по классу), затем failed.
61
+ - `purgeBook(pool, bookId)`; `progress(bookId, {finishedWithinMs})`; опциональный порт
62
+ `onArtifactPlaced(job, path)`; `retryPolicy(kind, cls, attempt, {previousErrorClass})`.
63
+ - legacy: единый предикат `persistence-port.isV2Book` (опциональная операция порта
64
+ `orchestration.isV2Book`, fail-closed) — command gate, reconcile, scheduler, scene window
65
+ пропускают v2-книги.
66
+
67
+ ### Этап 1a (2026-11-05): ядро `gen` + схема PG
68
+
69
+ ADR: animastor-docs `architecture/ORCHESTRATION_V2.md` (§3, §4, §6–§10, §13). Без
70
+ подключения к роутам backend, без выкатки.
71
+
72
+ #### Changed (breaking только по раскладке файлов)
73
+
74
+ - Весь код 0.3.x перенесён без изменений логики в `src/legacy/`
75
+ (`legacy/host`, `legacy/orchestration`, `legacy/runtime`, `legacy/index.js`).
76
+ Корень `src/index.js` экспортирует тот же API, что 0.3.5 (дескрипторы свойств, ленивые
77
+ геттеры сохранены), плюс новое пространство `gen`. Глубокие импорты
78
+ `src/runtime/*` / `src/orchestration/*` → `src/legacy/runtime/*` / `src/legacy/orchestration/*`.
79
+
80
+ #### Added — `gen` (src/gen/)
81
+
82
+ - `migrate(pool)` — идемпотентная миграция (`sql/001-gen-core.js`): `gen_commands`,
83
+ `gen_jobs` (ADR §4.1–4.2; CHECK по статусам / kind / executor / связке kind↔executor /
84
+ lane; partial UNIQUE «одна живая работа на юнит»; `UNIQUE(book_id, client_action_id)`;
85
+ индексы выдачи, сторожа, прогресса), `books.orchestration` (`legacy`|`v2`, default
86
+ `legacy`), `workers.current_job_id`, `scene_assets.job_id` / `sha256`.
87
+ - `createOrchestration({pool, ports, uploadSecret, outputDir, sharedLimit, …})`:
88
+ `createCommand`, `cancel`, `claim`, `beacon`, `acceptResult`, `acceptError`,
89
+ `sweepOnce` / `startSweeper` / `stopSweeper`, `runLocalOnce` (executor `local`),
90
+ `progress`, `listenProgress` (`LISTEN gen_progress`).
91
+ - Порты (`ports.js`, проверка при инициализации): `planUnits`, `buildPayload`,
92
+ `artifactPath`, `validateResult`, `runLocal`, `laneFor`, `timeoutFor`, `retryPolicy`;
93
+ опционально `maxAttemptsFor`, `isLayerEnabled`. Значения по умолчанию: политика повторов
94
+ = `gpu-retry-policy.cjs:50–53`, таймауты = media-registry, `makeLaneFor` = логика
95
+ `gpu-dispatcher.js:213–222`, `createDefaultValidateResult` (mp3 magic + длительность по
96
+ кадрам + RMS-тишина через ffmpeg, порог параметром; png / mp4 magic).
97
+ - Зависимостей не добавлено: pg-клиент передаёт хост (`pg` — только devDependency тестов).
98
+
99
+ #### Tests
100
+
101
+ - `npm run test:gen` — 43 теста на стеке animastor-test (чистая схема на тест; 1 тест реального ffmpeg-декодера пропускается без ffmpeg). Legacy-набор
102
+ `npm test` без изменений (59).
103
+
3
104
  ## 0.3.5 (2026-11-05) — утечка квоты диспатча, reconcile не понижает закоммиченное
4
105
 
5
106
  Основание: `reports/2026-11-05/live-check-A-B-C.md` §6, §10 и
package/README.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # @animastor/orchestration
2
2
 
3
+ ## 1.x — orchestration v2 (`gen`)
4
+
5
+ ADR: animastor-docs `architecture/ORCHESTRATION_V2.md`. The new core lives in
6
+ `src/gen/` and is exported as `gen`. The 0.3.x contour described below ships
7
+ unchanged in `src/legacy/` (same root exports) until migration stage 4.
8
+
9
+ ```js
10
+ const { gen } = require('@animastor/orchestration');
11
+ await gen.migrate(pool); // idempotent; needs books/workers/scene_assets
12
+ const orch = gen.createOrchestration({
13
+ pool, // pg Pool supplied by the host
14
+ ports: { planUnits, buildPayload, artifactPath, validateResult, runLocal,
15
+ laneFor, timeoutFor, retryPolicy }, // see src/gen/ports.js
16
+ uploadSecret, // >= 32 bytes, HMAC of upload tokens
17
+ outputDir, // {build}/.incoming cleanup
18
+ sharedLimit: null, // ADR §10; NULL = off
19
+ });
20
+ await orch.createCommand({ workspaceId, userId, bookId, kind: 'regenerate',
21
+ scope: { level: 'scene', chapter_id, scene_id },
22
+ layers: ['audio'], clientActionId });
23
+ await orch.claim({ workerId, workerType: 'audio', mode: 'private', workspaceId });
24
+ await orch.acceptResult(jobId, attempt, uploadToken, readableStream);
25
+ orch.startSweeper(10_000);
26
+ ```
27
+
28
+ **1.1.0 (images, stage 2a).** `iu_image` results are checked by `inspectPng`
29
+ (structure + CRC, dimensions > 0, pixel data, not a blank frame — luma stddev ≥
30
+ `minLumaStddev`, default 2.0); a unit may carry `input.part_hash` (part-level
31
+ «already done» skip) and `input.scene_parts` (scene asset `ready` once every
32
+ listed part is accepted — for part kinds without a merge stage).
33
+
34
+ `gen` requires only node builtins and its own files: no `src/legacy`, Redis,
35
+ Express or ComfyUI. Tests: `npm run test:gen` (env `PG_*` of the animastor-test
36
+ stack; refuses a DB not ending in `_test` or port 5432).
37
+
38
+ ## 0.3.x contour (`src/legacy/`)
39
+
3
40
  Generation orchestration and runtime contour of the Animastor backend,
4
41
  physically extracted from the host (`backend/src/orchestration/**` +
5
42
  `backend/src/runtime/**` — §32.30; recon:
package/package.json CHANGED
@@ -1,14 +1,16 @@
1
1
  {
2
2
  "name": "@animastor/orchestration",
3
- "version": "0.3.5",
4
- "description": "Animastor Orchestration — the generation orchestration/runtime contour of the Animastor backend, physically extracted from the host (§32.30): the unified generation lifecycle owner (orchestrator facade, stage executor, scene callbacks/restoration), the dispatch engine and its lease/quota/retry managers, the reconciliation engine and counter reconciliation, the scene window/scheduler/worker-health, the runtime-result emitter/consumer, and the eight O-2..O-10 port contracts (Persistence, SceneData, PlaceholderAudio, ProgressEvents, AudioFsm, VideoFsm, HubCancel, LayerConfig). The package reaches the host (runtime config slices, Redis-domain state layer, media facades, the S-5 seam registry, the artifact root, the PW-2 workspace resolver) ONLY through the composition-root host-bindings seam — no backend/src require, no storage/book/routes/services, no Redis, no PG, no Express inside.",
3
+ "version": "1.1.0",
4
+ "description": "Animastor Orchestration 1.1.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
- "orchestration",
8
- "runtime",
9
7
  "dispatch",
8
+ "generation",
9
+ "job-queue",
10
+ "orchestration",
11
+ "postgres",
10
12
  "reconciliation",
11
- "generation"
13
+ "runtime"
12
14
  ],
13
15
  "main": "src/index.js",
14
16
  "exports": {
@@ -16,13 +18,13 @@
16
18
  },
17
19
  "files": [
18
20
  "src/",
19
- "test/",
20
21
  "README.md",
21
22
  "LICENSE",
22
23
  "CHANGELOG.md"
23
24
  ],
24
25
  "scripts": {
25
- "test": "mocha --exit --require test/test-bindings.js test/*.test.js"
26
+ "test": "mocha --exit --require test/test-bindings.js test/*.test.js",
27
+ "test:gen": "mocha --exit 'test/gen/*.test.js'"
26
28
  },
27
29
  "engines": {
28
30
  "node": ">=18"
@@ -47,6 +49,7 @@
47
49
  },
48
50
  "devDependencies": {
49
51
  "chai": "^6.2.2",
50
- "mocha": "^11.7.5"
52
+ "mocha": "^11.7.5",
53
+ "pg": "^8.23.1"
51
54
  }
52
55
  }
@@ -0,0 +1,425 @@
1
+ // ======================================================
2
+ // gen/accept — result / error acceptance (ADR §7, transitions §6.3)
3
+ // ======================================================
4
+ // I2: the job status lives only in gen_jobs; scene_assets is written only
5
+ // here (the acceptance transaction).
6
+ // I4: a result is accepted only for the CURRENT attempt of a running job;
7
+ // anything else → 409 stale_attempt and the uploaded file is discarded.
8
+ // I5: `ready` only after a real result with sha256 has been renamed into place.
9
+ //
10
+ // Lock order everywhere: gen_commands rows linked to the job (FOR SHARE /
11
+ // UPDATE) → gen_jobs row (FOR UPDATE) → scene advisory lock. cancel() takes
12
+ // the same order. Stage transitions follow gen_command_jobs (§4.2a, §6.3).
13
+
14
+ 'use strict';
15
+
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+ const crypto = require('crypto');
19
+
20
+ const {
21
+ GenError, withTx, isUuid, notifyProgress, verifyUploadToken, linkJobs,
22
+ EXECUTOR_OF_KIND, LAYER_OF_KIND, LIVE,
23
+ } = require('./util');
24
+ const { checkLane } = require('./ports');
25
+
26
+ const PART_KINDS = new Set(['audio_chunk', 'iu_image', 'video_group']);
27
+ const FINAL_FORMAT = { audio_merge: 'mp3', video_merge: 'mp4' };
28
+ const PART_FORMAT = { iu_image: 'png' };
29
+
30
+ /** input.scene_parts → [{unit_key, part_hash}] (non-empty, string fields) or null. */
31
+ function partsManifest(v) {
32
+ if (!Array.isArray(v) || v.length === 0) return null;
33
+ const out = [];
34
+ for (const p of v) {
35
+ if (!p || typeof p.unit_key !== 'string' || !p.unit_key || typeof p.part_hash !== 'string' || !p.part_hash) return null;
36
+ out.push({ unit_key: p.unit_key, part_hash: p.part_hash });
37
+ }
38
+ return out;
39
+ }
40
+ const DEFAULT_MAX_UPLOAD_BYTES = 2 * 1024 * 1024 * 1024;
41
+
42
+ function epochS() { return Math.floor(Date.now() / 1000); }
43
+
44
+ async function unlinkQuiet(p) {
45
+ if (!p) return;
46
+ try { await fs.promises.unlink(p); } catch (_) { /* already gone */ }
47
+ }
48
+
49
+ async function drain(stream) {
50
+ if (!stream || typeof stream.resume !== 'function') return;
51
+ try { stream.resume(); } catch (_) { /* ignore */ }
52
+ }
53
+
54
+ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_UPLOAD_BYTES }) {
55
+ const sceneLockKey = (j) => `animastor:gen-v2:scene:${JSON.stringify([j.book_id, j.chapter_id, j.scene_id])}`;
56
+
57
+ // ── shared: a failed attempt → retry with backoff or failed (§7 «Ошибка», §9 пп.1–2)
58
+ async function failAttemptTx(client, job, errorClass, reason) {
59
+ const policy = ports.retryPolicy(job.kind, errorClass, job.attempt, { previousErrorClass: job.error_class || null }) || { retry: false, delay_ms: 0 };
60
+ const retry = policy.retry === true && job.attempt < job.max_attempts;
61
+ const delay = Math.max(0, Number(policy.delay_ms) || 0);
62
+ const r = retry
63
+ ? await client.query(
64
+ `UPDATE gen_jobs SET status = 'queued', not_before = now() + make_interval(secs => $2::numeric / 1000),
65
+ worker_id = NULL, deadline = NULL, error_class = $3, error = $4
66
+ WHERE job_id = $1 RETURNING status, not_before`,
67
+ [job.job_id, delay, errorClass, reason])
68
+ : await client.query(
69
+ `UPDATE gen_jobs SET status = 'failed', finished_at = now(), deadline = NULL, error_class = $2, error = $3
70
+ WHERE job_id = $1 RETURNING status, not_before`,
71
+ [job.job_id, errorClass, reason]);
72
+ if (job.worker_id) {
73
+ await client.query(
74
+ 'UPDATE workers SET current_job_id = NULL WHERE worker_id = $1 AND current_job_id = $2',
75
+ [job.worker_id, job.job_id]);
76
+ }
77
+ await notifyProgress(client, job.book_id, job.command_id);
78
+ return { status: r.rows[0].status, not_before: r.rows[0].not_before, retry };
79
+ }
80
+
81
+ /**
82
+ * Fail the given attempt (one transaction). 409 when it is not the current running attempt.
83
+ * @returns {Promise<{status:number, job_status?:string, retry?:boolean, code?:string}>}
84
+ */
85
+ async function failAttempt(jobId, attempt, errorClass, reason) {
86
+ const cls = typeof errorClass === 'string' && errorClass ? errorClass.slice(0, 64) : 'unknown';
87
+ const why = reason == null ? null : String(reason).slice(0, 2000);
88
+ return withTx(pool, async (client) => {
89
+ const job = (await client.query('SELECT * FROM gen_jobs WHERE job_id = $1 FOR UPDATE', [jobId])).rows[0];
90
+ if (!job) return { status: 404, code: 'not_found' };
91
+ if (job.status !== 'running' || job.attempt !== attempt) return { status: 409, code: 'stale_attempt' };
92
+ const out = await failAttemptTx(client, job, cls, why);
93
+ return { status: 200, job_status: out.status, retry: out.retry };
94
+ });
95
+ }
96
+
97
+ // ── scene_assets (§4.3: written only by acceptance) ──────────────────────
98
+ async function upsertSceneAsset(client, job, finalPath, sha, bytes, validation) {
99
+ const assetType = job.layer;
100
+ const build = job.build_id;
101
+ const sceneHash = job.input.scene_hash || null;
102
+ if (PART_KINDS.has(job.kind)) {
103
+ // a part (chunk / IU / group) is recorded, the scene asset is not ready yet
104
+ const entry = { kind: job.kind, path: finalPath, sha256: sha, bytes, job_id: job.job_id, attempt: job.attempt };
105
+ if (typeof job.input.part_hash === 'string' && job.input.part_hash) entry.part_hash = job.input.part_hash;
106
+ const part = { [job.unit_key]: entry };
107
+ const sceneParts = partsManifest(job.input.scene_parts);
108
+ if (sceneParts) {
109
+ // 1.1.0 — a part kind WITHOUT a merge stage (iu_image): the scene asset is
110
+ // `ready` exactly when every part the planner listed for the scene
111
+ // (input.scene_parts = [{unit_key, part_hash}] in scene order) has an
112
+ // accepted entry with that part_hash; the acceptance that completes the
113
+ // set writes ready + sha256 (of the parts manifest «unit_key:sha256» per
114
+ // line, scene order) + job_id + path (the first part's file). Not complete
115
+ // → 'pending' (a half-regenerated scene is not ready for the new content).
116
+ // The row lock taken by the upsert serialises two IUs of one scene accepted
117
+ // in parallel; the second one sees the first one's part (READ COMMITTED
118
+ // re-reads the committed row on conflict).
119
+ const up = (await client.query(
120
+ `INSERT INTO scene_assets (book_id, chapter_id, scene_id, asset_type, build_id, scene_hash, status, metadata, updated_at)
121
+ VALUES ($1, $2, $3, $4, $5, $6, 'pending', jsonb_build_object('gen_parts', $7::jsonb), $8)
122
+ ON CONFLICT (book_id, chapter_id, scene_id, asset_type, build_id) DO UPDATE SET
123
+ metadata = jsonb_set(
124
+ CASE WHEN jsonb_typeof(scene_assets.metadata) = 'object' THEN scene_assets.metadata ELSE '{}'::jsonb END,
125
+ '{gen_parts}',
126
+ COALESCE(CASE WHEN jsonb_typeof(scene_assets.metadata->'gen_parts') = 'object'
127
+ THEN scene_assets.metadata->'gen_parts' END, '{}'::jsonb) || $7::jsonb),
128
+ updated_at = EXCLUDED.updated_at
129
+ RETURNING id, metadata->'gen_parts' AS parts`,
130
+ [job.book_id, job.chapter_id, job.scene_id, assetType, build, sceneHash, JSON.stringify(part), epochS()])).rows[0];
131
+ const parts = up.parts && typeof up.parts === 'object' ? up.parts : {};
132
+ const complete = sceneParts.every((p) => parts[p.unit_key] && parts[p.unit_key].part_hash === p.part_hash);
133
+ if (complete) {
134
+ const manifest = sceneParts.map((p) => `${p.unit_key}:${parts[p.unit_key].sha256 || ''}`).join('\n');
135
+ await client.query(
136
+ `UPDATE scene_assets SET scene_hash = $2, status = 'ready', error = NULL, sha256 = $3, job_id = $4,
137
+ path = $5, format = $6
138
+ WHERE id = $1`,
139
+ [up.id, sceneHash, crypto.createHash('sha256').update(manifest).digest('hex'), job.job_id,
140
+ parts[sceneParts[0].unit_key].path || finalPath, PART_FORMAT[job.kind] || null]);
141
+ } else {
142
+ await client.query(
143
+ `UPDATE scene_assets SET scene_hash = $2, status = 'pending', sha256 = NULL, job_id = NULL WHERE id = $1`,
144
+ [up.id, sceneHash]);
145
+ }
146
+ return;
147
+ }
148
+ await client.query(
149
+ `INSERT INTO scene_assets (book_id, chapter_id, scene_id, asset_type, build_id, scene_hash, status, metadata, updated_at)
150
+ VALUES ($1, $2, $3, $4, $5, $6, 'pending', jsonb_build_object('gen_parts', $7::jsonb), $8)
151
+ ON CONFLICT (book_id, chapter_id, scene_id, asset_type, build_id) DO UPDATE SET
152
+ metadata = jsonb_set(
153
+ CASE WHEN jsonb_typeof(scene_assets.metadata) = 'object' THEN scene_assets.metadata ELSE '{}'::jsonb END,
154
+ '{gen_parts}',
155
+ COALESCE(CASE WHEN jsonb_typeof(scene_assets.metadata->'gen_parts') = 'object'
156
+ THEN scene_assets.metadata->'gen_parts' END, '{}'::jsonb) || $7::jsonb),
157
+ updated_at = EXCLUDED.updated_at`,
158
+ [job.book_id, job.chapter_id, job.scene_id, assetType, build, sceneHash, JSON.stringify(part), epochS()]);
159
+ return;
160
+ }
161
+ const duration = validation && Number.isFinite(validation.durationSec) ? validation.durationSec : null;
162
+ await client.query(
163
+ `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)
166
+ ON CONFLICT (book_id, chapter_id, scene_id, asset_type, build_id) DO UPDATE SET
167
+ path = EXCLUDED.path, scene_hash = EXCLUDED.scene_hash, status = 'ready', error = NULL,
168
+ job_id = EXCLUDED.job_id, sha256 = EXCLUDED.sha256,
169
+ duration_sec = COALESCE(EXCLUDED.duration_sec, scene_assets.duration_sec),
170
+ format = EXCLUDED.format, updated_at = EXCLUDED.updated_at`,
171
+ [job.book_id, job.chapter_id, job.scene_id, assetType, finalPath, build, sceneHash,
172
+ job.job_id, sha, duration, FINAL_FORMAT[job.kind], epochS()]);
173
+ }
174
+
175
+ // ── stage transitions (§6.3) — same transaction as the finished job ─────
176
+ /** Insert (or join) next-stage jobs and link them to every qualifying command. */
177
+ async function insertStageJobs(client, cmds, units) {
178
+ let created = 0;
179
+ const owner = cmds[0];
180
+ const ids = cmds.map((c) => c.command_id);
181
+ for (const u of units) {
182
+ const executor = EXECUTOR_OF_KIND[u.kind];
183
+ let lane = null;
184
+ if (executor !== 'local') {
185
+ lane = await ports.laneFor(owner.workspace_id, executor.slice(4));
186
+ if (!checkLane(lane)) throw new GenError('bad_lane', 500, 'laneFor returned an invalid lane');
187
+ }
188
+ const r = await client.query(
189
+ `INSERT INTO gen_jobs (command_id, workspace_id, user_id, book_id, chapter_id, scene_id, unit_key,
190
+ kind, executor, layer, build_id, lane, max_attempts, input, created_at)
191
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12::jsonb, $13, $14::jsonb, clock_timestamp())
192
+ ON CONFLICT (book_id, chapter_id, scene_id, kind, unit_key) WHERE status IN ('queued','running')
193
+ DO NOTHING RETURNING job_id`,
194
+ [owner.command_id, owner.workspace_id, owner.user_id, owner.book_id, u.chapter_id, u.scene_id, u.unit_key,
195
+ u.kind, executor, LAYER_OF_KIND[u.kind], u.build_id, lane ? JSON.stringify(lane) : null,
196
+ ports.maxAttemptsFor(u.kind), JSON.stringify(u.input)]);
197
+ created += r.rowCount;
198
+ const live = await client.query(
199
+ `SELECT job_id FROM gen_jobs WHERE book_id = $1 AND chapter_id = $2 AND scene_id = $3 AND kind = $4
200
+ AND unit_key = $5 AND status IN ('queued','running')`,
201
+ [owner.book_id, u.chapter_id, u.scene_id, u.kind, u.unit_key]);
202
+ await linkJobs(client, ids, live.rows.map((x) => x.job_id));
203
+ }
204
+ return created;
205
+ }
206
+
207
+ /**
208
+ * Stage complete for the scene: nothing of `kind` live for the scene, and every unit of
209
+ * `kind` the qualifying commands wait for has its LATEST job (same build + content) done.
210
+ */
211
+ async function sceneStageComplete(client, job, kind, commandIds) {
212
+ const live = await client.query(
213
+ `SELECT 1 FROM gen_jobs WHERE book_id = $1 AND chapter_id = $2 AND scene_id = $3 AND kind = $4
214
+ AND status = ANY($5::text[]) LIMIT 1`,
215
+ [job.book_id, job.chapter_id, job.scene_id, kind, LIVE]);
216
+ if (live.rowCount) return false;
217
+ const r = await client.query(
218
+ `WITH units AS (
219
+ SELECT DISTINCT j.unit_key FROM gen_jobs j JOIN gen_command_jobs l ON l.job_id = j.job_id
220
+ WHERE l.command_id = ANY($6::uuid[]) AND j.book_id = $1 AND j.chapter_id = $2 AND j.scene_id = $3 AND j.kind = $4
221
+ ), latest AS (
222
+ SELECT DISTINCT ON (j.unit_key) j.unit_key, j.status FROM gen_jobs j JOIN units u ON u.unit_key = j.unit_key
223
+ WHERE j.book_id = $1 AND j.chapter_id = $2 AND j.scene_id = $3 AND j.kind = $4 AND j.build_id = $5
224
+ ORDER BY j.unit_key, j.created_at DESC
225
+ )
226
+ SELECT (SELECT count(*) FROM units)::int AS units,
227
+ (SELECT count(*) FROM latest WHERE status = 'done')::int AS done`,
228
+ [job.book_id, job.chapter_id, job.scene_id, kind, job.build_id, commandIds]);
229
+ return r.rows[0].units > 0 && r.rows[0].units === r.rows[0].done;
230
+ }
231
+
232
+ /** Latest done part of every unit of the scene for this build/content (merge input snapshot). */
233
+ async function doneParts(client, job, kind) {
234
+ const r = await client.query(
235
+ `SELECT DISTINCT ON (unit_key) unit_key, job_id, result_path, result_sha256, input->'part_meta' AS meta
236
+ FROM gen_jobs
237
+ WHERE book_id = $1 AND chapter_id = $2 AND scene_id = $3 AND kind = $4 AND status = 'done'
238
+ AND build_id = $5 AND (input->>'scene_hash') IS NOT DISTINCT FROM $6
239
+ ORDER BY unit_key, finished_at DESC`,
240
+ [job.book_id, job.chapter_id, job.scene_id, kind, job.build_id, job.input.scene_hash ?? null]);
241
+ 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
+ }
243
+
244
+ /**
245
+ * §6.3: a next stage is created only if at least one command linked to the finished job is
246
+ * active, has the layer and the layer is enabled; the new job is linked to all such commands.
247
+ */
248
+ async function transitions(client, cmds, job) {
249
+ const nextLayer = job.kind === 'iu_image' ? 'video' : job.layer;
250
+ const qualifying = [];
251
+ for (const c of cmds) {
252
+ if (c.status === 'active' && c.layers.includes(nextLayer) && await ports.isLayerEnabled(c.book_id, nextLayer)) qualifying.push(c);
253
+ }
254
+ if (!qualifying.length) return 0;
255
+ const ids = qualifying.map((c) => c.command_id);
256
+ const mergeInput = async (kind) => ({
257
+ scene_hash: job.input.scene_hash ?? null,
258
+ parts: await doneParts(client, job, kind),
259
+ });
260
+ 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
+
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
+ if (job.kind === 'audio_chunk') {
267
+ return insertStageJobs(client, qualifying, [sceneUnit('audio_merge', await mergeInput('audio_chunk'))]);
268
+ }
269
+ if (job.kind === 'video_group') {
270
+ return insertStageJobs(client, qualifying, [sceneUnit('video_merge', await mergeInput('video_group'))]);
271
+ }
272
+ if (job.kind === 'iu_image') {
273
+ const owner = qualifying[0];
274
+ const planned = await ports.planUnits(
275
+ { bookId: owner.book_id, workspaceId: owner.workspace_id, userId: owner.user_id },
276
+ { level: 'scene', chapter_id: job.chapter_id, scene_id: job.scene_id }, 'video');
277
+ const groups = (Array.isArray(planned) ? planned : []).filter((u) => u && u.kind === 'video_group'
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 } })));
281
+ }
282
+ return 0;
283
+ }
284
+
285
+ /**
286
+ * Steps 1(validate)–5 of §7 for a file already on disk at tmpPath.
287
+ * @returns {Promise<{status:number, code?:string, reason?:string, idempotent?:boolean, sha256?:string, job_status?:string, stage_jobs_created?:number}>}
288
+ */
289
+ async function finishAccept(pre, attempt, tmpPath, sha, bytes) {
290
+ const finalPath = ports.artifactPath(pre);
291
+ if (typeof finalPath !== 'string' || !path.isAbsolute(finalPath)) {
292
+ await unlinkQuiet(tmpPath);
293
+ throw new GenError('bad_artifact_path', 500, 'artifactPath(job) must return an absolute path');
294
+ }
295
+ // replay of an already committed attempt — no validation, no writes
296
+ if (pre.status === 'done' && pre.attempt === attempt) {
297
+ await unlinkQuiet(tmpPath);
298
+ return pre.result_sha256 === sha
299
+ ? { status: 200, idempotent: true, sha256: sha, job_status: 'done' }
300
+ : { status: 409, code: 'stale_attempt' };
301
+ }
302
+ const validation = await ports.validateResult(pre, tmpPath);
303
+ if (!validation || validation.ok !== true) {
304
+ await unlinkQuiet(tmpPath);
305
+ const reason = (validation && validation.reason) || 'invalid';
306
+ const r = await failAttempt(pre.job_id, attempt, 'invalid_result', `invalid_result: ${reason}`);
307
+ if (r.status !== 200) return r;
308
+ return { status: 422, code: 'invalid_result', reason, job_status: r.job_status };
309
+ }
310
+
311
+ let renamed = false;
312
+ try {
313
+ return await withTx(pool, async (client) => {
314
+ const cmds = (await client.query(
315
+ `SELECT c.* FROM gen_commands c JOIN gen_command_jobs l ON l.command_id = c.command_id
316
+ WHERE l.job_id = $1 ORDER BY c.created_at, c.command_id FOR SHARE OF c`, [pre.job_id])).rows;
317
+ const job = (await client.query('SELECT * FROM gen_jobs WHERE job_id = $1 FOR UPDATE', [pre.job_id])).rows[0];
318
+ if (job && job.status === 'done' && job.attempt === attempt && job.result_sha256 === sha) {
319
+ return { status: 200, idempotent: true, sha256: sha, job_status: 'done' };
320
+ }
321
+ if (!job || job.status !== 'running' || job.attempt !== attempt) {
322
+ return { status: 409, code: 'stale_attempt' };
323
+ }
324
+ await fs.promises.mkdir(path.dirname(finalPath), { recursive: true });
325
+ await fs.promises.rename(tmpPath, finalPath); // §7 п.3 (atomic, same partition)
326
+ renamed = true;
327
+ if (ports.onArtifactPlaced) await ports.onArtifactPlaced(job, finalPath); // e.g. drop the placeholder sidecar
328
+ await client.query(
329
+ `UPDATE gen_jobs SET status = 'done', result_path = $2, result_sha256 = $3, result_bytes = $4,
330
+ finished_at = now(), deadline = NULL
331
+ WHERE job_id = $1`, [job.job_id, finalPath, sha, bytes]);
332
+ if (job.worker_id) {
333
+ await client.query(
334
+ 'UPDATE workers SET current_job_id = NULL WHERE worker_id = $1 AND current_job_id = $2',
335
+ [job.worker_id, job.job_id]);
336
+ }
337
+ await upsertSceneAsset(client, job, finalPath, sha, bytes, validation);
338
+ const stage = await transitions(client, cmds, job);
339
+ await notifyProgress(client, job.book_id, job.command_id);
340
+ return { status: 200, sha256: sha, job_status: 'done', stage_jobs_created: stage };
341
+ });
342
+ } finally {
343
+ if (!renamed) await unlinkQuiet(tmpPath); // rejected / failed before rename → discard
344
+ }
345
+ }
346
+
347
+ async function readJob(jobId) {
348
+ return (await pool.query('SELECT * FROM gen_jobs WHERE job_id = $1', [jobId])).rows[0] || null;
349
+ }
350
+
351
+ function checkIds(jobId, attempt) {
352
+ if (!isUuid(jobId)) throw new GenError('not_found', 404, 'unknown job');
353
+ if (!Number.isInteger(attempt) || attempt < 1) throw new GenError('bad_request', 400, 'attempt must be an integer >= 1');
354
+ }
355
+
356
+ /**
357
+ * PUT /internal/gen/jobs/:job_id/result?attempt=N (ADR §7).
358
+ * @param {string} jobId
359
+ * @param {number} attempt
360
+ * @param {string} token upload token from claim
361
+ * @param {AsyncIterable<Buffer>} stream raw file body
362
+ */
363
+ async function acceptResult(jobId, attempt, token, stream) {
364
+ checkIds(jobId, attempt);
365
+ if (!verifyUploadToken(uploadSecret, token, jobId, attempt)) {
366
+ await drain(stream);
367
+ throw new GenError('unauthorized', 401, 'bad upload token');
368
+ }
369
+ const pre = await readJob(jobId);
370
+ if (!pre) { await drain(stream); throw new GenError('not_found', 404, 'unknown job'); }
371
+ const current = (pre.status === 'running' || pre.status === 'done') && pre.attempt === attempt;
372
+ if (!current) { await drain(stream); return { status: 409, code: 'stale_attempt' }; }
373
+
374
+ const finalPath = ports.artifactPath(pre);
375
+ if (typeof finalPath !== 'string' || !path.isAbsolute(finalPath)) {
376
+ await drain(stream);
377
+ throw new GenError('bad_artifact_path', 500, 'artifactPath(job) must return an absolute path');
378
+ }
379
+ // §7 п.1: stream → {dir}/.incoming/{job_id}.{attempt}.{nonce}.tmp, sha256 + size on the fly, fsync
380
+ const incoming = path.join(path.dirname(finalPath), '.incoming');
381
+ await fs.promises.mkdir(incoming, { recursive: true });
382
+ const tmpPath = path.join(incoming, `${jobId}.${attempt}.${crypto.randomBytes(4).toString('hex')}.tmp`);
383
+ const hash = crypto.createHash('sha256');
384
+ let bytes = 0;
385
+ const fh = await fs.promises.open(tmpPath, 'wx', 0o640);
386
+ try {
387
+ for await (const chunk of stream) {
388
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
389
+ bytes += buf.length;
390
+ if (bytes > maxUploadBytes) throw new GenError('too_large', 413, 'upload exceeds the size limit');
391
+ hash.update(buf);
392
+ await fh.write(buf);
393
+ }
394
+ await fh.sync();
395
+ } catch (err) {
396
+ await fh.close().catch(() => {});
397
+ await unlinkQuiet(tmpPath);
398
+ throw err;
399
+ }
400
+ await fh.close();
401
+ return finishAccept(pre, attempt, tmpPath, hash.digest('hex'), bytes);
402
+ }
403
+
404
+ /**
405
+ * POST /internal/gen/jobs/:job_id/error?attempt=N (ADR §7 «Ошибка», §13.2).
406
+ * @param {{error_class?:string, reason?:string}} body
407
+ */
408
+ async function acceptError(jobId, attempt, token, body = {}) {
409
+ checkIds(jobId, attempt);
410
+ if (!verifyUploadToken(uploadSecret, token, jobId, attempt)) throw new GenError('unauthorized', 401, 'bad upload token');
411
+ return failAttempt(jobId, attempt, body.error_class, body.reason);
412
+ }
413
+
414
+ /** Accept a file produced by the backend itself (executor='local'); no token. */
415
+ async function acceptLocalFile(job, filePath) {
416
+ const hash = crypto.createHash('sha256');
417
+ let bytes = 0;
418
+ 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);
420
+ }
421
+
422
+ return { acceptResult, acceptError, failAttempt, acceptLocalFile };
423
+ }
424
+
425
+ module.exports = { createAccept };