// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file Pre-training corpus schema-invariant audit over a built or assembled parquet manifest. * * Catches stale adapter outputs before a training launch bills GPU hours. * Each invariant scans the parquet files a manifest lists through DuckDB, reports exact per-source * denominators and violation counts, and confirms concrete failing sample rows with UTF-16 span slicing. * * A missing manifest, an empty file list, a missing parquet file, or an unreadable parquet file throws * rather than reporting zero violations. */ import { thoroughfareClassOf } from "@mailwoman/codex/labels/street/thoroughfare-classes" import { readLocalJSONFile } from "@mailwoman/core/fs/readers" import { isFile } from "@mailwoman/core/fs/readers/stat" import { foldNFKCWhitespace } from "@mailwoman/normalize/fold" import { dirname, type PathBuilderLike, resolvePath } from "path-ts" import { PARQUET_MANIFEST_FILE } from "#build/holdout-check" import { type DuckDBLimits, escapeSQLString, openDuckDB } from "#parquet/duckdb" import { componentAtIndexSQL } from "#parquet/span-sql" import { baseManifestFiles, localManifestFilePath } from "#tools/overlay/manifest" /** * Route and thoroughfare words disallowed in a US `street_prefix` span. * Supplements {@link thoroughfareClassOf} (locale `"us"`). * * Under USPS Publication 28 and `SCHEMA.mdx`, a US `street_prefix` holds only a pre-directional * or positional pre-modifier (`N`, `SW`, `North`, `Upper`, `Old`). * Numbered-route words and thoroughfare types belong inside `street` or `street_suffix`. */ export const US_STREET_PREFIX_DISALLOWED_WORDS: ReadonlySet = new Set([ "alternate", "alt", "bus", "business", "byp", "bypass", "calle", "corte", "county", "dr", "drive", "farm", "fm", "interstate", "loop", "market", "paseo", "piazza", "placita", "plaza", "ranch", "rm", "spur", "sr", "state", "tpke", "trace", "trail", "trl", "turnpike", "us", "via", "way", ]) /** * One concrete row violating a corpus schema invariant, with exact UTF-16 span substrings. */ export interface SchemaInvariantSample { source_id: string source: string raw: string street_prefix: string street: string | null offending_token: string } /** * Frequency of one offending `street_prefix` string inside a failing source. */ export interface SchemaInvariantPrefixCount { prefix: string count: number offending_token: string } /** * Measured denominator, violation count, top offending values, and sample rows for one source. */ export interface SchemaInvariantSourceReport { us_rows: number checked_rows: number violation_rows: number violation_rate: number top_prefixes: SchemaInvariantPrefixCount[] samples: SchemaInvariantSample[] } /** * Outcome of one schema invariant across all scanned sources. */ export interface SchemaInvariantResult { id: "us_street_prefix_directional_only" status: "pass" | "fail" total_us_rows: number total_checked_rows: number violation_rows: number violation_rate: number by_source: Record } /** * Complete corpus schema-invariant audit report for one manifest. */ export interface SchemaInvariantAuditReport { corpus_dir: string manifest_path: string files_scanned: number sources_filter: string[] | null status: "pass" | "fail" invariants: SchemaInvariantResult[] } /** * Options for {@linkcode auditCorpusSchemaInvariants}. */ export interface SchemaInvariantAuditOptions { corpusDir: PathBuilderLike manifestPath?: PathBuilderLike /** * Optional source filter. * * An empty collection throws rather than producing a vacuous pass. */ sources?: readonly string[] | ReadonlySet | null sampleLimit?: number topPrefixLimit?: number limits?: DuckDBLimits } /** * Returns the first thoroughfare or route token in a US `street_prefix` span, or `null`. * * Removes periods before tokenizing so `U.S.` folds to `us` and `N.` folds to `n`. * * @public */ export function findDisallowedUSStreetPrefixToken(prefix: string): string | null { const folded = foldNFKCWhitespace(prefix).replaceAll(".", "") if (!folded) return null const tokens = folded.split(/[^\p{L}\p{N}]+/u).filter((token) => token.length > 0) for (const token of tokens) { if (thoroughfareClassOf(token, "us") != null || US_STREET_PREFIX_DISALLOWED_WORDS.has(token)) { return token } } return null } function sqlQuoted(value: string): string { return `'${escapeSQLString(value)}'` } function toStringArray(value: unknown): string[] { if (Array.isArray(value)) return value.map((entry) => String(entry)) if (value && typeof value === "object" && "items" in value) { const items = (value as { items?: unknown }).items if (Array.isArray(items)) return items.map((entry) => String(entry)) } return [] } function toNumberArray(value: unknown): number[] { if (Array.isArray(value)) return value.map((entry) => Number(entry)) if (value && typeof value === "object" && "items" in value) { const items = (value as { items?: unknown }).items if (Array.isArray(items)) return items.map((entry) => Number(entry)) } return [] } /** * Maximum number of missing parquet paths printed inline in an audit refusal error. */ const MAX_REPORTED_MISSING_PATHS = 5 function sliceSpanUTF16(raw: string, tags: string[], starts: number[], ends: number[], target: string): string | null { const index = tags.indexOf(target) if (index === -1) return null const start = starts[index] const end = ends[index] if (typeof start !== "number" || typeof end !== "number") return null return raw.slice(start, end) } /** * Audits a corpus manifest's parquet files for adapter schema invariants before training. * * Currently enforces `us_street_prefix_directional_only`: every `US` row's `street_prefix` span * must hold only directional or positional pre-modifiers, never thoroughfare types or route words. * Non-US rows are excluded because Romance conventions place thoroughfare types * (`Rue`, `Via`, `Calle`) in `street_prefix`. * * @throws When the manifest is missing or lists no files, when any listed parquet file * is missing or unreadable, or when `sources` is explicitly empty. */ export async function auditCorpusSchemaInvariants( options: SchemaInvariantAuditOptions ): Promise { const corpusDir = options.corpusDir.toString() const manifestPath = (options.manifestPath ?? resolvePath(corpusDir, PARQUET_MANIFEST_FILE)).toString() const sampleLimit = options.sampleLimit ?? 5 const topPrefixLimit = options.topPrefixLimit ?? 15 if (!(await isFile(manifestPath))) { throw new Error(`Corpus schema-invariant audit requires manifest at ${manifestPath}, but the file is missing.`) } let sourcesFilter: string[] | null = null if (options.sources != null) { sourcesFilter = [...new Set(options.sources)].toSorted() if (!sourcesFilter.length) { throw new Error("Corpus schema-invariant audit received an empty sources filter.") } } const manifest = await readLocalJSONFile(manifestPath) const entries = baseManifestFiles(manifest) if (!entries.length) { throw new Error(`Corpus manifest ${manifestPath} lists zero parquet files.`) } const manifestDir = dirname(manifestPath) const parquetPaths: string[] = [] const missingPaths: string[] = [] for (const entry of entries) { const resolved = resolvePath(manifestDir, localManifestFilePath(entry.path)).toString() if (await isFile(resolved)) { parquetPaths.push(resolved) } else { missingPaths.push(resolved) } } if (missingPaths.length) { const preview = missingPaths.slice(0, MAX_REPORTED_MISSING_PATHS).join(", ") const extra = missingPaths.length > MAX_REPORTED_MISSING_PATHS ? ` (+${missingPaths.length - MAX_REPORTED_MISSING_PATHS} more)` : "" throw new Error( `Corpus schema-invariant audit cannot read ${missingPaths.length} missing parquet file(s) from ${manifestPath}: ${preview}${extra}` ) } const fileListSQL = parquetPaths.map(sqlQuoted).join(", ") const sourcePredicate = sourcesFilter ? ` AND source IN (${sourcesFilter.map(sqlQuoted).join(", ")})` : "" using db = await openDuckDB(options.limits) const denominatorResult = await db.runAndReadAll( `SELECT source, ` + `count(*)::BIGINT AS us_rows, ` + `count(*) FILTER (WHERE list_contains(span_tags, 'street_prefix'))::BIGINT AS checked_rows ` + `FROM read_parquet([${fileListSQL}], union_by_name=true) ` + `WHERE country = 'US'${sourcePredicate} ` + `GROUP BY source ORDER BY source` ) const bySource = new Map() let totalUSRows = 0 let totalCheckedRows = 0 for (const row of denominatorResult.getRowObjects()) { const source = String(row.source) const usRows = Number(row.us_rows) const checkedRows = Number(row.checked_rows) totalUSRows += usRows totalCheckedRows += checkedRows bySource.set(source, { us_rows: usRows, checked_rows: checkedRows, violation_rows: 0, violation_rate: 0, top_prefixes: [], samples: [], }) } const prefixExpr = componentAtIndexSQL("idx", "raw") const prefixResult = await db.runAndReadAll( `WITH us_prefixed AS (` + `SELECT source, raw, span_starts, span_ends, list_position(span_tags, 'street_prefix') AS idx ` + `FROM read_parquet([${fileListSQL}], union_by_name=true) ` + `WHERE country = 'US' AND list_contains(span_tags, 'street_prefix')${sourcePredicate}` + `) ` + `SELECT source, trim(${prefixExpr}) AS prefix, count(*)::BIGINT AS n ` + `FROM us_prefixed GROUP BY source, prefix` ) const offendingBySource = new Map>() const rawOffendingPrefixesBySource = new Map>() for (const row of prefixResult.getRowObjects()) { const source = String(row.source) const rawPrefix = String(row.prefix ?? "") const count = Number(row.n) const offendingToken = findDisallowedUSStreetPrefixToken(rawPrefix) if (!offendingToken) continue const foldedKey = foldNFKCWhitespace(rawPrefix) let sourceMap = offendingBySource.get(source) if (!sourceMap) { sourceMap = new Map() offendingBySource.set(source, sourceMap) } const prev = sourceMap.get(foldedKey) sourceMap.set(foldedKey, { count: (prev?.count ?? 0) + count, token: offendingToken }) let rawSet = rawOffendingPrefixesBySource.get(source) if (!rawSet) { rawSet = new Set() rawOffendingPrefixesBySource.set(source, rawSet) } rawSet.add(rawPrefix) } let totalViolations = 0 for (const [source, sourceMap] of offendingBySource) { const entry = bySource.get(source) if (!entry) continue const sorted = [...sourceMap.entries()] .map(([prefix, info]) => ({ prefix, count: info.count, offending_token: info.token })) .toSorted((a, b) => b.count - a.count || a.prefix.localeCompare(b.prefix)) const violations = sorted.reduce((sum, item) => sum + item.count, 0) entry.violation_rows = violations entry.violation_rate = entry.checked_rows > 0 ? violations / entry.checked_rows : 0 entry.top_prefixes = sorted.slice(0, topPrefixLimit) totalViolations += violations if (sampleLimit > 0) { const candidatePrefixes = [...(rawOffendingPrefixesBySource.get(source) ?? [])].slice(0, 64) if (candidatePrefixes.length) { const inList = candidatePrefixes.map(sqlQuoted).join(", ") const fetchLimit = Math.max(sampleLimit * 3, 15) const sampleResult = await db.runAndReadAll( `WITH us_prefixed AS (` + `SELECT source, source_id, raw, span_tags, span_starts, span_ends, ` + `list_position(span_tags, 'street_prefix') AS idx ` + `FROM read_parquet([${fileListSQL}], union_by_name=true) ` + `WHERE country = 'US' AND source = ${sqlQuoted(source)} ` + `AND list_contains(span_tags, 'street_prefix')` + `) ` + `SELECT source, source_id, raw, span_tags, span_starts, span_ends ` + `FROM us_prefixed ` + `WHERE trim(${prefixExpr}) IN (${inList}) ` + `LIMIT ${fetchLimit}` ) for (const row of sampleResult.getRowObjects()) { if (entry.samples.length >= sampleLimit) break const raw = String(row.raw ?? "") const tags = toStringArray(row.span_tags) const starts = toNumberArray(row.span_starts) const ends = toNumberArray(row.span_ends) const exactPrefix = sliceSpanUTF16(raw, tags, starts, ends, "street_prefix") if (exactPrefix == null) continue const confirmedToken = findDisallowedUSStreetPrefixToken(exactPrefix) if (!confirmedToken) continue entry.samples.push({ source_id: String(row.source_id ?? ""), source: String(row.source ?? ""), raw, street_prefix: exactPrefix, street: sliceSpanUTF16(raw, tags, starts, ends, "street"), offending_token: confirmedToken, }) } } } } const invariant: SchemaInvariantResult = { id: "us_street_prefix_directional_only", status: totalViolations === 0 ? "pass" : "fail", total_us_rows: totalUSRows, total_checked_rows: totalCheckedRows, violation_rows: totalViolations, violation_rate: totalCheckedRows > 0 ? totalViolations / totalCheckedRows : 0, by_source: Object.fromEntries(bySource), } return { corpus_dir: corpusDir, manifest_path: manifestPath, files_scanned: parquetPaths.length, sources_filter: sourcesFilter, status: invariant.status, invariants: [invariant], } }