taskforce-model-foundry 0.2.0 → 0.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.
@@ -0,0 +1,52 @@
1
+ // Bind an independently scored, predeclared quality suite to a trained job.
2
+ // The scorer is outside Foundry; Foundry verifies its evidence and gates.
3
+ import path from 'node:path';
4
+ import { readJson } from '../core/fsx.mjs';
5
+ import { sha256File, sha256Json } from '../core/hash.mjs';
6
+ import { evaluateGates, readMetric } from './gates.mjs';
7
+ import { ExportBlockedError } from '../export/package.mjs';
8
+
9
+ export const EXTERNAL_QUALITY_FORMAT = 'tmf.external-quality/v1';
10
+ export const externalQualityContractDigest = (contract) => sha256Json(contract);
11
+
12
+ // Convenience for an external scorer. This is an integrity checksum, not a
13
+ // signature or proof that the scorer's measurements are truthful.
14
+ export function sealExternalQualityEvidence(report) {
15
+ return { ...report, reportDigest: sha256Json({ ...report, reportDigest: undefined }) };
16
+ }
17
+
18
+ function blocked(message, failed = []) {
19
+ throw new ExportBlockedError(`export blocked: ${message}`, { status: 'external_quality', failed });
20
+ }
21
+
22
+ export async function verifyExternalQuality({ contract, evidence, artifacts, evalReport, baseDir }) {
23
+ if (!evidence) blocked('predeclared external quality evidence is missing');
24
+ if (typeof evidence !== 'string') blocked('external quality evidence must be a report file path');
25
+ const file = path.resolve(baseDir, evidence);
26
+ let report;
27
+ try { report = await readJson(file); } catch (err) { blocked(`external quality report is unreadable: ${err.message}`); }
28
+ if (!report || report.format !== EXTERNAL_QUALITY_FORMAT) blocked('external quality report format mismatch');
29
+ if (contract.profile && report.profile !== contract.profile) blocked('external quality profile differs from the frozen contract');
30
+ const digest = sha256Json({ ...report, reportDigest: undefined });
31
+ if (report.reportDigest !== digest) blocked('external quality report digest mismatch');
32
+ if (report.jobId !== artifacts.jobId) blocked('external quality report belongs to another job');
33
+ if (report.suiteSha256 !== contract.suiteSha256 || report.scorerSha256 !== contract.scorerSha256) {
34
+ blocked('external quality suite/scorer differs from the predeclared contract');
35
+ }
36
+ if (report.contractDigest !== sha256Json(contract)) blocked('external quality contract digest mismatch');
37
+ if (report.evalReportDigest !== evalReport.reportDigest) blocked('external quality report is bound to a different technical evaluation');
38
+ if (!evalReport.lineage?.tunedFingerprint || report.tunedFingerprint !== evalReport.lineage.tunedFingerprint) {
39
+ blocked('external quality report is bound to a different tuned model fingerprint');
40
+ }
41
+ const checkpoint = artifacts.adapterCheckpoint ?? artifacts.tunedCheckpoint;
42
+ if (!checkpoint || report.checkpointSha256 !== await sha256File(checkpoint)) blocked('external quality report is bound to a different trained checkpoint');
43
+ for (const gate of contract.gates) {
44
+ if (!Number.isFinite(readMetric(report.metrics, gate.metric))) blocked(`external quality metric ${gate.metric} is not a finite number`);
45
+ if (gate.minSamples && !Number.isInteger(readMetric(report.metrics, gate.sampleMetric))) {
46
+ blocked(`external quality sample count ${gate.sampleMetric} is not an integer`);
47
+ }
48
+ }
49
+ const gates = evaluateGates(report.metrics ?? {}, contract.gates);
50
+ if (!gates.passed) blocked(`external quality gates failed (${gates.summary})`, gates.failed.map((gate) => gate.id));
51
+ return { file, fileSha256: await sha256File(file), report, gates, contractDigest: sha256Json(contract) };
52
+ }
@@ -10,6 +10,7 @@ import path from 'node:path';
10
10
  import { copyFile, readFile, readdir } from 'node:fs/promises';
11
11
  import { ensureDir, writeJson, writeFileAtomic, exists } from '../core/fsx.mjs';
12
12
  import { sha256File, sha256Json, stableStringify } from '../core/hash.mjs';
13
+ import { VERSION } from '../version.mjs';
13
14
 
14
15
  export const EXPORT_FORMAT = 'tmf.export/v1';
15
16
 
@@ -59,6 +60,12 @@ function metricSummary(report) {
59
60
  };
60
61
  }
61
62
 
63
+ function isSyntheticData(config) {
64
+ const datasets = config?.data?.datasets;
65
+ return Array.isArray(datasets) && datasets.length > 0 && datasets.every((dataset) =>
66
+ dataset === 'synthetic' || dataset?.source === 'synthetic' || dataset?.license === 'synthetic');
67
+ }
68
+
62
69
  function renderModelCard({ name, version, createdAt, report, artifacts, config, files }) {
63
70
  const s = metricSummary(report);
64
71
  const num = (v) => (typeof v === 'number' ? v.toFixed(6) : 'n/a');
@@ -72,9 +79,9 @@ Exported ${createdAt} by taskforce-model-foundry.
72
79
 
73
80
  ## What this is
74
81
 
75
- A small post-trained model produced from **synthetic data generated by this
76
- toolkit**. It is a demonstration-scale artifact: it is not trained on real
77
- enterprise data, and it carries no claim of fitness for production use.
82
+ ${isSyntheticData(config)
83
+ ? 'A small post-trained model produced from **synthetic data generated by this toolkit**. It is a demonstration-scale artifact, not a claim of fitness for production use.'
84
+ : 'A post-trained model. Inspect the dataset provenance and independent evaluation reports before making any fitness-for-use claim.'}
78
85
 
79
86
  - Mode: \`${config?.mode ?? artifacts?.metrics?.mode ?? 'unknown'}\`
80
87
  - Backend: \`${report.backend?.id ?? 'unknown'}\`
@@ -244,9 +251,10 @@ export async function exportModel({
244
251
  outDir,
245
252
  artifacts,
246
253
  evalReport,
254
+ externalQuality = null,
247
255
  config = null,
248
256
  name = config?.project ?? 'taskforce-model',
249
- version = '0.2.0',
257
+ version = VERSION,
250
258
  toolkitVersion = null,
251
259
  clock = () => new Date().toISOString(),
252
260
  }) {
@@ -264,6 +272,7 @@ export async function exportModel({
264
272
  artifacts.tunedCheckpoint ? { from: artifacts.tunedCheckpoint, to: 'weights/tuned.json', role: 'tuned' } : null,
265
273
  artifacts.dataReportFile ? { from: artifacts.dataReportFile, to: 'data-report.json', role: 'data-report' } : null,
266
274
  evalReport.reportFile ? { from: evalReport.reportFile, to: 'eval-report.json', role: 'eval-report' } : null,
275
+ externalQuality ? { from: externalQuality.file, to: 'external-quality-report.json', role: 'external-quality-report' } : null,
267
276
  ].filter(Boolean);
268
277
 
269
278
  const files = [];
@@ -271,7 +280,11 @@ export async function exportModel({
271
280
  if (!(await exists(copy.from))) throw new Error(`exportModel: missing input ${copy.role}: ${copy.from}`);
272
281
  const dest = path.join(root, copy.to);
273
282
  await copyFile(copy.from, dest);
274
- files.push({ path: copy.to, role: copy.role, sha256: await sha256File(dest), source: copy.from });
283
+ const copiedSha256 = await sha256File(dest);
284
+ if (copy.role === 'external-quality-report' && copiedSha256 !== externalQuality.fileSha256) {
285
+ throw new Error('external quality evidence changed between verification and export copy');
286
+ }
287
+ files.push({ path: copy.to, role: copy.role, sha256: copiedSha256, source: copy.from });
275
288
  }
276
289
  // A `hf-peft` checkpoint file is a *pointer*: it names a local model dir and
277
290
  // an adapter dir rather than carrying weights. Copying only the pointer would
@@ -296,7 +309,7 @@ export async function exportModel({
296
309
  reportFile: artifacts.dataReportFile ?? null,
297
310
  splits: evalReport.inputs?.splits ?? null,
298
311
  datasets: config?.data?.datasets ?? null,
299
- synthetic: true,
312
+ synthetic: isSyntheticData(config),
300
313
  },
301
314
  parameters: {
302
315
  mode: config?.mode ?? null,
@@ -316,6 +329,11 @@ export async function exportModel({
316
329
  gates: evalReport.gates?.results ?? [],
317
330
  lineage: evalReport.lineage ?? null,
318
331
  },
332
+ externalQuality: externalQuality ? {
333
+ reportDigest: externalQuality.report.reportDigest,
334
+ contractDigest: externalQuality.contractDigest,
335
+ gates: externalQuality.gates.results,
336
+ } : null,
319
337
  baseCheckpoint: files.find((f) => f.role === 'base')?.sha256 ?? null,
320
338
  };
321
339
 
package/src/index.mjs CHANGED
@@ -6,6 +6,7 @@
6
6
 
7
7
  export { PRODUCT, doctor, synthesize, train, status, evaluate } from './api.mjs';
8
8
  export { exportModel as exportBundle } from './api.mjs';
9
+ export { qualityContext } from './api.mjs';
9
10
  export {
10
11
  CONFIG_FORMAT, CONFIG_DEFAULTS, validateConfig, loadConfig, findConfigFile,
11
12
  exampleConfig, formatConfigErrors, ConfigError,
@@ -17,6 +18,7 @@ export * as jobs from './jobs/runner.mjs';
17
18
  export * as trainJob from './jobs/train.mjs';
18
19
  export * as evalJob from './jobs/evaluate.mjs';
19
20
  export * as gates from './eval/gates.mjs';
21
+ export * as externalQuality from './eval/external-quality.mjs';
20
22
  export * as backends from './train/backends/index.mjs';
21
23
  export * as exporter from './export/package.mjs';
22
24
  export { exportModel, assertDeliverable, ExportBlockedError, EXPORT_FORMAT } from './export/package.mjs';
@@ -15,6 +15,7 @@ if (await sha256File(request.configFile) !== request.configDigest) {
15
15
  }
16
16
  process.env.TMF_DEVICE = request.device;
17
17
  process.env.TMF_PYTHON = request.pythonBin;
18
+ if (request.hfMaxMemoryMb !== null) process.env.TMF_HF_MAX_MEMORY_MB = request.hfMaxMemoryMb;
18
19
  // The HF backend uses cwd for its transient spec/output directories. Keep
19
20
  // separate background requests from racing on those files.
20
21
  process.chdir(path.dirname(statusFile));
@@ -13,9 +13,9 @@ import { sha256File, sha256Json } from '../core/hash.mjs';
13
13
  const workerFile = fileURLToPath(new URL('./async-evaluate-worker.mjs', import.meta.url));
14
14
  const execFileAsync = promisify(execFile);
15
15
 
16
- function requireJobId(jobId) {
16
+ export function requireJobId(jobId) {
17
17
  if (typeof jobId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(jobId) || jobId === '..') {
18
- throw new Error('background evaluation requires a safe, explicit jobId');
18
+ throw new Error('background work requires a safe, explicit jobId');
19
19
  }
20
20
  return jobId;
21
21
  }
@@ -32,18 +32,19 @@ function reportMatches(report, status) {
32
32
  return report.reportDigest === sha256Json({ ...report, reportDigest: undefined });
33
33
  }
34
34
 
35
- async function launchWorker(requestFile, statusFile, unit, logFile) {
36
- if (process.env.TMF_EVAL_LAUNCHER !== 'direct' && process.platform === 'linux') {
35
+ export async function launchBackgroundWorker(workerPath, requestFile, statusFile, unit, logFile) {
36
+ const launcher = process.env.TMF_BACKGROUND_LAUNCHER ?? process.env.TMF_EVAL_LAUNCHER;
37
+ if (launcher !== 'direct' && process.platform === 'linux') {
37
38
  try {
38
- await execFileAsync('systemd-run', ['--user', '--collect', '--unit=' + unit, process.execPath, workerFile, requestFile, statusFile], { timeout: 10000 });
39
+ await execFileAsync('systemd-run', ['--user', '--collect', '--unit=' + unit, process.execPath, workerPath, requestFile, statusFile], { timeout: 10000 });
39
40
  return { launcher: 'systemd', unit, restartDurable: true };
40
41
  } catch (err) {
41
- if (process.env.TMF_EVAL_LAUNCHER === 'systemd') throw err;
42
+ if (launcher === 'systemd') throw err;
42
43
  }
43
44
  }
44
45
  const log = await open(logFile, 'a');
45
46
  try {
46
- const child = spawn(process.execPath, [workerFile, requestFile, statusFile], {
47
+ const child = spawn(process.execPath, [workerPath, requestFile, statusFile], {
47
48
  detached: true, stdio: ['ignore', log.fd, log.fd], env: process.env,
48
49
  });
49
50
  if (!child.pid) throw new Error('background evaluation worker did not start');
@@ -60,7 +61,11 @@ export async function startBackgroundEvaluation({ baseDir, configFile, jobId, ga
60
61
  const output = path.resolve(config.baseDir, reportFile ?? path.join(config.runRootAbsolute, jobId, 'eval-report.json'));
61
62
  const device = process.env.TMF_DEVICE ?? 'cpu';
62
63
  if (!['cpu', 'cuda'].includes(device)) throw new Error('unsupported TMF_DEVICE=' + device);
63
- const request = { configFile: file, configDigest: await sha256File(file), jobId, gates, reportFile: output, maxNewTokens, device, pythonBin: process.env.TMF_PYTHON ?? 'python3' };
64
+ const request = {
65
+ configFile: file, configDigest: await sha256File(file), jobId, gates, reportFile: output,
66
+ maxNewTokens, device, pythonBin: process.env.TMF_PYTHON ?? 'python3',
67
+ hfMaxMemoryMb: process.env.TMF_HF_MAX_MEMORY_MB ?? null,
68
+ };
64
69
  const requestId = sha256Json(request).slice(0, 24);
65
70
  const loc = await location({ baseDir, configFile: file, jobId, requestId });
66
71
  await ensureDir(loc.root);
@@ -85,7 +90,7 @@ export async function startBackgroundEvaluation({ baseDir, configFile, jobId, ga
85
90
  const status = { requestId, jobId, state: 'queued', attempt, reportFile: output, createdAt: new Date().toISOString(), device };
86
91
  await writeJson(loc.statusFile, status);
87
92
  try {
88
- const launch = await launchWorker(requestFile, loc.statusFile, 'tmf-eval-' + requestId + '-' + attempt, path.join(attemptDir, 'worker.log'));
93
+ const launch = await launchBackgroundWorker(workerFile, requestFile, loc.statusFile, 'tmf-eval-' + requestId + '-' + attempt, path.join(attemptDir, 'worker.log'));
89
94
  const now = await readJsonIfExists(loc.statusFile);
90
95
  if (now?.state === 'queued' && now.attempt === attempt) await writeJson(loc.statusFile, { ...now, ...launch });
91
96
  } catch (err) {
@@ -0,0 +1,51 @@
1
+ import path from 'node:path';
2
+ import { readJson, writeJson, exists } from '../core/fsx.mjs';
3
+ import { sha256File } from '../core/hash.mjs';
4
+ import { train, status as trainingStatus } from '../api.mjs';
5
+
6
+ const [, , requestFile, statusFile] = process.argv;
7
+ if (!requestFile || !statusFile) throw new Error('training worker requires request and status files');
8
+ const request = await readJson(requestFile);
9
+ const cancelFile = path.join(path.dirname(requestFile), 'cancel.json');
10
+ const old = await readJson(statusFile);
11
+ if (old.requestId !== request.requestId || old.attempt !== request.attempt) {
12
+ throw new Error('background training attempt no longer owns the status file');
13
+ }
14
+ if (await sha256File(request.configFile) !== request.configDigest) {
15
+ throw new Error('background training config changed since submission');
16
+ }
17
+ if (old.state === 'cancel_requested' || await exists(cancelFile)) {
18
+ await writeJson(statusFile, { ...old, state: 'cancelled', finishedAt: new Date().toISOString() });
19
+ process.exit(130);
20
+ }
21
+ process.env.TMF_DEVICE = request.device;
22
+ process.env.TMF_PYTHON = request.pythonBin;
23
+ if (request.hfMaxMemoryMb !== null) process.env.TMF_HF_MAX_MEMORY_MB = request.hfMaxMemoryMb;
24
+ process.chdir(path.dirname(statusFile));
25
+ const controller = new AbortController();
26
+ for (const signal of ['SIGTERM', 'SIGINT']) {
27
+ process.on(signal, () => controller.abort(new Error(`operator cancelled with ${signal}`)));
28
+ }
29
+ const common = { ...old };
30
+ await writeJson(statusFile, { ...common, state: 'running', pid: process.pid, startedAt: new Date().toISOString() });
31
+ if (await exists(cancelFile)) controller.abort(new Error('operator cancelled before training started'));
32
+ try {
33
+ const result = await train({
34
+ baseDir: path.dirname(request.configFile), configFile: request.configFile, jobId: request.jobId,
35
+ resume: request.resume, resumeCancelled: request.resumeCancelled, auditEveryStep: request.auditEveryStep, signal: controller.signal,
36
+ });
37
+ await writeJson(statusFile, {
38
+ ...common, state: result.job.state, pid: process.pid, finishedAt: new Date().toISOString(),
39
+ jobState: result.job.state, checkpoint: result.artifacts?.adapterCheckpoint ?? result.artifacts?.tunedCheckpoint ?? null,
40
+ });
41
+ if (result.job.state !== 'succeeded') process.exitCode = 1;
42
+ } catch (err) {
43
+ const durable = await trainingStatus({ baseDir: path.dirname(request.configFile), configFile: request.configFile, jobId: request.jobId });
44
+ const cancelled = controller.signal.aborted || durable.state?.state === 'cancelled';
45
+ await writeJson(statusFile, {
46
+ ...common, state: cancelled ? 'cancelled' : 'failed', pid: process.pid,
47
+ finishedAt: new Date().toISOString(), jobState: durable.state?.state ?? null,
48
+ error: { code: err?.code ?? 'action-failed', message: err?.message ?? String(err) },
49
+ });
50
+ process.exitCode = cancelled ? 130 : 1;
51
+ }
@@ -0,0 +1,135 @@
1
+ // Durable CLI/host training request, outside the caller's process lifetime.
2
+ import { mkdir } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { loadConfig } from '../config.mjs';
6
+ import { ensureDir, exists, readJsonIfExists, writeJson } from '../core/fsx.mjs';
7
+ import { sha256File, sha256Json } from '../core/hash.mjs';
8
+ import { status as trainingStatus } from '../api.mjs';
9
+ import { launchBackgroundWorker, requireJobId } from './async-evaluate.mjs';
10
+
11
+ const workerFile = fileURLToPath(new URL('./async-train-worker.mjs', import.meta.url));
12
+
13
+ async function location({ baseDir, configFile, jobId, requestId }) {
14
+ const { file, config } = await loadConfig({ file: configFile, baseDir });
15
+ const root = path.join(config.runRootAbsolute, requireJobId(jobId), 'background-training');
16
+ const dir = path.join(root, requestId);
17
+ return { file, root, dir, statusFile: path.join(dir, 'status.json') };
18
+ }
19
+
20
+ export async function startBackgroundTraining({
21
+ baseDir, configFile, jobId, resume = true, resumeCancelled = false, auditEveryStep = 10, retry = false,
22
+ } = {}) {
23
+ requireJobId(jobId);
24
+ const { file } = await loadConfig({ file: configFile, baseDir });
25
+ const device = process.env.TMF_DEVICE ?? 'cpu';
26
+ if (!['cpu', 'cuda'].includes(device)) throw new Error('unsupported TMF_DEVICE=' + device);
27
+ const request = {
28
+ kind: 'train', configFile: file, configDigest: await sha256File(file), jobId,
29
+ resume, resumeCancelled, auditEveryStep, device, pythonBin: process.env.TMF_PYTHON ?? 'python3',
30
+ hfMaxMemoryMb: process.env.TMF_HF_MAX_MEMORY_MB ?? null,
31
+ };
32
+ // Resume-cancelled changes the next attempt, not the identity of the job.
33
+ // Otherwise the job-level ownership lock would reject a legitimate resume.
34
+ const requestId = sha256Json({ ...request, resumeCancelled: undefined }).slice(0, 24);
35
+ const loc = await location({ baseDir, configFile: file, jobId, requestId });
36
+ await ensureDir(loc.root);
37
+ // A jobId is immutable, so it belongs to one background request for its
38
+ // lifetime. mkdir is atomic across concurrent callers; changed config or
39
+ // device needs a new jobId rather than racing two workers on the same state.
40
+ const activeDir = path.join(loc.root, 'active.lock');
41
+ const activeFile = path.join(activeDir, 'request.json');
42
+ try {
43
+ await mkdir(activeDir);
44
+ await writeJson(activeFile, { requestId });
45
+ } catch (err) {
46
+ if (err.code !== 'EEXIST') throw err;
47
+ const active = await readJsonIfExists(activeFile);
48
+ if (!active?.requestId) throw new Error('background training job launch is initializing; retry status shortly');
49
+ if (active.requestId !== requestId) throw new Error(`training job ${jobId} is bound to request ${active.requestId}; use a new jobId for changed inputs`);
50
+ }
51
+ let attempt = 1;
52
+ try {
53
+ await mkdir(loc.dir);
54
+ } catch (err) {
55
+ if (err.code !== 'EEXIST') throw err;
56
+ const prior = await backgroundTrainingStatus({ baseDir, configFile: file, jobId, requestId });
57
+ const canResumeCancelled = prior.state === 'cancelled' && resumeCancelled;
58
+ if (!canResumeCancelled && (!retry || !['failed', 'interrupted'].includes(prior.state))) return prior;
59
+ attempt = (prior.attempt ?? 1) + 1;
60
+ }
61
+ const attemptDir = path.join(loc.dir, `attempt-${attempt}`);
62
+ try {
63
+ await mkdir(attemptDir);
64
+ } catch (err) {
65
+ if (err.code !== 'EEXIST') throw err;
66
+ return backgroundTrainingStatus({ baseDir, configFile: file, jobId, requestId });
67
+ }
68
+ const requestFile = path.join(attemptDir, 'request.json');
69
+ await writeJson(requestFile, { ...request, requestId, attempt });
70
+ const status = {
71
+ requestId, jobId, state: 'queued', attempt, createdAt: new Date().toISOString(), device,
72
+ logFile: path.join(attemptDir, 'worker.log'),
73
+ };
74
+ await writeJson(loc.statusFile, status);
75
+ try {
76
+ const launch = await launchBackgroundWorker(workerFile, requestFile, loc.statusFile,
77
+ `tmf-train-${requestId}-${attempt}`, status.logFile);
78
+ await writeJson(path.join(attemptDir, 'launch.json'), launch);
79
+ const now = await readJsonIfExists(loc.statusFile);
80
+ if (now?.state === 'queued' && now.attempt === attempt) await writeJson(loc.statusFile, { ...now, ...launch });
81
+ } catch (err) {
82
+ await writeJson(loc.statusFile, {
83
+ ...status, state: 'failed', finishedAt: new Date().toISOString(),
84
+ error: { code: 'WORKER_LAUNCH_FAILED', message: err.message },
85
+ });
86
+ }
87
+ return backgroundTrainingStatus({ baseDir, configFile: file, jobId, requestId });
88
+ }
89
+
90
+ export async function backgroundTrainingStatus({ baseDir, configFile, jobId, requestId }) {
91
+ requireJobId(jobId);
92
+ if (typeof requestId !== 'string' || !/^[a-f0-9]{24}$/.test(requestId)) throw new Error('requestId must be a 24-character hex digest');
93
+ const loc = await location({ baseDir, configFile, jobId, requestId });
94
+ const status = await readJsonIfExists(loc.statusFile);
95
+ if (!status) {
96
+ if (!(await exists(loc.dir))) throw new Error('background training not found: ' + requestId);
97
+ return { requestId, jobId, state: 'initializing', statusFile: loc.statusFile };
98
+ }
99
+ const launch = await readJsonIfExists(path.join(loc.dir, `attempt-${status.attempt}`, 'launch.json'));
100
+ const withLaunch = launch ? { ...status, ...launch } : status;
101
+ if (status.state === 'running' && status.pid) {
102
+ try {
103
+ process.kill(status.pid, 0);
104
+ } catch (err) {
105
+ if (err.code === 'ESRCH') {
106
+ const durable = await trainingStatus({ baseDir, configFile: loc.file, jobId });
107
+ const fresh = durable.found && durable.state?.updatedAt >= status.startedAt;
108
+ const state = fresh && durable.state?.state === 'succeeded' ? 'succeeded'
109
+ : fresh && durable.state?.state === 'cancelled' ? 'cancelled' : 'interrupted';
110
+ const result = {
111
+ ...withLaunch, state, finishedAt: new Date().toISOString(),
112
+ jobState: fresh ? durable.state?.state : null,
113
+ };
114
+ if (state === 'interrupted') result.error = { code: 'WORKER_EXITED', message: 'worker exited without a matching durable job result; retry explicitly' };
115
+ await writeJson(loc.statusFile, result);
116
+ return { ...result, statusFile: loc.statusFile };
117
+ }
118
+ }
119
+ }
120
+ return { ...withLaunch, statusFile: loc.statusFile };
121
+ }
122
+
123
+ export async function cancelBackgroundTraining({ baseDir, configFile, jobId, requestId }) {
124
+ const status = await backgroundTrainingStatus({ baseDir, configFile, jobId, requestId });
125
+ if (!['queued', 'running'].includes(status.state)) return status;
126
+ const loc = await location({ baseDir, configFile, jobId, requestId });
127
+ await writeJson(path.join(loc.dir, `attempt-${status.attempt}`, 'cancel.json'), { requestedAt: new Date().toISOString() });
128
+ const latest = await readJsonIfExists(status.statusFile);
129
+ if (latest?.state === 'running' && latest.pid) {
130
+ try { process.kill(latest.pid, 'SIGTERM'); } catch (err) { if (err.code !== 'ESRCH') throw err; }
131
+ } else if (latest?.state === 'queued') {
132
+ await writeJson(status.statusFile, { ...latest, state: 'cancel_requested' });
133
+ }
134
+ return backgroundTrainingStatus({ baseDir, configFile, jobId, requestId });
135
+ }
@@ -18,6 +18,7 @@
18
18
 
19
19
  import * as api from '../api.mjs';
20
20
  import { startBackgroundEvaluation, backgroundEvaluationStatus } from './async-evaluate.mjs';
21
+ import { startBackgroundTraining, backgroundTrainingStatus, cancelBackgroundTraining } from './async-train.mjs';
21
22
  import { VERSION } from '../version.mjs';
22
23
 
23
24
  /** Bumped only on a breaking change to the action set or envelope shape. */
@@ -50,9 +51,30 @@ const ACTIONS = {
50
51
  },
51
52
  train: {
52
53
  summary: 'Run a post-training job that updates real weights or an adapter.',
53
- params: ['configFile', 'jobId', 'resume', 'resumeCancelled', 'auditEveryStep'],
54
+ params: ['configFile', 'jobId', 'resume', 'resumeCancelled', 'auditEveryStep', 'background', 'retry'],
54
55
  compute: true,
55
- handler: (ctx, p) => api.train({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, resume: p.resume ?? true, resumeCancelled: p.resumeCancelled ?? false, auditEveryStep: p.auditEveryStep ?? 10 }),
56
+ handler: (ctx, p) => {
57
+ if (p.retry && !p.background) throw new Error('train retry requires background=true');
58
+ if (p.background && p.resume === false) throw new Error('background training requires resume=true');
59
+ if (p.background && !p.jobId) throw new Error('background training requires jobId');
60
+ return p.background
61
+ ? startBackgroundTraining({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId, resumeCancelled: p.resumeCancelled ?? false, auditEveryStep: p.auditEveryStep ?? 10, retry: p.retry ?? false })
62
+ : api.train({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, resume: p.resume ?? true, resumeCancelled: p.resumeCancelled ?? false, auditEveryStep: p.auditEveryStep ?? 10 });
63
+ },
64
+ },
65
+ train_status: {
66
+ summary: 'Read a durable background training receipt without consuming compute.',
67
+ params: ['configFile', 'jobId', 'requestId'],
68
+ required: ['jobId', 'requestId'],
69
+ compute: false,
70
+ handler: (ctx, p) => backgroundTrainingStatus({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId, requestId: p.requestId }),
71
+ },
72
+ train_cancel: {
73
+ summary: 'Cancel a background training request while preserving completed checkpoints.',
74
+ params: ['configFile', 'jobId', 'requestId'],
75
+ required: ['jobId', 'requestId'],
76
+ compute: true,
77
+ handler: (ctx, p) => cancelBackgroundTraining({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId, requestId: p.requestId }),
56
78
  },
57
79
  evaluate: {
58
80
  summary: 'Score base vs trained model on the independent holdout and apply gates.',
@@ -71,9 +93,9 @@ const ACTIONS = {
71
93
  },
72
94
  export: {
73
95
  summary: 'Package weights/adapter with lineage, model card and checksums.',
74
- params: ['configFile', 'jobId', 'evalReport', 'outDir', 'version', 'evaluateIfMissing'],
96
+ params: ['configFile', 'jobId', 'evalReport', 'qualityReport', 'outDir', 'version', 'evaluateIfMissing'],
75
97
  compute: true,
76
- handler: (ctx, p) => api.exportModel({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, evalReport: p.evalReport ?? null, outDir: p.outDir ?? null, version: p.version ?? null, evaluateIfMissing: p.evaluateIfMissing ?? true }),
98
+ handler: (ctx, p) => api.exportModel({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, evalReport: p.evalReport ?? null, qualityReport: p.qualityReport ?? null, outDir: p.outDir ?? null, version: p.version ?? null, evaluateIfMissing: p.evaluateIfMissing ?? true }),
77
99
  },
78
100
  };
79
101
 
@@ -12,7 +12,7 @@
12
12
  // so "resume" is the same code path as "load a checkpoint someone else wrote".
13
13
 
14
14
  import path from 'node:path';
15
- import { runJob, JobCancelledError } from './runner.mjs';
15
+ import { runJob, JobCancelledError, BudgetExceededError } from './runner.mjs';
16
16
  import { runDataPipeline } from '../data/pipeline.mjs';
17
17
  import { buildTokenizer, encodeRecords } from '../train/dataset.mjs';
18
18
  import { ensureDir, readJsonl, writeJson } from '../core/fsx.mjs';
@@ -64,6 +64,7 @@ export async function runTrainingJob({
64
64
  modelConfig = {},
65
65
  hyper = {},
66
66
  trainBudget = {},
67
+ externalQuality = null,
67
68
  mode = DEFAULT_TRAIN_JOB_OPTIONS.mode,
68
69
  seed = DEFAULT_TRAIN_JOB_OPTIONS.seed,
69
70
  maxVocab = DEFAULT_TRAIN_JOB_OPTIONS.maxVocab,
@@ -106,6 +107,7 @@ export async function runTrainingJob({
106
107
  seed,
107
108
  maxVocab,
108
109
  maxSeqLen,
110
+ ...(externalQuality ? { externalQuality } : {}),
109
111
  };
110
112
 
111
113
  const steps = [
@@ -197,20 +199,40 @@ export async function runTrainingJob({
197
199
  baseFingerprint: beforeFingerprint,
198
200
  });
199
201
 
200
- const trained = await backend.train({
201
- handle,
202
- examples,
203
- examplesFile: prepared.examplesFile ?? null,
204
- mode,
205
- hyper,
206
- budget: trainBudget,
207
- seed,
208
- outDir: modelDir,
209
- signal,
210
- resume: null,
211
- hooks: { onStep: makeStepHook({ signal, audit, budget: jobBudget, auditEveryStep }) },
212
- });
202
+ let trained;
203
+ try {
204
+ trained = await backend.train({
205
+ handle,
206
+ examples,
207
+ examplesFile: prepared.examplesFile ?? null,
208
+ mode,
209
+ hyper,
210
+ budget: backend.id === 'hf-peft' ? {
211
+ ...trainBudget,
212
+ maxTokens: jobBudget.limits.maxTokens == null ? null : jobBudget.limits.maxTokens - jobBudget.usage.tokens,
213
+ } : trainBudget,
214
+ seed,
215
+ outDir: modelDir,
216
+ signal,
217
+ resume: null,
218
+ hooks: { onStep: makeStepHook({ signal, audit, budget: jobBudget, auditEveryStep }) },
219
+ });
220
+ } catch (err) {
221
+ if (err?.code === 'BACKEND_TOKEN_BUDGET') {
222
+ throw new BudgetExceededError(err.message, { limit: 'maxTokens', limitValue: jobBudget.limits.maxTokens });
223
+ }
224
+ throw err;
225
+ }
213
226
  const { metrics, history, stopReason } = trained;
227
+ // HF runs outside Node, so its per-batch count returns at job-step end.
228
+ // The Python collator already stops before a batch that would exceed
229
+ // the cap; charging here records the verified consumption durably.
230
+ if (backend.id === 'hf-peft') {
231
+ if (!Number.isSafeInteger(metrics.tokensSeen) || metrics.tokensSeen < 0) {
232
+ throw new Error('hf-peft did not report a valid consumed-token count');
233
+ }
234
+ jobBudget.charge({ tokens: metrics.tokensSeen });
235
+ }
214
236
  // A backend may return a moved handle (hf-peft points it at the adapter
215
237
  // directory the worker just wrote); saving the pre-train handle would
216
238
  // persist a checkpoint that does not reference the trained weights.
@@ -268,6 +290,7 @@ export async function runTrainingJob({
268
290
  data: outputs.data,
269
291
  base: outputs.base,
270
292
  train: outputs.train,
293
+ ...(externalQuality ? { externalQuality } : {}),
271
294
  };
272
295
  const manifestFile = path.join(jobDir, 'train-manifest.json');
273
296
  await writeJson(manifestFile, manifest);
@@ -299,5 +322,6 @@ export function trainingArtifacts(job) {
299
322
  adapterCheckpoint: train.kind === 'adapter' ? train.checkpoint : null,
300
323
  tunedCheckpoint: train.kind === 'adapter' ? null : train.checkpoint,
301
324
  metrics: train.metrics,
325
+ externalQuality: job.result.externalQuality ?? null,
302
326
  };
303
327
  }