// Run the batch auto-annotator over a set of episodes AND commit the result // in one call: the unattended form of the Batch page (same loaders, same // staging, same guarded commit), for callers that want a dataset's // annotations completed without a review stop — "score all episodes" in // the rollout review panel runs it after the rollout scoring so a rollout // dataset ends up with both files in one click. The committed atoms are // `source: auto` by construction and stay replaceable by a later run. import { getEpisodeDataSafe } from "@/app/[org]/[dataset]/[episode]/fetch-data"; import { findRawSensorCsvs } from "@/utils/episodeDiscovery"; import { commitBatchToHub, fetchAnnotationsFromHub, fetchBranchSha, } from "@/utils/hubCommit"; import { fetchRepoText } from "./annotateEpisode"; import { EPISODE_READ_TIMEOUT_MS, entriesForCommit, runBatch, type BatchOutput, } from "./batchAnnotate"; import { saveStoredBatch, type StoredBatch } from "./batchStore"; import { createBrowserPool, poolReader, type EpisodePool, } from "./batchWorkers"; import { clearStagedMarker, readLocalAtoms, readStagedMarker, stageLocalAtoms, } from "./localAtoms"; import type { RigProfile, ProfileSource } from "./rigProfile"; export interface AutoAnnotateOptions { repoId: string; org: string; dataset: string; root: string | null; episodes: number[]; profile: RigProfile; profileSource: ProfileSource | null; useRaw?: boolean; /** worker threads; 0 or 1 = main thread only */ workers?: number; signal?: AbortSignal; onProgress?: (done: number, total: number, episode: number) => void; onNote?: (note: string) => void; } export interface AutoAnnotateResult { output: BatchOutput; /** episode files committed (0 when nothing changed or the run aborted) */ committed: number; /** episodes whose staged copy could not be found at commit time */ missing: number[]; /** why nothing was committed, when committed is 0 */ skippedReason?: string; } /** Run the detector over `episodes`, stage the proposals like the Batch * page does, then commit every changed file in one Hub commit pinned to * the version read at the start. Human atoms survive (mergeAutoAtoms), the * save rule applies (atomsForSave), and a dataset that moved in between * makes the commit fail with the Hub's 412 rather than overwrite. */ export async function autoAnnotateAndCommit( o: AutoAnnotateOptions, ): Promise { const { repoId, org, dataset, root } = o; const useRaw = o.useRaw ?? true; const baseSha = await fetchBranchSha(repoId).catch(() => null); let pool: EpisodePool | null = null; const workers = Math.max(0, Math.floor(o.workers ?? 0)); if (workers > 1) { pool = createBrowserPool(workers, (message, jobs) => o.onNote?.( `a worker died (${message}); ${jobs} episode(s) ran on the main thread instead`, ), ); } const readEpisode = pool ? poolReader(pool, { profile: o.profile, org, dataset, root, useRaw, thresholds: {}, }) : undefined; let output: BatchOutput; try { output = await runBatch({ repoId, episodes: o.episodes, profile: o.profile, profileSource: o.profileSource, thresholds: {}, useRaw, loaders: { loadEpisode: (ep) => getEpisodeDataSafe(org, dataset, ep), listRawFiles: () => findRawSensorCsvs(repoId, root), fetchText: (p) => fetchRepoText(repoId, root, p), fetchExisting: (ep) => fetchAnnotationsFromHub(repoId, ep), readLocal: (ep) => readLocalAtoms(repoId, ep), readStaged: (ep) => readStagedMarker(repoId, ep), }, stage: (ep, atoms) => stageLocalAtoms(repoId, ep, atoms), concurrency: Math.max(1, workers), readEpisode, readTimeoutMs: EPISODE_READ_TIMEOUT_MS, baseSha, onProgress: (row, done, total) => o.onProgress?.(done, total, row.episode), signal: o.signal, }); } finally { pool?.terminate(); } const stored: StoredBatch = { report: output.report, committedAt: null }; saveStoredBatch(repoId, stored); if (output.report.aborted) { return { output, committed: 0, missing: [], skippedReason: "stopped" }; } if (!baseSha) { return { output, committed: 0, missing: [], skippedReason: "the Hub did not answer with the dataset's version at the start; the proposals are staged, commit them from the Batch tab after a rerun", }; } const { entries, missing } = entriesForCommit( output.report, (ep) => readLocalAtoms(repoId, ep), output.files, o.profile, ); if (entries.length === 0) { return { output, committed: 0, missing, skippedReason: "nothing changed" }; } await commitBatchToHub(repoId, entries, output.report, { parentCommit: baseSha, }); const sent = new Set(entries.map((e) => e.episodeId)); for (const ep of sent) clearStagedMarker(repoId, ep); const report = { ...output.report, episodes: output.report.episodes.map((r) => sent.has(r.episode) ? { ...r, staged: false, committed: true } : r, ), }; saveStoredBatch(repoId, { report, committedAt: new Date().toISOString() }); return { output: { ...output, report }, committed: entries.length, missing }; }