@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.
- package/CHANGELOG.md +70 -0
- package/README.md +31 -0
- package/package.json +11 -8
- package/src/gen/accept.js +370 -0
- package/src/gen/claim.js +155 -0
- package/src/gen/commands.js +338 -0
- package/src/gen/index.js +107 -0
- package/src/gen/local-runner.js +80 -0
- package/src/gen/ports.js +163 -0
- package/src/gen/progress.js +99 -0
- package/src/gen/sql/001-gen-core.js +130 -0
- package/src/gen/sql/002-command-jobs.js +58 -0
- package/src/gen/sql/003-scope-scenes.js +38 -0
- package/src/gen/sql/index.js +35 -0
- package/src/gen/sweeper.js +141 -0
- package/src/gen/util.js +136 -0
- package/src/gen/validate-media.js +181 -0
- package/src/index.js +15 -91
- package/src/legacy/index.js +100 -0
- package/src/{runtime → legacy/runtime}/command-gate.js +11 -2
- package/src/{runtime → legacy/runtime}/persistence-port.js +21 -0
- package/src/{runtime → legacy/runtime}/reconciliation-engine.js +15 -0
- package/src/{runtime → legacy/runtime}/runtime-scheduler.js +9 -0
- package/src/{runtime → legacy/runtime}/scene-window.js +4 -0
- package/test/artifact-root-binding.test.js +0 -174
- package/test/capacity-deferral.test.js +0 -265
- package/test/counter-reconciliation.test.js +0 -164
- package/test/mocks/redis-mock.js +0 -231
- package/test/reconcile-quota-leak.test.js +0 -366
- package/test/stage146-d1-artifact-naming.test.js +0 -103
- package/test/stage147-a1-null-build-gate.test.js +0 -211
- package/test/test-bindings.js +0 -60
- /package/src/{host → legacy/host}/host-bindings.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/index.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/orchestrator.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/runtime-result-consumer.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/scene-callbacks.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/scene-orchestrator.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/scene-restoration.js +0 -0
- /package/src/{orchestration → legacy/orchestration}/scene-utils.js +0 -0
- /package/src/{runtime → legacy/runtime}/active-scenes-index.js +0 -0
- /package/src/{runtime → legacy/runtime}/audio-fsm-port.js +0 -0
- /package/src/{runtime → legacy/runtime}/circuit-breaker.js +0 -0
- /package/src/{runtime → legacy/runtime}/counter-reconciliation.js +0 -0
- /package/src/{runtime → legacy/runtime}/dispatch-engine.js +0 -0
- /package/src/{runtime → legacy/runtime}/dispatch-outcomes.js +0 -0
- /package/src/{runtime → legacy/runtime}/failure-taxonomy.js +0 -0
- /package/src/{runtime → legacy/runtime}/hub-cancel-port.js +0 -0
- /package/src/{runtime → legacy/runtime}/layer-config-port.js +0 -0
- /package/src/{runtime → legacy/runtime}/lease-manager.js +0 -0
- /package/src/{runtime → legacy/runtime}/placeholder-audio-port.js +0 -0
- /package/src/{runtime → legacy/runtime}/progress-events-port.js +0 -0
- /package/src/{runtime → legacy/runtime}/retry-budget-manager.js +0 -0
- /package/src/{runtime → legacy/runtime}/runtime-metrics.js +0 -0
- /package/src/{runtime → legacy/runtime}/runtime-result-emitter.js +0 -0
- /package/src/{runtime → legacy/runtime}/scene-data-port.js +0 -0
- /package/src/{runtime → legacy/runtime}/video-fsm-port.js +0 -0
- /package/src/{runtime → legacy/runtime}/worker-health.js +0 -0
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// ======================================================
|
|
2
|
+
// gen/local-runner — executor='local' jobs (merge), ADR §5
|
|
3
|
+
// ======================================================
|
|
4
|
+
// Takes a queued local job exactly like a worker claim (SKIP LOCKED, attempt
|
|
5
|
+
// +1, deadline), runs the host port runLocal(job) → {path}, and accepts the
|
|
6
|
+
// produced file through the SAME acceptance transaction as GPU results.
|
|
7
|
+
// A backend restart mid-run leaves the job running; its deadline expires and
|
|
8
|
+
// the sweeper re-queues it (§9) — nothing is lost, nothing new is created.
|
|
9
|
+
|
|
10
|
+
'use strict';
|
|
11
|
+
|
|
12
|
+
const { withTx, notifyProgress } = require('./util');
|
|
13
|
+
|
|
14
|
+
function createLocalRunner({ pool, ports, accept, logger = console }) {
|
|
15
|
+
const timeoutsJson = JSON.stringify({
|
|
16
|
+
audio_merge: ports.timeoutFor('audio_merge'),
|
|
17
|
+
video_merge: ports.timeoutFor('video_merge'),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
/** @returns {Promise<null|{job_id:string, attempt:number, status:number, job_status?:string, code?:string}>} */
|
|
21
|
+
async function runLocalOnce() {
|
|
22
|
+
const job = await withTx(pool, async (client) => {
|
|
23
|
+
const r = await client.query(
|
|
24
|
+
`UPDATE gen_jobs j
|
|
25
|
+
SET status = 'running', attempt = j.attempt + 1, worker_id = NULL, claimed_at = now(),
|
|
26
|
+
deadline = now() + make_interval(secs => (($1::jsonb)->>j.kind)::numeric / 1000)
|
|
27
|
+
WHERE j.job_id = (
|
|
28
|
+
SELECT job_id FROM gen_jobs
|
|
29
|
+
WHERE executor = 'local' AND status = 'queued' AND not_before <= now()
|
|
30
|
+
ORDER BY created_at, job_id
|
|
31
|
+
LIMIT 1 FOR UPDATE SKIP LOCKED)
|
|
32
|
+
RETURNING j.*`, [timeoutsJson]);
|
|
33
|
+
if (r.rows[0]) await notifyProgress(client, r.rows[0].book_id, r.rows[0].command_id);
|
|
34
|
+
return r.rows[0] || null;
|
|
35
|
+
});
|
|
36
|
+
if (!job) return null;
|
|
37
|
+
let out;
|
|
38
|
+
try {
|
|
39
|
+
out = await ports.runLocal(job);
|
|
40
|
+
if (!out || typeof out.path !== 'string') throw Object.assign(new Error('runLocal must return {path}'), { error_class: 'deterministic' });
|
|
41
|
+
} catch (err) {
|
|
42
|
+
const r = await accept.failAttempt(job.job_id, job.attempt, (err && err.error_class) || 'unknown', `run_local: ${err && err.message}`);
|
|
43
|
+
return { job_id: job.job_id, attempt: job.attempt, ...r };
|
|
44
|
+
}
|
|
45
|
+
const r = await accept.acceptLocalFile(job, out.path);
|
|
46
|
+
return { job_id: job.job_id, attempt: job.attempt, ...r };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
let timer = null;
|
|
50
|
+
let running = false;
|
|
51
|
+
let stopped = true;
|
|
52
|
+
/** Drain local jobs every intervalMs (one at a time). */
|
|
53
|
+
function startLocalRunner(intervalMs = 2_000) {
|
|
54
|
+
if (!stopped) return;
|
|
55
|
+
stopped = false;
|
|
56
|
+
const tick = async () => {
|
|
57
|
+
if (stopped) return;
|
|
58
|
+
if (!running) {
|
|
59
|
+
running = true;
|
|
60
|
+
try {
|
|
61
|
+
while (!stopped && await runLocalOnce()) { /* drain */ }
|
|
62
|
+
} catch (err) {
|
|
63
|
+
logger.error && logger.error(`[gen-v2] local runner: ${err && err.message}`);
|
|
64
|
+
} finally { running = false; }
|
|
65
|
+
}
|
|
66
|
+
if (!stopped) { timer = setTimeout(tick, intervalMs); if (timer.unref) timer.unref(); }
|
|
67
|
+
};
|
|
68
|
+
timer = setTimeout(tick, 0);
|
|
69
|
+
if (timer.unref) timer.unref();
|
|
70
|
+
}
|
|
71
|
+
function stopLocalRunner() {
|
|
72
|
+
stopped = true;
|
|
73
|
+
if (timer) clearTimeout(timer);
|
|
74
|
+
timer = null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return { runLocalOnce, startLocalRunner, stopLocalRunner };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = { createLocalRunner };
|
package/src/gen/ports.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// ======================================================
|
|
2
|
+
// gen/ports — host port contract + validation (ADR ORCHESTRATION_V2 §5)
|
|
3
|
+
// ======================================================
|
|
4
|
+
// The core knows nothing about books, ComfyUI or file naming. The host
|
|
5
|
+
// (backend) supplies these functions at initialisation; validatePorts()
|
|
6
|
+
// rejects a missing or malformed port before anything runs.
|
|
7
|
+
//
|
|
8
|
+
// planUnits(book, scope, layer) → Promise<Unit[]>
|
|
9
|
+
// book = {bookId, workspaceId, userId}
|
|
10
|
+
// scope = {level, chapter_id?, scene_id?, unit_id?, scene_ids?} (level 'scenes' → scene_ids, book order)
|
|
11
|
+
// Unit = {chapter_id, scene_id, kind, unit_key, build_id, input, scene_hash?}
|
|
12
|
+
// build_id = the book build at command time (gen_jobs.build_id, §4.2)
|
|
13
|
+
// buildPayload(job) → Promise<object> ComfyUI params etc. (claim, §8.1)
|
|
14
|
+
// artifactPath(job) → string absolute final path (accept, §7 п.3)
|
|
15
|
+
// validateResult(job, tmpPath) → Promise<{ok, reason?}> (§7 п.1; default: validate-media)
|
|
16
|
+
// runLocal(job) → Promise<{path}> executor='local' (merge); a file to accept
|
|
17
|
+
// laneFor(workspaceId, workerType) → Promise<{kind, workspace_id?, policy_id?}>
|
|
18
|
+
// (logic of gpu-dispatcher.js:213–222; default: makeLaneFor)
|
|
19
|
+
// timeoutFor(kind) → ms (deadline = claimed_at + timeout, §4.2)
|
|
20
|
+
// retryPolicy(kind, error_class, attempt, {previousErrorClass}) → {retry, delay_ms}
|
|
21
|
+
// (values of gpu-retry-policy.cjs:50–53)
|
|
22
|
+
// Optional:
|
|
23
|
+
// maxAttemptsFor(kind) → int ≥ 1 (default: 1 + max retries of the policy)
|
|
24
|
+
// isLayerEnabled(bookId, layer) → Promise<boolean> (§6.3 «только если слой включён»; default true)
|
|
25
|
+
// onArtifactPlaced(job, finalPath) → called inside the acceptance transaction right after the
|
|
26
|
+
// rename (§7 п.3), e.g. to drop a placeholder sidecar marker
|
|
27
|
+
|
|
28
|
+
'use strict';
|
|
29
|
+
|
|
30
|
+
const { GenError, KINDS } = require('./util');
|
|
31
|
+
|
|
32
|
+
const REQUIRED = Object.freeze([
|
|
33
|
+
'planUnits', 'buildPayload', 'artifactPath', 'validateResult',
|
|
34
|
+
'runLocal', 'laneFor', 'timeoutFor', 'retryPolicy',
|
|
35
|
+
]);
|
|
36
|
+
const OPTIONAL = Object.freeze(['maxAttemptsFor', 'isLayerEnabled', 'onArtifactPlaced']);
|
|
37
|
+
|
|
38
|
+
// ── default retry policy: gpu-retry-policy.cjs:50–53 ─────────────────────
|
|
39
|
+
const RETRY_POLICY = Object.freeze({
|
|
40
|
+
deterministic: Object.freeze({ retries: 0, pausesMs: Object.freeze([]) }),
|
|
41
|
+
transient: Object.freeze({ retries: 2, pausesMs: Object.freeze([30_000, 120_000]) }),
|
|
42
|
+
oom: Object.freeze({ retries: 1, pausesMs: Object.freeze([60_000]) }),
|
|
43
|
+
unknown: Object.freeze({ retries: 0, pausesMs: Object.freeze([]) }),
|
|
44
|
+
// ADR §7 / §13.4 (редакция 06.11): silence / broken file — one retry, then failed
|
|
45
|
+
invalid_result: Object.freeze({ retries: 1, pausesMs: Object.freeze([30_000]) }),
|
|
46
|
+
});
|
|
47
|
+
/** v2 error classes produced by the core itself → policy class. */
|
|
48
|
+
const CLASS_ALIASES = Object.freeze({
|
|
49
|
+
timeout: 'transient', // sweeper: deadline passed (§9 п.1)
|
|
50
|
+
worker_offline: 'transient', // sweeper: worker silent > 60 s (§9 п.2)
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
function policyClass(errorClass) {
|
|
54
|
+
const c = CLASS_ALIASES[errorClass] || errorClass;
|
|
55
|
+
return RETRY_POLICY[c] ? c : 'unknown';
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {string} _kind
|
|
60
|
+
* @param {string} errorClass
|
|
61
|
+
* @param {number} attempt the attempt that just failed (1-based)
|
|
62
|
+
* @param {{previousErrorClass?:string|null}} [ctx] error class of the attempt before
|
|
63
|
+
*/
|
|
64
|
+
function defaultRetryPolicy(_kind, errorClass, attempt, ctx = {}) {
|
|
65
|
+
const cls = policyClass(errorClass);
|
|
66
|
+
const p = RETRY_POLICY[cls];
|
|
67
|
+
// invalid_result: ONE retry per job (counted by class, not by attempt number —
|
|
68
|
+
// an earlier timeout must not eat it); a second invalid result → failed
|
|
69
|
+
if (cls === 'invalid_result') {
|
|
70
|
+
return ctx.previousErrorClass === 'invalid_result' ? { retry: false, delay_ms: 0 } : { retry: true, delay_ms: p.pausesMs[0] };
|
|
71
|
+
}
|
|
72
|
+
const idx = Math.max(0, (Number(attempt) || 1) - 1);
|
|
73
|
+
if (idx < p.retries) return { retry: true, delay_ms: p.pausesMs[idx] ?? p.pausesMs[p.pausesMs.length - 1] ?? 0 };
|
|
74
|
+
return { retry: false, delay_ms: 0 };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function defaultMaxAttemptsFor(_kind) {
|
|
78
|
+
return 1 + Math.max(...Object.values(RETRY_POLICY).map((p) => p.retries)); // 3 (TRANSIENT)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ── default timeouts: media-registry jobMs (generation default-registrations) ──
|
|
82
|
+
const TIMEOUT_MS = Object.freeze({
|
|
83
|
+
audio_chunk: 30 * 60_000,
|
|
84
|
+
iu_image: 30 * 60_000,
|
|
85
|
+
video_group: 60 * 60_000,
|
|
86
|
+
audio_merge: 10 * 60_000,
|
|
87
|
+
video_merge: 20 * 60_000,
|
|
88
|
+
});
|
|
89
|
+
function defaultTimeoutFor(kind) { return TIMEOUT_MS[kind]; }
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Lane decision of gpu-dispatcher.js:213–222 over two host lookups:
|
|
93
|
+
* book workspace has an active private worker of the type → private lane;
|
|
94
|
+
* else a users-share grant policy → policy lane; else the system pool.
|
|
95
|
+
* @param {{hasActivePrivateWorker:(ws,type)=>Promise<boolean>, grantPolicyLane:(ws,type)=>Promise<{policy_id}|null>}} lookups
|
|
96
|
+
*/
|
|
97
|
+
function makeLaneFor({ hasActivePrivateWorker, grantPolicyLane }) {
|
|
98
|
+
if (typeof hasActivePrivateWorker !== 'function' || typeof grantPolicyLane !== 'function') {
|
|
99
|
+
throw new GenError('bad_ports', 500, 'makeLaneFor needs hasActivePrivateWorker and grantPolicyLane');
|
|
100
|
+
}
|
|
101
|
+
return async function laneFor(workspaceId, workerType) {
|
|
102
|
+
if (workspaceId && await hasActivePrivateWorker(workspaceId, workerType)) {
|
|
103
|
+
return { kind: 'private', workspace_id: workspaceId };
|
|
104
|
+
}
|
|
105
|
+
if (workspaceId) {
|
|
106
|
+
const lane = await grantPolicyLane(workspaceId, workerType);
|
|
107
|
+
if (lane && lane.policy_id) return { kind: 'policy', policy_id: lane.policy_id };
|
|
108
|
+
}
|
|
109
|
+
return { kind: 'system' };
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Validate a lane object produced by laneFor. */
|
|
114
|
+
function checkLane(lane) {
|
|
115
|
+
if (!lane || typeof lane !== 'object') return false;
|
|
116
|
+
if (lane.kind === 'private') return typeof lane.workspace_id === 'string' && lane.workspace_id.length > 0;
|
|
117
|
+
if (lane.kind === 'policy') return typeof lane.policy_id === 'string' && lane.policy_id.length > 0;
|
|
118
|
+
return lane.kind === 'system';
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Validate the host ports at initialisation. Throws GenError('bad_ports').
|
|
123
|
+
* @returns {object} frozen, normalised ports (optional ones defaulted)
|
|
124
|
+
*/
|
|
125
|
+
function validatePorts(ports) {
|
|
126
|
+
if (!ports || typeof ports !== 'object') throw new GenError('bad_ports', 500, 'ports object required');
|
|
127
|
+
const missing = REQUIRED.filter((n) => typeof ports[n] !== 'function');
|
|
128
|
+
const badOptional = OPTIONAL.filter((n) => ports[n] !== undefined && typeof ports[n] !== 'function');
|
|
129
|
+
if (missing.length || badOptional.length) {
|
|
130
|
+
throw new GenError('bad_ports', 500,
|
|
131
|
+
`ports: missing/invalid ${[...missing, ...badOptional].join(', ')}`);
|
|
132
|
+
}
|
|
133
|
+
const out = { ...ports };
|
|
134
|
+
if (!out.maxAttemptsFor) out.maxAttemptsFor = defaultMaxAttemptsFor;
|
|
135
|
+
if (!out.isLayerEnabled) out.isLayerEnabled = async () => true;
|
|
136
|
+
for (const kind of KINDS) {
|
|
137
|
+
const t = out.timeoutFor(kind);
|
|
138
|
+
if (!Number.isFinite(t) || t <= 0) throw new GenError('bad_ports', 500, `timeoutFor(${kind}) must be > 0 ms, got ${t}`);
|
|
139
|
+
const m = out.maxAttemptsFor(kind);
|
|
140
|
+
if (!Number.isInteger(m) || m < 1) throw new GenError('bad_ports', 500, `maxAttemptsFor(${kind}) must be an integer >= 1`);
|
|
141
|
+
}
|
|
142
|
+
const probe = out.retryPolicy('audio_chunk', 'transient', 1);
|
|
143
|
+
if (!probe || typeof probe.retry !== 'boolean' || !Number.isFinite(probe.delay_ms) || probe.delay_ms < 0) {
|
|
144
|
+
throw new GenError('bad_ports', 500, 'retryPolicy must return {retry:boolean, delay_ms:number>=0}');
|
|
145
|
+
}
|
|
146
|
+
return Object.freeze(out);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
module.exports = {
|
|
150
|
+
REQUIRED_PORTS: REQUIRED,
|
|
151
|
+
OPTIONAL_PORTS: OPTIONAL,
|
|
152
|
+
RETRY_POLICY,
|
|
153
|
+
TIMEOUT_MS,
|
|
154
|
+
validatePorts,
|
|
155
|
+
checkLane,
|
|
156
|
+
policyClass,
|
|
157
|
+
defaults: Object.freeze({
|
|
158
|
+
retryPolicy: defaultRetryPolicy,
|
|
159
|
+
maxAttemptsFor: defaultMaxAttemptsFor,
|
|
160
|
+
timeoutFor: defaultTimeoutFor,
|
|
161
|
+
makeLaneFor,
|
|
162
|
+
}),
|
|
163
|
+
};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// ======================================================
|
|
2
|
+
// gen/progress — SQL aggregate over gen_jobs (ADR §9 «Прогресс») + LISTEN
|
|
3
|
+
// ======================================================
|
|
4
|
+
// The panel shows table rows, nothing else: per active command of the book,
|
|
5
|
+
// per layer and per scene — queued / running / done / failed / cancelled.
|
|
6
|
+
// Only gen_command_jobs ⨝ gen_jobs (ADR §4.2a, §9). Jobs another command
|
|
7
|
+
// created and this one joined are additionally reported as joined_queued /
|
|
8
|
+
// joined_running (they are already inside the per-status totals).
|
|
9
|
+
|
|
10
|
+
'use strict';
|
|
11
|
+
|
|
12
|
+
const { requireText, PROGRESS_CHANNEL } = require('./util');
|
|
13
|
+
|
|
14
|
+
const STATUSES = ['queued', 'running', 'done', 'failed', 'cancelled'];
|
|
15
|
+
const zero = () => ({ queued: 0, running: 0, done: 0, failed: 0, cancelled: 0, joined_queued: 0, joined_running: 0, retrying: 0 });
|
|
16
|
+
|
|
17
|
+
function createProgress({ pool }) {
|
|
18
|
+
/** @returns {Promise<{book_id:string, totals:object, commands:object[]}>} */
|
|
19
|
+
/**
|
|
20
|
+
* @param {string} bookId
|
|
21
|
+
* @param {{finishedWithinMs?:number}} [opts] also return commands finished within this window
|
|
22
|
+
* (a panel shows the final 100% / failed row before it disappears)
|
|
23
|
+
*/
|
|
24
|
+
async function progress(bookId, opts = {}) {
|
|
25
|
+
requireText(bookId, 'bookId');
|
|
26
|
+
const within = Number(opts.finishedWithinMs) > 0 ? Number(opts.finishedWithinMs) : 0;
|
|
27
|
+
const cmds = (await pool.query(
|
|
28
|
+
`SELECT command_id, kind, scope, layers, force, status, created_at, finished_at, error, summary, user_id
|
|
29
|
+
FROM gen_commands
|
|
30
|
+
WHERE book_id = $1 AND (status = 'active'
|
|
31
|
+
OR ($2::numeric > 0 AND finished_at > now() - make_interval(secs => $2::numeric / 1000)))
|
|
32
|
+
ORDER BY created_at`, [bookId, within])).rows;
|
|
33
|
+
const ids = cmds.map((c) => c.command_id);
|
|
34
|
+
const rows = ids.length ? (await pool.query(
|
|
35
|
+
`SELECT l.command_id, j.layer, j.chapter_id, j.scene_id, j.status,
|
|
36
|
+
(j.command_id <> l.command_id) AS foreign, count(*)::int AS n,
|
|
37
|
+
count(*) FILTER (WHERE j.status = 'queued' AND j.attempt > 0)::int AS retrying,
|
|
38
|
+
count(*) FILTER (WHERE j.kind IN ('audio_merge','video_merge'))::int AS merges
|
|
39
|
+
FROM gen_command_jobs l JOIN gen_jobs j ON j.job_id = l.job_id
|
|
40
|
+
WHERE l.command_id = ANY($1::uuid[])
|
|
41
|
+
GROUP BY 1, 2, 3, 4, 5, 6`, [ids])).rows : [];
|
|
42
|
+
|
|
43
|
+
const byCmd = new Map(cmds.map((c) => [c.command_id, {
|
|
44
|
+
command_id: c.command_id, kind: c.kind, scope: c.scope, layers: c.layers, force: c.force,
|
|
45
|
+
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,
|
|
47
|
+
totals: zero(), by_layer: {}, merges: {}, scenes: new Map(),
|
|
48
|
+
}]));
|
|
49
|
+
const add = (row, field) => {
|
|
50
|
+
const c = byCmd.get(row.command_id);
|
|
51
|
+
if (!c) return;
|
|
52
|
+
c.totals[field] += row.n;
|
|
53
|
+
if (!c.by_layer[row.layer]) c.by_layer[row.layer] = zero();
|
|
54
|
+
c.by_layer[row.layer][field] += row.n;
|
|
55
|
+
const sk = `${row.chapter_id}\u0000${row.scene_id}\u0000${row.layer}`;
|
|
56
|
+
if (!c.scenes.has(sk)) c.scenes.set(sk, { chapter_id: row.chapter_id, scene_id: row.scene_id, layer: row.layer, ...zero() });
|
|
57
|
+
c.scenes.get(sk)[field] += row.n;
|
|
58
|
+
};
|
|
59
|
+
for (const r of rows) {
|
|
60
|
+
if (STATUSES.includes(r.status)) add(r, r.status);
|
|
61
|
+
if (r.retrying) add({ ...r, n: r.retrying }, 'retrying');
|
|
62
|
+
if (r.merges) { const c = byCmd.get(r.command_id); if (c) c.merges[r.layer] = (c.merges[r.layer] || 0) + r.merges; }
|
|
63
|
+
if (r.foreign && r.status === 'queued') add(r, 'joined_queued');
|
|
64
|
+
if (r.foreign && r.status === 'running') add(r, 'joined_running');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const totals = zero();
|
|
68
|
+
const commands = [...byCmd.values()].map((c) => {
|
|
69
|
+
for (const k of Object.keys(totals)) totals[k] += c.totals[k];
|
|
70
|
+
return { ...c, scenes: [...c.scenes.values()] };
|
|
71
|
+
});
|
|
72
|
+
return { book_id: bookId, totals, commands };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* LISTEN gen_progress on a dedicated pooled client.
|
|
77
|
+
* @param {(evt:{book_id:string, command_id:string|null})=>void} onEvent
|
|
78
|
+
* @returns {Promise<{close:()=>Promise<void>}>}
|
|
79
|
+
*/
|
|
80
|
+
async function listenProgress(onEvent) {
|
|
81
|
+
const client = await pool.connect();
|
|
82
|
+
const handler = (msg) => {
|
|
83
|
+
if (msg.channel !== PROGRESS_CHANNEL) return;
|
|
84
|
+
try { onEvent(JSON.parse(msg.payload)); } catch (_) { /* malformed payload / handler error */ }
|
|
85
|
+
};
|
|
86
|
+
client.on('notification', handler);
|
|
87
|
+
await client.query(`LISTEN ${PROGRESS_CHANNEL}`);
|
|
88
|
+
return {
|
|
89
|
+
async close() {
|
|
90
|
+
client.removeListener('notification', handler);
|
|
91
|
+
try { await client.query(`UNLISTEN ${PROGRESS_CHANNEL}`); } finally { client.release(); }
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return { progress, listenProgress };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
module.exports = { createProgress };
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// ======================================================
|
|
2
|
+
// gen/sql/001-gen-core — v2 orchestration schema (ADR ORCHESTRATION_V2 §4)
|
|
3
|
+
// ======================================================
|
|
4
|
+
// Style of the backend schema.js (host storage): an ordered list of idempotent
|
|
5
|
+
// statements (CREATE … IF NOT EXISTS, ADD COLUMN IF NOT EXISTS, constraints
|
|
6
|
+
// guarded by a pg_constraint lookup). Safe to run on every start.
|
|
7
|
+
//
|
|
8
|
+
// Pre-existing host tables touched (additive only, nothing dropped):
|
|
9
|
+
// books.orchestration TEXT NOT NULL DEFAULT 'legacy' CHECK IN (legacy, v2)
|
|
10
|
+
// workers.current_job_id UUID
|
|
11
|
+
// scene_assets.job_id UUID (ADR §4.3 — written only by acceptance, §7)
|
|
12
|
+
// scene_assets.sha256 TEXT (ADR §4.3)
|
|
13
|
+
//
|
|
14
|
+
// Table/constraint names are resolved through search_path (regclass), so the
|
|
15
|
+
// same statements run unchanged inside a per-test schema.
|
|
16
|
+
|
|
17
|
+
'use strict';
|
|
18
|
+
|
|
19
|
+
const ADD_CHECK = (table, name, expr) => `
|
|
20
|
+
DO $$
|
|
21
|
+
BEGIN
|
|
22
|
+
IF NOT EXISTS (
|
|
23
|
+
SELECT 1 FROM pg_constraint
|
|
24
|
+
WHERE conname = '${name}' AND conrelid = '${table}'::regclass
|
|
25
|
+
) THEN
|
|
26
|
+
ALTER TABLE ${table} ADD CONSTRAINT ${name} CHECK (${expr});
|
|
27
|
+
END IF;
|
|
28
|
+
END $$`;
|
|
29
|
+
|
|
30
|
+
const GEN_CORE_SQL = Object.freeze([
|
|
31
|
+
// ── host tables: additive columns ─────────────────────────────────────
|
|
32
|
+
`ALTER TABLE books ADD COLUMN IF NOT EXISTS orchestration TEXT NOT NULL DEFAULT 'legacy'`,
|
|
33
|
+
ADD_CHECK('books', 'books_orchestration_check', `orchestration IN ('legacy','v2')`),
|
|
34
|
+
`ALTER TABLE workers ADD COLUMN IF NOT EXISTS current_job_id UUID`,
|
|
35
|
+
`ALTER TABLE scene_assets ADD COLUMN IF NOT EXISTS job_id UUID`,
|
|
36
|
+
`ALTER TABLE scene_assets ADD COLUMN IF NOT EXISTS sha256 TEXT`,
|
|
37
|
+
|
|
38
|
+
// ── gen_commands (ADR §4.1) ───────────────────────────────────────────
|
|
39
|
+
`CREATE TABLE IF NOT EXISTS gen_commands (
|
|
40
|
+
command_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
41
|
+
workspace_id UUID NOT NULL,
|
|
42
|
+
user_id UUID NOT NULL,
|
|
43
|
+
book_id TEXT NOT NULL,
|
|
44
|
+
kind TEXT NOT NULL,
|
|
45
|
+
scope JSONB NOT NULL,
|
|
46
|
+
layers TEXT[] NOT NULL,
|
|
47
|
+
force BOOLEAN NOT NULL DEFAULT false,
|
|
48
|
+
client_action_id TEXT,
|
|
49
|
+
status TEXT NOT NULL DEFAULT 'active',
|
|
50
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
51
|
+
finished_at TIMESTAMPTZ,
|
|
52
|
+
cancelled_by TEXT,
|
|
53
|
+
error TEXT,
|
|
54
|
+
CONSTRAINT gen_commands_client_action_uniq UNIQUE (book_id, client_action_id)
|
|
55
|
+
)`,
|
|
56
|
+
ADD_CHECK('gen_commands', 'gen_commands_kind_check', `kind IN ('regenerate','generate_all')`),
|
|
57
|
+
ADD_CHECK('gen_commands', 'gen_commands_status_check',
|
|
58
|
+
`status IN ('active','done','partial','failed','cancelled')`),
|
|
59
|
+
ADD_CHECK('gen_commands', 'gen_commands_scope_check',
|
|
60
|
+
`jsonb_typeof(scope) = 'object' AND COALESCE(scope->>'level', '') IN ('book','chapter','scene','unit')`),
|
|
61
|
+
ADD_CHECK('gen_commands', 'gen_commands_layers_check',
|
|
62
|
+
`cardinality(layers) > 0 AND layers <@ ARRAY['audio','image','video']::text[]`),
|
|
63
|
+
`CREATE INDEX IF NOT EXISTS idx_gen_commands_book_status ON gen_commands (book_id, status)`,
|
|
64
|
+
|
|
65
|
+
// ── gen_jobs (ADR §4.2) ───────────────────────────────────────────────
|
|
66
|
+
`CREATE TABLE IF NOT EXISTS gen_jobs (
|
|
67
|
+
job_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
68
|
+
command_id UUID NOT NULL REFERENCES gen_commands(command_id) ON DELETE CASCADE,
|
|
69
|
+
workspace_id UUID NOT NULL,
|
|
70
|
+
user_id UUID NOT NULL,
|
|
71
|
+
book_id TEXT NOT NULL,
|
|
72
|
+
chapter_id TEXT NOT NULL,
|
|
73
|
+
scene_id TEXT NOT NULL,
|
|
74
|
+
unit_key TEXT NOT NULL,
|
|
75
|
+
kind TEXT NOT NULL,
|
|
76
|
+
executor TEXT NOT NULL,
|
|
77
|
+
lane JSONB,
|
|
78
|
+
status TEXT NOT NULL DEFAULT 'queued',
|
|
79
|
+
attempt INTEGER NOT NULL DEFAULT 0,
|
|
80
|
+
max_attempts INTEGER NOT NULL DEFAULT 1,
|
|
81
|
+
worker_id UUID,
|
|
82
|
+
deadline TIMESTAMPTZ,
|
|
83
|
+
not_before TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
84
|
+
input JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
85
|
+
result_path TEXT,
|
|
86
|
+
result_sha256 TEXT,
|
|
87
|
+
result_bytes BIGINT,
|
|
88
|
+
error_class TEXT,
|
|
89
|
+
error TEXT,
|
|
90
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
91
|
+
claimed_at TIMESTAMPTZ,
|
|
92
|
+
finished_at TIMESTAMPTZ
|
|
93
|
+
)`,
|
|
94
|
+
ADD_CHECK('gen_jobs', 'gen_jobs_status_check',
|
|
95
|
+
`status IN ('queued','running','done','failed','cancelled')`),
|
|
96
|
+
ADD_CHECK('gen_jobs', 'gen_jobs_kind_check',
|
|
97
|
+
`kind IN ('audio_chunk','iu_image','video_group','audio_merge','video_merge')`),
|
|
98
|
+
ADD_CHECK('gen_jobs', 'gen_jobs_executor_check',
|
|
99
|
+
`executor IN ('gpu:audio','gpu:image','gpu:video','local')`),
|
|
100
|
+
// kind ↔ executor are bound one-to-one (no audio job on a video worker)
|
|
101
|
+
ADD_CHECK('gen_jobs', 'gen_jobs_kind_executor_check',
|
|
102
|
+
`(kind = 'audio_chunk' AND executor = 'gpu:audio')
|
|
103
|
+
OR (kind = 'iu_image' AND executor = 'gpu:image')
|
|
104
|
+
OR (kind = 'video_group' AND executor = 'gpu:video')
|
|
105
|
+
OR (kind IN ('audio_merge','video_merge') AND executor = 'local')`),
|
|
106
|
+
// GPU work always carries a lane (§4.2, gpu-dispatcher.js:213–222); local work none
|
|
107
|
+
ADD_CHECK('gen_jobs', 'gen_jobs_lane_check',
|
|
108
|
+
`(executor = 'local' AND lane IS NULL)
|
|
109
|
+
OR (executor <> 'local' AND COALESCE(lane->>'kind', '') IN ('private','policy','system'))`),
|
|
110
|
+
ADD_CHECK('gen_jobs', 'gen_jobs_attempt_check', `attempt >= 0 AND max_attempts >= 1`),
|
|
111
|
+
ADD_CHECK('gen_jobs', 'gen_jobs_running_check',
|
|
112
|
+
`status <> 'running' OR (deadline IS NOT NULL AND attempt >= 1)`),
|
|
113
|
+
|
|
114
|
+
// claim (§4.2 «выдача»)
|
|
115
|
+
`CREATE INDEX IF NOT EXISTS idx_gen_jobs_claim ON gen_jobs (executor, status, not_before) WHERE status = 'queued'`,
|
|
116
|
+
// one live job per unit (§4.2, §6.2)
|
|
117
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS uniq_gen_jobs_live_unit
|
|
118
|
+
ON gen_jobs (book_id, chapter_id, scene_id, kind, unit_key)
|
|
119
|
+
WHERE status IN ('queued','running')`,
|
|
120
|
+
// sweeper (§4.2 «сторож»)
|
|
121
|
+
`CREATE INDEX IF NOT EXISTS idx_gen_jobs_deadline ON gen_jobs (deadline) WHERE status = 'running'`,
|
|
122
|
+
// progress (§4.2)
|
|
123
|
+
`CREATE INDEX IF NOT EXISTS idx_gen_jobs_command_status ON gen_jobs (command_id, status)`,
|
|
124
|
+
// beacon / worker_offline sweep / fairness counts (additions, not in ADR list)
|
|
125
|
+
`CREATE INDEX IF NOT EXISTS idx_gen_jobs_worker_running ON gen_jobs (worker_id) WHERE status = 'running'`,
|
|
126
|
+
`CREATE INDEX IF NOT EXISTS idx_gen_jobs_ws_running ON gen_jobs (workspace_id, executor) WHERE status = 'running'`,
|
|
127
|
+
`CREATE INDEX IF NOT EXISTS idx_gen_jobs_book_scene ON gen_jobs (book_id, chapter_id, scene_id)`,
|
|
128
|
+
]);
|
|
129
|
+
|
|
130
|
+
module.exports = { GEN_CORE_SQL };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// ======================================================
|
|
2
|
+
// gen/sql/002-command-jobs — ADR ORCHESTRATION_V2 §4.1, §4.2, §4.2a (редакция 06.11)
|
|
3
|
+
// ======================================================
|
|
4
|
+
// Idempotent on top of 001 (safe on every start):
|
|
5
|
+
// gen_jobs.build_id TEXT NOT NULL (was input.build_id; backfilled)
|
|
6
|
+
// gen_jobs.layer TEXT NOT NULL audio|image|video, derived from kind
|
|
7
|
+
// gen_commands.summary JSONB {jobs_created, joined, skipped_ready}
|
|
8
|
+
// gen_command_jobs (command_id, job_id) PK — which commands wait for a job
|
|
9
|
+
// (backfilled from gen_jobs.command_id)
|
|
10
|
+
|
|
11
|
+
'use strict';
|
|
12
|
+
|
|
13
|
+
const ADD_CHECK = (table, name, expr) => `
|
|
14
|
+
DO $$
|
|
15
|
+
BEGIN
|
|
16
|
+
IF NOT EXISTS (
|
|
17
|
+
SELECT 1 FROM pg_constraint
|
|
18
|
+
WHERE conname = '${name}' AND conrelid = '${table}'::regclass
|
|
19
|
+
) THEN
|
|
20
|
+
ALTER TABLE ${table} ADD CONSTRAINT ${name} CHECK (${expr});
|
|
21
|
+
END IF;
|
|
22
|
+
END $$`;
|
|
23
|
+
|
|
24
|
+
const LAYER_OF_KIND_SQL = `CASE kind
|
|
25
|
+
WHEN 'audio_chunk' THEN 'audio' WHEN 'audio_merge' THEN 'audio'
|
|
26
|
+
WHEN 'iu_image' THEN 'image'
|
|
27
|
+
WHEN 'video_group' THEN 'video' WHEN 'video_merge' THEN 'video' END`;
|
|
28
|
+
|
|
29
|
+
const GEN_COMMAND_JOBS_SQL = Object.freeze([
|
|
30
|
+
// ── gen_jobs.build_id ────────────────────────────────────────────────
|
|
31
|
+
`ALTER TABLE gen_jobs ADD COLUMN IF NOT EXISTS build_id TEXT`,
|
|
32
|
+
`UPDATE gen_jobs SET build_id = COALESCE(NULLIF(input->>'build_id', ''), 'default') WHERE build_id IS NULL`,
|
|
33
|
+
`ALTER TABLE gen_jobs ALTER COLUMN build_id SET NOT NULL`,
|
|
34
|
+
|
|
35
|
+
// ── gen_jobs.layer ───────────────────────────────────────────────────
|
|
36
|
+
`ALTER TABLE gen_jobs ADD COLUMN IF NOT EXISTS layer TEXT`,
|
|
37
|
+
`UPDATE gen_jobs SET layer = ${LAYER_OF_KIND_SQL} WHERE layer IS NULL`,
|
|
38
|
+
`ALTER TABLE gen_jobs ALTER COLUMN layer SET NOT NULL`,
|
|
39
|
+
ADD_CHECK('gen_jobs', 'gen_jobs_layer_check', `layer IN ('audio','image','video')`),
|
|
40
|
+
ADD_CHECK('gen_jobs', 'gen_jobs_layer_kind_check', `layer = (${LAYER_OF_KIND_SQL})`),
|
|
41
|
+
`CREATE INDEX IF NOT EXISTS idx_gen_jobs_book_layer_live ON gen_jobs (book_id, layer) WHERE status IN ('queued','running')`,
|
|
42
|
+
|
|
43
|
+
// ── gen_commands.summary ─────────────────────────────────────────────
|
|
44
|
+
`ALTER TABLE gen_commands ADD COLUMN IF NOT EXISTS summary JSONB`,
|
|
45
|
+
|
|
46
|
+
// ── gen_command_jobs (§4.2a) ─────────────────────────────────────────
|
|
47
|
+
`CREATE TABLE IF NOT EXISTS gen_command_jobs (
|
|
48
|
+
command_id UUID NOT NULL REFERENCES gen_commands(command_id) ON DELETE CASCADE,
|
|
49
|
+
job_id UUID NOT NULL REFERENCES gen_jobs(job_id) ON DELETE CASCADE,
|
|
50
|
+
PRIMARY KEY (command_id, job_id)
|
|
51
|
+
)`,
|
|
52
|
+
`CREATE INDEX IF NOT EXISTS idx_gen_command_jobs_job ON gen_command_jobs (job_id)`,
|
|
53
|
+
`INSERT INTO gen_command_jobs (command_id, job_id)
|
|
54
|
+
SELECT command_id, job_id FROM gen_jobs
|
|
55
|
+
ON CONFLICT DO NOTHING`,
|
|
56
|
+
]);
|
|
57
|
+
|
|
58
|
+
module.exports = { GEN_COMMAND_JOBS_SQL };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// ======================================================
|
|
2
|
+
// gen/sql/003-scope-scenes — ADR ORCHESTRATION_V2 §11.1, §13 п.8 (stage 1c)
|
|
3
|
+
// ======================================================
|
|
4
|
+
// gen_commands.scope gains level 'scenes' {level:'scenes', scene_ids:[…]}
|
|
5
|
+
// («from the current scene to the end», expanded by the host in book order).
|
|
6
|
+
// The constraint keeps its NAME (gen_commands_scope_check) and gets a new
|
|
7
|
+
// definition: 001's ADD_CHECK adds it only when the name is missing, so the
|
|
8
|
+
// old definition never comes back on the next start. Idempotent.
|
|
9
|
+
// NULL-safe: a CHECK that evaluates to NULL passes, hence the COALESCEs.
|
|
10
|
+
|
|
11
|
+
'use strict';
|
|
12
|
+
|
|
13
|
+
const SCOPE_CHECK = `jsonb_typeof(scope) = 'object'
|
|
14
|
+
AND COALESCE(scope->>'level', '') IN ('book','chapter','scenes','scene','unit')
|
|
15
|
+
AND CASE WHEN scope->>'level' = 'scenes'
|
|
16
|
+
THEN COALESCE(jsonb_typeof(scope->'scene_ids'), '') = 'array' AND COALESCE(scope->'scene_ids' <> '[]'::jsonb, false)
|
|
17
|
+
ELSE true END`;
|
|
18
|
+
|
|
19
|
+
const GEN_SCOPE_SCENES_SQL = Object.freeze([
|
|
20
|
+
`DO $$
|
|
21
|
+
BEGIN
|
|
22
|
+
IF EXISTS (
|
|
23
|
+
SELECT 1 FROM pg_constraint
|
|
24
|
+
WHERE conname = 'gen_commands_scope_check' AND conrelid = 'gen_commands'::regclass
|
|
25
|
+
AND pg_get_constraintdef(oid) NOT LIKE '%scenes%'
|
|
26
|
+
) THEN
|
|
27
|
+
ALTER TABLE gen_commands DROP CONSTRAINT gen_commands_scope_check;
|
|
28
|
+
END IF;
|
|
29
|
+
IF NOT EXISTS (
|
|
30
|
+
SELECT 1 FROM pg_constraint
|
|
31
|
+
WHERE conname = 'gen_commands_scope_check' AND conrelid = 'gen_commands'::regclass
|
|
32
|
+
) THEN
|
|
33
|
+
ALTER TABLE gen_commands ADD CONSTRAINT gen_commands_scope_check CHECK (${SCOPE_CHECK});
|
|
34
|
+
END IF;
|
|
35
|
+
END $$`,
|
|
36
|
+
]);
|
|
37
|
+
|
|
38
|
+
module.exports = { GEN_SCOPE_SCENES_SQL, SCOPE_CHECK };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// ======================================================
|
|
2
|
+
// gen/sql — migration runner (idempotent, one transaction)
|
|
3
|
+
// ======================================================
|
|
4
|
+
'use strict';
|
|
5
|
+
|
|
6
|
+
const { GEN_CORE_SQL } = require('./001-gen-core');
|
|
7
|
+
const { GEN_COMMAND_JOBS_SQL } = require('./002-command-jobs');
|
|
8
|
+
const { GEN_SCOPE_SCENES_SQL } = require('./003-scope-scenes');
|
|
9
|
+
const { withTx } = require('../util');
|
|
10
|
+
|
|
11
|
+
const MIGRATIONS = Object.freeze([
|
|
12
|
+
Object.freeze({ id: '001-gen-core', statements: GEN_CORE_SQL }),
|
|
13
|
+
Object.freeze({ id: '002-command-jobs', statements: GEN_COMMAND_JOBS_SQL }),
|
|
14
|
+
Object.freeze({ id: '003-scope-scenes', statements: GEN_SCOPE_SCENES_SQL }),
|
|
15
|
+
]);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Apply all v2 migrations. Requires the host tables books, workers and
|
|
19
|
+
* scene_assets to exist (backend schema.js runs first). Serialised across
|
|
20
|
+
* processes by a transaction-scoped advisory lock; every statement is
|
|
21
|
+
* idempotent, so running it on each start is safe.
|
|
22
|
+
* @param {{connect: Function}} pool pg Pool (or compatible)
|
|
23
|
+
* @returns {Promise<{applied: string[]}>}
|
|
24
|
+
*/
|
|
25
|
+
async function migrate(pool) {
|
|
26
|
+
return withTx(pool, async (client) => {
|
|
27
|
+
await client.query(`SELECT pg_advisory_xact_lock(hashtext('animastor:gen-v2:migrate'))`);
|
|
28
|
+
for (const m of MIGRATIONS) {
|
|
29
|
+
for (const sql of m.statements) await client.query(sql);
|
|
30
|
+
}
|
|
31
|
+
return { applied: MIGRATIONS.map((m) => m.id) };
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = { migrate, MIGRATIONS };
|