// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * Build a parquet file from the DeepSeek-generated kryptonite jsonl and emit the * corpus-v0.4.0 manifest. corpus-v0.4.0 is a pure adapter-addition revision: * it points at every parquet file from v0.3.0 plus the new kryptonite file(s). * No v0.3.0 bytes are touched or re-shuffled. * * See docs/records/engineering/CORPUS_V0_4_0_GENERATION.mdx for the why. that doc also * pins the DeepSeek model version + prompt versions used to produce the jsonl. * * Invoke via `mailwoman corpus recipe kryptonite \ * --jsonl /data/corpus/versioned/v0.4.0/kryptonite/canonical-kryptonite.jsonl \ * --base-manifest /data/corpus/versioned/v0.3.0/corpus-v0.3.0/manifest.json \ * --out-dir /data/corpus/versioned/v0.4.0` */ import { sha256File } from "@mailwoman/core/crypto/hash" import { readLocalJSONFile } from "@mailwoman/core/fs/readers" import { pathExists } from "@mailwoman/core/fs/readers/stat" import { writeLocalJSONFile, writeLocalTextFile, makeDirectories } from "@mailwoman/core/fs/writers" import { PathBuilder, type PathBuilderLike } from "path-ts" import { JSONSpliterator } from "spliterator" import { moduleGraphHash } from "#build/code-hash" import { corpusDirectoryName } from "#directory" import { PARQUET_COLUMNS, PARQUET_COMPRESSION, ROW_GROUP_SIZE } from "#parquet/schema" import { type ParquetManifest, writeParquetSplits } from "#parquet/writers" import { KRYPTONITE_COUNTRY } from "#recipes/deepseek/batches" import { baseManifestFiles } from "#tools/overlay/manifest" import { type CanonicalRow, type LabeledRow, requireSurface } from "#types" import { alignRow } from "#utils" export interface KryptoniteOverlayOptions { jsonl: string baseManifest: string outDir: PathBuilderLike /** * @defaultValue `"0.4.0"` */ corpusVersion?: string /** * @defaultValue `"deepseek-kryptonite"` */ source?: string } /** * Read the jsonl's rows. * * @throws When the rows name more than one source. * The files' extract hash covers the whole jsonl. * The hash remains exact only while every row belongs to the one source those files hold. */ export async function* canonicalRows(jsonl: string): AsyncIterable { let first: string | null = null for await (const raw of JSONSpliterator.fromAsync>(jsonl)) { // Strip sidecar underscore-prefixed fields the generator left behind for debugging. const components = raw["components"] as Record const source = (raw["source"] as string) ?? "deepseek-kryptonite" first ??= source if (source !== first) { throw new Error( `${jsonl} holds rows of ${first} and ${source}. A kryptonite overlay hashes the whole jsonl as its ` + `extract, so the jsonl must hold one source.` ) } // The generator tagged its `french-saint` rows FR, though they're US addresses like every kryptonite row. const tagged = source === "deepseek-kryptonite" ? KRYPTONITE_COUNTRY : null yield { raw: raw["raw"] as string, components, // country-branch: every kryptonite row is a US address, so a row without a country reads as US. // A country on each generated row would replace the fallback. country: tagged?.country ?? (raw["country"] as string) ?? "US", locale: tagged?.locale ?? (raw["locale"] as string) ?? undefined, source, source_id: raw["source_id"] as string, license: (raw["license"] as string) ?? "Synthetic (DeepSeek-v4-flash, AGPL-compatible)", register: (raw["register"] as string | null) ?? null, surface: requireSurface(raw, "deepseek-kryptonite"), } } } async function* labeledRows(jsonl: string, quarantineLog: string[]): AsyncIterable { for await (const row of canonicalRows(jsonl)) { const result = alignRow(row) if (result.kind === "labeled") { yield result.row } else { quarantineLog.push(`${row.source_id}\t${result.row.reason}`) } } } export async function buildKryptoniteOverlay( options: KryptoniteOverlayOptions, report?: (line: string) => void ): Promise { const corpusVersion = options.corpusVersion ?? "0.4.0" const source = options.source ?? "deepseek-kryptonite" if (!(await pathExists(options.jsonl))) throw new Error(`jsonl not found: ${options.jsonl}`) if (!(await pathExists(options.baseManifest))) throw new Error(`base-manifest not found: ${options.baseManifest}`) const outDir = PathBuilder.from(options.outDir) const corpusDir = outDir(corpusDirectoryName(corpusVersion)) await makeDirectories(outDir) const quarantine: string[] = [] const newManifest = await writeParquetSplits( { train: labeledRows(options.jsonl, quarantine) }, { outputDir: outDir, corpusVersion, derivationFor: async () => ({ extractHash: await sha256File(options.jsonl), codeHash: await moduleGraphHash([import.meta.filename]), config: { tool: "kryptonite", source }, }), } ) report?.( `wrote ${newManifest.total_rows} rows into ${newManifest.files.length} parquet file(s); ` + `quarantined ${quarantine.length}` ) if (quarantine.length) { const qPath = corpusDir("quarantine-kryptonite.tsv") await writeLocalTextFile(quarantine, qPath) report?.(`quarantine log → ${qPath}`) } // Compose the final corpus-v0.4.0 manifest: every parquet file from base + the new file(s). const base = await readLocalJSONFile(options.baseManifest) const combined: ParquetManifest = { corpus_version: corpusVersion, schema: PARQUET_COLUMNS, rows_per_file: base.rows_per_file, row_group_size: base.row_group_size ?? ROW_GROUP_SIZE, files: [...baseManifestFiles<(typeof base)["files"][number]>(base), ...newManifest.files], counts: { train: base.counts.train + (newManifest.counts.train ?? 0), val: base.counts.val, test: base.counts.test, }, total_rows: base.total_rows + newManifest.total_rows, } // The v0.3.0 files have no `source`: they mix sources, so audit.ts falls back to its // first_source_id-prefix inference for them (it re-derives on its own when `source` is absent). const combinedPath = corpusDir("MANIFEST.json") await writeLocalJSONFile(combined, combinedPath) report?.(`wrote combined manifest → ${combinedPath}`) report?.(` total_rows=${combined.total_rows} (base=${base.total_rows}, added=${newManifest.total_rows})`) report?.( ` files=${combined.files.length} (base=${baseManifestFiles<(typeof base)["files"][number]>(base).length}, added=${newManifest.files.length})` ) report?.(` compression=${PARQUET_COMPRESSION}`) }