@animastor/orchestration 0.3.5 → 1.0.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 +70 -0
  2. package/README.md +31 -0
  3. package/package.json +11 -8
  4. package/src/gen/accept.js +370 -0
  5. package/src/gen/claim.js +155 -0
  6. package/src/gen/commands.js +338 -0
  7. package/src/gen/index.js +107 -0
  8. package/src/gen/local-runner.js +80 -0
  9. package/src/gen/ports.js +163 -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 +181 -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 +4 -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,75 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.0 (2026-11-06) — первая публикация: оркестрация v2, ядро `gen` (этапы 1a–1c)
4
+
5
+ Опубликованный пакет: `src/` (`src/gen` с миграциями `sql/001–003`, `src/legacy` — код 0.3.x),
6
+ README, LICENSE, CHANGELOG; `test/` и фикстуры в пакет не входят. Ниже — по этапам.
7
+
8
+ ### Этап 1c: scope `scenes`
9
+
10
+ ADR `architecture/ORCHESTRATION_V2.md` (редакция 06.11, §11.1, §13 п.8).
11
+
12
+ - `scope.level = 'scenes'` — `{level:'scenes', scene_ids:[…]}` (непустой список, порядок
13
+ сохраняется, дубли отбрасываются; `chapter_id` / `scene_id` к нему не применяются).
14
+ Так хост передаёт «с текущей сцены до конца», развёрнутое в порядке книги.
15
+ - `sql/003-scope-scenes`: CHECK `gen_commands_scope_check` пересоздаётся под тем же именем
16
+ с уровнем `scenes` (NULL-безопасно); `ADD_CHECK` из 001 старое определение не возвращает.
17
+
18
+ ### Этап 1b: gen_command_jobs, build_id/layer, отмена по слою
19
+
20
+ ADR `architecture/ORCHESTRATION_V2.md` (редакция 06.11, §4.2a, §6.3–6.4, §7, §13.6).
21
+
22
+ - `sql/002-command-jobs` (поверх 001, идемпотентно): `gen_jobs.build_id` NOT NULL (из
23
+ `input.build_id`), `gen_jobs.layer` NOT NULL + CHECK, `gen_commands.summary`, таблица
24
+ `gen_command_jobs` (PK, FK, бэкфилл).
25
+ - Присоединение — явной связью; прогресс и завершение команды — только по `gen_command_jobs`.
26
+ - `cancel({bookId, layer})` (аудио снимает и `audio_merge`); отмена по executor удалена;
27
+ `cancel({commandId})` не трогает работы, нужные другой активной команде.
28
+ - Ступени §6.3 — только при связанной активной команде со слоем; новая работа связывается со всеми такими.
29
+ - `invalid_result` — один повтор на работу (считается по классу), затем failed.
30
+ - `purgeBook(pool, bookId)`; `progress(bookId, {finishedWithinMs})`; опциональный порт
31
+ `onArtifactPlaced(job, path)`; `retryPolicy(kind, cls, attempt, {previousErrorClass})`.
32
+ - legacy: единый предикат `persistence-port.isV2Book` (опциональная операция порта
33
+ `orchestration.isV2Book`, fail-closed) — command gate, reconcile, scheduler, scene window
34
+ пропускают v2-книги.
35
+
36
+ ### Этап 1a (2026-11-05): ядро `gen` + схема PG
37
+
38
+ ADR: animastor-docs `architecture/ORCHESTRATION_V2.md` (§3, §4, §6–§10, §13). Без
39
+ подключения к роутам backend, без выкатки.
40
+
41
+ #### Changed (breaking только по раскладке файлов)
42
+
43
+ - Весь код 0.3.x перенесён без изменений логики в `src/legacy/`
44
+ (`legacy/host`, `legacy/orchestration`, `legacy/runtime`, `legacy/index.js`).
45
+ Корень `src/index.js` экспортирует тот же API, что 0.3.5 (дескрипторы свойств, ленивые
46
+ геттеры сохранены), плюс новое пространство `gen`. Глубокие импорты
47
+ `src/runtime/*` / `src/orchestration/*` → `src/legacy/runtime/*` / `src/legacy/orchestration/*`.
48
+
49
+ #### Added — `gen` (src/gen/)
50
+
51
+ - `migrate(pool)` — идемпотентная миграция (`sql/001-gen-core.js`): `gen_commands`,
52
+ `gen_jobs` (ADR §4.1–4.2; CHECK по статусам / kind / executor / связке kind↔executor /
53
+ lane; partial UNIQUE «одна живая работа на юнит»; `UNIQUE(book_id, client_action_id)`;
54
+ индексы выдачи, сторожа, прогресса), `books.orchestration` (`legacy`|`v2`, default
55
+ `legacy`), `workers.current_job_id`, `scene_assets.job_id` / `sha256`.
56
+ - `createOrchestration({pool, ports, uploadSecret, outputDir, sharedLimit, …})`:
57
+ `createCommand`, `cancel`, `claim`, `beacon`, `acceptResult`, `acceptError`,
58
+ `sweepOnce` / `startSweeper` / `stopSweeper`, `runLocalOnce` (executor `local`),
59
+ `progress`, `listenProgress` (`LISTEN gen_progress`).
60
+ - Порты (`ports.js`, проверка при инициализации): `planUnits`, `buildPayload`,
61
+ `artifactPath`, `validateResult`, `runLocal`, `laneFor`, `timeoutFor`, `retryPolicy`;
62
+ опционально `maxAttemptsFor`, `isLayerEnabled`. Значения по умолчанию: политика повторов
63
+ = `gpu-retry-policy.cjs:50–53`, таймауты = media-registry, `makeLaneFor` = логика
64
+ `gpu-dispatcher.js:213–222`, `createDefaultValidateResult` (mp3 magic + длительность по
65
+ кадрам + RMS-тишина через ffmpeg, порог параметром; png / mp4 magic).
66
+ - Зависимостей не добавлено: pg-клиент передаёт хост (`pg` — только devDependency тестов).
67
+
68
+ #### Tests
69
+
70
+ - `npm run test:gen` — 43 теста на стеке animastor-test (чистая схема на тест; 1 тест реального ffmpeg-декодера пропускается без ffmpeg). Legacy-набор
71
+ `npm test` без изменений (59).
72
+
3
73
  ## 0.3.5 (2026-11-05) — утечка квоты диспатча, reconcile не понижает закоммиченное
4
74
 
5
75
  Основание: `reports/2026-11-05/live-check-A-B-C.md` §6, §10 и
package/README.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # @animastor/orchestration
2
2
 
3
+ ## 1.0.0 — 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
+ `gen` requires only node builtins and its own files: no `src/legacy`, Redis,
29
+ Express or ComfyUI. Tests: `npm run test:gen` (env `PG_*` of the animastor-test
30
+ stack; refuses a DB not ending in `_test` or port 5432).
31
+
32
+ ## 0.3.x contour (`src/legacy/`)
33
+
3
34
  Generation orchestration and runtime contour of the Animastor backend,
4
35
  physically extracted from the host (`backend/src/orchestration/**` +
5
36
  `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.0.0",
4
+ "description": "Animastor Orchestration 1.0.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,370 @@
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 DEFAULT_MAX_UPLOAD_BYTES = 2 * 1024 * 1024 * 1024;
29
+
30
+ function epochS() { return Math.floor(Date.now() / 1000); }
31
+
32
+ async function unlinkQuiet(p) {
33
+ if (!p) return;
34
+ try { await fs.promises.unlink(p); } catch (_) { /* already gone */ }
35
+ }
36
+
37
+ async function drain(stream) {
38
+ if (!stream || typeof stream.resume !== 'function') return;
39
+ try { stream.resume(); } catch (_) { /* ignore */ }
40
+ }
41
+
42
+ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_UPLOAD_BYTES }) {
43
+ const sceneLockKey = (j) => `animastor:gen-v2:scene:${JSON.stringify([j.book_id, j.chapter_id, j.scene_id])}`;
44
+
45
+ // ── shared: a failed attempt → retry with backoff or failed (§7 «Ошибка», §9 пп.1–2)
46
+ async function failAttemptTx(client, job, errorClass, reason) {
47
+ const policy = ports.retryPolicy(job.kind, errorClass, job.attempt, { previousErrorClass: job.error_class || null }) || { retry: false, delay_ms: 0 };
48
+ const retry = policy.retry === true && job.attempt < job.max_attempts;
49
+ const delay = Math.max(0, Number(policy.delay_ms) || 0);
50
+ const r = retry
51
+ ? await client.query(
52
+ `UPDATE gen_jobs SET status = 'queued', not_before = now() + make_interval(secs => $2::numeric / 1000),
53
+ worker_id = NULL, deadline = NULL, error_class = $3, error = $4
54
+ WHERE job_id = $1 RETURNING status, not_before`,
55
+ [job.job_id, delay, errorClass, reason])
56
+ : await client.query(
57
+ `UPDATE gen_jobs SET status = 'failed', finished_at = now(), deadline = NULL, error_class = $2, error = $3
58
+ WHERE job_id = $1 RETURNING status, not_before`,
59
+ [job.job_id, errorClass, reason]);
60
+ if (job.worker_id) {
61
+ await client.query(
62
+ 'UPDATE workers SET current_job_id = NULL WHERE worker_id = $1 AND current_job_id = $2',
63
+ [job.worker_id, job.job_id]);
64
+ }
65
+ await notifyProgress(client, job.book_id, job.command_id);
66
+ return { status: r.rows[0].status, not_before: r.rows[0].not_before, retry };
67
+ }
68
+
69
+ /**
70
+ * Fail the given attempt (one transaction). 409 when it is not the current running attempt.
71
+ * @returns {Promise<{status:number, job_status?:string, retry?:boolean, code?:string}>}
72
+ */
73
+ async function failAttempt(jobId, attempt, errorClass, reason) {
74
+ const cls = typeof errorClass === 'string' && errorClass ? errorClass.slice(0, 64) : 'unknown';
75
+ const why = reason == null ? null : String(reason).slice(0, 2000);
76
+ return withTx(pool, async (client) => {
77
+ const job = (await client.query('SELECT * FROM gen_jobs WHERE job_id = $1 FOR UPDATE', [jobId])).rows[0];
78
+ if (!job) return { status: 404, code: 'not_found' };
79
+ if (job.status !== 'running' || job.attempt !== attempt) return { status: 409, code: 'stale_attempt' };
80
+ const out = await failAttemptTx(client, job, cls, why);
81
+ return { status: 200, job_status: out.status, retry: out.retry };
82
+ });
83
+ }
84
+
85
+ // ── scene_assets (§4.3: written only by acceptance) ──────────────────────
86
+ async function upsertSceneAsset(client, job, finalPath, sha, bytes, validation) {
87
+ const assetType = job.layer;
88
+ const build = job.build_id;
89
+ const sceneHash = job.input.scene_hash || null;
90
+ if (PART_KINDS.has(job.kind)) {
91
+ // a part (chunk / IU / group) is recorded, the scene asset is not ready yet
92
+ const part = { [job.unit_key]: { kind: job.kind, path: finalPath, sha256: sha, bytes, job_id: job.job_id, attempt: job.attempt } };
93
+ await client.query(
94
+ `INSERT INTO scene_assets (book_id, chapter_id, scene_id, asset_type, build_id, scene_hash, status, metadata, updated_at)
95
+ VALUES ($1, $2, $3, $4, $5, $6, 'pending', jsonb_build_object('gen_parts', $7::jsonb), $8)
96
+ ON CONFLICT (book_id, chapter_id, scene_id, asset_type, build_id) DO UPDATE SET
97
+ metadata = jsonb_set(
98
+ CASE WHEN jsonb_typeof(scene_assets.metadata) = 'object' THEN scene_assets.metadata ELSE '{}'::jsonb END,
99
+ '{gen_parts}',
100
+ COALESCE(CASE WHEN jsonb_typeof(scene_assets.metadata->'gen_parts') = 'object'
101
+ THEN scene_assets.metadata->'gen_parts' END, '{}'::jsonb) || $7::jsonb),
102
+ updated_at = EXCLUDED.updated_at`,
103
+ [job.book_id, job.chapter_id, job.scene_id, assetType, build, sceneHash, JSON.stringify(part), epochS()]);
104
+ return;
105
+ }
106
+ const duration = validation && Number.isFinite(validation.durationSec) ? validation.durationSec : null;
107
+ await client.query(
108
+ `INSERT INTO scene_assets (book_id, chapter_id, scene_id, asset_type, path, build_id, scene_hash, status,
109
+ job_id, sha256, duration_sec, format, updated_at)
110
+ VALUES ($1, $2, $3, $4, $5, $6, $7, 'ready', $8, $9, $10, $11, $12)
111
+ ON CONFLICT (book_id, chapter_id, scene_id, asset_type, build_id) DO UPDATE SET
112
+ path = EXCLUDED.path, scene_hash = EXCLUDED.scene_hash, status = 'ready', error = NULL,
113
+ job_id = EXCLUDED.job_id, sha256 = EXCLUDED.sha256,
114
+ duration_sec = COALESCE(EXCLUDED.duration_sec, scene_assets.duration_sec),
115
+ format = EXCLUDED.format, updated_at = EXCLUDED.updated_at`,
116
+ [job.book_id, job.chapter_id, job.scene_id, assetType, finalPath, build, sceneHash,
117
+ job.job_id, sha, duration, FINAL_FORMAT[job.kind], epochS()]);
118
+ }
119
+
120
+ // ── stage transitions (§6.3) — same transaction as the finished job ─────
121
+ /** Insert (or join) next-stage jobs and link them to every qualifying command. */
122
+ async function insertStageJobs(client, cmds, units) {
123
+ let created = 0;
124
+ const owner = cmds[0];
125
+ const ids = cmds.map((c) => c.command_id);
126
+ for (const u of units) {
127
+ const executor = EXECUTOR_OF_KIND[u.kind];
128
+ let lane = null;
129
+ if (executor !== 'local') {
130
+ lane = await ports.laneFor(owner.workspace_id, executor.slice(4));
131
+ if (!checkLane(lane)) throw new GenError('bad_lane', 500, 'laneFor returned an invalid lane');
132
+ }
133
+ const r = await client.query(
134
+ `INSERT INTO gen_jobs (command_id, workspace_id, user_id, book_id, chapter_id, scene_id, unit_key,
135
+ kind, executor, layer, build_id, lane, max_attempts, input, created_at)
136
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12::jsonb, $13, $14::jsonb, clock_timestamp())
137
+ ON CONFLICT (book_id, chapter_id, scene_id, kind, unit_key) WHERE status IN ('queued','running')
138
+ DO NOTHING RETURNING job_id`,
139
+ [owner.command_id, owner.workspace_id, owner.user_id, owner.book_id, u.chapter_id, u.scene_id, u.unit_key,
140
+ u.kind, executor, LAYER_OF_KIND[u.kind], u.build_id, lane ? JSON.stringify(lane) : null,
141
+ ports.maxAttemptsFor(u.kind), JSON.stringify(u.input)]);
142
+ created += r.rowCount;
143
+ const live = await client.query(
144
+ `SELECT job_id FROM gen_jobs WHERE book_id = $1 AND chapter_id = $2 AND scene_id = $3 AND kind = $4
145
+ AND unit_key = $5 AND status IN ('queued','running')`,
146
+ [owner.book_id, u.chapter_id, u.scene_id, u.kind, u.unit_key]);
147
+ await linkJobs(client, ids, live.rows.map((x) => x.job_id));
148
+ }
149
+ return created;
150
+ }
151
+
152
+ /**
153
+ * Stage complete for the scene: nothing of `kind` live for the scene, and every unit of
154
+ * `kind` the qualifying commands wait for has its LATEST job (same build + content) done.
155
+ */
156
+ async function sceneStageComplete(client, job, kind, commandIds) {
157
+ const live = await client.query(
158
+ `SELECT 1 FROM gen_jobs WHERE book_id = $1 AND chapter_id = $2 AND scene_id = $3 AND kind = $4
159
+ AND status = ANY($5::text[]) LIMIT 1`,
160
+ [job.book_id, job.chapter_id, job.scene_id, kind, LIVE]);
161
+ if (live.rowCount) return false;
162
+ const r = await client.query(
163
+ `WITH units AS (
164
+ SELECT DISTINCT j.unit_key FROM gen_jobs j JOIN gen_command_jobs l ON l.job_id = j.job_id
165
+ 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
166
+ ), latest AS (
167
+ 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
168
+ WHERE j.book_id = $1 AND j.chapter_id = $2 AND j.scene_id = $3 AND j.kind = $4 AND j.build_id = $5
169
+ ORDER BY j.unit_key, j.created_at DESC
170
+ )
171
+ SELECT (SELECT count(*) FROM units)::int AS units,
172
+ (SELECT count(*) FROM latest WHERE status = 'done')::int AS done`,
173
+ [job.book_id, job.chapter_id, job.scene_id, kind, job.build_id, commandIds]);
174
+ return r.rows[0].units > 0 && r.rows[0].units === r.rows[0].done;
175
+ }
176
+
177
+ /** Latest done part of every unit of the scene for this build/content (merge input snapshot). */
178
+ async function doneParts(client, job, kind) {
179
+ const r = await client.query(
180
+ `SELECT DISTINCT ON (unit_key) unit_key, job_id, result_path, result_sha256, input->'part_meta' AS meta
181
+ FROM gen_jobs
182
+ WHERE book_id = $1 AND chapter_id = $2 AND scene_id = $3 AND kind = $4 AND status = 'done'
183
+ AND build_id = $5 AND (input->>'scene_hash') IS NOT DISTINCT FROM $6
184
+ ORDER BY unit_key, finished_at DESC`,
185
+ [job.book_id, job.chapter_id, job.scene_id, kind, job.build_id, job.input.scene_hash ?? null]);
186
+ 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 }));
187
+ }
188
+
189
+ /**
190
+ * §6.3: a next stage is created only if at least one command linked to the finished job is
191
+ * active, has the layer and the layer is enabled; the new job is linked to all such commands.
192
+ */
193
+ async function transitions(client, cmds, job) {
194
+ const nextLayer = job.kind === 'iu_image' ? 'video' : job.layer;
195
+ const qualifying = [];
196
+ for (const c of cmds) {
197
+ if (c.status === 'active' && c.layers.includes(nextLayer) && await ports.isLayerEnabled(c.book_id, nextLayer)) qualifying.push(c);
198
+ }
199
+ if (!qualifying.length) return 0;
200
+ const ids = qualifying.map((c) => c.command_id);
201
+ const mergeInput = async (kind) => ({
202
+ scene_hash: job.input.scene_hash ?? null,
203
+ parts: await doneParts(client, job, kind),
204
+ });
205
+ const sceneUnit = (kind, input) => ({ chapter_id: job.chapter_id, scene_id: job.scene_id, kind, unit_key: 'scene', build_id: job.build_id, input });
206
+
207
+ if (job.kind === 'audio_chunk' || job.kind === 'video_group' || job.kind === 'iu_image') {
208
+ await client.query('SELECT pg_advisory_xact_lock(hashtext($1))', [sceneLockKey(job)]);
209
+ if (!(await sceneStageComplete(client, job, job.kind, ids))) return 0;
210
+ }
211
+ if (job.kind === 'audio_chunk') {
212
+ return insertStageJobs(client, qualifying, [sceneUnit('audio_merge', await mergeInput('audio_chunk'))]);
213
+ }
214
+ if (job.kind === 'video_group') {
215
+ return insertStageJobs(client, qualifying, [sceneUnit('video_merge', await mergeInput('video_group'))]);
216
+ }
217
+ if (job.kind === 'iu_image') {
218
+ const owner = qualifying[0];
219
+ const planned = await ports.planUnits(
220
+ { bookId: owner.book_id, workspaceId: owner.workspace_id, userId: owner.user_id },
221
+ { level: 'scene', chapter_id: job.chapter_id, scene_id: job.scene_id }, 'video');
222
+ const groups = (Array.isArray(planned) ? planned : []).filter((u) => u && u.kind === 'video_group'
223
+ && u.chapter_id === job.chapter_id && u.scene_id === job.scene_id
224
+ && typeof u.unit_key === 'string' && typeof u.build_id === 'string' && u.input && typeof u.input === 'object');
225
+ return insertStageJobs(client, qualifying, groups.map((u) => ({ ...u, input: { ...u.input, scene_hash: u.scene_hash ?? u.input.scene_hash ?? null } })));
226
+ }
227
+ return 0;
228
+ }
229
+
230
+ /**
231
+ * Steps 1(validate)–5 of §7 for a file already on disk at tmpPath.
232
+ * @returns {Promise<{status:number, code?:string, reason?:string, idempotent?:boolean, sha256?:string, job_status?:string, stage_jobs_created?:number}>}
233
+ */
234
+ async function finishAccept(pre, attempt, tmpPath, sha, bytes) {
235
+ const finalPath = ports.artifactPath(pre);
236
+ if (typeof finalPath !== 'string' || !path.isAbsolute(finalPath)) {
237
+ await unlinkQuiet(tmpPath);
238
+ throw new GenError('bad_artifact_path', 500, 'artifactPath(job) must return an absolute path');
239
+ }
240
+ // replay of an already committed attempt — no validation, no writes
241
+ if (pre.status === 'done' && pre.attempt === attempt) {
242
+ await unlinkQuiet(tmpPath);
243
+ return pre.result_sha256 === sha
244
+ ? { status: 200, idempotent: true, sha256: sha, job_status: 'done' }
245
+ : { status: 409, code: 'stale_attempt' };
246
+ }
247
+ const validation = await ports.validateResult(pre, tmpPath);
248
+ if (!validation || validation.ok !== true) {
249
+ await unlinkQuiet(tmpPath);
250
+ const reason = (validation && validation.reason) || 'invalid';
251
+ const r = await failAttempt(pre.job_id, attempt, 'invalid_result', `invalid_result: ${reason}`);
252
+ if (r.status !== 200) return r;
253
+ return { status: 422, code: 'invalid_result', reason, job_status: r.job_status };
254
+ }
255
+
256
+ let renamed = false;
257
+ try {
258
+ return await withTx(pool, async (client) => {
259
+ const cmds = (await client.query(
260
+ `SELECT c.* FROM gen_commands c JOIN gen_command_jobs l ON l.command_id = c.command_id
261
+ WHERE l.job_id = $1 ORDER BY c.created_at, c.command_id FOR SHARE OF c`, [pre.job_id])).rows;
262
+ const job = (await client.query('SELECT * FROM gen_jobs WHERE job_id = $1 FOR UPDATE', [pre.job_id])).rows[0];
263
+ if (job && job.status === 'done' && job.attempt === attempt && job.result_sha256 === sha) {
264
+ return { status: 200, idempotent: true, sha256: sha, job_status: 'done' };
265
+ }
266
+ if (!job || job.status !== 'running' || job.attempt !== attempt) {
267
+ return { status: 409, code: 'stale_attempt' };
268
+ }
269
+ await fs.promises.mkdir(path.dirname(finalPath), { recursive: true });
270
+ await fs.promises.rename(tmpPath, finalPath); // §7 п.3 (atomic, same partition)
271
+ renamed = true;
272
+ if (ports.onArtifactPlaced) await ports.onArtifactPlaced(job, finalPath); // e.g. drop the placeholder sidecar
273
+ await client.query(
274
+ `UPDATE gen_jobs SET status = 'done', result_path = $2, result_sha256 = $3, result_bytes = $4,
275
+ finished_at = now(), deadline = NULL
276
+ WHERE job_id = $1`, [job.job_id, finalPath, sha, bytes]);
277
+ if (job.worker_id) {
278
+ await client.query(
279
+ 'UPDATE workers SET current_job_id = NULL WHERE worker_id = $1 AND current_job_id = $2',
280
+ [job.worker_id, job.job_id]);
281
+ }
282
+ await upsertSceneAsset(client, job, finalPath, sha, bytes, validation);
283
+ const stage = await transitions(client, cmds, job);
284
+ await notifyProgress(client, job.book_id, job.command_id);
285
+ return { status: 200, sha256: sha, job_status: 'done', stage_jobs_created: stage };
286
+ });
287
+ } finally {
288
+ if (!renamed) await unlinkQuiet(tmpPath); // rejected / failed before rename → discard
289
+ }
290
+ }
291
+
292
+ async function readJob(jobId) {
293
+ return (await pool.query('SELECT * FROM gen_jobs WHERE job_id = $1', [jobId])).rows[0] || null;
294
+ }
295
+
296
+ function checkIds(jobId, attempt) {
297
+ if (!isUuid(jobId)) throw new GenError('not_found', 404, 'unknown job');
298
+ if (!Number.isInteger(attempt) || attempt < 1) throw new GenError('bad_request', 400, 'attempt must be an integer >= 1');
299
+ }
300
+
301
+ /**
302
+ * PUT /internal/gen/jobs/:job_id/result?attempt=N (ADR §7).
303
+ * @param {string} jobId
304
+ * @param {number} attempt
305
+ * @param {string} token upload token from claim
306
+ * @param {AsyncIterable<Buffer>} stream raw file body
307
+ */
308
+ async function acceptResult(jobId, attempt, token, stream) {
309
+ checkIds(jobId, attempt);
310
+ if (!verifyUploadToken(uploadSecret, token, jobId, attempt)) {
311
+ await drain(stream);
312
+ throw new GenError('unauthorized', 401, 'bad upload token');
313
+ }
314
+ const pre = await readJob(jobId);
315
+ if (!pre) { await drain(stream); throw new GenError('not_found', 404, 'unknown job'); }
316
+ const current = (pre.status === 'running' || pre.status === 'done') && pre.attempt === attempt;
317
+ if (!current) { await drain(stream); return { status: 409, code: 'stale_attempt' }; }
318
+
319
+ const finalPath = ports.artifactPath(pre);
320
+ if (typeof finalPath !== 'string' || !path.isAbsolute(finalPath)) {
321
+ await drain(stream);
322
+ throw new GenError('bad_artifact_path', 500, 'artifactPath(job) must return an absolute path');
323
+ }
324
+ // §7 п.1: stream → {dir}/.incoming/{job_id}.{attempt}.{nonce}.tmp, sha256 + size on the fly, fsync
325
+ const incoming = path.join(path.dirname(finalPath), '.incoming');
326
+ await fs.promises.mkdir(incoming, { recursive: true });
327
+ const tmpPath = path.join(incoming, `${jobId}.${attempt}.${crypto.randomBytes(4).toString('hex')}.tmp`);
328
+ const hash = crypto.createHash('sha256');
329
+ let bytes = 0;
330
+ const fh = await fs.promises.open(tmpPath, 'wx', 0o640);
331
+ try {
332
+ for await (const chunk of stream) {
333
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
334
+ bytes += buf.length;
335
+ if (bytes > maxUploadBytes) throw new GenError('too_large', 413, 'upload exceeds the size limit');
336
+ hash.update(buf);
337
+ await fh.write(buf);
338
+ }
339
+ await fh.sync();
340
+ } catch (err) {
341
+ await fh.close().catch(() => {});
342
+ await unlinkQuiet(tmpPath);
343
+ throw err;
344
+ }
345
+ await fh.close();
346
+ return finishAccept(pre, attempt, tmpPath, hash.digest('hex'), bytes);
347
+ }
348
+
349
+ /**
350
+ * POST /internal/gen/jobs/:job_id/error?attempt=N (ADR §7 «Ошибка», §13.2).
351
+ * @param {{error_class?:string, reason?:string}} body
352
+ */
353
+ async function acceptError(jobId, attempt, token, body = {}) {
354
+ checkIds(jobId, attempt);
355
+ if (!verifyUploadToken(uploadSecret, token, jobId, attempt)) throw new GenError('unauthorized', 401, 'bad upload token');
356
+ return failAttempt(jobId, attempt, body.error_class, body.reason);
357
+ }
358
+
359
+ /** Accept a file produced by the backend itself (executor='local'); no token. */
360
+ async function acceptLocalFile(job, filePath) {
361
+ const hash = crypto.createHash('sha256');
362
+ let bytes = 0;
363
+ for await (const chunk of fs.createReadStream(filePath)) { hash.update(chunk); bytes += chunk.length; }
364
+ return finishAccept(job, job.attempt, filePath, hash.digest('hex'), bytes);
365
+ }
366
+
367
+ return { acceptResult, acceptError, failAttempt, acceptLocalFile };
368
+ }
369
+
370
+ module.exports = { createAccept };