@animastor/orchestration 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -0
- package/README.md +19 -0
- package/package.json +2 -2
- package/src/gen/accept.js +166 -39
- package/src/gen/claim.js +62 -3
- package/src/gen/commands.js +126 -73
- package/src/gen/index.js +13 -7
- package/src/gen/local-runner.js +4 -3
- package/src/gen/log.js +63 -0
- package/src/gen/ports.js +17 -3
- package/src/gen/progress.js +13 -1
- package/src/gen/sql/004-command-skips.js +26 -0
- package/src/gen/sql/index.js +2 -0
- package/src/gen/stage.js +185 -0
- package/src/gen/sweeper.js +13 -4
package/src/gen/commands.js
CHANGED
|
@@ -10,11 +10,16 @@
|
|
|
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,
|
|
16
18
|
} = require('./util');
|
|
17
19
|
const { checkLane } = require('./ports');
|
|
20
|
+
const {
|
|
21
|
+
normalisePlan, readyParts, mergePartsOf, mergeUnitFor, linkSceneLive, recordSkips, skipSummary,
|
|
22
|
+
} = require('./stage');
|
|
18
23
|
|
|
19
24
|
const COMMAND_KINDS = Object.freeze(['regenerate', 'generate_all']);
|
|
20
25
|
const SCOPE_LEVELS = Object.freeze(['book', 'chapter', 'scenes', 'scene', 'unit']);
|
|
@@ -88,13 +93,13 @@ async function purgeBookRows(pool, bookId) {
|
|
|
88
93
|
});
|
|
89
94
|
}
|
|
90
95
|
|
|
91
|
-
function createCommands({ pool, ports }) {
|
|
96
|
+
function createCommands({ pool, ports, genLog = NOOP_LOG }) {
|
|
92
97
|
/**
|
|
93
98
|
* ADR §6.1 — one transaction.
|
|
94
99
|
* @returns {Promise<{command_id:string, created:boolean, existing:boolean, status:string, layers:string[],
|
|
95
100
|
* summary:{jobs_created:number, joined:number, skipped_ready:number}}>}
|
|
96
101
|
*/
|
|
97
|
-
async function
|
|
102
|
+
async function createCommandTx(params = {}) {
|
|
98
103
|
const workspaceId = requireUuid(params.workspaceId, 'workspaceId');
|
|
99
104
|
const userId = requireUuid(params.userId, 'userId');
|
|
100
105
|
const bookId = requireText(params.bookId, 'bookId');
|
|
@@ -151,78 +156,22 @@ function createCommands({ pool, ports }) {
|
|
|
151
156
|
if (ins.rowCount === 0) return existingResponse(await existingOf()); // concurrent twin committed first
|
|
152
157
|
const cmd = ins.rows[0];
|
|
153
158
|
|
|
154
|
-
// §6.1 п.3: plan units per layer
|
|
159
|
+
// §6.1 п.3: plan units per layer. Audio / image first, video last: the video
|
|
160
|
+
// planner (1.3.0) runs on THIS transaction and must see the image / audio jobs
|
|
161
|
+
// this very command has just created (they are what a video scene waits for).
|
|
155
162
|
const bookRef = { bookId, workspaceId, userId };
|
|
156
|
-
const
|
|
163
|
+
const planCtx = { db: client };
|
|
157
164
|
const seen = new Set();
|
|
158
|
-
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
for (const u of planned) {
|
|
165
|
+
const takeUnits = (list, layer) => {
|
|
166
|
+
const out = [];
|
|
167
|
+
for (const u of list) {
|
|
162
168
|
checkUnit(u, layer);
|
|
163
169
|
if (seen.has(unitKey(u))) continue; // video+image may both plan the same IU
|
|
164
170
|
seen.add(unitKey(u));
|
|
165
|
-
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
// §6.1 п.3: skip units whose scene asset is ready for the current content (PG scene_assets only)
|
|
170
|
-
let skipped = 0;
|
|
171
|
-
let todo = units;
|
|
172
|
-
if (!force && units.length) {
|
|
173
|
-
const k5 = (g) => `${g.chapter_id}\u0000${g.scene_id}\u0000${g.asset_type}\u0000${g.build_id}\u0000${g.scene_hash}`;
|
|
174
|
-
const gkey = (u) => k5({ ...u, asset_type: LAYER_OF_KIND[u.kind] });
|
|
175
|
-
const groups = new Map();
|
|
176
|
-
for (const u of units) {
|
|
177
|
-
if (typeof u.scene_hash !== 'string' || !u.scene_hash) continue; // readiness unprovable → do it
|
|
178
|
-
if (!groups.has(gkey(u))) groups.set(gkey(u), { chapter_id: u.chapter_id, scene_id: u.scene_id, asset_type: LAYER_OF_KIND[u.kind], build_id: u.build_id, scene_hash: u.scene_hash });
|
|
179
|
-
}
|
|
180
|
-
const readyKeys = new Set();
|
|
181
|
-
if (groups.size) {
|
|
182
|
-
const list = [...groups.values()];
|
|
183
|
-
const r = await client.query(
|
|
184
|
-
`SELECT g.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[])
|
|
185
|
-
WITH ORDINALITY AS g(chapter_id, scene_id, asset_type, build_id, scene_hash, ord)
|
|
186
|
-
WHERE EXISTS (SELECT 1 FROM scene_assets a
|
|
187
|
-
WHERE a.book_id = $1 AND a.chapter_id = g.chapter_id AND a.scene_id = g.scene_id
|
|
188
|
-
AND a.asset_type = g.asset_type AND a.build_id = g.build_id
|
|
189
|
-
AND a.status = 'ready' AND a.scene_hash = g.scene_hash)`,
|
|
190
|
-
[bookId, list.map((x) => x.chapter_id), list.map((x) => x.scene_id), list.map((x) => x.asset_type),
|
|
191
|
-
list.map((x) => x.build_id), list.map((x) => x.scene_hash)]);
|
|
192
|
-
for (const row of r.rows) readyKeys.add(k5(list[Number(row.ord) - 1]));
|
|
171
|
+
out.push(u);
|
|
193
172
|
}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
if (readyKeys.has(gkey(u))) { skipped += 1; return false; }
|
|
197
|
-
return true;
|
|
198
|
-
});
|
|
199
|
-
// 1.1.0 — part-level readiness (opt-in: the unit carries input.part_hash).
|
|
200
|
-
// A part (e.g. one IU picture) whose accepted snapshot hash is recorded in
|
|
201
|
-
// scene_assets.metadata.gen_parts[unit_key].part_hash for the same build is
|
|
202
|
-
// already done for the current content — skip it even if its scene is not
|
|
203
|
-
// complete («сгенерировать недостающее» = only the missing / changed parts).
|
|
204
|
-
// A row the host marked 'stale' proves nothing. Units without part_hash
|
|
205
|
-
// (audio) keep the scene-level rule above unchanged.
|
|
206
|
-
const parted = todo.filter((u) => typeof u.input.part_hash === 'string' && u.input.part_hash);
|
|
207
|
-
if (parted.length) {
|
|
208
|
-
const r = await client.query(
|
|
209
|
-
`SELECT t.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])
|
|
210
|
-
WITH ORDINALITY AS t(chapter_id, scene_id, asset_type, build_id, unit_key, part_hash, ord)
|
|
211
|
-
WHERE EXISTS (SELECT 1 FROM scene_assets a
|
|
212
|
-
WHERE a.book_id = $1 AND a.chapter_id = t.chapter_id AND a.scene_id = t.scene_id
|
|
213
|
-
AND a.asset_type = t.asset_type AND a.build_id = t.build_id
|
|
214
|
-
AND a.status IN ('pending', 'ready')
|
|
215
|
-
AND jsonb_typeof(a.metadata->'gen_parts') = 'object'
|
|
216
|
-
AND a.metadata->'gen_parts'->t.unit_key->>'part_hash' = t.part_hash)`,
|
|
217
|
-
[bookId, parted.map((u) => u.chapter_id), parted.map((u) => u.scene_id), parted.map((u) => LAYER_OF_KIND[u.kind]),
|
|
218
|
-
parted.map((u) => u.build_id), parted.map((u) => u.unit_key), parted.map((u) => u.input.part_hash)]);
|
|
219
|
-
const done = new Set(r.rows.map((row) => parted[Number(row.ord) - 1]));
|
|
220
|
-
if (done.size) {
|
|
221
|
-
skipped += done.size;
|
|
222
|
-
todo = todo.filter((u) => !done.has(u));
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
}
|
|
173
|
+
return out;
|
|
174
|
+
};
|
|
226
175
|
|
|
227
176
|
// lanes, one lookup per worker type (§4.2: computed at creation)
|
|
228
177
|
const laneCache = new Map();
|
|
@@ -240,10 +189,73 @@ function createCommands({ pool, ports }) {
|
|
|
240
189
|
return laneCache.get(type);
|
|
241
190
|
};
|
|
242
191
|
|
|
243
|
-
// §6.1 п.4: insert; a unit live under another command → joined (link to the live job)
|
|
244
192
|
let created = 0;
|
|
245
193
|
let joined = 0;
|
|
246
|
-
|
|
194
|
+
let skipped = 0;
|
|
195
|
+
|
|
196
|
+
/** §6.1 пп.3–4 for one batch of planned units: skip ready, insert / join the rest. */
|
|
197
|
+
const place = async (units) => {
|
|
198
|
+
let todo = units;
|
|
199
|
+
if (!force && units.length) {
|
|
200
|
+
// scene level: the scene asset is ready for the current content (PG scene_assets only)
|
|
201
|
+
const k5 = (g) => `${g.chapter_id}\u0000${g.scene_id}\u0000${g.asset_type}\u0000${g.build_id}\u0000${g.scene_hash}`;
|
|
202
|
+
const gkey = (u) => k5({ ...u, asset_type: LAYER_OF_KIND[u.kind] });
|
|
203
|
+
const groups = new Map();
|
|
204
|
+
for (const u of units) {
|
|
205
|
+
if (typeof u.scene_hash !== 'string' || !u.scene_hash) continue; // readiness unprovable → do it
|
|
206
|
+
if (!groups.has(gkey(u))) groups.set(gkey(u), { chapter_id: u.chapter_id, scene_id: u.scene_id, asset_type: LAYER_OF_KIND[u.kind], build_id: u.build_id, scene_hash: u.scene_hash });
|
|
207
|
+
}
|
|
208
|
+
const readyKeys = new Set();
|
|
209
|
+
if (groups.size) {
|
|
210
|
+
const list = [...groups.values()];
|
|
211
|
+
const r = await client.query(
|
|
212
|
+
`SELECT g.ord FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[])
|
|
213
|
+
WITH ORDINALITY AS g(chapter_id, scene_id, asset_type, build_id, scene_hash, ord)
|
|
214
|
+
WHERE EXISTS (SELECT 1 FROM scene_assets a
|
|
215
|
+
WHERE a.book_id = $1 AND a.chapter_id = g.chapter_id AND a.scene_id = g.scene_id
|
|
216
|
+
AND a.asset_type = g.asset_type AND a.build_id = g.build_id
|
|
217
|
+
AND a.status = 'ready' AND a.scene_hash = g.scene_hash)`,
|
|
218
|
+
[bookId, list.map((x) => x.chapter_id), list.map((x) => x.scene_id), list.map((x) => x.asset_type),
|
|
219
|
+
list.map((x) => x.build_id), list.map((x) => x.scene_hash)]);
|
|
220
|
+
for (const row of r.rows) readyKeys.add(k5(list[Number(row.ord) - 1]));
|
|
221
|
+
}
|
|
222
|
+
todo = units.filter((u) => {
|
|
223
|
+
if (typeof u.scene_hash !== 'string' || !u.scene_hash) return true;
|
|
224
|
+
if (readyKeys.has(gkey(u))) { skipped += 1; return false; }
|
|
225
|
+
return true;
|
|
226
|
+
});
|
|
227
|
+
// 1.1.0 — part-level readiness (opt-in: the unit carries input.part_hash).
|
|
228
|
+
// A part (e.g. one IU picture, one video group) whose accepted snapshot hash
|
|
229
|
+
// is recorded in scene_assets.metadata.gen_parts[unit_key].part_hash for the
|
|
230
|
+
// same build is already done for the current content — skip it even if its
|
|
231
|
+
// scene is not complete («сгенерировать недостающее» = only the missing /
|
|
232
|
+
// changed parts). A row the host marked 'stale' proves nothing. Units without
|
|
233
|
+
// part_hash (audio) keep the scene-level rule above unchanged.
|
|
234
|
+
const done = await readyParts(client, bookId, todo);
|
|
235
|
+
if (done.size) {
|
|
236
|
+
// 1.3.0 — a part kind with a merge stage (input.merge_parts: video_group):
|
|
237
|
+
// every part of the scene is already done but the scene is not ready for
|
|
238
|
+
// this content → the merge alone is created (local, no GPU). Parts whose
|
|
239
|
+
// done job cannot be found go back to the plan.
|
|
240
|
+
const byScene = new Map();
|
|
241
|
+
for (const u of todo) {
|
|
242
|
+
if (!mergePartsOf(u.input)) continue;
|
|
243
|
+
const sk = `${u.chapter_id}\u0000${u.scene_id}`;
|
|
244
|
+
if (!byScene.has(sk)) byScene.set(sk, []);
|
|
245
|
+
byScene.get(sk).push(u);
|
|
246
|
+
}
|
|
247
|
+
const extra = [];
|
|
248
|
+
for (const list of byScene.values()) {
|
|
249
|
+
if (!list.every((u) => done.has(u))) continue; // some parts run → the transition merges
|
|
250
|
+
const merge = await mergeUnitFor(client, bookId, list[0]);
|
|
251
|
+
if (merge) extra.push(merge);
|
|
252
|
+
else for (const u of list) done.delete(u);
|
|
253
|
+
}
|
|
254
|
+
skipped += done.size;
|
|
255
|
+
todo = todo.filter((u) => !done.has(u)).concat(extra);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (!todo.length) return;
|
|
247
259
|
const cols = { ch: [], sc: [], uk: [], kind: [], ex: [], layer: [], build: [], lane: [], max: [], input: [] };
|
|
248
260
|
for (const u of todo) {
|
|
249
261
|
const ex = EXECUTOR_OF_KIND[u.kind];
|
|
@@ -254,6 +266,7 @@ function createCommands({ pool, ports }) {
|
|
|
254
266
|
cols.max.push(ports.maxAttemptsFor(u.kind));
|
|
255
267
|
cols.input.push(JSON.stringify({ ...u.input, scene_hash: u.scene_hash ?? u.input.scene_hash ?? null }));
|
|
256
268
|
}
|
|
269
|
+
// §6.1 п.4: insert; a unit live under another command → joined (link to the live job)
|
|
257
270
|
const ins2 = await client.query(
|
|
258
271
|
`INSERT INTO gen_jobs (command_id, workspace_id, user_id, book_id, chapter_id, scene_id, unit_key,
|
|
259
272
|
kind, executor, layer, build_id, lane, max_attempts, input, created_at)
|
|
@@ -268,7 +281,7 @@ function createCommands({ pool, ports }) {
|
|
|
268
281
|
RETURNING job_id`,
|
|
269
282
|
[cmd.command_id, workspaceId, userId, bookId, cols.ch, cols.sc, cols.uk, cols.kind, cols.ex,
|
|
270
283
|
cols.layer, cols.build, cols.lane, cols.max, cols.input]);
|
|
271
|
-
created
|
|
284
|
+
created += ins2.rowCount;
|
|
272
285
|
// live jobs of the same units (ours just inserted + other commands' → joined)
|
|
273
286
|
const live = await client.query(
|
|
274
287
|
`SELECT j.job_id, j.command_id FROM gen_jobs j
|
|
@@ -276,10 +289,37 @@ function createCommands({ pool, ports }) {
|
|
|
276
289
|
ON j.chapter_id = t.ch AND j.scene_id = t.sc AND j.kind = t.kind AND j.unit_key = t.uk
|
|
277
290
|
WHERE j.book_id = $1 AND j.status IN ('queued','running')`,
|
|
278
291
|
[bookId, cols.ch, cols.sc, cols.kind, cols.uk]);
|
|
279
|
-
joined
|
|
292
|
+
joined += live.rows.filter((r) => r.command_id !== cmd.command_id).length;
|
|
280
293
|
await linkJobs(client, [cmd.command_id], live.rows.map((r) => r.job_id));
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
const nonVideo = [];
|
|
297
|
+
for (const layer of effective.filter((l) => l !== 'video')) {
|
|
298
|
+
const plan = normalisePlan(await ports.planUnits(bookRef, scope, layer, planCtx), layer);
|
|
299
|
+
nonVideo.push(...takeUnits(plan.units, layer));
|
|
281
300
|
}
|
|
282
|
-
|
|
301
|
+
await place(nonVideo);
|
|
302
|
+
|
|
303
|
+
// 1.3.0 — video (§6.5, §13 п.11): the planner decides per scene: groups now /
|
|
304
|
+
// wait for live images or audio (the command joins those jobs; the groups come
|
|
305
|
+
// from the transition of their acceptance) / skip with a reason.
|
|
306
|
+
let skips = [];
|
|
307
|
+
if (effective.includes('video')) {
|
|
308
|
+
const plan = normalisePlan(await ports.planUnits(bookRef, scope, 'video', planCtx), 'video');
|
|
309
|
+
await place(takeUnits(plan.units, 'video'));
|
|
310
|
+
if (plan.waits.length) {
|
|
311
|
+
// joined = links to live jobs another command created (our own image / audio jobs are not «joined»)
|
|
312
|
+
const foreign = async () => (await client.query(
|
|
313
|
+
`SELECT count(*)::int AS n FROM gen_command_jobs l JOIN gen_jobs j ON j.job_id = l.job_id
|
|
314
|
+
WHERE l.command_id = $1 AND j.command_id <> $1`, [cmd.command_id])).rows[0].n;
|
|
315
|
+
const before = await foreign();
|
|
316
|
+
await linkSceneLive(client, [cmd.command_id], bookId, plan.waits);
|
|
317
|
+
joined += (await foreign()) - before;
|
|
318
|
+
}
|
|
319
|
+
skips = plan.skipped;
|
|
320
|
+
await recordSkips(client, [cmd.command_id], skips);
|
|
321
|
+
}
|
|
322
|
+
const summary = { jobs_created: created, joined, skipped_ready: skipped, ...skipSummary(skips) };
|
|
283
323
|
await client.query('UPDATE gen_commands SET summary = $2::jsonb WHERE command_id = $1', [cmd.command_id, JSON.stringify(summary)]);
|
|
284
324
|
await notifyProgress(client, bookId, cmd.command_id);
|
|
285
325
|
return {
|
|
@@ -361,6 +401,19 @@ function createCommands({ pool, ports }) {
|
|
|
361
401
|
|
|
362
402
|
const purgeBook = (bookId) => purgeBookRows(pool, bookId);
|
|
363
403
|
|
|
404
|
+
/** createCommandTx + the О3 `command-created` info line (also for a repeated click: existing=true). */
|
|
405
|
+
async function createCommand(params = {}) {
|
|
406
|
+
const t0 = Date.now();
|
|
407
|
+
const r = await createCommandTx(params);
|
|
408
|
+
genLog.event('command-created', {
|
|
409
|
+
book_id: params.bookId, command_id: r.command_id, layers: r.layers, status: r.status,
|
|
410
|
+
scope: params.scope && params.scope.level, existing: r.existing === true ? true : undefined,
|
|
411
|
+
jobs_created: r.summary && r.summary.jobs_created, joined: r.summary && r.summary.joined,
|
|
412
|
+
skipped_ready: r.summary && r.summary.skipped_ready, ms: Date.now() - t0,
|
|
413
|
+
});
|
|
414
|
+
return r;
|
|
415
|
+
}
|
|
416
|
+
|
|
364
417
|
return { createCommand, cancel, purgeBook };
|
|
365
418
|
}
|
|
366
419
|
|
package/src/gen/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// ======================================================
|
|
2
|
-
// @animastor/orchestration · gen — orchestration v2 core (1.
|
|
2
|
+
// @animastor/orchestration · gen — orchestration v2 core (1.3.0)
|
|
3
3
|
// ======================================================
|
|
4
4
|
// ADR: animastor-docs architecture/ORCHESTRATION_V2.md. The single source of
|
|
5
5
|
// truth is PG (gen_commands, gen_jobs). This namespace depends ONLY on the
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
// await gen.migrate(pool);
|
|
11
11
|
// const orch = gen.createOrchestration({ pool, ports, uploadSecret, outputDir });
|
|
12
12
|
// orch.createCommand(...), orch.cancel(...), orch.purgeBook(bookId), orch.claim(...), orch.acceptResult(...),
|
|
13
|
-
// orch.acceptError(...), orch.beacon(...), orch.sweepOnce(), orch.startSweeper(ms),
|
|
13
|
+
// orch.acceptError(...), orch.beacon(...), orch.openInput(...), orch.sweepOnce(), orch.startSweeper(ms),
|
|
14
14
|
// orch.stop(), orch.progress(bookId), orch.listenProgress(fn), orch.runLocalOnce()
|
|
15
15
|
|
|
16
16
|
'use strict';
|
|
@@ -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
|
-
|
|
58
|
-
const
|
|
59
|
-
const
|
|
60
|
-
const
|
|
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
|
|
|
@@ -67,6 +70,7 @@ function createOrchestration(o = {}) {
|
|
|
67
70
|
purgeBook: commands.purgeBook,
|
|
68
71
|
claim: claim.claim,
|
|
69
72
|
beacon: claim.beacon,
|
|
73
|
+
openInput: claim.openInput,
|
|
70
74
|
acceptResult: accept.acceptResult,
|
|
71
75
|
acceptError: accept.acceptError,
|
|
72
76
|
sweepOnce: sweeper.sweepOnce,
|
|
@@ -106,5 +110,7 @@ module.exports = Object.freeze({
|
|
|
106
110
|
DEFAULT_MIN_LUMA_STDDEV: media.DEFAULT_MIN_LUMA_STDDEV,
|
|
107
111
|
}),
|
|
108
112
|
GenError: util.GenError,
|
|
113
|
+
/** pure formatter of the [gen-v2] info lines (О3) — for host tests / log parsers */
|
|
114
|
+
formatGenEvent,
|
|
109
115
|
PROGRESS_CHANNEL: util.PROGRESS_CHANNEL,
|
|
110
116
|
});
|
package/src/gen/local-runner.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
const { withTx, notifyProgress } = require('./util');
|
|
13
13
|
|
|
14
|
-
function createLocalRunner({ pool, ports, accept, logger =
|
|
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'),
|
|
@@ -42,7 +42,8 @@ function createLocalRunner({ pool, ports, accept, logger = console }) {
|
|
|
42
42
|
const r = await accept.failAttempt(job.job_id, job.attempt, (err && err.error_class) || 'unknown', `run_local: ${err && err.message}`);
|
|
43
43
|
return { job_id: job.job_id, attempt: job.attempt, ...r };
|
|
44
44
|
}
|
|
45
|
-
|
|
45
|
+
// 1.3.0: out.meta (e.g. measured chunk durations) reaches onArtifactPlaced inside the acceptance tx
|
|
46
|
+
const r = await accept.acceptLocalFile(job, out.path, out.meta === undefined ? null : out.meta);
|
|
46
47
|
return { job_id: job.job_id, attempt: job.attempt, ...r };
|
|
47
48
|
}
|
|
48
49
|
|
|
@@ -60,7 +61,7 @@ function createLocalRunner({ pool, ports, accept, logger = console }) {
|
|
|
60
61
|
try {
|
|
61
62
|
while (!stopped && await runLocalOnce()) { /* drain */ }
|
|
62
63
|
} catch (err) {
|
|
63
|
-
logger.error && logger.error(`[gen-v2] local runner: ${err && err.message}`);
|
|
64
|
+
logger && logger.error && logger.error(`[gen-v2] local runner: ${err && err.message}`);
|
|
64
65
|
} finally { running = false; }
|
|
65
66
|
}
|
|
66
67
|
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 };
|
package/src/gen/ports.js
CHANGED
|
@@ -28,8 +28,22 @@
|
|
|
28
28
|
// Optional:
|
|
29
29
|
// maxAttemptsFor(kind) → int ≥ 1 (default: 1 + max retries of the policy)
|
|
30
30
|
// isLayerEnabled(bookId, layer) → Promise<boolean> (§6.3 «только если слой включён»; default true)
|
|
31
|
-
// onArtifactPlaced(job, finalPath) → called inside the acceptance transaction right after the
|
|
32
|
-
// rename (§7 п.3), e.g. to drop a placeholder sidecar marker
|
|
31
|
+
// onArtifactPlaced(job, finalPath, ctx) → called inside the acceptance transaction right after the
|
|
32
|
+
// rename (§7 п.3), e.g. to drop a placeholder sidecar marker.
|
|
33
|
+
// 1.3.0: ctx = {db, meta} — db: the acceptance transaction client
|
|
34
|
+
// (writes commit or roll back with the result); meta: what runLocal
|
|
35
|
+
// returned next to {path} (local jobs), else null
|
|
36
|
+
// inputFiles(job) → [{name, path, sha256, bytes}] (1.3.0) input files of a GPU job,
|
|
37
|
+
// served by GET /internal/gen/jobs/:id/input/:name (§8.1); listed
|
|
38
|
+
// in the claimed task as input_files [{name, sha256, bytes}]
|
|
39
|
+
//
|
|
40
|
+
// 1.3.0 planUnits(book, scope, layer, ctx): ctx = {db} — the command / acceptance transaction
|
|
41
|
+
// client (read-only use). For layer 'video' the result may be {units, waits, skipped}:
|
|
42
|
+
// waits [{chapter_id, scene_id}] — the scene waits for live images / audio: the command
|
|
43
|
+
// joins those jobs, the video stage follows their acceptance (§6.3, §6.5)
|
|
44
|
+
// skipped [{chapter_id, scene_id, reason: 'skipped_*'}] — summary + gen_command_skips
|
|
45
|
+
// A part unit may carry input.merge_parts [{unit_key, part_hash}] (every part of the scene):
|
|
46
|
+
// its merge is created when all those parts are done (video_group → video_merge).
|
|
33
47
|
|
|
34
48
|
'use strict';
|
|
35
49
|
|
|
@@ -39,7 +53,7 @@ const REQUIRED = Object.freeze([
|
|
|
39
53
|
'planUnits', 'buildPayload', 'artifactPath', 'validateResult',
|
|
40
54
|
'runLocal', 'laneFor', 'timeoutFor', 'retryPolicy',
|
|
41
55
|
]);
|
|
42
|
-
const OPTIONAL = Object.freeze(['maxAttemptsFor', 'isLayerEnabled', 'onArtifactPlaced']);
|
|
56
|
+
const OPTIONAL = Object.freeze(['maxAttemptsFor', 'isLayerEnabled', 'onArtifactPlaced', 'inputFiles']);
|
|
43
57
|
|
|
44
58
|
// ── default retry policy: gpu-retry-policy.cjs:50–53 ─────────────────────
|
|
45
59
|
const RETRY_POLICY = Object.freeze({
|
package/src/gen/progress.js
CHANGED
|
@@ -40,10 +40,22 @@ function createProgress({ pool }) {
|
|
|
40
40
|
WHERE l.command_id = ANY($1::uuid[])
|
|
41
41
|
GROUP BY 1, 2, 3, 4, 5, 6`, [ids])).rows : [];
|
|
42
42
|
|
|
43
|
+
// 1.3.0 — why the command made no work for a scene (§6.5, §13 п.11 п.9): {reason: [scene_id…]}
|
|
44
|
+
const skipRows = ids.length ? (await pool.query(
|
|
45
|
+
`SELECT command_id, reason, scene_id FROM gen_command_skips WHERE command_id = ANY($1::uuid[])
|
|
46
|
+
ORDER BY created_at, chapter_id, scene_id`, [ids])).rows : [];
|
|
47
|
+
const skippedOf = new Map();
|
|
48
|
+
for (const r of skipRows) {
|
|
49
|
+
if (!skippedOf.has(r.command_id)) skippedOf.set(r.command_id, {});
|
|
50
|
+
const m = skippedOf.get(r.command_id);
|
|
51
|
+
if (!m[r.reason]) m[r.reason] = [];
|
|
52
|
+
if (!m[r.reason].includes(r.scene_id)) m[r.reason].push(r.scene_id);
|
|
53
|
+
}
|
|
54
|
+
|
|
43
55
|
const byCmd = new Map(cmds.map((c) => [c.command_id, {
|
|
44
56
|
command_id: c.command_id, kind: c.kind, scope: c.scope, layers: c.layers, force: c.force,
|
|
45
57
|
status: c.status, user_id: c.user_id, created_at: c.created_at, finished_at: c.finished_at,
|
|
46
|
-
error: c.error, summary: c.summary,
|
|
58
|
+
error: c.error, summary: c.summary, skipped: skippedOf.get(c.command_id) || {},
|
|
47
59
|
totals: zero(), by_layer: {}, merges: {}, scenes: new Map(),
|
|
48
60
|
}]));
|
|
49
61
|
const add = (row, field) => {
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// ======================================================
|
|
2
|
+
// gen/sql/004-command-skips — ADR ORCHESTRATION_V2 §6.5, §13 п.11 (stage 3, video)
|
|
3
|
+
// ======================================================
|
|
4
|
+
// gen_command_skips: why a command did NOT create work for a scene
|
|
5
|
+
// (skipped_needs_audio / skipped_image_dirty / skipped_needs_image, …).
|
|
6
|
+
// Written when the command is created (also mirrored into gen_commands.summary)
|
|
7
|
+
// and by stage transitions inside the acceptance transaction (a video command
|
|
8
|
+
// waited for images / audio and the scene turned out not ready). Insert-only:
|
|
9
|
+
// the acceptance transaction never updates gen_commands rows (it holds them
|
|
10
|
+
// FOR SHARE — an UPDATE there could deadlock two parallel acceptances).
|
|
11
|
+
// Progress reads it. Rows go with the command (ON DELETE CASCADE).
|
|
12
|
+
|
|
13
|
+
'use strict';
|
|
14
|
+
|
|
15
|
+
const GEN_COMMAND_SKIPS_SQL = Object.freeze([
|
|
16
|
+
`CREATE TABLE IF NOT EXISTS gen_command_skips (
|
|
17
|
+
command_id UUID NOT NULL REFERENCES gen_commands(command_id) ON DELETE CASCADE,
|
|
18
|
+
chapter_id TEXT NOT NULL,
|
|
19
|
+
scene_id TEXT NOT NULL,
|
|
20
|
+
reason TEXT NOT NULL CHECK (reason ~ '^skipped_[a-z_]{1,48}$'),
|
|
21
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
22
|
+
PRIMARY KEY (command_id, chapter_id, scene_id, reason)
|
|
23
|
+
)`,
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
module.exports = { GEN_COMMAND_SKIPS_SQL };
|
package/src/gen/sql/index.js
CHANGED
|
@@ -6,12 +6,14 @@
|
|
|
6
6
|
const { GEN_CORE_SQL } = require('./001-gen-core');
|
|
7
7
|
const { GEN_COMMAND_JOBS_SQL } = require('./002-command-jobs');
|
|
8
8
|
const { GEN_SCOPE_SCENES_SQL } = require('./003-scope-scenes');
|
|
9
|
+
const { GEN_COMMAND_SKIPS_SQL } = require('./004-command-skips');
|
|
9
10
|
const { withTx } = require('../util');
|
|
10
11
|
|
|
11
12
|
const MIGRATIONS = Object.freeze([
|
|
12
13
|
Object.freeze({ id: '001-gen-core', statements: GEN_CORE_SQL }),
|
|
13
14
|
Object.freeze({ id: '002-command-jobs', statements: GEN_COMMAND_JOBS_SQL }),
|
|
14
15
|
Object.freeze({ id: '003-scope-scenes', statements: GEN_SCOPE_SCENES_SQL }),
|
|
16
|
+
Object.freeze({ id: '004-command-skips', statements: GEN_COMMAND_SKIPS_SQL }),
|
|
15
17
|
]);
|
|
16
18
|
|
|
17
19
|
/**
|