// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * Two-tier base-row corpus compaction for the v9 training pipeline. * * Preserves all `val` and `test` rows untouched so evaluation splits and holdout admission remain intact. * Filters `train` rows to `augmentation IS NULL` so build-time copies are dropped. * * Keeps all canonical base `train` rows for Tier-1 sources. * Deduplicates Tier-2 train rows across sources and caps each digit-masked skeleton bucket * while keeping rare unit, PO box, cedex, intersection, venue, and building patterns exempt. */ import { sha256File } from "@mailwoman/core/crypto/hash" import { readLocalJSONFile } from "@mailwoman/core/fs/readers" import { isFile, pathExists, statPath } from "@mailwoman/core/fs/readers/stat" import { cloneFileTo, makeDirectories, movePath, removePathIfPresent, writeLocalJSONFile, } from "@mailwoman/core/fs/writers" import { PathBuilder, resolvePath, type PathBuilderLike } from "path-ts" import { escapeSQLString, openDuckDB, type DisposableDuckDB, type DuckDBLimits } from "#parquet/duckdb" import { PARQUET_COLUMNS, PARQUET_COMPRESSION, ROW_GROUP_SIZE, ROWS_PER_FILE } from "#parquet/schema" import { baseManifestFiles, localManifestFilePath } from "#tools/overlay/manifest" import { readSplitAttribute, splitAttributeFilename, type SplitAttributeFile } from "#tools/overlay/split/attribute" import type { SplitName } from "#utils/split" /** * Default maximum number of Tier-2 train rows kept per digit-masked skeleton bucket. */ export const DEFAULT_SKELETON_CAP = 6 /** * Default Tier-2 dense register sources subject to cross-source deduplication and skeleton capping. * * The multi-country European `overture` source stays in Tier 1 rather than here: * its rows span 16 countries at roughly 100k to 150k rows each. * Skeleton-capping it dropped 700,104 of 1,825,956 rows in `v0.9.0-compact`, * including ES and IT single-letter unit rows and CZ/SI addresses. */ export const DEFAULT_TIER2_SOURCES = [ "usgov-nad", "ban", "ban-gp", "ban-gf", "ban-mq", "ban-re", "ban-yt", "ban-bl", "ban-mf", "ban-pm", "ban-wf", "ban-pf", "usgov-nppes", "tiger", "usgov-usgs-structures", "state-ia-contractors", "state-ny-notaries", "state-tx-notaries", "overture-latam", "gleif-lei", ] as const /** * Bare component tags identifying rare address structures exempt from standard Tier-2 skeleton capping. */ const RARE_PATTERN_TAGS = [ "unit", "po_box", "cedex", "intersection_a", "venue", "building_name", "building_number", ] as const /** * Options for {@linkcode compactCorpusV9}. */ export interface CompactCorpusV9Options { /** * Input corpus directory holding `MANIFEST.json`, or direct path to `MANIFEST.json`. */ inPath: PathBuilderLike /** * Output directory for compacted Parquet files, `MANIFEST.json`, and `COMPACTION_REPORT.json`. */ outDir: PathBuilderLike /** * Output `corpus_version` recorded in `MANIFEST.json`. * * Defaults to `-v9-compact`. */ version?: string /** * Maximum Tier-2 train rows kept per `(country, labels, digit-masked raw)` skeleton bucket. * * @default 6 */ skeletonCap?: number /** * Optional cap for rare Tier-2 pattern rows (`unit`, `po_box`, `cedex`, * `intersection_a`, `venue`, `building_name`, `building_number`). * * A `null` value keeps rare patterns uncapped. * Bare single-letter `unit` rows (one token matching a single letter, such as ES * `CALLE LA CRUZ A, 45` or IT `VIA NAPOLI A 5`) stay uncapped even when `rareSkeletonCap` is set. * * @default null */ rareSkeletonCap?: number | null /** * Sources treated as Tier-2 dense registers. * * Every other source is treated as Tier 1. * * @default {@linkcode DEFAULT_TIER2_SOURCES} */ tier2Sources?: readonly string[] /** * Optional path prefix written into `MANIFEST.json` entries. * * Defaults to the local `outDir` path. */ modalRoot?: string /** * Optional DuckDB memory/thread/spill settings. */ limits?: DuckDBLimits } /** * Per-source row counts across compaction stages. */ export interface CompactSourceStats { source: string tier: 1 | 2 inputTrainRows: number inputValRows: number inputTestRows: number keptTrainRows: number keptValRows: number keptTestRows: number droppedAugmentationRows: number droppedDedupRows: number droppedSkeletonCapRows: number } /** * Summary report written to `COMPACTION_REPORT.json` beside the compacted `MANIFEST.json`. */ export interface CompactionReport { compacted_at: string input_manifest: string corpus_version: string skeleton_cap: number rare_skeleton_cap: number | null tier2_sources: string[] totals: { input_rows: number kept_rows: number input_train_rows: number kept_train_rows: number input_val_rows: number kept_val_rows: number input_test_rows: number kept_test_rows: number dropped_augmentation_rows: number dropped_dedup_rows: number dropped_skeleton_cap_rows: number } sources: CompactSourceStats[] } /** * Result of {@linkcode compactCorpusV9}. */ export interface CompactCorpusV9Result { manifestPath: string reportPath: string report: CompactionReport } interface InputManifestFile { path: string source?: string split?: SplitName split_attribute?: { path: string sha256: string policy_hash: string counts: Record } rows?: number bytes?: number sha256?: string first_source_id?: string last_source_id?: string compression?: string format?: string } interface InputManifest { corpus_version?: string schema?: unknown rows_per_file?: number row_group_size?: number files?: InputManifestFile[] counts?: Record total_rows?: number evaluation_groups?: unknown source_rights?: unknown deletions?: unknown } interface OutputManifestDescriptor { path: string format: "parquet" compression: typeof PARQUET_COMPRESSION rows: number bytes: number sha256: string first_source_id: string last_source_id: string source: string split?: SplitName split_attribute?: { path: string sha256: string policy_hash: string counts: Record } } interface PreparedFile { index: number entry: InputManifestFile localParquetPath: string source: string tier: 1 | 2 hasAugmentation: boolean hasSpanTags: boolean hasTokens: boolean splitAttribute: SplitAttributeFile | null } async function resolveInputFilePath(recordedPath: string): Promise { if (await pathExists(recordedPath)) return recordedPath const local = localManifestFilePath(recordedPath) if (await pathExists(local)) return local throw new Error(`compactCorpusV9: input file does not exist at ${recordedPath} or ${local}`) } function makeSourceStats(source: string, tier: 1 | 2): CompactSourceStats { return { source, tier, inputTrainRows: 0, inputValRows: 0, inputTestRows: 0, keptTrainRows: 0, keptValRows: 0, keptTestRows: 0, droppedAugmentationRows: 0, droppedDedupRows: 0, droppedSkeletonCapRows: 0, } } function recordedOutPath(outDir: PathBuilder, relative: string, modalRoot: string | undefined): string { if (!modalRoot) return outDir(relative).toString() return `${modalRoot.replace(/\/+$/u, "")}/${relative.replace(/^\/+/u, "")}` } async function prepareInputFiles( db: DisposableDuckDB, manifestFiles: readonly InputManifestFile[], tier2Set: ReadonlySet, statsFor: (source: string, tier: 1 | 2) => CompactSourceStats ): Promise { const prepared: PreparedFile[] = [] for (const [index, entry] of manifestFiles.entries()) { const localParquetPath = await resolveInputFilePath(entry.path) const columnsResult = await db.runAndReadAll( `SELECT name FROM parquet_schema('${escapeSQLString(localParquetPath)}')` ) const columns = new Set(columnsResult.getRowObjectsJson().map((row) => String(row["name"]))) let source = entry.source if (!source) { const srcResult = await db.runAndReadAll( `SELECT DISTINCT source FROM read_parquet('${escapeSQLString(localParquetPath)}')` ) const found = srcResult.getRowObjectsJson().map((row) => String(row["source"])) if (found.length !== 1) { throw new Error( `compactCorpusV9: ${localParquetPath} declares no manifest source and holds ${found.length} sources` ) } source = found[0]! } if (!entry.split && !entry.split_attribute) { throw new Error(`compactCorpusV9: manifest entry ${entry.path} declares neither split nor split_attribute`) } const splitAttribute = entry.split_attribute ? await readSplitAttribute(await resolveInputFilePath(entry.split_attribute.path)) : null const tier: 1 | 2 = tier2Set.has(source) ? 2 : 1 statsFor(source, tier) prepared.push({ index, entry, localParquetPath, source, tier, hasAugmentation: columns.has("augmentation"), hasSpanTags: columns.has("span_tags"), hasTokens: columns.has("tokens"), splitAttribute, }) } return prepared } async function loadHeldOutTable(db: DisposableDuckDB, prepared: readonly PreparedFile[]): Promise { await db.run("CREATE TEMP TABLE held_out (file_idx INTEGER, source_id VARCHAR, split VARCHAR)") const heldAppender = await db.createAppender("held_out") for (const file of prepared) { if (!file.splitAttribute) continue for (const id of file.splitAttribute.val) { heldAppender.appendInteger(file.index) heldAppender.appendVarchar(id) heldAppender.appendVarchar("val") heldAppender.endRow() } for (const id of file.splitAttribute.test) { heldAppender.appendInteger(file.index) heldAppender.appendVarchar(id) heldAppender.appendVarchar("test") heldAppender.endRow() } } heldAppender.closeSync() } async function buildTier2KeepTable( db: DisposableDuckDB, prepared: readonly PreparedFile[], skeletonCap: number, rareSkeletonCap: number | null, statsFor: (source: string, tier: 1 | 2) => CompactSourceStats ): Promise { await db.run( "CREATE TEMP TABLE tier2_candidates (" + "file_idx INTEGER, " + "file_row_number BIGINT, " + "source VARCHAR, " + "source_id VARCHAR, " + "dedup_key VARCHAR, " + "skeleton_key VARCHAR, " + "is_rare BOOLEAN, " + "is_single_letter_unit BOOLEAN, " + "tie_hash VARCHAR)" ) const rareTagsSQL = `[${RARE_PATTERN_TAGS.map((tag) => `'${tag}'`).join(", ")}]` for (const file of prepared) { if (file.tier !== 2) continue if (!file.splitAttribute && file.entry.split !== "train") continue const scan = `read_parquet('${escapeSQLString(file.localParquetPath)}', file_row_number = true)` const trainPredicate = file.splitAttribute ? `p.source_id NOT IN (SELECT source_id FROM held_out WHERE file_idx = ${file.index})` : "TRUE" const augPredicate = file.hasAugmentation ? "p.augmentation IS NULL" : "TRUE" const augDroppedExpr = file.hasAugmentation ? "count(*) FILTER (WHERE p.augmentation IS NOT NULL)" : "0" const countsRow = ( await db.runAndReadAll( `SELECT count(*) AS total_train, ${augDroppedExpr} AS dropped_aug FROM ${scan} p WHERE ${trainPredicate}` ) ).getRowObjectsJson()[0]! const sourceStats = statsFor(file.source, 2) sourceStats.inputTrainRows += Number(countsRow["total_train"]) sourceStats.droppedAugmentationRows += Number(countsRow["dropped_aug"]) const rareExpr = file.hasSpanTags ? `(list_has_any(list_transform(p.labels, lambda x: regexp_replace(x, '^[BI]-', '')), ${rareTagsSQL}) ` + `OR list_has_any(p.span_tags, ${rareTagsSQL}))` : `list_has_any(list_transform(p.labels, lambda x: regexp_replace(x, '^[BI]-', '')), ${rareTagsSQL})` const unitTokensExpr = `list_filter(list_zip(p.tokens, p.labels), lambda x: x[2] IN ('B-unit', 'I-unit'))` const singleLetterUnitExpr = file.hasTokens ? `(CASE WHEN len(${unitTokensExpr}) = 1 ` + `THEN regexp_matches(${unitTokensExpr}[1][1], '^\\p{L}$') ` + `ELSE FALSE END)` : "FALSE" await db.run( `INSERT INTO tier2_candidates ` + `SELECT ${file.index}, p.file_row_number, '${escapeSQLString(file.source)}', p.source_id, ` + `sha256(coalesce(p.country, '') || chr(0) || lower(trim(p.raw)) || chr(0) || array_to_string(p.labels, ',')), ` + `sha256(coalesce(p.country, '') || chr(0) || array_to_string(p.labels, ',') || chr(0) || ` + `regexp_replace(lower(p.raw), '[0-9]+', '#', 'g')), ` + `${rareExpr}, ` + `${singleLetterUnitExpr}, ` + `md5(coalesce(p.source_id, '') || ':' || p.raw) ` + `FROM ${scan} p WHERE (${trainPredicate}) AND (${augPredicate})` ) } await db.run( "CREATE TEMP TABLE tier2_deduped AS " + "SELECT file_idx, file_row_number, source, source_id, skeleton_key, is_rare, is_single_letter_unit, tie_hash, " + "row_number() OVER (PARTITION BY dedup_key ORDER BY source, source_id, file_idx, file_row_number) AS dedup_rn " + "FROM tier2_candidates" ) await db.run("DROP TABLE tier2_candidates") const dedupDrops = await db.runAndReadAll( "SELECT source, count(*) AS dropped FROM tier2_deduped WHERE dedup_rn > 1 GROUP BY source" ) for (const row of dedupDrops.getRowObjectsJson()) { statsFor(String(row["source"]), 2).droppedDedupRows += Number(row["dropped"]) } await db.run( "CREATE TEMP TABLE tier2_ranked AS " + "SELECT file_idx, file_row_number, source, is_rare, is_single_letter_unit, " + "row_number() OVER (PARTITION BY skeleton_key ORDER BY tie_hash, source, source_id, file_idx, file_row_number) AS skel_rn " + "FROM tier2_deduped WHERE dedup_rn = 1" ) await db.run("DROP TABLE tier2_deduped") const keepPredicate = rareSkeletonCap == null ? `(is_rare OR skel_rn <= ${skeletonCap})` : `(is_single_letter_unit OR (is_rare AND skel_rn <= ${rareSkeletonCap}) OR (NOT is_rare AND skel_rn <= ${skeletonCap}))` const skelDrops = await db.runAndReadAll( `SELECT source, count(*) AS dropped FROM tier2_ranked WHERE NOT ${keepPredicate} GROUP BY source` ) for (const row of skelDrops.getRowObjectsJson()) { statsFor(String(row["source"]), 2).droppedSkeletonCapRows += Number(row["dropped"]) } await db.run( `CREATE TEMP TABLE tier2_kept AS ` + `SELECT file_idx, file_row_number FROM tier2_ranked WHERE ${keepPredicate}` ) await db.run("DROP TABLE tier2_ranked") } async function writeCompactedFile( db: DisposableDuckDB, file: PreparedFile, outDir: PathBuilder, modalRoot: string | undefined, sourceStats: CompactSourceStats, splitCounts: Record ): Promise { const scan = `read_parquet('${escapeSQLString(file.localParquetPath)}', file_row_number = true)` // Case 1: Dedicated val or test split file — preserve verbatim. if (!file.splitAttribute && file.entry.split && file.entry.split !== "train") { const split = file.entry.split const splitSubdir = outDir(split) await makeDirectories(splitSubdir) const summaryRow = ( await db.runAndReadAll( `SELECT count(*) AS rows, arg_min(source_id, file_row_number) AS first_id, ` + `arg_max(source_id, file_row_number) AS last_id FROM ${scan}` ) ).getRowObjectsJson()[0]! const rows = Number(summaryRow["rows"]) if (split === "val") { sourceStats.inputValRows += rows sourceStats.keptValRows += rows } else { sourceStats.inputTestRows += rows sourceStats.keptTestRows += rows } splitCounts[split] += rows const sha256 = await sha256File(file.localParquetPath) const fileName = `${file.source}-${String(file.index).padStart(4, "0")}-${sha256.slice(0, 12)}.parquet` const relative = `${split}/${fileName}` const destination = outDir(relative) await cloneFileTo(file.localParquetPath, destination) return { split, path: recordedOutPath(outDir, relative, modalRoot), format: "parquet", compression: PARQUET_COMPRESSION, rows, bytes: (await statPath(destination)).size, sha256, first_source_id: String(summaryRow["first_id"] ?? ""), last_source_id: String(summaryRow["last_id"] ?? ""), source: file.source, } } // Case 2: Dedicated train split file. if (!file.splitAttribute && file.entry.split === "train") { const trainSubdir = outDir("train") await makeDirectories(trainSubdir) const staging = trainSubdir(`${file.source}-${file.index}.parquet.partial`).toString() if (file.tier === 1) { const augPredicate = file.hasAugmentation ? "augmentation IS NULL" : "TRUE" const augDroppedExpr = file.hasAugmentation ? "count(*) FILTER (WHERE augmentation IS NOT NULL)" : "0" const countsRow = ( await db.runAndReadAll(`SELECT count(*) AS total, ${augDroppedExpr} AS dropped_aug FROM ${scan}`) ).getRowObjectsJson()[0]! sourceStats.inputTrainRows += Number(countsRow["total"]) sourceStats.droppedAugmentationRows += Number(countsRow["dropped_aug"]) await db.run( `COPY (SELECT * EXCLUDE (file_row_number) FROM ${scan} ` + `WHERE ${augPredicate} ORDER BY file_row_number) ` + `TO '${escapeSQLString(staging)}' ` + `(FORMAT PARQUET, COMPRESSION ${PARQUET_COMPRESSION}, ROW_GROUP_SIZE ${ROW_GROUP_SIZE})` ) } else { await db.run( `COPY (SELECT p.* EXCLUDE (file_row_number) FROM ${scan} p ` + `JOIN tier2_kept k ON k.file_idx = ${file.index} AND k.file_row_number = p.file_row_number ` + `ORDER BY p.file_row_number) ` + `TO '${escapeSQLString(staging)}' ` + `(FORMAT PARQUET, COMPRESSION ${PARQUET_COMPRESSION}, ROW_GROUP_SIZE ${ROW_GROUP_SIZE})` ) } const summaryRow = ( await db.runAndReadAll( `SELECT count(*) AS rows, arg_min(source_id, file_row_number) AS first_id, ` + `arg_max(source_id, file_row_number) AS last_id ` + `FROM read_parquet('${escapeSQLString(staging)}', file_row_number = true)` ) ).getRowObjectsJson()[0]! const keptRows = Number(summaryRow["rows"]) if (keptRows === 0) { await removePathIfPresent(staging) return null } sourceStats.keptTrainRows += keptRows splitCounts.train += keptRows const sha256 = await sha256File(staging) const fileName = `${file.source}-${String(file.index).padStart(4, "0")}-${sha256.slice(0, 12)}.parquet` const relative = `train/${fileName}` const destination = outDir(relative) await movePath(staging, destination) return { split: "train", path: recordedOutPath(outDir, relative, modalRoot), format: "parquet", compression: PARQUET_COMPRESSION, rows: keptRows, bytes: (await statPath(destination)).size, sha256, first_source_id: String(summaryRow["first_id"]), last_source_id: String(summaryRow["last_id"]), source: file.source, } } // Case 3: Split-attribute file holding train, val, and test rows together. const attr = file.splitAttribute! const staging = outDir(`${file.source}-${file.index}.parquet.partial`).toString() const heldCounts = ( await db.runAndReadAll( `SELECT count(*) FILTER (WHERE h.split = 'val') AS val_rows, ` + `count(*) FILTER (WHERE h.split = 'test') AS test_rows ` + `FROM ${scan} p JOIN held_out h ON h.file_idx = ${file.index} AND h.source_id = p.source_id` ) ).getRowObjectsJson()[0]! const valRows = Number(heldCounts["val_rows"]) const testRows = Number(heldCounts["test_rows"]) sourceStats.inputValRows += valRows sourceStats.keptValRows += valRows sourceStats.inputTestRows += testRows sourceStats.keptTestRows += testRows if (file.tier === 1) { const augPredicate = file.hasAugmentation ? "p.augmentation IS NULL" : "TRUE" const augDroppedExpr = file.hasAugmentation ? "count(*) FILTER (WHERE p.augmentation IS NOT NULL)" : "0" const trainCounts = ( await db.runAndReadAll( `SELECT count(*) AS total_train, ${augDroppedExpr} AS dropped_aug ` + `FROM ${scan} p WHERE p.source_id NOT IN (SELECT source_id FROM held_out WHERE file_idx = ${file.index})` ) ).getRowObjectsJson()[0]! sourceStats.inputTrainRows += Number(trainCounts["total_train"]) sourceStats.droppedAugmentationRows += Number(trainCounts["dropped_aug"]) await db.run( `COPY (SELECT p.* EXCLUDE (file_row_number) FROM ${scan} p ` + `WHERE p.source_id IN (SELECT source_id FROM held_out WHERE file_idx = ${file.index}) ` + `OR (${augPredicate}) ` + `ORDER BY p.file_row_number) ` + `TO '${escapeSQLString(staging)}' ` + `(FORMAT PARQUET, COMPRESSION ${PARQUET_COMPRESSION}, ROW_GROUP_SIZE ${ROW_GROUP_SIZE})` ) } else { await db.run( `COPY (SELECT p.* EXCLUDE (file_row_number) FROM ${scan} p ` + `LEFT JOIN tier2_kept k ON k.file_idx = ${file.index} AND k.file_row_number = p.file_row_number ` + `WHERE p.source_id IN (SELECT source_id FROM held_out WHERE file_idx = ${file.index}) ` + `OR k.file_row_number IS NOT NULL ` + `ORDER BY p.file_row_number) ` + `TO '${escapeSQLString(staging)}' ` + `(FORMAT PARQUET, COMPRESSION ${PARQUET_COMPRESSION}, ROW_GROUP_SIZE ${ROW_GROUP_SIZE})` ) } const summaryRow = ( await db.runAndReadAll( `SELECT count(*) AS rows, arg_min(source_id, file_row_number) AS first_id, ` + `arg_max(source_id, file_row_number) AS last_id ` + `FROM read_parquet('${escapeSQLString(staging)}', file_row_number = true)` ) ).getRowObjectsJson()[0]! const keptTotal = Number(summaryRow["rows"]) if (keptTotal === 0) { await removePathIfPresent(staging) return null } const keptTrain = keptTotal - valRows - testRows sourceStats.keptTrainRows += keptTrain splitCounts.train += keptTrain splitCounts.val += valRows splitCounts.test += testRows const sha256 = await sha256File(staging) const fileName = `${file.source}-${String(file.index).padStart(4, "0")}-${sha256.slice(0, 12)}.parquet` const destination = outDir(fileName) await movePath(staging, destination) const attrName = splitAttributeFilename(fileName, attr.policyHash) const attrPath = outDir(attrName) const updatedAttribute: SplitAttributeFile = { ...attr, file: { name: fileName, sha256, rows: keptTotal }, counts: { train: keptTrain, val: valRows, test: testRows }, } await writeLocalJSONFile(updatedAttribute, attrPath) const attrSHA256 = await sha256File(attrPath) return { path: recordedOutPath(outDir, fileName, modalRoot), format: "parquet", compression: PARQUET_COMPRESSION, rows: keptTotal, bytes: (await statPath(destination)).size, sha256, first_source_id: String(summaryRow["first_id"]), last_source_id: String(summaryRow["last_id"]), source: file.source, split_attribute: { path: recordedOutPath(outDir, attrName, modalRoot), sha256: attrSHA256, policy_hash: attr.policyHash, counts: { train: keptTrain, val: valRows, test: testRows }, }, } } function summarizeTotals(sources: readonly CompactSourceStats[]): CompactionReport["totals"] { const totals: CompactionReport["totals"] = { input_rows: 0, kept_rows: 0, input_train_rows: 0, kept_train_rows: 0, input_val_rows: 0, kept_val_rows: 0, input_test_rows: 0, kept_test_rows: 0, dropped_augmentation_rows: 0, dropped_dedup_rows: 0, dropped_skeleton_cap_rows: 0, } for (const source of sources) { totals.input_train_rows += source.inputTrainRows totals.kept_train_rows += source.keptTrainRows totals.input_val_rows += source.inputValRows totals.kept_val_rows += source.keptValRows totals.input_test_rows += source.inputTestRows totals.kept_test_rows += source.keptTestRows totals.dropped_augmentation_rows += source.droppedAugmentationRows totals.dropped_dedup_rows += source.droppedDedupRows totals.dropped_skeleton_cap_rows += source.droppedSkeletonCapRows } totals.input_rows = totals.input_train_rows + totals.input_val_rows + totals.input_test_rows totals.kept_rows = totals.kept_train_rows + totals.kept_val_rows + totals.kept_test_rows return totals } /** * Compacts a corpus manifest into a two-tier base-row v9 corpus while preserving all `val` * and `test` rows and split-attribute holdout boundaries untouched. */ export async function compactCorpusV9(options: CompactCorpusV9Options): Promise { const skeletonCap = options.skeletonCap ?? DEFAULT_SKELETON_CAP const rareSkeletonCap = options.rareSkeletonCap ?? null if (!Number.isInteger(skeletonCap) || skeletonCap < 1) { throw new Error(`compactCorpusV9: skeletonCap must be a positive integer, got ${skeletonCap}`) } if (rareSkeletonCap != null && (!Number.isInteger(rareSkeletonCap) || rareSkeletonCap < 1)) { throw new Error(`compactCorpusV9: rareSkeletonCap must be null or a positive integer, got ${rareSkeletonCap}`) } const inputPathStr = resolvePath(options.inPath) const manifestPath = (await isFile(inputPathStr)) ? inputPathStr : resolvePath(inputPathStr, "MANIFEST.json") const manifest = await readLocalJSONFile(manifestPath) const manifestFiles = baseManifestFiles(manifest) const tier2List = [...new Set(options.tier2Sources ?? DEFAULT_TIER2_SOURCES)].toSorted() const tier2Set = new Set(tier2List) const outDir = PathBuilder.from(options.outDir) await makeDirectories(outDir) const corpusVersion = options.version ?? `${manifest.corpus_version ?? "v0.9.0"}-v9-compact` const statsBySource = new Map() const statsFor = (source: string, tier: 1 | 2): CompactSourceStats => { let entry = statsBySource.get(source) if (!entry) { entry = makeSourceStats(source, tier) statsBySource.set(source, entry) } return entry } using db = await openDuckDB(options.limits) const prepared = await prepareInputFiles(db, manifestFiles, tier2Set, statsFor) await loadHeldOutTable(db, prepared) await buildTier2KeepTable(db, prepared, skeletonCap, rareSkeletonCap, statsFor) // Switch to single-threaded insertion-order-preserving mode for deterministic Parquet COPY output. await db.run("SET preserve_insertion_order=true") await db.run("SET threads=1") const outputFiles: OutputManifestDescriptor[] = [] const splitCounts: Record = { train: 0, val: 0, test: 0 } for (const file of prepared) { const descriptor = await writeCompactedFile( db, file, outDir, options.modalRoot, statsFor(file.source, file.tier), splitCounts ) if (descriptor) { outputFiles.push(descriptor) } } const sortedFiles = outputFiles.toSorted((a, b) => { const splitA = a.split ?? "" const splitB = b.split ?? "" return splitA === splitB ? a.path.localeCompare(b.path) : splitA.localeCompare(splitB) }) const totalRows = splitCounts.train + splitCounts.val + splitCounts.test const outManifest = { corpus_version: corpusVersion, schema: manifest.schema ?? PARQUET_COLUMNS, rows_per_file: manifest.rows_per_file ?? ROWS_PER_FILE, row_group_size: ROW_GROUP_SIZE, files: sortedFiles, counts: splitCounts, total_rows: totalRows, ...(manifest.evaluation_groups ? { evaluation_groups: manifest.evaluation_groups } : {}), ...(manifest.source_rights ? { source_rights: manifest.source_rights } : {}), ...(manifest.deletions ? { deletions: manifest.deletions } : {}), compaction_report: "COMPACTION_REPORT.json", } const outManifestPath = outDir("MANIFEST.json") await writeLocalJSONFile(outManifest, outManifestPath) const sources = [...statsBySource.values()].toSorted((a, b) => a.source.localeCompare(b.source)) const report: CompactionReport = { compacted_at: new Date().toISOString(), input_manifest: manifestPath, corpus_version: corpusVersion, skeleton_cap: skeletonCap, rare_skeleton_cap: rareSkeletonCap, tier2_sources: tier2List, totals: summarizeTotals(sources), sources, } const reportPath = outDir("COMPACTION_REPORT.json") await writeLocalJSONFile(report, reportPath) return { manifestPath: outManifestPath.toString(), reportPath: reportPath.toString(), report, } }