Spaces:
Configuration error

File size: 9,648 Bytes
023064b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/**
 * Batch queue manager for the CLI video generator.
 *
 * Implements Feature B of the PRE-15 spec: a managed, resumable batch with
 * explicit concurrency, per-job status, retry, and a machine-readable summary.
 *
 * - Concurrency is bounded by the existing `MAX_CONCURRENT_JOBS` env (see
 *   `src/constants/config.ts`), not a new knob.
 * - Retries use `AVG_BATCH_MAX_RETRIES` (default 1) with a fixed backoff.
 * - `--resume` re-reads the manifest in `output/batch-manifest.json` and skips
 *   completed jobs.
 *
 * This module is intentionally I/O + scheduler-light: it does not talk to the
 * pipeline engine directly, it receives an `executeJob` callback so it can be
 * unit-tested against a fake without spinning up Remotion.
 */

import * as fs from 'fs';
import * as path from 'path';
import { z } from 'zod';
import { resolveProjectPath, resolveWorkspacePath } from '../../shared/runtime/paths';

/**
 * Read an integer env knob at *call time* (not at module load) so the batch
 * honors live overrides of `MAX_CONCURRENT_JOBS` / `AVG_BATCH_MAX_RETRIES` /
 * `AVG_BATCH_RETRY_BACKOFF_MS`. The imported/captured module-level constants
 * freeze at import, which is too early for tests and for env changes between
 * runs.
 */
function readEnvInt(name: string, fallback: number, min: number): number {
    const raw = process.env[name];
    if (raw === undefined) {
        return fallback;
    }
    const parsed = Number.parseInt(raw, 10);
    if (!Number.isFinite(parsed) || parsed < min) {
        return fallback;
    }
    return parsed;
}

function readMaxConcurrentJobs(): number {
    return Math.max(1, readEnvInt('MAX_CONCURRENT_JOBS', 1, 1));
}

function readAvgBatchMaxRetries(): number {
    return Math.max(0, readEnvInt('AVG_BATCH_MAX_RETRIES', 1, 0));
}

function readRetryBackoffMs(): number {
    return Math.max(0, readEnvInt('AVG_BATCH_RETRY_BACKOFF_MS', 1500, 0));
}

export const BATCH_MANIFEST_PATH = resolveWorkspacePath('cache', 'batch-manifest.json');

export type JobOutcome = 'completed' | 'failed' | 'cancelled' | 'pending';

const jobSchema = z.object({
    id: z.string(),
    index: z.number().int(),
    title: z.string(),
    outcome: z.enum(['completed', 'failed', 'cancelled', 'pending']),
    attempts: z.number().int().min(0),
    outputPath: z.string().optional(),
    error: z.string().optional(),
    startedAt: z.number().nullable(),
    finishedAt: z.number().nullable(),
});

export const batchManifestSchema = z.object({
    version: z.literal(1),
    concurrency: z.number().int().positive(),
    maxRetries: z.number().int().min(0),
    createdAt: z.number(),
    updatedAt: z.number(),
    jobs: z.array(jobSchema),
});

export type BatchJobEntry = z.infer<typeof jobSchema>;
export type BatchManifest = z.infer<typeof batchManifestSchema>;

export interface BatchJobInput {
    /** Stable identifier; reused as the resume key. */
    id: string;
    /** Original position in the input file (0-based). */
    index: number;
    title: string;
}

export interface RunBatchOptions {
    concurrency?: number;
    maxRetries?: number;
    failFast?: boolean;
    resume?: boolean;
    onlyIds?: string[];
    /** Execute one job. Must resolve with a result describing outcome. */
    executeJob: (job: BatchJobInput) => Promise<BatchJobResult>;
}

export interface BatchJobResult {
    outcome: JobOutcome;
    outputPath?: string;
    error?: string;
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

function isPermanentError(error: unknown): boolean {
    const message = error instanceof Error ? error.message : String(error);
    return /schema|validation|invalid/i.test(message);
}

function emptyManifest(concurrency: number, maxRetries: number): BatchManifest {
    const now = Date.now();
    return {
        version: 1,
        concurrency,
        maxRetries,
        createdAt: now,
        updatedAt: now,
        jobs: [],
    };
}

function readManifestSafe(manifestPath: string): BatchManifest | null {
    try {
        if (!fs.existsSync(manifestPath)) {
            return null;
        }
        const parsed = batchManifestSchema.safeParse(JSON.parse(fs.readFileSync(manifestPath, 'utf-8')));
        return parsed.success ? parsed.data : null;
    } catch {
        return null;
    }
}

function writeManifest(manifestPath: string, manifest: BatchManifest): void {
    const dir = path.dirname(manifestPath);
    fs.mkdirSync(dir, { recursive: true });
    manifest.updatedAt = Date.now();
    fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2), 'utf-8');
}

function summarize(manifest: BatchManifest): BatchManifestSummary {
    const counts = { completed: 0, failed: 0, cancelled: 0, pending: 0 };
    for (const job of manifest.jobs) {
        counts[job.outcome] += 1;
    }
    return {
        total: manifest.jobs.length,
        ...counts,
        allCompleted: counts.failed === 0 && counts.cancelled === 0 && counts.pending === 0,
    };
}

export interface BatchManifestSummary {
    total: number;
    completed: number;
    failed: number;
    cancelled: number;
    pending: number;
    allCompleted: boolean;
}

/**
 * Run a batch of jobs through a bounded-concurrency pool with retry + resume.
 *
 * @returns the written manifest (also persisted to `output/batch-manifest.json`)
 */
export async function runBatch(
    inputs: BatchJobInput[],
    options: RunBatchOptions,
    manifestPath: string = BATCH_MANIFEST_PATH,
): Promise<BatchManifest> {
    const concurrency = Math.max(1, options.concurrency ?? readMaxConcurrentJobs());
    const maxRetries = Math.max(0, options.maxRetries ?? readAvgBatchMaxRetries());

    const previous = options.resume ? readManifestSafe(manifestPath) : null;
    const completedIds = new Set((previous?.jobs ?? []).filter((j) => j.outcome === 'completed').map((j) => j.id));

    const onlyIds = options.onlyIds && options.onlyIds.length > 0 ? new Set(options.onlyIds) : null;

    const entries = new Map<string, BatchJobEntry>();
    if (previous) {
        for (const job of previous.jobs) {
            entries.set(job.id, { ...job });
        }
    }
    for (const input of inputs) {
        if (!entries.has(input.id)) {
            entries.set(input.id, {
                id: input.id,
                index: input.index,
                title: input.title,
                outcome: 'pending',
                attempts: 0,
                startedAt: null,
                finishedAt: null,
            });
        }
    }

    const queue = inputs.filter((input) => {
        if (completedIds.has(input.id)) {
            return false;
        }
        if (onlyIds && !onlyIds.has(input.id)) {
            return false;
        }
        return true;
    });

    const manifest: BatchManifest = previous ?? emptyManifest(concurrency, maxRetries);

    // Keep the on-disk manifest in sync with live progress. The `jobs` array is
    // rebuilt from the live `entries` map before every write so a crash mid-batch
    // leaves an accurate manifest for `--resume` (previously it held stale data
    // until the very end, causing completed jobs to be re-run).
    const syncManifest = () => {
        manifest.jobs = [...entries.values()].sort((a, b) => a.index - b.index);
        writeManifest(manifestPath, manifest);
    };

    const orderedQueue = [...queue].sort((a, b) => a.index - b.index);
    const active = new Set<Promise<void>>();
    let failedHard = false;

    const worker = async (input: BatchJobInput): Promise<void> => {
        if (failedHard) {
            return;
        }

        const entry = entries.get(input.id)!;
        let attempts = 0;
        let outcome: JobOutcome = 'failed';
        let outputPath: string | undefined;
        let lastError: string | undefined;

        entry.startedAt = Date.now();
        entry.attempts = 0;
        syncManifest();

        for (;;) {
            attempts += 1;
            entry.attempts = attempts;
            try {
                const result = await options.executeJob(input);
                outcome = result.outcome;
                outputPath = result.outputPath;
                lastError = result.error;
            } catch (error) {
                outcome = 'failed';
                lastError = error instanceof Error ? error.message : String(error);
            }

            if (outcome === 'completed' || outcome === 'cancelled') {
                break;
            }

            // `failed`: retry on transient, mark permanently failed on schema errors.
            const canRetry = attempts <= maxRetries && !isPermanentError(lastError);
            if (!canRetry) {
                break;
            }

            await sleep(readRetryBackoffMs());
        }

        entry.outcome = outcome;
        entry.outputPath = outputPath;
        entry.error = outcome === 'failed' ? lastError : undefined;
        entry.finishedAt = Date.now();
        entries.set(input.id, entry);
        syncManifest();

        if (outcome === 'failed' && options.failFast) {
            failedHard = true;
        }
    };

    for (const input of orderedQueue) {
        if (failedHard) {
            break;
        }
        const task = worker(input).then(() => {
            active.delete(task);
        });
        active.add(task);

        if (active.size >= concurrency) {
            await Promise.race(active);
        }
    }

    await Promise.allSettled([...active]);

    manifest.jobs = [...entries.values()].sort((a, b) => a.index - b.index);
    writeManifest(manifestPath, manifest);
    return manifest;
}

export { readManifestSafe, summarize };