// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file The settings a corpus build resolves from its options, and the derivation of each source's files. * * The serial build and the parallel coordinator both read these. Both paths assign a source's files * the same derivation identity. */ import { sha256Hex } from "@mailwoman/core/crypto/hash" import { pathExists } from "@mailwoman/core/fs/readers/stat" import { canonicalJSON } from "@mailwoman/core/values/json" import { LicensePolicy } from "@mailwoman/license/policy" import { adapterModules, moduleGraphHashes } from "#build/code-hash" import { defaultRegionNameInputs } from "#build/region/names" import { BuildProfile, PriorOutput, type BuildCorpusOptions } from "#build/types" import { extractFingerprint, type FileDerivation, inputCheckouts } from "#parquet/record" import { ROWS_PER_FILE } from "#parquet/schema" import { DEFAULT_SHUFFLE_SEED, DEFAULT_SHUFFLE_WINDOW } from "#parquet/shuffle" import { committedRowLicenseInputs } from "#source-register/row-license" import type { AdapterOptions, CorpusAdapter } from "#types" import type { CountryHoldout } from "#utils/split" /** * A build's options with every default applied. */ export interface ResolvedBuildSettings { synthesize: boolean rowsPerFile: number shuffleWindow: number shuffleSeed: number profile: BuildProfile licensePolicy: LicensePolicy excludeLicenses: readonly RegExp[] priorOutput: PriorOutput resume: boolean } export function resolveCorpusSettings(opts: BuildCorpusOptions): ResolvedBuildSettings { const priorOutput = opts.priorOutput ?? PriorOutput.Refuse return { synthesize: opts.synthesize ?? true, rowsPerFile: opts.rowsPerFile ?? ROWS_PER_FILE, shuffleWindow: opts.shuffleWindow ?? DEFAULT_SHUFFLE_WINDOW, shuffleSeed: opts.shuffleSeed ?? DEFAULT_SHUFFLE_SEED, profile: opts.profile ?? BuildProfile.Exploratory, licensePolicy: opts.licensePolicy ?? LicensePolicy.All, excludeLicenses: opts.excludeLicenses ?? [], priorOutput, resume: priorOutput === PriorOutput.Resume, } } /** * The build config every source's files are derived under. */ export function derivationConfig( settings: ResolvedBuildSettings, holdouts: Record ): Record { return { tool: "build", synthesize: settings.synthesize, profile: settings.profile, licensePolicy: settings.licensePolicy, excludeLicenses: settings.excludeLicenses.map((pattern) => pattern.source), holdouts, shuffleSeed: settings.shuffleSeed, shuffleWindow: settings.shuffleWindow, } } /** * The extract hash of one adapter's rows: its options with its input replaced by the input's fingerprint. * * A base row's `source` is its adapter's id (the runner refuses any other), a synthesized * row keeps its ancestor's `source`, and the runner deduplicates within one adapter's run. * A source's files therefore read only that adapter's input. * * A street index enters as its file's fingerprint, because a rebuilt index at the * same path changes how the unit splitter reads a street. * * `outputDir` is left out: it locates an adapter's side state and doesn't change a row. * A partition's `rowRange` and `duckdb` limits are left out because a partitioned * run writes the bytes of one unpartitioned run. * * `trainShare` is left out because align applies it after the adapter, * so the adapter run stays reusable when it changes. * It enters the source's parquet derivation instead. */ export async function adapterExtractHash(options: AdapterOptions): Promise { const { inputPath, outputDir: _outputDir, trainShare: _trainShare, rowRange: _rowRange, duckdb: _duckdb, streetIndex, ...rest } = options return sha256Hex( canonicalJSON({ ...rest, ...(streetIndex ? { streetIndex: await extractFingerprint(streetIndex) } : {}), input: await extractFingerprint(inputPath), }) ) } const fingerprintOf = async (path: string): Promise => (await pathExists(path)) ? extractFingerprint(path) : "absent" /** * The fingerprint of each data file that changes an aligned row, keyed by its role. * * The code hash follows module imports and so misses a file read at run time. * An edited source register or corpus-source input table changes a row's license, * so each one enters every source's derivation. */ export async function alignDataFingerprints(): Promise> { const licenses = committedRowLicenseInputs() return { sourceRegister: await fingerprintOf(licenses.register), corpusSourceInputs: await fingerprintOf(licenses.corpusSourceInputs), } } /** * The keys {@linkcode regionCheckFingerprints} returns. * * A source record written before the region data left the derivation holds * them in its derivation's `alignData`. */ export const REGION_CHECK_INPUTS = ["regionDatabase", "geonames", "secondLevelRegions"] as const /** * The fingerprint of each file the component check's `region:unknown` rule reads, keyed by its role. * * The region data changes no row's bytes. * `region:unknown` is reported and never quarantines a row. * * The data changes only that rule's count, so it stays out of the derivation. * A source's record states the fingerprints beside the count. * * A build that reuses the source under other region data recounts the rule (`#build/region/recount`). * * An absent database records `absent`, because align then reads no region data. */ export async function regionCheckFingerprints(): Promise> { const regions = defaultRegionNameInputs() return { regionDatabase: await fingerprintOf(regions.database), geonames: await fingerprintOf(regions.geonamesDirectory), secondLevelRegions: await fingerprintOf(regions.secondLevelTable), } } /** * The build pipeline's root module, repository-relative: every base source passes through it. */ const BUILD_MODULE = "packages/corpus/lib/build.ts" /** * The derivation of each configured adapter's files, from one cruise of the module graph. * * A source's code hash covers the build pipeline (`lib/build.ts` and what it reaches) and the * adapter's own module graph, so an edit to one adapter changes only that adapter's files. */ export async function adapterDerivations( adapters: readonly CorpusAdapter[], adapterInputs: Record, config: Record ): Promise<((source: string) => Promise) & { modules: ReadonlyMap }> { const modules = await adapterModules(adapters) const codeHashes = await moduleGraphHashes( Object.fromEntries([...modules].map(([id, module]) => [id, [BUILD_MODULE, module]])) ) const derived = new Map>() const alignData = alignDataFingerprints() return Object.assign(derivationOf, { modules }) function derivationOf(source: string): Promise { let derivation = derived.get(source) if (!derivation) { derived.set(source, (derivation = derive(source))) } return derivation } async function derive(source: string): Promise { const options = adapterInputs[source] const codeHash = codeHashes.get(source) if (!options || !codeHash) { throw new Error(`buildCorpus: rows of ${source} reached the parquet phase and no configured adapter has that id`) } return { extractHash: await adapterExtractHash(options), codeHash, config: { ...config, alignData: await alignData, ...(typeof options.trainShare === "number" ? { trainShare: options.trainShare } : {}), }, ...(await inputCheckouts(options.inputPath)), } } }