// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file The coordinator of a parallel corpus build: it runs each source's work in worker processes and assembles * the corpus a serial build writes from the sources' completion records. * * Sources are independent from the adapter through the parquet write. A source's rows come from its own adapter * (the runner refuses any other `source`), its files are derived from its own extract and code, its shuffle draws * from a generator seeded by its own id, and its part boundaries count its own rows. A build of one source by itself * therefore writes the bytes it writes in a serial build. What the serial build shares across sources (the split * files, the corpus parquet manifest, the license tallies, the quarantine file, the frozen source record and the * top-level manifest) the coordinator assembles from the records in adapter order. * * Each source runs as `adapter`, then one `align` task per byte range of its canonical file, then `finish` * (`#build/worker`). A task runs in its own process with the heap, DuckDB limits and temporary root of its * worker class (`#build/budget`). The scheduler admits a task while fewer than `jobs` run and their reservations * fit in the host budget, runs one resident-record adapter at a time, and prefers the largest source's next task, * because the largest source's chain of tasks bounds the build's wall time. * * A failed task fails its source. The other sources run to completion and keep their records. * The build rejects with each failed task and its log, and writes no corpus manifest. `--resume` reuses every * complete source and continues each incomplete one from its adapter run, finished ranges and finished parts. * The signal handler stops every worker with SIGTERM and rejects the same way. */ import { readLocalJSONFile, readLocalTextFile } from "@mailwoman/core/fs/readers" import { tryStat } from "@mailwoman/core/fs/readers/stat" import { openReadStream, openWriteStream, pipeline } from "@mailwoman/core/fs/streams" import { temporaryDirectory } from "@mailwoman/core/fs/temporary" import { makeDirectories, removePathIfPresent, writeLocalJSONFile } from "@mailwoman/core/fs/writers" import { forkProcess, type ChildProcess } from "@mailwoman/core/scripting/process" import { childEnv } from "@mailwoman/core/scripting/utils" import { sleep } from "@mailwoman/core/utils/sleep" import type { PathBuilder, PathBuilderLike } from "path-ts" import { TextSpliterator } from "spliterator" import { adapterRunInputs, reusableRun } from "#build/adapters" import { alignSettings, trainSharesOf } from "#build/align" import { planAlignRanges, reusableAlignRange, type AlignRangePlan } from "#build/align/range" import { mergeAlignTotals } from "#build/align/totals" import { WORKER_CLASSES, workerReservationBytes, type WorkerBudget, type WorkerClass } from "#build/budget" import { readSourceDecisionTable } from "#build/eligibility" import { admitParquetManifest, UNCHECKED_PARQUET_MANIFEST_FILE } from "#build/holdout-check" import { writeBuildManifests } from "#build/manifest" import { tryReadDefaultRegionNames, type RegionNames } from "#build/region/names" import { importPriorSource } from "#build/reuse" import { adapterDerivations, derivationConfig, regionCheckFingerprints, type ResolvedBuildSettings, } from "#build/settings" import { readReusableSource, sourceStateDirectory, SOURCE_RECORD_FILE, type SourceBuildSettings, type SourceCompletionRecord, } from "#build/source-record" import type { BuildCorpusManifest, BuildCorpusOptions, BuildStage } from "#build/types" import { workerModulePath, type AlignTaskSettings, type WorkerMessage, type WorkerTask } from "#build/worker" import { corpusDirectoryName } from "#directory" import { resolveDerivation } from "#parquet/record" import { parquetManifestOf } from "#parquet/writers" import type { SourceRightsAdmission } from "#source-register/corpus-inputs" import type { AdapterOptions, CorpusAdapter } from "#types" import { defaultHoldouts, SPLIT_NAMES, writeSplitManifestsFromLabeledFiles, type SplitName } from "#utils/split" /** * Canonical bytes per align range when the caller states none. * * A source smaller than this aligns in one task. * The 2026-10-20 profile aligned 14.6 M rows in 189 s, so a 2 GiB range of `usgov-nad`'s * rows takes minutes and a large source spreads over every worker. */ export const ALIGN_RANGE_BYTES = 2 * 1024 ** 3 /** * What the coordinator needs from `buildCorpus`. */ export interface ParallelBuildContext { opts: BuildCorpusOptions /** * The configured adapters, in the order a serial build drives them. */ adapters: readonly CorpusAdapter[] skipped: string[] settings: ResolvedBuildSettings rights: SourceRightsAdmission outputDir: PathBuilder intermediateDir: PathBuilder builtAt: string budget: WorkerBudget } /** * One finished worker process, as `WORKERS.json` records it. */ interface WorkerRun { task: string source: string kind: WorkerTask["kind"] workerClass: WorkerClass pid: number | null heapLimitBytes: number | null maxRSSBytes: number | null startedAt: string elapsedMs: number exitCode: number | null signal: string | null log: string } interface PendingTask { task: WorkerTask workerClass: WorkerClass /** * Larger runs first. * * A source's estimated size, then the task's distance along the source's chain. */ priority: [number, number] resolve: () => void reject: (error: Error) => void } const KIND_RANK: Record = { adapter: 0, align: 1, finish: 2 } const STAGE_OF: Record = { adapter: "adapter-run", align: "align", finish: "parquet" } /** * The last lines of a worker's log, for the error that reports its failure. */ async function logTail(path: string, lines = 20): Promise { const text = await readLocalTextFile(path).catch(() => "") return TextSpliterator.from(text.trimEnd(), { delimiter: "\n" }).toArray().slice(-lines).join("\n") } /** * Runs worker tasks under the job count and memory budget. */ class WorkerPool { readonly runs: WorkerRun[] = [] #queue: PendingTask[] = [] #running = new Map() #cancelled: Error | null = null readonly #jobs: number readonly #budgetBytes: number readonly #logDir: PathBuilder readonly #taskDir: PathBuilder readonly #onProgress: (stage: BuildStage, message: string) => void constructor(opts: { jobs: number budgetBytes: number logDir: PathBuilder taskDir: PathBuilder onProgress: (stage: BuildStage, message: string) => void }) { this.#jobs = opts.jobs this.#budgetBytes = opts.budgetBytes this.#logDir = opts.logDir this.#taskDir = opts.taskDir this.#onProgress = opts.onProgress } run(task: WorkerTask, workerClass: WorkerClass, sourceWeight: number): Promise { if (this.#cancelled) return Promise.reject(this.#cancelled) return new Promise((resolve, reject) => { this.#queue.push({ task, workerClass, priority: [sourceWeight, KIND_RANK[task.kind]], resolve, reject }) this.#dispatch() }) } /** * Stop every running worker and refuse every queued task with `reason`. */ cancel(reason: Error): void { if (this.#cancelled) return this.#cancelled = reason for (const pending of this.#queue.splice(0)) { pending.reject(reason) } // A slot whose process hasn't been forked yet has no child, and its start sees the cancellation. for (const { child } of this.#running.values()) { child?.kill("SIGTERM") } } /** * Resolve once every running worker has exited. */ async drained(): Promise { while (this.#running.size) { await sleep(50) } } #reservedBytes(): number { let reserved = 0 for (const { workerClass } of this.#running.values()) { reserved += workerReservationBytes(workerClass) } return reserved } #admits(pending: PendingTask): boolean { if (this.#running.size >= this.#jobs) return false return this.#reservedBytes() + workerReservationBytes(pending.workerClass) <= this.#budgetBytes } #dispatch(): void { if (this.#cancelled) return // Highest priority first. // A task that doesn't fit waits rather than letting a smaller one pass it. const ordered = this.#queue.toSorted((a, b) => b.priority[0] - a.priority[0] || b.priority[1] - a.priority[1]) for (const pending of ordered) { if (this.#running.size >= this.#jobs || !this.#admits(pending)) return this.#queue.splice(this.#queue.indexOf(pending), 1) void this.#start(pending) } } async #start(pending: PendingTask): Promise { const { task, workerClass } = pending const name = task.id.replaceAll("/", "__") const taskPath = this.#taskDir(`${name}.json`) const logPath = this.#logDir(`${name}.log`).toString() const startedAt = new Date() const resources = WORKER_CLASSES[workerClass] const run: WorkerRun = { task: task.id, source: task.source, kind: task.kind, workerClass, pid: null, heapLimitBytes: null, maxRSSBytes: null, startedAt: startedAt.toISOString(), elapsedMs: 0, exitCode: null, signal: null, log: logPath, } // Reserved before the first await, so the next dispatch counts this worker. const slot: { child: ChildProcess | null; workerClass: WorkerClass } = { child: null, workerClass } this.#running.set(task.id, slot) try { await makeDirectories(task.temporaryRoot) await writeLocalJSONFile(task, taskPath) // A cancellation during the two writes above found no process to stop, so none is started. if (this.#cancelled) throw this.#cancelled const log = openWriteStream(logPath, { flags: "a" }) const child = forkProcess(workerModulePath(), [taskPath.toString()], { execArgv: [`--max-old-space-size=${Math.floor(resources.heapBytes / 1024 ** 2)}`], // The parent process's NODE_OPTIONS may set its own heap ceiling. // That ceiling would contend with this worker's explicit limit. env: childEnv({ MAILWOMAN_TEMP_ROOT: task.temporaryRoot, NODE_OPTIONS: null }), stdio: ["ignore", "pipe", "pipe", "ipc"], }) slot.child = child run.pid = child.pid ?? null child.stdout?.pipe(log, { end: false }) child.stderr?.pipe(log, { end: false }) child.on("message", (message: WorkerMessage) => { if (message.type === "started") { run.heapLimitBytes = message.heapLimitBytes } else if (message.type === "finished") { run.maxRSSBytes = message.maxRSSBytes } else { this.#onProgress(STAGE_OF[task.kind], `[${task.id}] ${message.message}`) } }) const [exitCode, signal] = await new Promise<[number | null, NodeJS.Signals | null]>((resolve, reject) => { child.on("error", reject) child.on("close", (code, sig) => resolve([code, sig])) }) log.end() run.exitCode = exitCode run.signal = signal run.elapsedMs = Date.now() - startedAt.getTime() this.runs.push(run) this.#running.delete(task.id) if (exitCode === 0) { this.#onProgress(STAGE_OF[task.kind], `[${task.id}] finished in ${(run.elapsedMs / 1000).toFixed(1)} s`) pending.resolve() } else { pending.reject( new Error( `corpus build worker ${task.id} (pid ${run.pid}) exited with ` + `${signal ? `signal ${signal}` : `code ${exitCode}`}. Its log is ${logPath}:\n${await logTail(logPath)}` ) ) } } catch (error) { this.#running.delete(task.id) pending.reject(error as Error) } finally { this.#dispatch() } } } /** * The number of align ranges for a canonical file of `bytes`: one per `rangeBytes`, * at most twice the job count. * * More ranges than workers lets a large source's ranges interleave with other sources' tasks, * and the cap keeps the per-process start cost below the work each range does. * The count changes which processes align which rows and never the bytes they write. */ export function alignRangeCount(bytes: number, rangeBytes: number, jobs: number): number { return Math.min(2 * jobs, Math.max(1, Math.ceil(bytes / rangeBytes))) } /** * Input rows per adapter partition. * * NAD's adapter reads about 14,700 rows a second on one core, so a partition * of this size runs in about 11 minutes. */ export const PARTITION_ROWS = 10_000_000 /** * The row ranges a source's adapter run is split into, or `null` to run it in one worker. * * A source splits when its adapter declares `inputRowCount`, no `limit` caps the run, * and its input holds more than one partition's rows. * A capped run stops at a count of the rows before it, and a partition can't know that count. */ export async function partitionRanges( adapter: CorpusAdapter, options: AdapterOptions, partitionRows: number ): Promise<{ start: number; end: number }[] | null> { if (!adapter.inputRowCount || typeof options.limit === "number") return null const rows = await adapter.inputRowCount(options) if (rows <= partitionRows) return null return Array.from({ length: Math.ceil(rows / partitionRows) }, (_, index) => ({ start: index * partitionRows, end: Math.min(rows, (index + 1) * partitionRows), })) } /** * Concatenate files in order into `destination`. * * One pipeline reads every source in order and writes the one write stream. * A pipeline per source with `end: false` leaves its four completion listeners on the * destination, so a build with more than ten sources tripped Node's max-listeners warning. */ export async function concatenateFiles(sources: readonly string[], destination: PathBuilderLike): Promise { async function* chunks(): AsyncGenerator { for (const source of sources) { yield* openReadStream(source) } } await pipeline(chunks, openWriteStream(destination, { flags: "w" })) } /** * Remove one source's parallel-build state and its adapter run, so a resumed build builds it again. */ async function forgetSource(intermediateDir: PathBuilder, source: string): Promise { await removePathIfPresent(sourceStateDirectory(intermediateDir, source)) await removePathIfPresent(intermediateDir(source, "MANIFEST.json")) } /** * Build every configured source in worker processes and assemble the corpus. */ export async function runParallelBuild(ctx: ParallelBuildContext): Promise { const { opts, settings, intermediateDir, outputDir } = ctx const onProgress = (stage: BuildStage, message: string): void => opts.onProgress?.(stage, message) const holdouts = defaultHoldouts() const decisionTable = await readSourceDecisionTable() for (const source of opts.freshSources ?? []) { await forgetSource(intermediateDir, source) } const derivationFor = await adapterDerivations(ctx.adapters, opts.adapterInputs, derivationConfig(settings, holdouts)) const taskSettings: AlignTaskSettings = { corpusVersion: opts.corpusVersion, synthesize: settings.synthesize, profile: settings.profile, licensePolicy: settings.licensePolicy, excludeLicenses: settings.excludeLicenses.map((pattern) => ({ source: pattern.source, flags: pattern.flags })), holdouts, trainShares: trainSharesOf(opts.adapterInputs), } const buildSettings: SourceBuildSettings = { align: alignSettings({ ...taskSettings, excludeLicenses: settings.excludeLicenses }), rowsPerFile: settings.rowsPerFile, shuffleSeed: settings.shuffleSeed, shuffleWindow: settings.shuffleWindow, } await using workRoot = await temporaryDirectory("mailwoman-corpus-workers-") const workersDir = intermediateDir("workers") // A resumed build appends to the earlier attempts' logs, so a failure's history stays readable. if (!settings.resume) { await removePathIfPresent(workersDir) } await makeDirectories(workersDir("tasks"), workersDir("logs")) const pool = new WorkerPool({ jobs: ctx.budget.jobs, budgetBytes: ctx.budget.budgetBytes, logDir: workersDir("logs"), taskDir: workersDir("tasks"), onProgress, }) const onAbort = (): void => pool.cancel(new Error(`corpus build cancelled: ${String(opts.signal?.reason ?? "aborted")}`)) opts.signal?.addEventListener("abort", onAbort, { once: true }) if (opts.signal?.aborted) { onAbort() } onProgress( "adapter-run", `parallel build: ${ctx.budget.jobs} workers in a ${(ctx.budget.budgetBytes / 1024 ** 3).toFixed(1)} GiB budget, ` + `${ctx.adapters.length} sources` ) // A reused source made under other region data recounts `region:unknown` under these. const regionCheck = await regionCheckFingerprints() let regionNames: Promise | null = null const readRegions = (): Promise => (regionNames ??= tryReadDefaultRegionNames()) const buildSource = async (adapter: CorpusAdapter): Promise => { const source = adapter.id const sourceDir = sourceStateDirectory(intermediateDir, source) const options = opts.adapterInputs[source]! const temporaryRoot = (task: string): string => workRoot.path(source, task).toString() // The build resolves this lazily because hashing a large extract for its fingerprint can take time. let derivation: ReturnType | null = null const sourceDerivation = (): ReturnType => (derivation ??= derivationFor(source)) if (settings.resume) { const reusable = await readReusableSource(sourceDir, { settings: buildSettings, derivation: await resolveDerivation(await sourceDerivation()), regionCheck, readRegions, }) if (reusable.record) { onProgress("adapter-run", `[${source}] reused the complete source (${reusable.record.parts.length} parts)`) return reusable.record } onProgress("adapter-run", `[${source}] not complete: ${reusable.problem}`) } for (const priorOutputDir of opts.reuseFrom ?? []) { const imported = await importPriorSource({ source, priorOutputDir, outputDir, expected: { settings: buildSettings, derivation: await resolveDerivation(await sourceDerivation()), regionCheck, readRegions, }, }) if (imported.record) { onProgress( "adapter-run", `[${source}] cloned the complete source from ${priorOutputDir.toString()} (${imported.record.parts.length} parts)` ) return imported.record } onProgress("adapter-run", `[${source}] not reusable from ${priorOutputDir.toString()}: ${imported.problem}`) } const inputStat = await tryStat(options.inputPath) // A directory input's size doesn't predict its rows, so it is ranked first and starts early. const inputWeight = inputStat?.isFile() ? inputStat.size : Number.MAX_SAFE_INTEGER const adapterDir = intermediateDir(source) const inputs = adapterRunInputs(await sourceDerivation()) let run = settings.resume ? await reusableRun(source, adapterDir, { corpusVersion: opts.corpusVersion, inputs }) : null if (run) { onProgress("adapter-run", `[${source}] reused the adapter run (${run.yielded} canonical rows)`) } else { const { signal: _signal, dropped: _dropped, ...serializable } = options const adapterTask = { kind: "adapter" as const, source, adapterModule: derivationFor.modules.get(source)!, adapterOptions: { ...serializable, inputPath: options.inputPath.toString() }, corpusVersion: opts.corpusVersion, inputs, intermediateDir: intermediateDir.toString(), } const ranges = await partitionRanges(adapter, options, opts.partitionRows ?? PARTITION_ROWS) if (ranges) { const partitionDir = adapterDir("partitions") await removePathIfPresent(partitionDir) await makeDirectories(partitionDir) const records = await Promise.all( ranges.map(async (rowRange, index) => { const recordPath = partitionDir(`part-${index}.json`).toString() await pool.run( { ...adapterTask, id: `${source}/adapter-${index + 1}-of-${ranges.length}`, resources: WORKER_CLASSES.partition, temporaryRoot: temporaryRoot(`adapter-${index}`), partition: { rowRange, outputPath: partitionDir(`part-${index}.tsv`).toString(), recordPath }, }, "partition", inputWeight ) return recordPath }) ) await pool.run( { ...adapterTask, id: `${source}/adapter-merge`, resources: WORKER_CLASSES.adapter, temporaryRoot: temporaryRoot("adapter"), mergeRecords: records, }, "adapter", inputWeight ) } else { await pool.run( { ...adapterTask, id: `${source}/adapter`, resources: WORKER_CLASSES.adapter, temporaryRoot: temporaryRoot("adapter"), }, "adapter", inputWeight ) } run = await readLocalJSONFile(adapterDir("MANIFEST.json")) } const canonicalPath = run!.jsonl_path const weight = run!.bytes const plans: AlignRangePlan[] = await planAlignRanges( canonicalPath, alignRangeCount(weight, opts.alignRangeBytes ?? ALIGN_RANGE_BYTES, ctx.budget.jobs) ) await Promise.all( plans.map(async (plan) => { if (settings.resume && (await reusableAlignRange(sourceDir, plan, buildSettings.align))) return await pool.run( { kind: "align", id: `${source}/align-${plan.index + 1}-of-${plan.count}`, source, resources: WORKER_CLASSES.align, temporaryRoot: temporaryRoot(`align-${plan.index}`), canonicalPath, plan, sourceDir: sourceDir.toString(), settings: taskSettings, }, "align", weight ) }) ) await pool.run( { kind: "finish", id: `${source}/finish`, source, resources: WORKER_CLASSES.finish, temporaryRoot: temporaryRoot("finish"), sourceDir: sourceDir.toString(), outputDir: outputDir.toString(), adapterManifestPath: adapterDir("MANIFEST.json").toString(), plans, settings: taskSettings, buildSettings, derivation: await sourceDerivation(), resume: settings.resume, }, "finish", weight ) return readLocalJSONFile(sourceDir(SOURCE_RECORD_FILE)) } const settled = await Promise.allSettled(ctx.adapters.map((adapter) => buildSource(adapter))) opts.signal?.removeEventListener("abort", onAbort) await pool.drained() await writeLocalJSONFile(pool.runs, workersDir("WORKERS.json")) const failures = settled.flatMap((outcome, index) => outcome.status === "rejected" ? [`${ctx.adapters[index]!.id}: ${(outcome.reason as Error).message}`] : [] ) if (failures.length) { throw new Error( `corpus build: ${failures.length} of ${ctx.adapters.length} sources did not finish, so no corpus manifest ` + `was written. Every finished source kept its ${SOURCE_RECORD_FILE}; rerun with --resume to reuse them.\n` + failures.join("\n") ) } const records = settled.map((outcome) => (outcome as PromiseFulfilledResult).value) const totals = mergeAlignTotals(records.map((record) => record.totals)) // A row's `source` is its adapter's id, so this admits only sources the first check admitted. // It stays because the serial build checks the source ids in its rows, // and both builds record the same admission. ctx.rights.admitAll(totals.rowsBySource.keys()) onProgress("split", `merging ${records.length} sources' sorted id lists (${totals.aligned} aligned rows)`) const splitCounts = await writeSplitManifestsFromLabeledFiles({ labeledPaths: Object.fromEntries( SPLIT_NAMES.map((split) => [split, intermediateDir(`labeled-${split}.jsonl`)]) ) as Record, sortedSourceIDPaths: Object.fromEntries( SPLIT_NAMES.map((split) => [split, records.map((record) => record.sourceIDs[split].path)]) ) as Record, outputDir: outputDir("splits"), corpusVersion: opts.corpusVersion, counts: totals.counts, holdouts, }) await concatenateFiles( records.flatMap((record) => record.quarantine.map((file) => file.path)), intermediateDir("quarantine.jsonl") ) onProgress("parquet", "writing the corpus parquet manifest") const parquetManifest = parquetManifestOf( records.flatMap((record) => record.parts), { corpusVersion: opts.corpusVersion, rowsPerFile: settings.rowsPerFile } ) // The manifest lands under the unchecked name, and the held-out span check moves it to // `MANIFEST.json` once it passes, so a corpus the check refuses has no manifest a training run reads. const corpusDir = outputDir(corpusDirectoryName(opts.corpusVersion)) await writeLocalJSONFile(parquetManifest, corpusDir(UNCHECKED_PARQUET_MANIFEST_FILE)) const holdoutCheck = await admitParquetManifest({ corpusDir, holdouts, onProgress }) return await writeBuildManifests({ outputDir, corpusVersion: opts.corpusVersion, builtAt: ctx.builtAt, profile: settings.profile, licensePolicy: settings.licensePolicy, adapterRuns: records.map((record) => record.adapter), skipped: ctx.skipped, splitCounts, holdouts, parquetManifest, holdoutCheck, totals, rights: ctx.rights, decisionTable, onProgress: opts.onProgress, }) }