Skip to content
Closed
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 ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ boundaries above remain the target modular MSA architecture.
| `tepp_simulation` | known-truth temporal/event data generation |
| `validation_core` | RMSE, bias, coverage, graph, and Monte Carlo metrics |
| `tepp_api` | versioned DTO, schema, and export contracts |
| `measurement_invariance` | configural/metric/scalar status; loading RMSE; no shared meaning from configural only |

No crate exposes placeholder production behavior in Task 1. This prevents an
empty façade from becoming a de facto public API before its invariants and tests
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ All notable changes to TEPP are documented here. The format follows Keep a Chang

### Added

- `measurement_invariance` explicit invariance status: configural structure cannot license shared metric meaning; metric and scalar status may; recovered group loadings match known truth with lower computed RMSE than a crossed-language collapse.
- `persistence_postgres` concurrent document-write stress: atomic revise `DO` block that requires exactly one open `system_to` close, SQLSTATE mapping onto `ConcurrentWriteConflict` / `DuplicateDocumentRecord`, and live multi-session insert/revise/append-only proofs. No new migration number.
- `tepp_api` naruon HTTP interchange: versioned `https` POST contracts for analysis-run create and modular export authorization that refuse table-access URLs, review/Copilot credential headers, reserved standard-header redefinition, principal-only export idempotency keys, and lexical inference claims (ADR 0011).
- `persistence_postgres` audit-event SQL contracts: append-only insert that refuses empty, oversized, or hostile `action_code` values before SQL is rendered.
Expand Down
4 changes: 4 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ members = [
"crates/tepp_simulation",
"crates/validation_core",
"crates/tepp_api",
"crates/measurement_invariance",
]
default-members = [
"crates/evidence_core",
Expand All @@ -23,6 +24,7 @@ default-members = [
"crates/tepp_simulation",
"crates/validation_core",
"crates/tepp_api",
"crates/measurement_invariance",
]

[workspace.package]
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ implemented in Rust.
## Current implementation state

This branch establishes the Task 1 Rust workspace and quality-gate foundation.
The ten bounded crates compile independently but intentionally expose no
The eleven bounded crates compile independently but intentionally expose no
placeholder production APIs. Domain behavior begins in Task 2 with immutable
evidence identifiers and source records.

Expand All @@ -22,6 +22,7 @@ crates/corpus_split
crates/tepp_simulation
crates/validation_core
crates/tepp_api
crates/measurement_invariance
```

## Local verification
Expand Down
17 changes: 17 additions & 0 deletions crates/measurement_invariance/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "measurement_invariance"
description = "Explicit invariance status gates and group-loading RMSE."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
homepage.workspace = true
readme.workspace = true
keywords.workspace = true
categories.workspace = true
publish = false

[lints]
workspace = true
53 changes: 53 additions & 0 deletions crates/measurement_invariance/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//! Fail-closed measurement-invariance errors.

use std::fmt;

/// A fail-closed measurement-invariance error.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum InvarianceError {
/// A weaker invariance status was treated as shared metric meaning.
InvarianceTooWeakForSharedMeaning,
/// An unknown invariance-status wire name was supplied.
UnknownInvarianceLevel,
/// Loading slices were empty, length-mismatched, or non-finite.
InvalidLoadingPayload,
}

impl fmt::Display for InvarianceError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let message = match self {
Self::InvarianceTooWeakForSharedMeaning => "invariance is too weak for shared meaning",
Self::UnknownInvarianceLevel => "unknown invariance level",
Self::InvalidLoadingPayload => "invalid invariance loading payload",
};
formatter.write_str(message)
}
}

impl std::error::Error for InvarianceError {}

#[cfg(test)]
mod tests {
use super::InvarianceError;

#[test]
fn error_messages_are_stable() {
for (error, message) in [
(
InvarianceError::InvarianceTooWeakForSharedMeaning,
"invariance is too weak for shared meaning",
),
(
InvarianceError::UnknownInvarianceLevel,
"unknown invariance level",
),
(
InvarianceError::InvalidLoadingPayload,
"invalid invariance loading payload",
),
] {
assert_eq!(error.to_string(), message);
}
}
}
23 changes: 23 additions & 0 deletions crates/measurement_invariance/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![allow(clippy::cast_precision_loss)]
//! Explicit invariance status and group-loading recovery for shared meaning.
//!
//! Configural structure alone cannot license shared metric meaning. Metric and
//! scalar status may; recovery reports computed loading RMSE against known
//! truth (ADR 0004/0005).

mod error;
mod loading;
mod status;

/// Fail-closed measurement-invariance errors.
pub use error::InvarianceError;
/// One group-specific loading.
pub use loading::GroupLoading;
/// RMSE of recovered loadings against known truth.
pub use loading::loading_root_mean_square_error;
/// Established invariance status.
pub use status::InvarianceLevel;
/// Refuse to treat a weaker status as shared meaning.
pub use status::refuse_noninvariant_as_shared_meaning;
87 changes: 87 additions & 0 deletions crates/measurement_invariance/src/loading.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//! Known-truth RMSE for multi-group loadings.

use crate::InvarianceError;

/// One group-specific loading used for invariance recovery.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GroupLoading {
group_index: u32,
loading: f64,
}

impl GroupLoading {
/// Construct a finite group loading.
///
/// Non-finite values are rejected later by
/// [`loading_root_mean_square_error`]; this constructor keeps the record
/// transparent so tests can compute the same residual.
#[must_use]
pub const fn new(group_index: u32, loading: f64) -> Self {
Self {
group_index,
loading,
}
}

/// Return the group index.
#[must_use]
pub const fn group_index(self) -> u32 {
self.group_index
}

/// Return the loading value.
#[must_use]
pub const fn loading(self) -> f64 {
self.loading
}
}

/// RMSE of recovered loadings against known-truth loadings.
///
/// # Errors
///
/// Returns [`InvarianceError::InvalidLoadingPayload`] when either slice is
/// empty, the lengths differ, a group index mismatches, or a loading is
/// non-finite.
pub fn loading_root_mean_square_error(
truth: &[GroupLoading],
decided: &[GroupLoading],
) -> Result<f64, InvarianceError> {
if truth.is_empty() || truth.len() != decided.len() {
return Err(InvarianceError::InvalidLoadingPayload);
}
let mut sum_squares = 0.0_f64;
for (truth_row, decided_row) in truth.iter().zip(decided) {
if truth_row.group_index() != decided_row.group_index()
|| !truth_row.loading().is_finite()
|| !decided_row.loading().is_finite()
{
return Err(InvarianceError::InvalidLoadingPayload);
}
let residual = decided_row.loading() - truth_row.loading();
sum_squares += residual * residual;
}
Ok((sum_squares / truth.len() as f64).sqrt())
}

#[cfg(test)]
mod tests {
use super::{GroupLoading, loading_root_mean_square_error};
use crate::InvarianceError;

#[test]
fn mismatched_groups_and_nan_fail_closed() {
let truth = [GroupLoading::new(0, 0.5)];
let other_group = [GroupLoading::new(1, 0.5)];
assert_eq!(
loading_root_mean_square_error(&truth, &other_group),
Err(InvarianceError::InvalidLoadingPayload)
);
let nan = [GroupLoading::new(0, f64::NAN)];
assert_eq!(
loading_root_mean_square_error(&truth, &nan),
Err(InvarianceError::InvalidLoadingPayload)
);
assert_eq!(GroupLoading::new(2, 0.1).group_index(), 2);
}
}
86 changes: 86 additions & 0 deletions crates/measurement_invariance/src/status.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
//! Explicit invariance status that may or may not license shared meaning.

use crate::InvarianceError;

/// Established invariance status for a multi-group comparison.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InvarianceLevel {
/// Same factor structure only; loadings are not comparable.
Configural,
/// Equal loadings; factor variances/means remain group-specific.
Metric,
/// Equal loadings and intercepts.
Scalar,
}

impl InvarianceLevel {
/// Stable wire name.
#[must_use]
pub const fn wire_name(self) -> &'static str {
match self {
Self::Configural => "configural",
Self::Metric => "metric",
Self::Scalar => "scalar",
}
}

/// Parse a stable wire invariance-status name.
///
/// # Errors
///
/// Returns [`InvarianceError::UnknownInvarianceLevel`] for unrecognized names.
pub fn from_wire_name(name: &str) -> Result<Self, InvarianceError> {
match name {
"configural" => Ok(Self::Configural),
"metric" => Ok(Self::Metric),
"scalar" => Ok(Self::Scalar),
_ => Err(InvarianceError::UnknownInvarianceLevel),
}
}

/// Return whether this status licenses shared metric meaning.
#[must_use]
pub const fn licenses_shared_meaning(self) -> bool {
matches!(self, Self::Metric | Self::Scalar)
}
}

/// Refuse to treat a weaker invariance status as shared meaning.
///
/// # Errors
///
/// Returns [`InvarianceError::InvarianceTooWeakForSharedMeaning`] when the
/// status is only configural.
pub fn refuse_noninvariant_as_shared_meaning(
level: InvarianceLevel,
) -> Result<(), InvarianceError> {
if level.licenses_shared_meaning() {
Ok(())
} else {
Err(InvarianceError::InvarianceTooWeakForSharedMeaning)
}
}

#[cfg(test)]
mod tests {
use super::InvarianceLevel;
use crate::InvarianceError;

#[test]
fn wire_names_round_trip() {
for level in [
InvarianceLevel::Configural,
InvarianceLevel::Metric,
InvarianceLevel::Scalar,
] {
assert_eq!(
InvarianceLevel::from_wire_name(level.wire_name()).expect("round trip"),
level
);
}
assert_eq!(
InvarianceLevel::from_wire_name("partial"),
Err(InvarianceError::UnknownInvarianceLevel)
);
}
}
7 changes: 7 additions & 0 deletions crates/measurement_invariance/tests/crate_contract.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//! Integration contract for the `measurement_invariance` package identity.

#[test]
fn package_identity_is_stable() {
let observed = std::hint::black_box(env!("CARGO_PKG_NAME"));
assert_eq!(observed, "measurement_invariance");
}
60 changes: 60 additions & 0 deletions crates/measurement_invariance/tests/invariance_status_contract.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//! Shared meaning requires an explicit invariance status and computed loading RMSE.

use measurement_invariance::{
GroupLoading, InvarianceError, InvarianceLevel, loading_root_mean_square_error,
refuse_noninvariant_as_shared_meaning,
};

#[test]
fn configural_status_cannot_claim_shared_metric_meaning() {
assert_eq!(
refuse_noninvariant_as_shared_meaning(InvarianceLevel::Configural),
Err(InvarianceError::InvarianceTooWeakForSharedMeaning)
);
assert_eq!(
refuse_noninvariant_as_shared_meaning(InvarianceLevel::Metric),
Ok(())
);
assert_eq!(
refuse_noninvariant_as_shared_meaning(InvarianceLevel::Scalar),
Ok(())
);
}

#[test]
fn aligned_loadings_have_lower_computed_rmse_than_a_crossed_collapse() {
let truth = [
GroupLoading::new(0, 0.80),
GroupLoading::new(1, 0.80),
GroupLoading::new(0, 0.40),
GroupLoading::new(1, 0.40),
];
let aligned = truth;
let crossed = [
GroupLoading::new(0, 0.80),
GroupLoading::new(1, 0.40),
GroupLoading::new(0, 0.40),
GroupLoading::new(1, 0.80),
];

let aligned_rmse = loading_root_mean_square_error(&truth, &aligned).expect("aligned");
let crossed_rmse = loading_root_mean_square_error(&truth, &crossed).expect("crossed");
let expected = {
let mut sum_squares = 0.0_f64;
for (truth_row, decided_row) in truth.iter().zip(aligned.iter()) {
let residual = decided_row.loading() - truth_row.loading();
sum_squares += residual * residual;
}
(sum_squares / f64::from(u32::try_from(truth.len()).expect("len"))).sqrt()
};
assert!((aligned_rmse - expected).abs() < f64::EPSILON);
assert!(aligned_rmse < crossed_rmse);
}

#[test]
fn empty_or_non_finite_loadings_fail_closed() {
assert_eq!(
loading_root_mean_square_error(&[], &[]),
Err(InvarianceError::InvalidLoadingPayload)
);
}
Loading
Loading