@animastor/orchestration 1.1.0 → 1.2.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 CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0 (2026-11-07) — наблюдаемость v2 (О3)
4
+
5
+ Основание: `reports/2026-11-07/orch-v2-image-scene-run.md` О3 и «мелочи». Minor: только
6
+ добавления, контракт портов 1.0.0 не меняется.
7
+
8
+ - **Строки `[gen-v2]`** через порт логгера (`createOrchestration({ logger })`, метод `info`,
9
+ иначе `log`; без логгера — молча): `command-created` (book, command, layers, scope,
10
+ jobs_created/joined/skipped_ready, existing для повторного клика), `claim` (job, kind,
11
+ unit_key, attempt/max_attempts, worker_id, ms), `accept` (sha256, bytes, width/height,
12
+ idempotent, stage_jobs_created, ms приёма, run_ms от claim), `error` (каждая неудачная
13
+ попытка: error_class, job_status, retry; 409 — `code=stale_attempt`), `requeue`
14
+ (возврат в очередь, delay_ms), `command-finished` (status, done/failed/cancelled, run_ms).
15
+ Печатаются только поля из белого списка (`gen/log.js` `FIELDS`): токены загрузки, пути
16
+ файлов и параметры задач в строки не попадают. Форматер — `gen.formatGenEvent`.
17
+ - Ядро `src/gen` больше не вызывает `console` само: `sweeper`/`local runner` пишут ошибки
18
+ через тот же порт (по умолчанию `createOrchestration` по-прежнему берёт `console`).
19
+ - **`scene_assets.width/height`** для изображений: размеры из PNG-валидатора сохраняются в
20
+ `gen_parts[unit_key]` и в строке сцены при `ready` (размер файла `path`, т. е. первой
21
+ части); для финальных видов — `COALESCE` из результата проверки, если он их знает.
22
+ - **Права принятых файлов 0644** (как у legacy); временный файл в `.incoming` — 0640.
23
+
3
24
  ## 1.1.0 (2026-11-07) — этап 2a: изображения (`iu_image`)
4
25
 
5
26
  ADR `architecture/ORCHESTRATION_V2.md` (§4.3, §7, §12 «2a», §13 п.9). Minor: только
package/README.md CHANGED
@@ -31,6 +31,14 @@ 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
+
34
42
  `gen` requires only node builtins and its own files: no `src/legacy`, Redis,
35
43
  Express or ComfyUI. Tests: `npm run test:gen` (env `PG_*` of the animastor-test
36
44
  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.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.",
3
+ "version": "1.2.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,12 @@ 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
+
27
+ const NOOP_LOG = Object.freeze({ event() {} });
28
+ /** Mode of an accepted artifact: world-readable like the legacy outputs (О3; the tmp file is 0640). */
29
+ const ARTIFACT_MODE = 0o644;
30
+ const dim = (v) => (Number.isInteger(v) && v > 0 ? v : null);
25
31
 
26
32
  const PART_KINDS = new Set(['audio_chunk', 'iu_image', 'video_group']);
27
33
  const FINAL_FORMAT = { audio_merge: 'mp3', video_merge: 'mp4' };
@@ -51,7 +57,7 @@ async function drain(stream) {
51
57
  try { stream.resume(); } catch (_) { /* ignore */ }
52
58
  }
53
59
 
54
- function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_UPLOAD_BYTES }) {
60
+ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_UPLOAD_BYTES, genLog = NOOP_LOG }) {
55
61
  const sceneLockKey = (j) => `animastor:gen-v2:scene:${JSON.stringify([j.book_id, j.chapter_id, j.scene_id])}`;
56
62
 
57
63
  // ── shared: a failed attempt → retry with backoff or failed (§7 «Ошибка», §9 пп.1–2)
@@ -75,7 +81,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
75
81
  [job.worker_id, job.job_id]);
76
82
  }
77
83
  await notifyProgress(client, job.book_id, job.command_id);
78
- return { status: r.rows[0].status, not_before: r.rows[0].not_before, retry };
84
+ return { status: r.rows[0].status, not_before: r.rows[0].not_before, retry, delay_ms: retry ? delay : undefined };
79
85
  }
80
86
 
81
87
  /**
@@ -85,13 +91,30 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
85
91
  async function failAttempt(jobId, attempt, errorClass, reason) {
86
92
  const cls = typeof errorClass === 'string' && errorClass ? errorClass.slice(0, 64) : 'unknown';
87
93
  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];
94
+ let job = null;
95
+ let out = null;
96
+ const r = await withTx(pool, async (client) => {
97
+ job = (await client.query('SELECT * FROM gen_jobs WHERE job_id = $1 FOR UPDATE', [jobId])).rows[0];
90
98
  if (!job) return { status: 404, code: 'not_found' };
91
99
  if (job.status !== 'running' || job.attempt !== attempt) return { status: 409, code: 'stale_attempt' };
92
- const out = await failAttemptTx(client, job, cls, why);
100
+ out = await failAttemptTx(client, job, cls, why);
93
101
  return { status: 200, job_status: out.status, retry: out.retry };
94
102
  });
103
+ // О3, after commit: `error` for every failed attempt, `requeue` when it goes back to the queue
104
+ const ids = job ? {
105
+ book_id: job.book_id, command_id: job.command_id, job_id: job.job_id, kind: job.kind, unit_key: job.unit_key,
106
+ worker_id: job.worker_id,
107
+ } : { job_id: jobId };
108
+ if (r.status !== 200) {
109
+ genLog.event('error', { ...ids, attempt, error_class: cls, code: r.code });
110
+ } else {
111
+ genLog.event('error', {
112
+ ...ids, attempt, max_attempts: job.max_attempts, error_class: cls, job_status: out.status, retry: out.retry,
113
+ run_ms: msBetween(job.claimed_at),
114
+ });
115
+ if (out.retry) genLog.event('requeue', { ...ids, attempt, max_attempts: job.max_attempts, error_class: cls, delay_ms: out.delay_ms });
116
+ }
117
+ return r;
95
118
  }
96
119
 
97
120
  // ── scene_assets (§4.3: written only by acceptance) ──────────────────────
@@ -102,6 +125,8 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
102
125
  if (PART_KINDS.has(job.kind)) {
103
126
  // a part (chunk / IU / group) is recorded, the scene asset is not ready yet
104
127
  const entry = { kind: job.kind, path: finalPath, sha256: sha, bytes, job_id: job.job_id, attempt: job.attempt };
128
+ // О3: the PNG validator knows the size — keep it with the part (scene_assets.width/height below)
129
+ if (validation && dim(validation.width) && dim(validation.height)) { entry.width = validation.width; entry.height = validation.height; }
105
130
  if (typeof job.input.part_hash === 'string' && job.input.part_hash) entry.part_hash = job.input.part_hash;
106
131
  const part = { [job.unit_key]: entry };
107
132
  const sceneParts = partsManifest(job.input.scene_parts);
@@ -132,12 +157,14 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
132
157
  const complete = sceneParts.every((p) => parts[p.unit_key] && parts[p.unit_key].part_hash === p.part_hash);
133
158
  if (complete) {
134
159
  const manifest = sceneParts.map((p) => `${p.unit_key}:${parts[p.unit_key].sha256 || ''}`).join('\n');
160
+ const first = parts[sceneParts[0].unit_key];
161
+ // width/height = those of the file `path` points at (the first part)
135
162
  await client.query(
136
163
  `UPDATE scene_assets SET scene_hash = $2, status = 'ready', error = NULL, sha256 = $3, job_id = $4,
137
- path = $5, format = $6
164
+ path = $5, format = $6, width = $7, height = $8
138
165
  WHERE id = $1`,
139
166
  [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]);
167
+ first.path || finalPath, PART_FORMAT[job.kind] || null, dim(first.width), dim(first.height)]);
141
168
  } else {
142
169
  await client.query(
143
170
  `UPDATE scene_assets SET scene_hash = $2, status = 'pending', sha256 = NULL, job_id = NULL WHERE id = $1`,
@@ -159,17 +186,21 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
159
186
  return;
160
187
  }
161
188
  const duration = validation && Number.isFinite(validation.durationSec) ? validation.durationSec : null;
189
+ const width = validation ? dim(validation.width) : null;
190
+ const height = validation ? dim(validation.height) : null;
162
191
  await client.query(
163
192
  `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)
193
+ job_id, sha256, duration_sec, format, updated_at, width, height)
194
+ VALUES ($1, $2, $3, $4, $5, $6, $7, 'ready', $8, $9, $10, $11, $12, $13, $14)
166
195
  ON CONFLICT (book_id, chapter_id, scene_id, asset_type, build_id) DO UPDATE SET
167
196
  path = EXCLUDED.path, scene_hash = EXCLUDED.scene_hash, status = 'ready', error = NULL,
168
197
  job_id = EXCLUDED.job_id, sha256 = EXCLUDED.sha256,
169
198
  duration_sec = COALESCE(EXCLUDED.duration_sec, scene_assets.duration_sec),
199
+ width = COALESCE(EXCLUDED.width, scene_assets.width),
200
+ height = COALESCE(EXCLUDED.height, scene_assets.height),
170
201
  format = EXCLUDED.format, updated_at = EXCLUDED.updated_at`,
171
202
  [job.book_id, job.chapter_id, job.scene_id, assetType, finalPath, build, sceneHash,
172
- job.job_id, sha, duration, FINAL_FORMAT[job.kind], epochS()]);
203
+ job.job_id, sha, duration, FINAL_FORMAT[job.kind], epochS(), width, height]);
173
204
  }
174
205
 
175
206
  // ── stage transitions (§6.3) — same transaction as the finished job ─────
@@ -286,7 +317,27 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
286
317
  * Steps 1(validate)–5 of §7 for a file already on disk at tmpPath.
287
318
  * @returns {Promise<{status:number, code?:string, reason?:string, idempotent?:boolean, sha256?:string, job_status?:string, stage_jobs_created?:number}>}
288
319
  */
289
- async function finishAccept(pre, attempt, tmpPath, sha, bytes) {
320
+ async function finishAccept(pre, attempt, tmpPath, sha, bytes, t0 = Date.now()) {
321
+ const r = await finishAcceptInner(pre, attempt, tmpPath, sha, bytes, t0);
322
+ // О3: `accept` for a committed result (or its idempotent replay); a stale
323
+ // attempt is an `error` line (code stale_attempt); invalid_result is logged by failAttempt.
324
+ const ids = {
325
+ book_id: pre.book_id, command_id: pre.command_id, job_id: pre.job_id, kind: pre.kind, unit_key: pre.unit_key,
326
+ attempt, worker_id: pre.worker_id,
327
+ };
328
+ if (r && r.status === 200) {
329
+ genLog.event('accept', {
330
+ ...ids, sha256: sha, bytes, width: r.width, height: r.height, idempotent: r.idempotent === true ? true : undefined,
331
+ stage_jobs_created: r.stage_jobs_created, ms: Date.now() - t0, run_ms: msBetween(pre.claimed_at),
332
+ });
333
+ } else if (r && r.code === 'stale_attempt') {
334
+ genLog.event('error', { ...ids, code: 'stale_attempt', sha256: sha, bytes });
335
+ }
336
+ if (r) { delete r.width; delete r.height; }
337
+ return r;
338
+ }
339
+
340
+ async function finishAcceptInner(pre, attempt, tmpPath, sha, bytes) {
290
341
  const finalPath = ports.artifactPath(pre);
291
342
  if (typeof finalPath !== 'string' || !path.isAbsolute(finalPath)) {
292
343
  await unlinkQuiet(tmpPath);
@@ -324,6 +375,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
324
375
  await fs.promises.mkdir(path.dirname(finalPath), { recursive: true });
325
376
  await fs.promises.rename(tmpPath, finalPath); // §7 п.3 (atomic, same partition)
326
377
  renamed = true;
378
+ await fs.promises.chmod(finalPath, ARTIFACT_MODE).catch(() => {}); // О3: 0644 like legacy outputs
327
379
  if (ports.onArtifactPlaced) await ports.onArtifactPlaced(job, finalPath); // e.g. drop the placeholder sidecar
328
380
  await client.query(
329
381
  `UPDATE gen_jobs SET status = 'done', result_path = $2, result_sha256 = $3, result_bytes = $4,
@@ -337,7 +389,10 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
337
389
  await upsertSceneAsset(client, job, finalPath, sha, bytes, validation);
338
390
  const stage = await transitions(client, cmds, job);
339
391
  await notifyProgress(client, job.book_id, job.command_id);
340
- return { status: 200, sha256: sha, job_status: 'done', stage_jobs_created: stage };
392
+ return {
393
+ status: 200, sha256: sha, job_status: 'done', stage_jobs_created: stage,
394
+ width: validation ? dim(validation.width) : null, height: validation ? dim(validation.height) : null,
395
+ };
341
396
  });
342
397
  } finally {
343
398
  if (!renamed) await unlinkQuiet(tmpPath); // rejected / failed before rename → discard
@@ -361,6 +416,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
361
416
  * @param {AsyncIterable<Buffer>} stream raw file body
362
417
  */
363
418
  async function acceptResult(jobId, attempt, token, stream) {
419
+ const t0 = Date.now();
364
420
  checkIds(jobId, attempt);
365
421
  if (!verifyUploadToken(uploadSecret, token, jobId, attempt)) {
366
422
  await drain(stream);
@@ -369,7 +425,11 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
369
425
  const pre = await readJob(jobId);
370
426
  if (!pre) { await drain(stream); throw new GenError('not_found', 404, 'unknown job'); }
371
427
  const current = (pre.status === 'running' || pre.status === 'done') && pre.attempt === attempt;
372
- if (!current) { await drain(stream); return { status: 409, code: 'stale_attempt' }; }
428
+ if (!current) {
429
+ await drain(stream);
430
+ 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' });
431
+ return { status: 409, code: 'stale_attempt' };
432
+ }
373
433
 
374
434
  const finalPath = ports.artifactPath(pre);
375
435
  if (typeof finalPath !== 'string' || !path.isAbsolute(finalPath)) {
@@ -398,7 +458,7 @@ function createAccept({ pool, ports, uploadSecret, maxUploadBytes = DEFAULT_MAX_
398
458
  throw err;
399
459
  }
400
460
  await fh.close();
401
- return finishAccept(pre, attempt, tmpPath, hash.digest('hex'), bytes);
461
+ return finishAccept(pre, attempt, tmpPath, hash.digest('hex'), bytes, t0);
402
462
  }
403
463
 
404
464
  /**
package/src/gen/claim.js CHANGED
@@ -17,7 +17,9 @@ const {
17
17
 
18
18
  const MODES = Object.freeze(['private', 'share', 'system']);
19
19
 
20
- function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, tokenGraceMs = 15 * 60_000 }) {
20
+ const NOOP_LOG = Object.freeze({ event() {} });
21
+
22
+ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, tokenGraceMs = 15 * 60_000, genLog = NOOP_LOG }) {
21
23
  const timeoutsJson = JSON.stringify(Object.fromEntries(KINDS.map((k) => [k, ports.timeoutFor(k)])));
22
24
 
23
25
  /**
@@ -32,6 +34,7 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
32
34
  * @returns {Promise<{task:null}|{task:object}>}
33
35
  */
34
36
  async function claim(p = {}) {
37
+ const t0 = Date.now();
35
38
  const workerId = requireUuid(p.workerId, 'workerId');
36
39
  if (!WORKER_TYPES.includes(p.workerType)) throw new GenError('bad_request', 400, 'workerType must be audio|image|video');
37
40
  if (!MODES.includes(p.mode)) throw new GenError('bad_request', 400, 'mode must be private|share|system');
@@ -108,6 +111,10 @@ function createClaim({ pool, ports, uploadSecret, accept, sharedLimit = null, to
108
111
  }
109
112
  const deadlineMs = new Date(job.deadline).getTime();
110
113
  const exp = deadlineMs + tokenGraceMs;
114
+ genLog.event('claim', {
115
+ book_id: job.book_id, command_id: job.command_id, job_id: job.job_id, kind: job.kind, unit_key: job.unit_key,
116
+ attempt: job.attempt, max_attempts: job.max_attempts, worker_id: workerId, ms: Date.now() - t0,
117
+ });
111
118
  return {
112
119
  task: {
113
120
  job_id: job.job_id,
@@ -10,6 +10,8 @@
10
10
 
11
11
  'use strict';
12
12
 
13
+ const NOOP_LOG = Object.freeze({ event() {} });
14
+
13
15
  const {
14
16
  GenError, withTx, requireUuid, requireText, isUuid, notifyProgress, linkJobs,
15
17
  EXECUTOR_OF_KIND, LAYER_OF_KIND, FIRST_STAGE_KINDS, LAYERS,
@@ -88,13 +90,13 @@ async function purgeBookRows(pool, bookId) {
88
90
  });
89
91
  }
90
92
 
91
- function createCommands({ pool, ports }) {
93
+ function createCommands({ pool, ports, genLog = NOOP_LOG }) {
92
94
  /**
93
95
  * ADR §6.1 — one transaction.
94
96
  * @returns {Promise<{command_id:string, created:boolean, existing:boolean, status:string, layers:string[],
95
97
  * summary:{jobs_created:number, joined:number, skipped_ready:number}}>}
96
98
  */
97
- async function createCommand(params = {}) {
99
+ async function createCommandTx(params = {}) {
98
100
  const workspaceId = requireUuid(params.workspaceId, 'workspaceId');
99
101
  const userId = requireUuid(params.userId, 'userId');
100
102
  const bookId = requireText(params.bookId, 'bookId');
@@ -361,6 +363,19 @@ function createCommands({ pool, ports }) {
361
363
 
362
364
  const purgeBook = (bookId) => purgeBookRows(pool, bookId);
363
365
 
366
+ /** createCommandTx + the О3 `command-created` info line (also for a repeated click: existing=true). */
367
+ async function createCommand(params = {}) {
368
+ const t0 = Date.now();
369
+ const r = await createCommandTx(params);
370
+ genLog.event('command-created', {
371
+ book_id: params.bookId, command_id: r.command_id, layers: r.layers, status: r.status,
372
+ scope: params.scope && params.scope.level, existing: r.existing === true ? true : undefined,
373
+ jobs_created: r.summary && r.summary.jobs_created, joined: r.summary && r.summary.joined,
374
+ skipped_ready: r.summary && r.summary.skipped_ready, ms: Date.now() - t0,
375
+ });
376
+ return r;
377
+ }
378
+
364
379
  return { createCommand, cancel, purgeBook };
365
380
  }
366
381
 
package/src/gen/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // ======================================================
2
- // @animastor/orchestration · gen — orchestration v2 core (1.1.0)
2
+ // @animastor/orchestration · gen — orchestration v2 core (1.2.0)
3
3
  // ======================================================
4
4
  // ADR: animastor-docs architecture/ORCHESTRATION_V2.md. The single source of
5
5
  // truth is PG (gen_commands, gen_jobs). This namespace depends ONLY on the
@@ -25,6 +25,7 @@ const { createAccept } = require('./accept');
25
25
  const { createSweeper } = require('./sweeper');
26
26
  const { createProgress } = require('./progress');
27
27
  const { createLocalRunner } = require('./local-runner');
28
+ const { createGenLog, formatGenEvent } = require('./log');
28
29
 
29
30
  /**
30
31
  * @param {object} o
@@ -37,7 +38,7 @@ const { createLocalRunner } = require('./local-runner');
37
38
  * @param {number} [o.incomingMaxAgeMs=3600000] §9 п.4
38
39
  * @param {number} [o.tokenGraceMs=900000] upload token validity after the deadline
39
40
  * @param {number} [o.maxUploadBytes]
40
- * @param {object} [o.logger=console]
41
+ * @param {object} [o.logger=console] host logger port: info/log ([gen-v2] events, О3), error
41
42
  */
42
43
  function createOrchestration(o = {}) {
43
44
  const { pool } = o;
@@ -54,10 +55,12 @@ function createOrchestration(o = {}) {
54
55
  const ports = portsMod.validatePorts(o.ports);
55
56
  const logger = o.logger || console;
56
57
 
57
- const accept = createAccept({ pool, ports, uploadSecret: secret, maxUploadBytes: o.maxUploadBytes });
58
- const commands = createCommands({ pool, ports });
59
- const claim = createClaim({ pool, ports, uploadSecret: secret, accept, sharedLimit: o.sharedLimit ?? null, tokenGraceMs: o.tokenGraceMs });
60
- const sweeper = createSweeper({ pool, accept, outputDir: o.outputDir || null, offlineAfterMs: o.offlineAfterMs, incomingMaxAgeMs: o.incomingMaxAgeMs, logger });
58
+ // О3: one-line [gen-v2] info events through the host logger port (gen/log.js)
59
+ const genLog = createGenLog(logger);
60
+ const accept = createAccept({ pool, ports, uploadSecret: secret, maxUploadBytes: o.maxUploadBytes, genLog });
61
+ const commands = createCommands({ pool, ports, genLog });
62
+ const claim = createClaim({ pool, ports, uploadSecret: secret, accept, sharedLimit: o.sharedLimit ?? null, tokenGraceMs: o.tokenGraceMs, genLog });
63
+ const sweeper = createSweeper({ pool, accept, outputDir: o.outputDir || null, offlineAfterMs: o.offlineAfterMs, incomingMaxAgeMs: o.incomingMaxAgeMs, logger, genLog });
61
64
  const progress = createProgress({ pool });
62
65
  const local = createLocalRunner({ pool, ports, accept, logger });
63
66
 
@@ -106,5 +109,7 @@ module.exports = Object.freeze({
106
109
  DEFAULT_MIN_LUMA_STDDEV: media.DEFAULT_MIN_LUMA_STDDEV,
107
110
  }),
108
111
  GenError: util.GenError,
112
+ /** pure formatter of the [gen-v2] info lines (О3) — for host tests / log parsers */
113
+ formatGenEvent,
109
114
  PROGRESS_CHANNEL: util.PROGRESS_CHANNEL,
110
115
  });
@@ -11,7 +11,7 @@
11
11
 
12
12
  const { withTx, notifyProgress } = require('./util');
13
13
 
14
- function createLocalRunner({ pool, ports, accept, logger = console }) {
14
+ function createLocalRunner({ pool, ports, accept, logger = null }) {
15
15
  const timeoutsJson = JSON.stringify({
16
16
  audio_merge: ports.timeoutFor('audio_merge'),
17
17
  video_merge: ports.timeoutFor('video_merge'),
@@ -60,7 +60,7 @@ function createLocalRunner({ pool, ports, accept, logger = console }) {
60
60
  try {
61
61
  while (!stopped && await runLocalOnce()) { /* drain */ }
62
62
  } catch (err) {
63
- logger.error && logger.error(`[gen-v2] local runner: ${err && err.message}`);
63
+ logger && logger.error && logger.error(`[gen-v2] local runner: ${err && err.message}`);
64
64
  } finally { running = false; }
65
65
  }
66
66
  if (!stopped) { timer = setTimeout(tick, intervalMs); if (timer.unref) timer.unref(); }
package/src/gen/log.js ADDED
@@ -0,0 +1,63 @@
1
+ // ======================================================
2
+ // gen/log — one-line info events of the v2 core (О3)
3
+ // ======================================================
4
+ // reports/2026-11-07/orch-v2-image-scene-run.md О3: claim, acceptance and the
5
+ // end of a command left no trace in the backend log; the run had to be
6
+ // reconstructed from HTTP lines, PG and the worker's own log.
7
+ //
8
+ // [gen-v2] <event> key=value key=value ...
9
+ //
10
+ // Events: command-created | claim | accept | error | requeue | command-finished.
11
+ // The logger is the host's port (createOrchestration({ logger })); the core
12
+ // never calls console itself. Only ALLOWLISTED fields are printed — never an
13
+ // upload token, a path or a payload (those may carry secrets or user text).
14
+
15
+ 'use strict';
16
+
17
+ const FIELDS = Object.freeze([
18
+ 'book_id', 'command_id', 'job_id', 'kind', 'unit_key', 'attempt', 'max_attempts', 'worker_id', 'executor', 'source',
19
+ 'status', 'job_status', 'code', 'error_class', 'retry', 'delay_ms',
20
+ 'sha256', 'bytes', 'width', 'height', 'idempotent', 'stage_jobs_created',
21
+ 'layers', 'scope', 'existing', 'jobs_created', 'joined', 'skipped_ready', 'done', 'failed', 'cancelled',
22
+ 'ms', 'run_ms',
23
+ ]);
24
+ const ALLOWED = new Set(FIELDS);
25
+
26
+ function fmt(v) {
27
+ if (v === null || v === undefined) return null;
28
+ if (Array.isArray(v)) return v.map(String).join(',');
29
+ if (typeof v === 'object') return JSON.stringify(v);
30
+ const s = String(v);
31
+ return /[\s"=]/.test(s) ? JSON.stringify(s) : s;
32
+ }
33
+
34
+ /** Pure: event name + fields → the log line (allowlisted keys, stable order). */
35
+ function formatGenEvent(event, fields = {}) {
36
+ const parts = [`[gen-v2] ${event}`];
37
+ for (const k of FIELDS) {
38
+ if (!Object.prototype.hasOwnProperty.call(fields, k)) continue;
39
+ const v = fmt(fields[k]);
40
+ if (v !== null) parts.push(`${k}=${v}`);
41
+ }
42
+ return parts.join(' ');
43
+ }
44
+
45
+ /** @param {object|null|undefined} logger host logger port ({info?, log?, warn?, error?}) */
46
+ function createGenLog(logger) {
47
+ const sink = logger && (typeof logger.info === 'function' ? logger.info.bind(logger)
48
+ : typeof logger.log === 'function' ? logger.log.bind(logger) : null);
49
+ function event(name, fields) {
50
+ if (!sink) return;
51
+ try { sink(formatGenEvent(name, fields)); } catch (_) { /* logging never breaks the core */ }
52
+ }
53
+ return { event };
54
+ }
55
+
56
+ /** Milliseconds between two timestamps (Date | string | number); null when unknown. */
57
+ function msBetween(from, to = Date.now()) {
58
+ const a = from instanceof Date ? from.getTime() : (from == null ? NaN : new Date(from).getTime());
59
+ const b = to instanceof Date ? to.getTime() : new Date(to).getTime();
60
+ return Number.isFinite(a) && Number.isFinite(b) ? Math.max(0, Math.round(b - a)) : null;
61
+ }
62
+
63
+ module.exports = { createGenLog, formatGenEvent, msBetween, FIELDS, ALLOWED };
@@ -14,10 +14,13 @@
14
14
  const fs = require('fs');
15
15
  const path = require('path');
16
16
  const { withTx, notifyProgress } = require('./util');
17
+ const { msBetween } = require('./log');
17
18
 
18
19
  const BATCH = 200;
19
20
 
20
- function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000, incomingMaxAgeMs = 60 * 60_000, logger = console }) {
21
+ const NOOP_LOG = Object.freeze({ event() {} });
22
+
23
+ function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000, incomingMaxAgeMs = 60 * 60_000, logger = null, genLog = NOOP_LOG }) {
21
24
  const offlineAfterS = Math.max(1, Math.round(offlineAfterMs / 1000));
22
25
 
23
26
  async function failMany(rows, cls, reason) {
@@ -59,9 +62,15 @@ function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000
59
62
  `UPDATE gen_commands SET status = $2, finished_at = now(), error = $3 WHERE command_id = $1`,
60
63
  [id, status, err]);
61
64
  await notifyProgress(client, c.book_id, id);
62
- return true;
65
+ return { book_id: c.book_id, status, k, run_ms: msBetween(c.created_at) };
63
66
  });
64
- if (done) n += 1;
67
+ if (done) {
68
+ n += 1;
69
+ genLog.event('command-finished', {
70
+ book_id: done.book_id, command_id: id, status: done.status,
71
+ done: done.k.done, failed: done.k.failed, cancelled: done.k.cancelled, run_ms: done.run_ms,
72
+ });
73
+ }
65
74
  }
66
75
  return n;
67
76
  }
@@ -121,7 +130,7 @@ function createSweeper({ pool, accept, outputDir = null, offlineAfterMs = 60_000
121
130
  if (!busy) {
122
131
  busy = true;
123
132
  try { await sweepOnce(); } catch (err) {
124
- logger.error && logger.error(`[gen-v2] sweeper: ${err && err.message}`);
133
+ logger && logger.error && logger.error(`[gen-v2] sweeper: ${err && err.message}`);
125
134
  } finally { busy = false; }
126
135
  }
127
136
  if (!stopped) { timer = setTimeout(tick, intervalMs); if (timer.unref) timer.unref(); }