From 620631093d96fe8a06a5a63e190e59a45a068238 Mon Sep 17 00:00:00 2001 From: seonghobae Date: Mon, 31 Aug 2026 21:48:37 +0000 Subject: [PATCH] feat(analysis): bind corpus-background refusals to an analysis-run profile GAP-004 leftover / ADR 0062. Bind existing corpus_background refusals (refuse_corpus_background_as_unique_content, refuse_corpus_background_as_stopword_deletion) to cutoff-safe corpus_background_v1. identity_recovery_rate stays library-side. Distinct from modality-source (#421), prompt-source (#419), style-source (#418), copy-identity (#416), and method-effects (#415). Not GPU, not MCMC, and not topic birth/split/merge. --- CHANGELOG.md | 2 + Cargo.lock | 1 + DOCUMENTATION.md | 1 + crates/analysis_engine/Cargo.toml | 2 + .../src/corpus_background_artifact.rs | 393 ++++++++++++++++++ crates/analysis_engine/src/lib.rs | 15 + .../corpus_background_execution_contract.rs | 194 +++++++++ docs/TRACEABILITY.md | 1 + .../0062-corpus-background-analysis-run.md | 83 ++++ docs/adr/README.md | 2 + .../corpus-background-analysis-run.md | 16 + 11 files changed, 710 insertions(+) create mode 100644 crates/analysis_engine/src/corpus_background_artifact.rs create mode 100644 crates/analysis_engine/tests/corpus_background_execution_contract.rs create mode 100644 docs/adr/0062-corpus-background-analysis-run.md create mode 100644 docs/doctoring/corpus-background-analysis-run.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 062a69412..cc5f1b762 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,8 @@ All notable changes to TEPP are documented here. The format follows Keep a Chang ## [Unreleased] +- **Corpus-background analysis-run profile**: `analysis_engine` binds existing `corpus_background::refuse_corpus_background_as_unique_content` and `refuse_corpus_background_as_stopword_deletion` to cutoff-safe `corpus_background_v1` (`tepp.corpus_background.v1`) with inference status `corpus_background_is_not_unique_content_not_stopword_deletion`. `identity_recovery_rate` stays library-side. Not modality-source, not prompt-source, not style-source, not copy-identity, not a simulation method-effect census, not GPU, not MCMC, and not topic birth/split/merge. + - `event_core` adds bounded Allen interval-consistency classification, atomic path-consistency closure, contradiction/resource refusals, and an explicit dependency-error fallback without claiming unrestricted global satisfiability. - `psychometric_core` recovers the Driver, Oud, and Voelkle (2017, Table 2, p. 12 `MANIFESTTRAITVAR`; §7.1, p. 19; p. 16 `MANIFESTTRAITVARstd`; footnote 4; 2017-era ctsem `summary.ctsemFit.R`; JSS PDF re-opened 2026-08-27T14:20Z from https://www.jstatsoft.org/index.php/jss/article/download/v077i05/1104) scalar standardised manifest-trait variance on current main after `0ce16e8` dropped the pre-consolidation code while research notes already named the map (register items 83–84). Table 2 names `MANIFESTTRAITVAR` `Ψ_τ` the additional time-invariant variance-covariance on the measurement level and sets it `NULL` when there is no manifest trait. Equation 5 writes `Γ ~ N(τ, Ψ)` and names that covariance the manifest traits. Section 7.1 names manifest traits stable individual differences in indicator levels, distinct from process-level `TRAITVAR` `φ_ξ`. Page 16 prints standardised matrices with the suffix `std` when appropriate. The printed example on p. 16 is `discreteDRIFTstd`, not `MANIFESTTRAITVARstd`. Footnote 4 standardises using only the relevant variance, not the total. The relevant variance for that named indicator-level correlation is `MANIFESTTRAITVAR`, not process-level `TRAITVAR` and not residual `MANIFESTVAR` `θ`. The 2017-era source forms `MANIFESTTRAITVARstd` only when `MANIFESTTRAITVAR != 0`, as `solve(sqrt(diag(MANIFESTTRAITVAR) + ridging)) %&% MANIFESTTRAITVAR` when `verbose = TRUE`. OpenMx `%&%` is `t(A) %*% B %*% A`. Unlike `TRAITVARstd`, that formation adds `diag(c(ridging), n.manifest)`. The default `ridging = FALSE` adds 0, not `0.0001`; that ridge is a numerical hack and is not this exact map. The scalar correlation is `ψ / ψ = 1` after strictly positive `MANIFESTTRAITVAR`. Form strictly positive `ψ` first, then `1 / √ψ`, then `(1 / √ψ) ψ (1 / √ψ)`. Unstandardised `MANIFESTTRAITVAR` is defined for a zero trait; standardised `MANIFESTTRAITVAR` is not. Zero `MANIFESTTRAITVAR` skips forming `MANIFESTTRAITVARstd` in the 2017-era source and fails closed here. Indicator-level trait variance is an event-time structural quantity, so a non-event clock fails closed. `MANIFESTTRAITVAR` does not require stable `a < 0`. Distinct positive `ψ` recover the same 1. `trait / trait = 1` is `TRAITVARstd` and recovers the same number and remains a distinct named quantity. `θ` is `MANIFESTVAR` and is measurement error, not this correlation. Meredith (1993) remains unread (web search 2026-08-27T14:20Z: Springer/Cambridge Core paywalled; Unpaywall historically `is_oa: false`; Springer `content/pdf` is an HTML stub). Mislevy (1991, *Psychometrika, 56*, 177–196) remains unread on the same terms (DOI `10.1007/bf02294457`). Still not a Kalman filter, not a matrix `expm`, not ESEM estimation, not DSEM, and not ctsem estimation. diff --git a/Cargo.lock b/Cargo.lock index 454a7d612..1f3c4989a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -71,6 +71,7 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" name = "analysis_engine" version = "0.2.0" dependencies = [ + "corpus_background", "corpus_split", "event_core", "membership_core", diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 6fa4b9683..f43eced43 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -71,6 +71,7 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | Hourly NIM OpenCode doctoring | [`docs/doctoring/hourly-nim-opencode-development.md`](docs/doctoring/hourly-nim-opencode-development.md) | | Analysis engine v1 doctoring | [`docs/doctoring/analysis-engine-v1.md`](docs/doctoring/analysis-engine-v1.md) | | Analysis engine gap-closure doctoring | [`docs/doctoring/analysis-engine-gap-closure.md`](docs/doctoring/analysis-engine-gap-closure.md) | +| Corpus-background analysis-run doctoring | [`docs/doctoring/corpus-background-analysis-run.md`](docs/doctoring/corpus-background-analysis-run.md) | | Corpus-split leakage-audit wire doctoring | [`docs/research/corpus-split-manifest-wire.md`](docs/research/corpus-split-manifest-wire.md) | | Unicode canonical-identity doctoring | [`docs/research/unicode-canonical-identity.md`](docs/research/unicode-canonical-identity.md) | | Change history | [`CHANGELOG.md`](CHANGELOG.md) | diff --git a/crates/analysis_engine/Cargo.toml b/crates/analysis_engine/Cargo.toml index 7322212b2..c9f0612e3 100644 --- a/crates/analysis_engine/Cargo.toml +++ b/crates/analysis_engine/Cargo.toml @@ -21,9 +21,11 @@ sha2 = { workspace = true } tepp_api = { path = "../tepp_api", version = "0.2.0" } temporal_core = { path = "../temporal_core", version = "0.2.0" } topic_measurement = { path = "../topic_measurement", version = "0.2.0" } +corpus_background = { path = "../corpus_background", version = "0.2.0" } uuid.workspace = true [dev-dependencies] +corpus_background = { path = "../corpus_background", version = "0.2.0" } corpus_split = { path = "../corpus_split", version = "0.2.0" } membership_core = { path = "../membership_core", version = "0.2.0" } relation_graph = { path = "../relation_graph", version = "0.2.0" } diff --git a/crates/analysis_engine/src/corpus_background_artifact.rs b/crates/analysis_engine/src/corpus_background_artifact.rs new file mode 100644 index 000000000..16ea0544b --- /dev/null +++ b/crates/analysis_engine/src/corpus_background_artifact.rs @@ -0,0 +1,393 @@ +//! Digest-bound corpus-background refusals as an analysis-run profile. + +use corpus_background::{ + CorpusBackgroundError, CorpusBackgroundKind, refuse_corpus_background_as_stopword_deletion, + refuse_corpus_background_as_unique_content, +}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use temporal_core::KnowledgeCutoff; +use tepp_api::{ + AnalysisResultSummary, AnalysisRunAccepted, AnalysisRunRequest, AnalysisRunTerminalResult, +}; + +use crate::{AnalysisEngineError, format_digest, require_receipt_identity, valid_identifier}; + +/// Versioned schema for a completed corpus-background artifact. +pub const CORPUS_BACKGROUND_ARTIFACT_SCHEMA_VERSION: &str = "tepp.corpus_background.v1"; +/// Model contract required by the corpus-background execution path. +pub const CORPUS_BACKGROUND_MODEL_CONTRACT_VERSION: &str = "corpus_background_v1"; +/// Analysis-run output profile required for a corpus-background artifact. +pub const CORPUS_BACKGROUND_OUTPUT_PROFILE: &str = "corpus_background_v1"; +/// Maximum canonical artifact JSON size. +pub const CORPUS_BACKGROUND_ARTIFACT_BYTE_LIMIT: usize = 256 * 1024; +const CORPUS_BACKGROUND_INFERENCE_STATUS: &str = + "corpus_background_is_not_unique_content_not_stopword_deletion"; + +/// One cutoff-admitted token treatment with a closed corpus-background kind. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CorpusBackgroundDocument { + document_id: String, + kind: CorpusBackgroundKind, +} + +impl CorpusBackgroundDocument { + /// Construct a bounded corpus-background document. + /// + /// # Errors + /// + /// Returns [`AnalysisEngineError::InvalidEvidence`] when the document + /// identity is empty or oversized. + pub fn new( + document_id: impl Into, + kind: CorpusBackgroundKind, + ) -> Result { + let document_id = document_id.into(); + if !valid_identifier(&document_id) { + return Err(AnalysisEngineError::InvalidEvidence); + } + Ok(Self { document_id, kind }) + } + + /// Return the opaque document identity. + #[must_use] + pub fn document_id(&self) -> &str { + &self.document_id + } + + /// Return the closed corpus-background kind. + #[must_use] + pub const fn kind(&self) -> CorpusBackgroundKind { + self.kind + } +} + +/// Completed, bounded corpus-background census for analysis-run clients. +#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct CorpusBackgroundArtifact { + /// Exact versioned schema identity. + pub schema_version: String, + /// Opaque accepted-run identity. + pub run_id: String, + /// Immutable source snapshot identity. + pub snapshot_id: String, + /// Historical evidence cutoff used to admit documents. + pub knowledge_cutoff: String, + /// Number of documents admitted at the cutoff. + pub document_count: u64, + /// Unique-content treatments admitted at the cutoff. + pub unique_content_count: u64, + /// Corpus-background treatments admitted at the cutoff. + pub corpus_background_count: u64, + /// Corpus-background wording refused as unique latent content. + pub refused_as_unique_content_count: u64, + /// Corpus-background wording refused as stopword deletion. + pub refused_as_stopword_deletion_count: u64, + /// Fixed claim boundary for consumer copy. + pub inference_status: String, +} + +impl CorpusBackgroundArtifact { + /// Parse and fully validate a bounded artifact JSON payload. + /// + /// # Errors + /// + /// Returns [`AnalysisEngineError::InvalidCorpusBackgroundArtifact`] when + /// the schema, identifiers, counts, or claim boundary fail. + pub fn from_json(payload: &str) -> Result { + if payload.len() > CORPUS_BACKGROUND_ARTIFACT_BYTE_LIMIT { + return Err(AnalysisEngineError::LimitExceeded); + } + let artifact: Self = serde_json::from_str(payload) + .map_err(|_| AnalysisEngineError::InvalidCorpusBackgroundArtifact)?; + artifact.validate()?; + Ok(artifact) + } + + /// Serialize canonical validated artifact JSON. + /// + /// # Errors + /// + /// Returns a typed validation, serialization, or size failure. + pub fn to_json(&self) -> Result { + self.validate()?; + let payload = + serde_json::to_string(self).map_err(|_| AnalysisEngineError::SerializationFailure)?; + if payload.len() > CORPUS_BACKGROUND_ARTIFACT_BYTE_LIMIT { + return Err(AnalysisEngineError::LimitExceeded); + } + Ok(payload) + } + + /// Return the lowercase SHA-256 digest of canonical artifact JSON. + /// + /// # Errors + /// + /// Returns a typed validation or serialization failure. + pub fn sha256(&self) -> Result { + self.to_json() + .map(|json| format_digest(Sha256::digest(json.into_bytes()))) + } + + fn validate(&self) -> Result<(), AnalysisEngineError> { + let kind_sum = self + .unique_content_count + .checked_add(self.corpus_background_count); + if self.schema_version != CORPUS_BACKGROUND_ARTIFACT_SCHEMA_VERSION + || !valid_identifier(&self.run_id) + || !valid_identifier(&self.snapshot_id) + || KnowledgeCutoff::parse_rfc3339(&self.knowledge_cutoff).is_err() + || self.document_count < 2 + || self.unique_content_count == 0 + || self.corpus_background_count == 0 + || kind_sum != Some(self.document_count) + || self.refused_as_unique_content_count != self.corpus_background_count + || self.refused_as_stopword_deletion_count != self.corpus_background_count + || self.inference_status != CORPUS_BACKGROUND_INFERENCE_STATUS + { + return Err(AnalysisEngineError::InvalidCorpusBackgroundArtifact); + } + Ok(()) + } +} + +/// One completed corpus-background artifact and its terminal result. +#[derive(Clone, Debug, PartialEq)] +pub struct CorpusBackgroundExecution { + /// Digest-bound completed corpus-background census. + pub artifact: CorpusBackgroundArtifact, + /// Terminal result carrying the artifact identity, digest, and schema. + pub terminal_result: AnalysisRunTerminalResult, +} + +/// Execute cutoff-safe corpus-background refusals as one analysis-run profile. +/// +/// The executor invokes [`refuse_corpus_background_as_unique_content`] and +/// [`refuse_corpus_background_as_stopword_deletion`] already on protected +/// main. It does not emit `identity_recovery_rate`, a +/// `scientific_acceptance` inspect metric, GPU kernels, MCMC, or topic +/// birth/split/merge events. +/// +/// # Errors +/// +/// Returns a request/receipt/snapshot/cutoff/profile error, empty or +/// single-kind corpus, duplicate document identity, or invalid artifact error. +pub fn execute_corpus_background_run( + request: &AnalysisRunRequest, + accepted: &AnalysisRunAccepted, + snapshot_id: &str, + knowledge_cutoff: KnowledgeCutoff, + documents: &[CorpusBackgroundDocument], + completed_at: impl Into, +) -> Result { + request.to_json()?; + accepted.to_json()?; + require_receipt_identity(request, accepted)?; + if request.snapshot_id != snapshot_id { + return Err(AnalysisEngineError::SnapshotMismatch); + } + if request.knowledge_cutoff != knowledge_cutoff.to_rfc3339() + || request.model_contract_version != CORPUS_BACKGROUND_MODEL_CONTRACT_VERSION + || request.output_profile != CORPUS_BACKGROUND_OUTPUT_PROFILE + { + return Err(AnalysisEngineError::InvalidEvidence); + } + + let mut seen = std::collections::BTreeSet::new(); + let mut unique_content_count = 0_u64; + let mut corpus_background_count = 0_u64; + let mut refused_as_unique_content_count = 0_u64; + let mut refused_as_stopword_deletion_count = 0_u64; + for document in documents { + if !seen.insert(document.document_id()) { + return Err(AnalysisEngineError::DuplicateEvidence); + } + match document.kind() { + CorpusBackgroundKind::UniqueContent => { + refuse_corpus_background_as_unique_content(document.kind()) + .map_err(map_background_error)?; + refuse_corpus_background_as_stopword_deletion(document.kind()) + .map_err(map_background_error)?; + unique_content_count = unique_content_count + .checked_add(1) + .ok_or(AnalysisEngineError::ArithmeticOverflow)?; + } + CorpusBackgroundKind::CorpusBackground => { + match refuse_corpus_background_as_unique_content(document.kind()) { + Err(CorpusBackgroundError::CorpusBackgroundIsNotUniqueContent) => { + refused_as_unique_content_count = refused_as_unique_content_count + .checked_add(1) + .ok_or(AnalysisEngineError::ArithmeticOverflow)?; + } + Ok(()) | Err(_) => return Err(AnalysisEngineError::InvalidEvidence), + } + match refuse_corpus_background_as_stopword_deletion(document.kind()) { + Err(CorpusBackgroundError::CorpusBackgroundIsNotStopwordDeletion) => { + refused_as_stopword_deletion_count = refused_as_stopword_deletion_count + .checked_add(1) + .ok_or(AnalysisEngineError::ArithmeticOverflow)?; + } + Ok(()) | Err(_) => return Err(AnalysisEngineError::InvalidEvidence), + } + corpus_background_count = corpus_background_count + .checked_add(1) + .ok_or(AnalysisEngineError::ArithmeticOverflow)?; + } + } + } + let document_count = + u64::try_from(documents.len()).map_err(|_| AnalysisEngineError::ArithmeticOverflow)?; + if document_count < 2 || unique_content_count == 0 || corpus_background_count == 0 { + return Err(AnalysisEngineError::InvalidEvidence); + } + + let artifact = CorpusBackgroundArtifact { + schema_version: CORPUS_BACKGROUND_ARTIFACT_SCHEMA_VERSION.into(), + run_id: accepted.run_id.clone(), + snapshot_id: snapshot_id.to_owned(), + knowledge_cutoff: knowledge_cutoff.to_rfc3339(), + document_count, + unique_content_count, + corpus_background_count, + refused_as_unique_content_count, + refused_as_stopword_deletion_count, + inference_status: CORPUS_BACKGROUND_INFERENCE_STATUS.into(), + }; + let digest = artifact.sha256()?; + let summary = AnalysisResultSummary::new( + "corpus_background", + document_count, + 4, + CORPUS_BACKGROUND_INFERENCE_STATUS, + )?; + let terminal_result = AnalysisRunTerminalResult::succeeded( + request, + accepted, + format!("corpus_background_artifact_{}", &digest[..16]), + digest, + CORPUS_BACKGROUND_ARTIFACT_SCHEMA_VERSION, + completed_at, + summary, + )?; + Ok(CorpusBackgroundExecution { + artifact, + terminal_result, + }) +} + +fn map_background_error(error: CorpusBackgroundError) -> AnalysisEngineError { + match error { + CorpusBackgroundError::CorpusBackgroundIsNotUniqueContent + | CorpusBackgroundError::CorpusBackgroundIsNotStopwordDeletion + | CorpusBackgroundError::InvalidCorpusBackgroundPayload + | _ => AnalysisEngineError::InvalidEvidence, + } +} + +#[cfg(test)] +mod tests { + use super::{ + CORPUS_BACKGROUND_ARTIFACT_BYTE_LIMIT, CORPUS_BACKGROUND_ARTIFACT_SCHEMA_VERSION, + CORPUS_BACKGROUND_INFERENCE_STATUS, CorpusBackgroundArtifact, + }; + use crate::AnalysisEngineError; + + fn artifact() -> CorpusBackgroundArtifact { + CorpusBackgroundArtifact { + schema_version: CORPUS_BACKGROUND_ARTIFACT_SCHEMA_VERSION.into(), + run_id: "run-1".into(), + snapshot_id: "snapshot-1".into(), + knowledge_cutoff: "2026-08-01T00:00:00Z".into(), + document_count: 3, + unique_content_count: 1, + corpus_background_count: 2, + refused_as_unique_content_count: 2, + refused_as_stopword_deletion_count: 2, + inference_status: CORPUS_BACKGROUND_INFERENCE_STATUS.into(), + } + } + + fn assert_invalid(artifact: &CorpusBackgroundArtifact) { + assert_eq!( + artifact.to_json(), + Err(AnalysisEngineError::InvalidCorpusBackgroundArtifact) + ); + } + + #[test] + fn artifact_round_trip_and_size_bounds_fail_closed() { + let artifact = artifact(); + let payload = artifact.to_json().expect("json"); + assert_eq!( + CorpusBackgroundArtifact::from_json(&payload), + Ok(artifact.clone()) + ); + assert_eq!(artifact.sha256().expect("digest").len(), 64); + assert_eq!( + CorpusBackgroundArtifact::from_json("{}"), + Err(AnalysisEngineError::InvalidCorpusBackgroundArtifact) + ); + assert_eq!( + CorpusBackgroundArtifact::from_json( + &"x".repeat(CORPUS_BACKGROUND_ARTIFACT_BYTE_LIMIT + 1) + ), + Err(AnalysisEngineError::LimitExceeded) + ); + } + + #[test] + fn artifact_metadata_tampering_fails_closed() { + let artifact = artifact(); + let invalid_artifacts = [ + { + let mut value = artifact.clone(); + value.schema_version.clear(); + value + }, + { + let mut value = artifact.clone(); + value.run_id.clear(); + value + }, + { + let mut value = artifact.clone(); + value.snapshot_id.clear(); + value + }, + { + let mut value = artifact.clone(); + value.knowledge_cutoff = "invalid".into(); + value + }, + { + let mut value = artifact.clone(); + value.document_count = 1; + value + }, + { + let mut value = artifact.clone(); + value.unique_content_count = 0; + value + }, + { + let mut value = artifact.clone(); + value.corpus_background_count = 0; + value + }, + { + let mut value = artifact.clone(); + value.refused_as_unique_content_count = 1; + value + }, + { + let mut value = artifact.clone(); + value.inference_status.clear(); + value + }, + ]; + for invalid in invalid_artifacts { + assert_invalid(&invalid); + } + } +} diff --git a/crates/analysis_engine/src/lib.rs b/crates/analysis_engine/src/lib.rs index 72bd5854c..cb5cd0d4b 100644 --- a/crates/analysis_engine/src/lib.rs +++ b/crates/analysis_engine/src/lib.rs @@ -11,6 +11,7 @@ //! contracts and preserves their artifact meaning. mod case_deletion_refit; +mod corpus_background_artifact; mod lineage_criterion; mod topic_context_posterior; mod topic_lineage_artifact; @@ -41,6 +42,13 @@ pub use case_deletion_refit::ExhaustiveCaseDeletionError; pub use case_deletion_refit::ExhaustiveCaseDeletionFits; /// Fit the full corpus and every actual one-document deletion. pub use case_deletion_refit::fit_exhaustive_case_deletion; +/// Corpus-background artifact and execution contracts from this engine. +pub use corpus_background_artifact::{ + CORPUS_BACKGROUND_ARTIFACT_BYTE_LIMIT, CORPUS_BACKGROUND_ARTIFACT_SCHEMA_VERSION, + CORPUS_BACKGROUND_MODEL_CONTRACT_VERSION, CORPUS_BACKGROUND_OUTPUT_PROFILE, + CorpusBackgroundArtifact, CorpusBackgroundDocument, CorpusBackgroundExecution, + execute_corpus_background_run, +}; /// Rust-owned independent TDT link-criterion posterior fitting contracts. pub use lineage_criterion::{ LineageCriterionFit, LineageCriterionFitError, LineageCriterionObservation, @@ -248,6 +256,8 @@ pub enum AnalysisEngineError { TopicMeasurement(TopicMeasurementError), /// A topic-lineage artifact violated its bounded schema or count invariants. InvalidTopicLineageArtifact, + /// A corpus-background artifact violated its bounded schema or count invariants. + InvalidCorpusBackgroundArtifact, } impl fmt::Display for AnalysisEngineError { @@ -262,6 +272,7 @@ impl fmt::Display for AnalysisEngineError { Self::LimitExceeded => "analysis corpus exceeded its execution bound", Self::TopicMeasurement(error) => return error.fmt(formatter), Self::InvalidTopicLineageArtifact => "invalid topic lineage artifact", + Self::InvalidCorpusBackgroundArtifact => "invalid corpus-background artifact", }; formatter.write_str(message) } @@ -681,6 +692,10 @@ mod tests { AnalysisEngineError::InvalidTopicLineageArtifact, "invalid topic lineage artifact", ), + ( + AnalysisEngineError::InvalidCorpusBackgroundArtifact, + "invalid corpus-background artifact", + ), ]; for (error, message) in messages { assert_eq!(error.to_string(), message); diff --git a/crates/analysis_engine/tests/corpus_background_execution_contract.rs b/crates/analysis_engine/tests/corpus_background_execution_contract.rs new file mode 100644 index 000000000..027595e47 --- /dev/null +++ b/crates/analysis_engine/tests/corpus_background_execution_contract.rs @@ -0,0 +1,194 @@ +//! End-to-end contract for cutoff-safe corpus-background refusals. + +use analysis_engine::{ + AnalysisEngineError, CORPUS_BACKGROUND_ARTIFACT_SCHEMA_VERSION, + CORPUS_BACKGROUND_MODEL_CONTRACT_VERSION, CORPUS_BACKGROUND_OUTPUT_PROFILE, + CorpusBackgroundDocument, execute_corpus_background_run, +}; +use corpus_background::CorpusBackgroundKind; +use temporal_core::KnowledgeCutoff; +use tepp_api::{AnalysisRunAccepted, AnalysisRunRequest, AnalysisRunTerminalState}; + +fn cutoff() -> KnowledgeCutoff { + KnowledgeCutoff::parse_rfc3339("2026-08-01T00:00:00Z").expect("cutoff") +} + +fn request() -> AnalysisRunRequest { + AnalysisRunRequest { + contract_version: 1, + idempotency_key: "corpus-background-idem".into(), + tenant_workspace_id: "tenant-workspace".into(), + snapshot_id: "snapshot-corpus-background".into(), + knowledge_cutoff: "2026-08-01T00:00:00Z".into(), + model_contract_version: CORPUS_BACKGROUND_MODEL_CONTRACT_VERSION.into(), + output_profile: CORPUS_BACKGROUND_OUTPUT_PROFILE.into(), + } +} + +fn accepted(request: &AnalysisRunRequest) -> AnalysisRunAccepted { + AnalysisRunAccepted::new( + "run-corpus-background", + "accepted", + &request.idempotency_key, + ) + .expect("accepted") +} + +fn mixed_documents() -> Vec { + vec![ + CorpusBackgroundDocument::new("unique-a", CorpusBackgroundKind::UniqueContent) + .expect("unique"), + CorpusBackgroundDocument::new("bg-b", CorpusBackgroundKind::CorpusBackground) + .expect("background"), + CorpusBackgroundDocument::new("bg-c", CorpusBackgroundKind::CorpusBackground) + .expect("background"), + ] +} + +fn execute( + request: &AnalysisRunRequest, + documents: &[CorpusBackgroundDocument], +) -> Result { + execute_corpus_background_run( + request, + &accepted(request), + "snapshot-corpus-background", + cutoff(), + documents, + "2026-08-02T00:00:00Z", + ) +} + +#[test] +fn mixed_background_kinds_emit_digest_bound_refusals_without_recovery_metric() { + let request = request(); + let execution = execute(&request, &mixed_documents()).expect("execution"); + assert_eq!( + execution.artifact.schema_version, + CORPUS_BACKGROUND_ARTIFACT_SCHEMA_VERSION + ); + assert_eq!(execution.artifact.document_count, 3); + assert_eq!(execution.artifact.unique_content_count, 1); + assert_eq!(execution.artifact.corpus_background_count, 2); + assert_eq!(execution.artifact.refused_as_unique_content_count, 2); + assert_eq!(execution.artifact.refused_as_stopword_deletion_count, 2); + assert_eq!( + execution.artifact.inference_status, + "corpus_background_is_not_unique_content_not_stopword_deletion" + ); + let payload = execution.artifact.to_json().expect("json"); + assert!(!payload.contains("identity_recovery_rate")); + assert!(!payload.contains("scientific_acceptance")); + assert_eq!( + execution.terminal_result.run_state, + AnalysisRunTerminalState::Succeeded + ); + assert_eq!( + execution.terminal_result.result_sha256.as_deref(), + Some(execution.artifact.sha256().expect("digest").as_str()) + ); + assert_eq!( + execution.terminal_result.result_schema_version.as_deref(), + Some(CORPUS_BACKGROUND_ARTIFACT_SCHEMA_VERSION) + ); +} + +#[test] +fn empty_unique_only_background_only_and_duplicate_identities_fail_closed() { + let request = request(); + assert_eq!( + execute(&request, &[]), + Err(AnalysisEngineError::InvalidEvidence) + ); + let unique_only = vec![ + CorpusBackgroundDocument::new("unique-a", CorpusBackgroundKind::UniqueContent) + .expect("unique"), + CorpusBackgroundDocument::new("unique-b", CorpusBackgroundKind::UniqueContent) + .expect("unique"), + ]; + assert_eq!( + execute(&request, &unique_only), + Err(AnalysisEngineError::InvalidEvidence) + ); + let background_only = vec![ + CorpusBackgroundDocument::new("bg-a", CorpusBackgroundKind::CorpusBackground) + .expect("background"), + CorpusBackgroundDocument::new("bg-b", CorpusBackgroundKind::CorpusBackground) + .expect("background"), + ]; + assert_eq!( + execute(&request, &background_only), + Err(AnalysisEngineError::InvalidEvidence) + ); + let duplicates = vec![ + CorpusBackgroundDocument::new("same", CorpusBackgroundKind::UniqueContent).expect("unique"), + CorpusBackgroundDocument::new("same", CorpusBackgroundKind::CorpusBackground) + .expect("background"), + ]; + assert_eq!( + execute(&request, &duplicates), + Err(AnalysisEngineError::DuplicateEvidence) + ); + assert_eq!( + CorpusBackgroundDocument::new("", CorpusBackgroundKind::UniqueContent), + Err(AnalysisEngineError::InvalidEvidence) + ); +} + +#[test] +fn execution_refuses_snapshot_profile_and_cutoff_mismatch() { + let request = request(); + let documents = mixed_documents(); + assert_eq!( + execute_corpus_background_run( + &request, + &accepted(&request), + "other-snapshot", + cutoff(), + &documents, + "2026-08-02T00:00:00Z", + ), + Err(AnalysisEngineError::SnapshotMismatch) + ); + let mut mismatched = request.clone(); + mismatched.knowledge_cutoff = "2026-07-01T00:00:00Z".into(); + assert_eq!( + execute_corpus_background_run( + &mismatched, + &accepted(&mismatched), + "snapshot-corpus-background", + cutoff(), + &documents, + "2026-08-02T00:00:00Z", + ), + Err(AnalysisEngineError::InvalidEvidence) + ); + for profile in [ + "trsl_topic_lineage_v1", + "fitted_candidate_k_v1", + "pareto_candidate_k_v1", + "joint_posterior_draws_v1", + "method_effects_v1", + "copy_identity_v1", + "style_source_v1", + "prompt_source_v1", + "modality_source_v1", + "composed_fitted_lineage_v1", + "case_deletion_refit_v1", + "topic_activity_v1", + ] { + let mut reused = request.clone(); + reused.output_profile = profile.into(); + assert_eq!( + execute_corpus_background_run( + &reused, + &accepted(&reused), + "snapshot-corpus-background", + cutoff(), + &documents, + "2026-08-02T00:00:00Z", + ), + Err(AnalysisEngineError::InvalidEvidence) + ); + } +} diff --git a/docs/TRACEABILITY.md b/docs/TRACEABILITY.md index 2b783c2ab..a2420db3d 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -58,6 +58,7 @@ The full APA 7th standards/literature register remains `docs/research/standards- | versioned service/API contracts and exports | PRD; API contract; ADR 0011/0013 | `tepp_api` analysis-run/export/JSON-LD/GraphML contracts on protected main (PR #21); HTTP service remaining accepted-target | partial | | versioned service/API contracts and exports | PRD; API contract; ADR 0011/0013 | `tepp_api` analysis-run/export/JSON-LD/GraphML contracts on protected main (PR #21); LineageWeave loopback contracts and request-bound terminal result are composed on the active product branch; production TLS remaining | partial | | executable cutoff-safe analysis runs | ADR 0012/0022; temporal research; API terminal-result contract | `analysis_engine` availability cutoff, snapshot binding, multiple-membership aggregation, digest-bound readiness artifact, and `tepp.trsl_topic_lineage.v1` execution through `topic_measurement`; synthetic recovery plus tamper/non-convergence tests and exact coverage on the active product branch | active-PR | +| corpus-background analysis-run profile | ADR 0004/0012/0022/0062; CorpusBackgroundKind CorpusBackground/UniqueContent | `analysis_engine` `corpus_background_v1` binds `refuse_corpus_background_as_unique_content` and `refuse_corpus_background_as_stopword_deletion`; digest-bound refusals, not `identity_recovery_rate` inspect metric, not GPU, not MCMC, not topic birth/split/merge; not implemented-main | active-PR | | immutable split/run/reproducibility manifests | ADR 0013; ERD | `tepp_api` reproducibility manifest contract on protected main; `persistence_postgres` append-only SQL insert/lookup for `reproducibility_manifest`, `corpus_split_manifest`, `model_run`, and `model_artifact` (migration `0003`); full physical ERD constraints remaining | partial | | multilingual shared latent semantic space | PRD; ADR 0004; ADR 0020 | `semantic_core` span-grounded units (active-PR); concept dictionary and shared latent estimator remaining | active-PR | | TRSL-TM temporal/relational topic posterior and backend compatibility | ADR 0012; ADR 0004 | `topic_measurement` stable ALR/ILR coordinates and bounded CPU `f64` reference estimator on protected main; `model_selection` fitted candidate-`K` scoring on this PR; calibrated posterior promotion, method effects, persistence, and accelerated backends remaining | partial | diff --git a/docs/adr/0062-corpus-background-analysis-run.md b/docs/adr/0062-corpus-background-analysis-run.md new file mode 100644 index 000000000..607283d20 --- /dev/null +++ b/docs/adr/0062-corpus-background-analysis-run.md @@ -0,0 +1,83 @@ +# ADR 0062 — Corpus-background refusals as an analysis-run output profile + +**Decision status:** Accepted +**Implementation maturity:** active-PR — composed on this branch; not implemented-main +**Date:** 2026-08-31 +**Supersedes:** None; complements ADR 0004/0012 (corpus-background wording is not unique content) and ADR 0022 (cutoff-safe analysis-run execution). Does not reuse ADR 0061 (modality-source), ADR 0060 (prompt-source), ADR 0059 (style-source), ADR 0058 (copy-identity), or ADR 0057 (simulation method-effect census). +**Figma File ID:** N/A — this increment changes a Rust service crate and has no user-interface surface. +**Storybook inventory:** N/A — no reusable web object or interaction changed. + +## Context + +Protected main already refuses to treat corpus-background wording as unique +latent content or as stopword deletion via +`corpus_background::refuse_corpus_background_as_unique_content` and +`refuse_corpus_background_as_stopword_deletion`. Operators still cannot +request that refusal census as a digest-bound analysis-run output. +Modality-source refusals (#421 / ADR 0061) bind `ModalityKind` and do not +replace `corpus_background`. + +`identity_recovery_rate` stays library-side. This slice does not put a +`scientific_acceptance` metric on inspect payloads. + +GPU kernels, MCMC, and topic birth/split/merge remain later GAP-004 work +and are not this slice. + +## Decision + +Add the `corpus_background_v1` analysis-run output profile to +`analysis_engine`. The executor: + +- consumes already-validated `CorpusBackgroundDocument` rows with closed + `CorpusBackgroundKind` values; +- requires the request snapshot and knowledge cutoff to match the offered + input construction; +- invokes `refuse_corpus_background_as_unique_content` and + `refuse_corpus_background_as_stopword_deletion` without reimplementing + the background/content vocabulary; +- emits a canonical SHA-256-digested `tepp.corpus_background.v1` artifact + with unique-content/corpus-background counts, matching refusal counts, + and inference status + `corpus_background_is_not_unique_content_not_stopword_deletion`; +- does not emit `identity_recovery_rate`, invent MCMC, select GPU + backends, or emit topic birth/split/merge events. + +## Alternatives considered + +1. Duplicate modality-source refusals (#421) — rejected because that + profile binds `ModalityKind` NonLexicalModality/UniqueContent and does + not bind `corpus_background`. +2. Put `identity_recovery_rate` on the operator artifact — rejected + because inspect payloads stay metric-free and + `tepp.scientific_acceptance.v1` never appears. +3. Bind the existing corpus-background refusals to ADR 0022's analysis-run + profile — accepted. + +## Consequences + +Operators can request cutoff-safe corpus-background refusals as a +digest-bound terminal result. The artifact does not claim MCMC, GPU +parity, modality-source, prompt-source, style-source, copy-identity, +method-effect estimation, or topic birth/split/merge. +Snapshot/profile/cutoff mismatch, empty or single-kind corpora, and +duplicate document identities fail closed. + +## Verification + +The PR includes Rust unit and integration tests for mixed unique/background +corpora, empty/unique-only/background-only/duplicate refusal, snapshot / +profile / cutoff mismatch, and artifact tampering. Run: + +```text +cargo fmt --all -- --check +cargo test -p analysis_engine +cargo clippy -p analysis_engine --all-targets -- -D warnings +python3 scripts/validate_documentation.py +``` + +## Rollback and supersession + +Rollback removes the `corpus_background_v1` profile. No persisted schema +migration is introduced. Supersede only with an ADR that keeps +corpus-background wording distinct from modality-source refusals and from +`identity_recovery_rate` inspect metrics. diff --git a/docs/adr/README.md b/docs/adr/README.md index 1254c8079..6f1fb7cbb 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -30,6 +30,7 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio | [0022](0022-deterministic-analysis-run-execution.md) | Deterministic cutoff-safe analysis-run execution | Accepted | active-PR | Closes the first executable product path from accepted run to digest-bound terminal result without claiming estimator authority. | | [0024](0024-lineage-pair-criterion-and-project-journey-posterior.md) | Independent Event Lineage pair criterion and posterior Project Journey | Proposed | active-PR | Strict artifacts preserve criterion/event-time draws, branches, ties, and CPU/GPU receipts without claiming the scientific estimator is complete. | | [0025](0025-macos-native-rust-mlx-metal-boundary.md) | macOS-native Rust-owned MLX Metal execution | Accepted | accepted-target | Compose authenticates to a native host service; Linux never claims Metal, and actual backend/parity receipts fail closed. | +| [0062](0062-corpus-background-analysis-run.md) | Corpus-background refusals as an analysis-run profile | Accepted | active-PR | Complements ADR 0004/0012/0022; `refuse_corpus_background_as_unique_content` + `refuse_corpus_background_as_stopword_deletion`, not modality-source. | | [0023](0023-lineage-criterion-anchor-contract.md) | TEPP-owned Event Lineage criterion anchor | Accepted | active-PR | PR #237 publishes the strict accepted/rejected artifact and identities; estimator execution remains fail-closed future work. | | [0024](0024-independent-topic-importance-anchor.md) | Posterior topic-context producer contract | Accepted | contract-only active-PR | Strict DTO/schema only; the current estimator does not emit it. fast-mlsirm owns case-deletion influence. | | [0001](0001-rust-first-modular-msa.md) | Rust-first numerical core and CPU `f64` reference | Accepted | partial | ADR 0011 owns cross-service/MSA authority; 0001 retains numerical/backend authority. | @@ -138,6 +139,7 @@ Use the narrowest owning ADR when decisions overlap: - **project-history wire-size symmetry:** ADR 0019. - **LineageWeave project-history service boundary:** ADR 0021. - **accepted-run execution and terminal artifact production:** ADR 0022. +- **corpus-background analysis-run profile:** ADR 0062. - **independent lineage criterion and posterior Project Journey:** ADR 0023. - **macOS-native Rust-owned MLX Metal execution:** ADR 0024. diff --git a/docs/doctoring/corpus-background-analysis-run.md b/docs/doctoring/corpus-background-analysis-run.md new file mode 100644 index 000000000..802f35502 --- /dev/null +++ b/docs/doctoring/corpus-background-analysis-run.md @@ -0,0 +1,16 @@ +# Corpus-background analysis-run composition + +**Active slice:** ADR 0062 / `corpus_background_v1` +**Protected-main status:** not implemented-main + +`corpus_background` already refuses to treat corpus-level background +wording as unique latent content or as stopword deletion. This slice +binds those refusals to a cutoff-safe analysis-run profile so operators +can request a digest-bound identity artifact. + +The artifact inference status is +`corpus_background_is_not_unique_content_not_stopword_deletion`. +`identity_recovery_rate` stays library-side. This is not a modality-source +census, not prompt-source, not style-source, not copy-identity, not a +simulation method-effect census, not GPU, not MCMC, and not topic +birth/split/merge.