Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/analysis_engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ categories.workspace = true
publish = false

[dependencies]
event_core = { path = "../event_core", version = "0.2.0" }
serde = { workspace = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
Expand Down
6 changes: 6 additions & 0 deletions crates/analysis_engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
//! estimation authority; it invokes estimators through their scientific crate
//! contracts and preserves their artifact meaning.

mod lineage_criterion;
mod topic_lineage_artifact;

use serde::Serialize;
Expand All @@ -24,6 +25,11 @@ use tepp_api::{
};
use topic_measurement::TopicMeasurementError;

/// Rust-owned independent TDT link-criterion posterior fitting contracts.
pub use lineage_criterion::{
LineageCriterionFit, LineageCriterionFitError, LineageCriterionObservation,
fit_lineage_criterion_posteriors,
};
/// Topic-lineage artifact and execution contracts from this engine.
pub use topic_lineage_artifact::{
TOPIC_LINEAGE_ARTIFACT_BYTE_LIMIT, TOPIC_LINEAGE_ARTIFACT_SCHEMA_VERSION,
Expand Down
113 changes: 113 additions & 0 deletions crates/analysis_engine/src/lineage_criterion.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
//! Rust-owned posterior fitting for independently observed TDT link criteria.
//!
//! This slice fits the identified independent criterion probability. Event-time
//! draws remain producer evidence from the temporal model; it does not infer a
//! date from record order or promote CHRONOS predictions to observed facts.

use std::collections::BTreeSet;

use event_core::{
CriterionPosteriorError, IndependentCriterionCounts, fit_independent_criterion_posterior,
};

/// Independent criterion counts and temporal draws for one exact pair.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct LineageCriterionObservation {
/// Opaque exact pair identity.
pub pair_id: String,
/// Independently observed positive TDT link outcomes.
pub successes: u32,
/// Total independently observed TDT link outcomes.
pub trials: u32,
/// Predecessor event-time draws supplied by the temporal model.
pub predecessor_event_time_draws: Vec<String>,
/// Successor event-time draws supplied by the temporal model.
pub successor_event_time_draws: Vec<String>,
}

/// Identified posterior output for one exact pair.
#[derive(Clone, Debug, PartialEq)]
pub struct LineageCriterionFit {
/// Opaque exact pair identity.
pub pair_id: String,
/// Jeffreys posterior mean.
pub posterior_mean: f64,
/// Jeffreys posterior variance.
pub posterior_variance: f64,
/// Deterministic posterior quadrature draws.
pub criterion_draws: Vec<f64>,
/// Unmodified predecessor event-time draws.
pub predecessor_event_time_draws: Vec<String>,
/// Unmodified successor event-time draws.
pub successor_event_time_draws: Vec<String>,
}

/// Fail-closed independent criterion fitting errors.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LineageCriterionFitError {
/// No exact pair was supplied.
EmptyInput,
/// Pair identity was empty, padded, too long, or duplicated.
InvalidPairIdentity,
/// Event-time draw counts differ from the requested common draw count.
TemporalDrawMismatch,
/// The independently identified scientific estimator rejected the input.
Criterion(CriterionPosteriorError),
}

/// Fit independent TDT link-criterion posteriors without local weights.
///
/// Input order is preserved. Temporal draws are carried without alteration;
/// record creation timestamps and nearest dates are never substituted.
///
/// # Errors
///
/// Fails closed for empty or duplicate pair identities, mixed draw counts, or
/// invalid independent criterion observations.
pub fn fit_lineage_criterion_posteriors(
observations: &[LineageCriterionObservation],
draw_count: usize,
) -> Result<Vec<LineageCriterionFit>, LineageCriterionFitError> {
if observations.is_empty() {
return Err(LineageCriterionFitError::EmptyInput);
}
let identities = observations
.iter()
.map(|observation| observation.pair_id.as_str())
.collect::<BTreeSet<_>>();
if identities.len() != observations.len()
|| observations.iter().any(|observation| {
observation.pair_id.is_empty()
|| observation.pair_id.len() > 256
|| observation.pair_id.trim() != observation.pair_id
})
{
return Err(LineageCriterionFitError::InvalidPairIdentity);
}
observations
.iter()
.map(|observation| {
if observation.predecessor_event_time_draws.len() != draw_count
|| observation.successor_event_time_draws.len() != draw_count
{
return Err(LineageCriterionFitError::TemporalDrawMismatch);
}
let posterior = fit_independent_criterion_posterior(
IndependentCriterionCounts {
successes: observation.successes,
trials: observation.trials,
},
draw_count,
)
.map_err(LineageCriterionFitError::Criterion)?;
Comment on lines +87 to +102

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 Info: Event-time and criterion draw counts share one parameter

fit_lineage_criterion_posteriors uses a single draw_count both to require that the event-time draw arrays have that length and as the criterion quadrature point count. The doc calls it a 'common draw count', so callers cannot request different sizes for the two.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Ok(LineageCriterionFit {
pair_id: observation.pair_id.clone(),
posterior_mean: posterior.mean,
posterior_variance: posterior.variance,
criterion_draws: posterior.plausible_values,
predecessor_event_time_draws: observation.predecessor_event_time_draws.clone(),
successor_event_time_draws: observation.successor_event_time_draws.clone(),
})
})
.collect()
}
72 changes: 72 additions & 0 deletions crates/analysis_engine/tests/lineage_criterion_estimator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
//! Deterministic recovery and fail-closed tests for the Rust criterion path.

use analysis_engine::{
LineageCriterionFitError, LineageCriterionObservation, fit_lineage_criterion_posteriors,
};
use event_core::CriterionPosteriorError;

fn observation(pair_id: &str, successes: u32, trials: u32) -> LineageCriterionObservation {
LineageCriterionObservation {
pair_id: pair_id.into(),
successes,
trials,
predecessor_event_time_draws: vec!["2026-01-01T00:00:00Z".into(); 32],
successor_event_time_draws: vec!["2026-01-02T00:00:00Z".into(); 32],
}
}

#[test]
fn rust_path_recovers_known_independent_pair_probabilities() {
let truth_counts = [
(0.1_f64, 1_000_u32),
(0.25, 2_500),
(0.5, 5_000),
(0.75, 7_500),
(0.9, 9_000),
];
let observations = truth_counts
.iter()
.enumerate()
.map(|(index, (_, successes))| observation(&format!("pair-{index}"), *successes, 10_000))
.collect::<Vec<_>>();
let fits = fit_lineage_criterion_posteriors(&observations, 32).expect("identified fits");
let rmse = fits
.iter()
.zip(truth_counts)
.map(|(fit, (truth, _))| (fit.posterior_mean - truth).powi(2))
.sum::<f64>()
/ 5.0;
assert!(rmse.sqrt() < 0.000_05);
assert_eq!(
fits[0].predecessor_event_time_draws,
observations[0].predecessor_event_time_draws
);
}

#[test]
fn rust_path_rejects_identity_draw_and_criterion_failures() {
assert_eq!(
fit_lineage_criterion_posteriors(&[], 32),
Err(LineageCriterionFitError::EmptyInput)
);

let duplicate = vec![observation("pair", 1, 2), observation("pair", 1, 2)];
assert_eq!(
fit_lineage_criterion_posteriors(&duplicate, 32),
Err(LineageCriterionFitError::InvalidPairIdentity)
);

let mut mixed = observation("pair", 1, 2);
mixed.successor_event_time_draws.pop();
assert_eq!(
fit_lineage_criterion_posteriors(&[mixed], 32),
Err(LineageCriterionFitError::TemporalDrawMismatch)
);

assert_eq!(
fit_lineage_criterion_posteriors(&[observation("pair", 3, 2)], 32),
Err(LineageCriterionFitError::Criterion(
CriterionPosteriorError::SuccessesExceedTrials
))
);
}
Loading
Loading