// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * Joins a corpus source id to the register sources whose data its rows are built from. * * A corpus source id is the `source` value stored on every corpus row, keyed by a * training config's `source_weights` and listed in a training manifest. * The register scopes a source to one publisher in one jurisdiction and records its license decision. * * This table is the one record joining the two. * Before it, a source whose register row was refused or never read could feed a corpus * build and a training run: HM Land Registry Price Paid Data reached `rendered-gb` * and `spliced-sub-venue` while its row read `unchecked` (#2635). * * The table is `packages/corpus/data/corpus-source-inputs.json`. * A derived or synthetic source lists every input whose data reaches one of its rows. * * An input with no register row gets one in `source-additions.json`, under an * `unchecked` decision, so the gap reads as a gap rather than as an absence. */ import { readLocalJSONFile } from "@mailwoman/core/fs/readers" import { writeLocalTextFile } from "@mailwoman/core/fs/writers" import { resolveModulePath } from "@mailwoman/core/module/resolvers" import { stringifyJSON, orderedJSON } from "@mailwoman/core/values/json" import { actionOperations, actionPurposes, LicenseAction } from "@mailwoman/license/actions" import { LicenseReviewState, OperationPermission, permissionFor, purposeFor, type LicenseDecision, type OperationDecision, type UsePurpose, } from "@mailwoman/license/decision" import { SourceOperation } from "@mailwoman/license/operations" import { refusingReservation, reservationProblem } from "@mailwoman/license/reservation" import { evaluateLicense, DecisionVerdict, type LicenseRequest } from "@mailwoman/license/tree" import { resolvePath, type PathBuilderLike } from "path-ts" import { readAddressSourceRegister } from "#source-register/register" import type { AddressSourceRecord, AddressSourceRegister } from "#source-register/types" /** * One register source whose data reaches a corpus source's rows. */ export interface CorpusSourceInput { /** * The register's `sourceID`. */ registerSource: string /** * The `licenseID` that register source points at, repeated so a reviewer reads the decision key here. * * {@linkcode auditCorpusSourceInputs} refuses a value that disagrees with the register. */ license: string /** * What the corpus source reads from it: the file, the fields and the component they fill. */ reads: string } /** * Everything one corpus source's rows are built from. */ export interface CorpusSourceMapping { /** * Other spellings rows of this source are stored under, such as the retired `synth-*` spelling. */ aliases?: readonly string[] /** * Every register source whose data reaches a row. */ inputs: readonly CorpusSourceInput[] /** * Inputs written in this repository need no register row. * Examples include a hand-written word list and a template. */ authored?: readonly string[] note?: string /** * What the source read in corpora built before its producer changed inputs under the same id. * * `inputs` describes what a build reads today. * The build and training checks read it. * * A corpus already built keeps the rows it was built from, so the release audit reads the * entry naming that corpus: `spliced-sub-venue` kept its name when its GB skeletons moved from * Price Paid Data to OS OpenData, and the published model trained on the Price Paid Data rows. */ history?: readonly CorpusSourceHistory[] } /** * The inputs one source read in the listed corpora. */ export interface CorpusSourceHistory { corpora: readonly string[] inputs: readonly CorpusSourceInput[] because: string } /** * The committed table. */ export interface CorpusSourceInputsFile { sources: Readonly> } /** * The table indexed for lookup under every spelling it records. */ export interface CorpusSourceInputs { readonly file: CorpusSourceInputsFile /** * The mapping a spelling resolves to, with the id it is filed under. */ resolve(source: string): { id: string; mapping: CorpusSourceMapping } | null } /** * Resolves the committed table through the package's `./data/*` export. */ export function corpusSourceInputsPath(): string { return resolveModulePath("@mailwoman/corpus/data/corpus-source-inputs.json") } /** * Indexes a table by id and alias. * * @throws When two entries claim one spelling, because a lookup would then answer for whichever came last. */ export function indexCorpusSourceInputs(file: CorpusSourceInputsFile): CorpusSourceInputs { const bySpelling = new Map() for (const [id, mapping] of Object.entries(file.sources)) { for (const spelling of [id, ...(mapping.aliases ?? [])]) { const claimed = bySpelling.get(spelling) if (claimed && claimed !== id) { throw new Error(`corpus source spelling ${stringifyJSON(spelling)} is claimed by both ${claimed} and ${id}`) } bySpelling.set(spelling, id) } } return { file, resolve(source) { const id = bySpelling.get(source) return id ? { id, mapping: file.sources[id]! } : null }, } } /** * One message per structural problem in the table, read against the register. */ export function auditCorpusSourceInputs(file: CorpusSourceInputsFile, register: AddressSourceRegister): string[] { const problems: string[] = [] const sources = new Map(register.sources.map((source) => [source.sourceID, source])) for (const [id, mapping] of Object.entries(file.sources)) { const named = stringifyJSON(id) if (!mapping.inputs.length && !mapping.authored?.length) { problems.push(`corpus source ${named} lists no input, so nothing records what its rows are built from`) } for (const entry of mapping.history ?? []) { if (!entry.corpora.length || !entry.because) { problems.push(`corpus source ${named} has a history entry naming no corpus or giving no reason`) } } for (const input of [...mapping.inputs, ...(mapping.history ?? []).flatMap((entry) => entry.inputs)]) { const row = sources.get(input.registerSource) if (!row) { problems.push( `corpus source ${named} reads register source ${stringifyJSON(input.registerSource)}, which the register ` + "does not carry. Add the row to `source-additions.json` and regenerate the register." ) continue } if (row.license !== input.license) { problems.push( `corpus source ${named} records license ${stringifyJSON(input.license)} for ${input.registerSource}, ` + `and the register points that source at ${stringifyJSON(row.license)}` ) } if (!input.reads) { problems.push(`corpus source ${named} reads ${input.registerSource} and does not say what it reads`) } } } return problems } /** * The register inputs a source's rows were built from in `corpusVersion`. * * A `history` entry naming the corpus wins over `inputs`, which describes what a build reads today. * Without `corpusVersion` the function reads today's inputs. */ export function mappingInputsFor(mapping: CorpusSourceMapping, corpusVersion?: string): readonly CorpusSourceInput[] { const former = corpusVersion ? mapping.history?.find((entry) => entry.corpora.includes(corpusVersion)) : null return former?.inputs ?? mapping.inputs } /** * Reads the committed table and checks it against the register. * * @throws When the file doesn't parse or the audit reports a problem. */ export async function readCorpusSourceInputs( register: AddressSourceRegister, path?: PathBuilderLike ): Promise { const resolved = path ?? corpusSourceInputsPath() const file = await readLocalJSONFile(resolved) const problems = auditCorpusSourceInputs(file, register) if (problems.length) { throw new Error(`${resolved} failed its audit against the register:\n ${problems.join("\n ")}`) } return indexCorpusSourceInputs(file) } /** * Why one corpus source lacks a permission the checked operations need, * those of the `train` action unless the caller passes others. */ export interface SourceRightsGap { /** * The corpus source id the caller supplied. */ source: string /** * The register source lacking the permission, or `null` when the table has no entry for the corpus source. */ registerSource: string | null licenseID: string | null /** * The decision's review state, or `null` when there's no decision to read. */ state: LicenseDecision["state"] | null /** * The operations the decision doesn't permit, then, for an elected decision, * the purposes it doesn't permit them for. */ missing: Array because: string /** * Present when the register source is reserved for evaluation. * * `--unshippable-reason` admits no reserved source, because a model trained on a local * experiment's output has seen the rows the reservation keeps unseen by every model. */ reserved?: true } /** * Every reason a corpus source's rows may not be built into a corpus or trained on. * * An empty array is the only answer a caller may read as permission. * A source the table doesn't map answers one gap whose `registerSource` is `null`, * because no mapping identifies that source's publishers. * * `corpusVersion` names a corpus already built, so a source whose inputs changed under * the same id is read against what that corpus's rows were built from. * A build or training check omits it and reads today's inputs. * * `request` defaults to the `train` action with no offering. * A release check passes the model release and the license expression its package offers. */ export function sourceRightsGaps( source: string, inputs: CorpusSourceInputs, register: AddressSourceRegister, corpusVersion?: string, request: Pick = { action: LicenseAction.Train, offering: null } ): SourceRightsGap[] { const operations = actionOperations(request.action) const purposes = actionPurposes(request.action, request.offering) const resolved = inputs.resolve(source) if (!resolved) { return [ { source, registerSource: null, licenseID: null, state: null, missing: [...operations], because: "no entry in packages/corpus/data/corpus-source-inputs.json says which register sources its rows are " + "built from", }, ] } const decisions = new Map(register.licenses.map((decision) => [decision.licenseID, decision])) const rows = new Map(register.sources.map((row) => [row.sourceID, row])) const gaps: SourceRightsGap[] = [] for (const input of mappingInputsFor(resolved.mapping, corpusVersion)) { const row = rows.get(input.registerSource) const decision = row ? decisions.get(row.license) : null if (!row || !decision) { gaps.push({ source, registerSource: input.registerSource, licenseID: row?.license ?? null, state: null, missing: [...operations], because: row ? `the register declares no decision ${stringifyJSON(row.license)}` : "the register has no such row", }) continue } const reservation = refusingReservation(row.reservation, decision, operations) if (reservation) { gaps.push({ source, registerSource: row.sourceID, licenseID: decision.licenseID, state: decision.state, missing: [SourceOperation.Train], because: reservationProblem(row.sourceID, reservation), reserved: true, }) continue } const readings: Array<{ term: SourceOperation | UsePurpose; reading: OperationDecision }> = [ ...operations.map((operation) => ({ term: operation, reading: permissionFor(decision, operation) })), // A purpose is missing when any operation reads it unpermitted, // and the first such reading gives the reason. // Only an elected decision reads purposes. // A gap under any other decision lists its unpermitted operations. ...(decision.state === LicenseReviewState.Elected ? purposes : []).flatMap((purpose) => { const unpermitted = operations .map((operation) => purposeFor(decision, operation, purpose).reading) .find((reading) => reading.permission !== OperationPermission.Permitted) return unpermitted ? [{ term: purpose, reading: unpermitted }] : [] }), ] const missing = readings.filter(({ reading }) => reading.permission !== OperationPermission.Permitted) if (!missing.length) continue gaps.push({ source, registerSource: row.sourceID, licenseID: decision.licenseID, state: decision.state, missing: missing.map(({ term }) => term), because: decision.state === LicenseReviewState.Refused ? `the decision is refused: ${decision.refusedBecause}` : missing[0]!.reading.because, }) } return gaps } /** * The register fields a permission check reads: each row's license and reservation, * and each license's decision. */ export interface RegisterDecisions { sources: ReadonlyArray> licenses: readonly LicenseDecision[] } /** * Whether one register row holds a decision under which the decision tree * answers `go` for the `train` action. * * A row the register lacks, or whose license has no decision, doesn't. */ export function registerSourcePermitsTraining(register: RegisterDecisions, registerSource: string): boolean { const row = register.sources.find((entry) => entry.sourceID === registerSource) if (!row) return false const request = { action: LicenseAction.Train, offering: null, sources: [{ source: row.sourceID, licenseID: row.license }], } return evaluateLicense(request, register).verdict === DecisionVerdict.Go } /** * One line naming the corpus source, the register row and the missing permission. */ export function describeSourceRightsGap(gap: SourceRightsGap): string { const missing = gap.missing.join(" and ") if (!gap.registerSource) { return `corpus source ${gap.source} is unmapped and so lacks a permission for ${missing}: ${gap.because}` } return ( `corpus source ${gap.source} reads register source ${gap.registerSource} ` + `(license ${gap.licenseID ?? "none"}, ${gap.state ?? "no decision"}), which does not permit ${missing}: ${gap.because}` ) } /** * Raised when a build or training run would admit a source lacking the permission. */ export class SourceRightsError extends Error { readonly gaps: readonly SourceRightsGap[] /** * @param overrideHint Follows the flag in the message, naming where else the caller * sets the override, as a training config's `data.unshippable_reason`. */ constructor(context: string, gaps: readonly SourceRightsGap[], overrideHint?: string) { const reserved = gaps.filter((gap) => gap.reserved) super( reserved.length ? `${context} refuses ${new Set(reserved.map((gap) => gap.source)).size} corpus source(s) whose register rows ` + "are reserved for evaluation, and no override admits one:\n " + reserved.map(describeSourceRightsGap).join("\n ") + "\nThe operator lifts a reservation by filling its `lifted` entry in " + "packages/corpus/data/source-resolutions.json." : `${context} refuses ${new Set(gaps.map((gap) => gap.source)).size} corpus source(s) whose register rows ` + `lack an elected decision permitting ${actionOperations(LicenseAction.Train).join(" and ")}:\n ` + gaps.map(describeSourceRightsGap).join("\n ") + "\nRecord the decision in packages/corpus/data/license-decisions.json, map the source in " + `packages/corpus/data/corpus-source-inputs.json, or pass --unshippable-reason ${overrideHint ? ` (${overrideHint})` : ""} for a local ` + "experiment, which marks the output as not shippable." ) this.name = "SourceRightsError" this.gaps = gaps } } /** * What a checked output records about the sources it admitted. * * Its field names use snake_case. * The record is written into corpus manifests and read by Python tools. */ export interface SourceRightsRecord { /** * False when an override admitted a source lacking the permission. */ shippable: boolean unshippable_reason: string | null /** * Every corpus source the check read, sorted. */ sources_checked: string[] gaps: SourceRightsGap[] /** * Inputs whose corpus sources couldn't be read, so the check couldn't judge them, * such as a base corpus whose files name no source and whose manifest has no record. */ unverified: string[] } /** * Checks corpus sources one at a time as an output admits them. */ export interface SourceRightsAdmission { /** * Admits a source or throws {@linkcode SourceRightsError}. * * Under an override it logs each gap once and returns them instead. */ admit(source: string): readonly SourceRightsGap[] /** * Admits several sources at once, so a refusal lists every one of them. */ admitAll(sources: Iterable): readonly SourceRightsGap[] /** * Refuses an input whose sources cannot be read, or records it under an override. * * An input the check cannot read stays unverified rather than clear. */ admitUnverified(description: string): void record(): SourceRightsRecord } /** * Options for {@linkcode createSourceRightsAdmission}. */ export interface SourceRightsAdmissionOptions { /** * Names the output in a refusal, as `corpus build v0.7.7` or `recipe sub-venue`. */ context: string /** * Why a local experiment admits sources lacking the permission. * * A caller that sets it marks the output unshippable rather than relaxing the rule. */ unshippableReason?: string | null /** * The built corpus the output reads, so a source whose inputs changed under the same id is * judged by the inputs that built that corpus, as {@linkcode sourceRightsGaps} reads it. * * A build omits it and is judged by today's inputs. */ corpusVersion?: string /** * Names where else the caller sets the override, in the refusal's message. */ overrideHint?: string log?: (line: string) => void } /** * Builds the admission check over an already-read register and table. * * @throws When `unshippableReason` is set and blank, because an override must say why. */ export function createSourceRightsAdmission( register: AddressSourceRegister, inputs: CorpusSourceInputs, options: SourceRightsAdmissionOptions ): SourceRightsAdmission { const reason = options.unshippableReason ?? null if (reason !== null && !reason.trim()) { throw new Error(`${options.context}: --unshippable-reason must say why the output is not shippable`) } const log = options.log ?? ((line: string) => console.error(line)) const checked = new Map() const admitAll = (sources: Iterable): readonly SourceRightsGap[] => { const fresh: SourceRightsGap[] = [] const all: SourceRightsGap[] = [] for (const source of sources) { const known = checked.get(source) if (known) { all.push(...known) continue } const gaps = sourceRightsGaps(source, inputs, register, options.corpusVersion) fresh.push(...gaps) all.push(...gaps) if (!gaps.length || (reason !== null && !gaps.some((gap) => gap.reserved))) { checked.set(source, gaps) } } if (!fresh.length) return all const reserved = fresh.filter((gap) => gap.reserved) // No override admits a reserved source, so its rows stay unseen by every model, local experiments included. if (reserved.length) throw new SourceRightsError(options.context, reserved, options.overrideHint) if (reason === null) throw new SourceRightsError(options.context, fresh, options.overrideHint) for (const gap of fresh) { log(`UNSHIPPABLE ${options.context}: ${describeSourceRightsGap(gap)} (override: ${reason})`) } return all } const unverified: string[] = [] return { admit: (source) => admitAll([source]), admitAll, admitUnverified: (description) => { if (reason === null) { throw new Error( `${options.context} cannot check the corpus sources of ${description}, and an input it cannot read is ` + "not one it found clear. Pass --unshippable-reason for a local experiment, which marks the " + "output as not shippable." ) } log(`UNSHIPPABLE ${options.context}: the corpus sources of ${description} were not checked (override: ${reason})`) unverified.push(description) }, record: () => { const gaps = [...checked.values()].flat() const shippable = gaps.length === 0 && unverified.length === 0 return { shippable, unshippable_reason: shippable ? null : reason, sources_checked: [...checked.keys()].toSorted(), gaps, unverified: [...unverified], } }, } } /** * The file name of the record a corpus builder writes beside its output. */ export const SOURCE_RIGHTS_FILE_NAME = "SOURCE_RIGHTS.json" /** * Writes `record` beside an output as {@linkcode SOURCE_RIGHTS_FILE_NAME}, * two-space indented with a trailing newline, the bytes the Python builders' * `write_rights_record` wrote for a record with no gaps. * * @returns The path written. */ export async function writeSourceRightsRecord(record: SourceRightsRecord, outDir: PathBuilderLike): Promise { const path = resolvePath(outDir, SOURCE_RIGHTS_FILE_NAME) await writeLocalTextFile(orderedJSON(record, { indent: "\t" }) + "\n", path) return path } /** * Reads the committed register and table and builds the admission check over them. */ export async function openSourceRightsAdmission(options: SourceRightsAdmissionOptions): Promise { const register = await readAddressSourceRegister() const inputs = await readCorpusSourceInputs(register) return createSourceRightsAdmission(register, inputs, options) }