Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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 |
| `subevent_containment` | subevent event-time intervals must stay inside the parent |

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

- `subevent_containment` parent-window gate: a half-open subevent interval that starts before or ends after its parent cannot attach; recovered containment flags match known truth at a higher computed rate than accepting every child (ADR 0003).
- `tepp_api` adaptive orchestration router (ADR 0010): versioned `direct`/`verify`/`committee`/`conductor`/`abstain` selection from CPU `f64` risk, ambiguity, evidence, and token-budget inputs; recorded stages, recursion, decomposition, access lists, and role-specific reasoning effort; fail-closed document-controlled policy/access/credentials; LLM plans remain proposals under deterministic statistical authority; comparable-budget ablation requires a direct baseline; credential-free contextual-orchestrator binding. Live NIM HTTP remains accepted-target.
- `tepp_api` purpose-bound provider-payload minimization: time-bounded `PurposeGrant` evaluation, fail-closed expired/not-yet-valid/inverted/cross-tenant/impossible-calendar denial, semantic UTC calendar validation, refusal to copy identity mappings into model-provider payloads or ordinary logs, preservation of opaque analytical identifiers and membership roles (no blanket PII mask), a separately authorized scientific re-identification path, and an internally bound FIPS 180-4 SHA-256 audit digest appended through `ReidentificationAuditSink` before disclosure.
- `persistence_postgres` backup/restore integrity: restored snapshots stay unusable until tenant, canonical `SHA-256`, knowledge-cutoff eligibility, temporal window order, and append-only triggers revalidate; SQL probes raise `restore integrity failed` (ADR 0013).
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/subevent_containment",
]
default-members = [
"crates/evidence_core",
Expand All @@ -23,6 +24,7 @@ default-members = [
"crates/tepp_simulation",
"crates/validation_core",
"crates/tepp_api",
"crates/subevent_containment",
]

[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/subevent_containment
```

## Local verification
Expand Down
17 changes: 17 additions & 0 deletions crates/subevent_containment/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "subevent_containment"
description = "Subevent intervals must stay inside the parent event interval."
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
46 changes: 46 additions & 0 deletions crates/subevent_containment/src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//! Fail-closed subevent-containment errors.

use std::fmt;

/// A fail-closed subevent-containment error.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum SubeventContainmentError {
/// The subevent interval is not inside the parent interval.
SubeventEscapesParent,
/// An interval or recovery slice was empty, inverted, or length-mismatched.
InvalidIntervalPayload,
}

impl fmt::Display for SubeventContainmentError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let message = match self {
Self::SubeventEscapesParent => "subevent interval escapes the parent event",
Self::InvalidIntervalPayload => "invalid subevent-containment payload",
};
formatter.write_str(message)
}
}

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

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

#[test]
fn error_messages_are_stable() {
for (error, message) in [
(
SubeventContainmentError::SubeventEscapesParent,
"subevent interval escapes the parent event",
),
(
SubeventContainmentError::InvalidIntervalPayload,
"invalid subevent-containment payload",
),
] {
assert_eq!(error.to_string(), message);
}
}
}
133 changes: 133 additions & 0 deletions crates/subevent_containment/src/interval.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
//! Half-open event-time intervals and parent containment.

use crate::SubeventContainmentError;

/// One half-open event-time interval `[start, end)` in seconds.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EventInterval {
start_seconds: i64,
end_seconds: i64,
}

impl EventInterval {
/// Construct a half-open interval with a strictly positive length.
///
/// # Errors
///
/// Returns [`SubeventContainmentError::InvalidIntervalPayload`] when
/// `end_seconds` is not greater than `start_seconds`.
pub const fn new(
start_seconds: i64,
end_seconds: i64,
) -> Result<Self, SubeventContainmentError> {
if end_seconds <= start_seconds {
return Err(SubeventContainmentError::InvalidIntervalPayload);
}
Ok(Self {
start_seconds,
end_seconds,
})
}

/// Inclusive start bound in seconds.
#[must_use]
pub const fn start_seconds(self) -> i64 {
self.start_seconds
}

/// Exclusive end bound in seconds.
#[must_use]
pub const fn end_seconds(self) -> i64 {
self.end_seconds
}
}

/// Return whether `child` lies entirely inside `parent`.
///
/// # Errors
///
/// This function is infallible for validated intervals and exists to keep the
/// public comparison surface explicit.
#[allow(clippy::unnecessary_wraps)]
pub fn interval_contains(
parent: EventInterval,
child: EventInterval,
) -> Result<bool, SubeventContainmentError> {
Ok(child.start_seconds >= parent.start_seconds && child.end_seconds <= parent.end_seconds)
}
Comment on lines +52 to +57

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: interval_contains documented as infallible yet returns Result

interval_contains at interval.rs always returns Ok(..) and its # Errors docstring states it is infallible; the Result wrapper and #[allow(clippy::unnecessary_wraps)] exist only to keep the public surface explicit. refuse_escaped_subevent propagates the never-taken ?. This is intentional per the docs but worth noting: consumers must still handle an error arm that can never occur, which slightly complicates the API contract.

Open in Devin Review

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

Comment on lines +52 to +57

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: Containment logic is correct for half-open intervals

interval_contains at interval.rs correctly implements half-open [start, end) containment: a child is contained iff child.start >= parent.start && child.end <= parent.end. EventInterval::new rejects zero-length/inverted intervals (end <= start), so the recovery and refusal paths cannot receive degenerate intervals. No correctness issue found.

Open in Devin Review

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


/// Refuse to attach a subevent that escapes the parent interval.
///
/// # Errors
///
/// Returns [`SubeventContainmentError::SubeventEscapesParent`] when the child
/// is not contained.
pub fn refuse_escaped_subevent(
parent: EventInterval,
child: EventInterval,
) -> Result<(), SubeventContainmentError> {
if interval_contains(parent, child)? {
return Ok(());
}
Err(SubeventContainmentError::SubeventEscapesParent)
}

/// Fraction of recovered containment flags that match known truth.
///
/// # Errors
///
/// Returns [`SubeventContainmentError::InvalidIntervalPayload`] when either
/// slice is empty or the lengths differ.
pub fn containment_recovery_rate(
truth: &[bool],
decided: &[bool],
) -> Result<f64, SubeventContainmentError> {
if truth.is_empty() || truth.len() != decided.len() {
return Err(SubeventContainmentError::InvalidIntervalPayload);
}
let mut matches = 0_u32;
for (truth_flag, decided_flag) in truth.iter().zip(decided) {
if truth_flag == decided_flag {
matches += 1;
}
}
Ok(f64::from(matches) / truth.len() as f64)
}
Comment on lines +81 to +95

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: Recovery-rate empty/length checks match documented contract

containment_recovery_rate at interval.rs returns InvalidIntervalPayload when truth.is_empty() or lengths differ. The docstring says "when either slice is empty or the lengths differ"; the empty-decided/non-empty-truth case is caught by the length check, and empty truth is caught directly, so the two conditions together cover all empty cases. Behavior is consistent with the contract.

Open in Devin Review

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


#[cfg(test)]
mod tests {
use super::{
EventInterval, containment_recovery_rate, interval_contains, refuse_escaped_subevent,
};
use crate::SubeventContainmentError;

#[test]
fn local_branches_cover_containment_and_payloads() {
let parent = EventInterval::new(10, 40).expect("parent");
let inside = EventInterval::new(15, 30).expect("inside");
assert_eq!(parent.start_seconds(), 10);
assert_eq!(parent.end_seconds(), 40);
assert!(interval_contains(parent, inside).expect("inside"));
refuse_escaped_subevent(parent, inside).expect("contained");
let early = EventInterval::new(0, 20).expect("early");
assert!(!interval_contains(parent, early).expect("early"));
assert_eq!(
refuse_escaped_subevent(parent, early),
Err(SubeventContainmentError::SubeventEscapesParent)
);
assert_eq!(
EventInterval::new(4, 4),
Err(SubeventContainmentError::InvalidIntervalPayload)
);
let matched = containment_recovery_rate(&[true], &[true]).expect("rate");
assert!((matched - 1.0).abs() < f64::EPSILON);
assert_eq!(
containment_recovery_rate(&[], &[]),
Err(SubeventContainmentError::InvalidIntervalPayload)
);
assert_eq!(
containment_recovery_rate(&[true], &[]),
Err(SubeventContainmentError::InvalidIntervalPayload)
);
}
}
21 changes: 21 additions & 0 deletions crates/subevent_containment/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![allow(clippy::cast_precision_loss)]
//! Subevent intervals must stay inside the parent event interval.
//!
//! A subevent is part of a versioned event instance. Its event-time interval
//! cannot start before or end after the parent (ADR 0003).

mod error;
mod interval;

/// Fail-closed subevent-containment errors.
pub use error::SubeventContainmentError;
/// One half-open event-time interval.
pub use interval::EventInterval;
/// Fraction of recovered containment flags that match known truth.
pub use interval::containment_recovery_rate;
/// Return whether a child interval lies entirely inside a parent interval.
pub use interval::interval_contains;
/// Refuse to attach a subevent that escapes the parent interval.
pub use interval::refuse_escaped_subevent;
79 changes: 79 additions & 0 deletions crates/subevent_containment/tests/containment_contract.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//! A subevent cannot escape its parent event-time interval.

use subevent_containment::{
EventInterval, SubeventContainmentError, containment_recovery_rate, interval_contains,
refuse_escaped_subevent,
};

fn interval(start: i64, end: i64) -> EventInterval {
EventInterval::new(start, end).expect("interval")
}

#[test]
fn escaped_subevents_cannot_attach_to_the_parent() {
let parent = interval(10, 40);
let inside = interval(15, 30);
let early = interval(0, 20);
let late = interval(30, 50);
assert!(interval_contains(parent, inside).expect("inside"));
refuse_escaped_subevent(parent, inside).expect("contained");
assert!(!interval_contains(parent, early).expect("early"));
assert_eq!(
refuse_escaped_subevent(parent, early),
Err(SubeventContainmentError::SubeventEscapesParent)
);
assert_eq!(
refuse_escaped_subevent(parent, late),
Err(SubeventContainmentError::SubeventEscapesParent)
);
}

#[test]
fn recovered_containment_matches_known_truth_better_than_accepting_all() {
let parent = interval(10, 40);
let children = [interval(15, 30), interval(0, 20), interval(12, 18)];
let truth = [true, false, true];
let recovered = [
interval_contains(parent, children[0]).expect("c0"),
interval_contains(parent, children[1]).expect("c1"),
interval_contains(parent, children[2]).expect("c2"),
];
let collapsed = [true, true, true];
let recovered_rate = containment_recovery_rate(&truth, &recovered).expect("recovered");
let collapsed_rate = containment_recovery_rate(&truth, &collapsed).expect("collapsed");
let expected = {
let mut matches = 0_u32;
for (truth_flag, decided_flag) in truth.iter().zip(recovered.iter()) {
if truth_flag == decided_flag {
matches += 1;
}
}
f64::from(matches) / f64::from(u32::try_from(truth.len()).expect("len"))
};
assert!((recovered_rate - expected).abs() < f64::EPSILON);
assert!(recovered_rate > collapsed_rate);
}

#[test]
fn empty_or_invalid_interval_payloads_fail_closed() {
assert_eq!(
EventInterval::new(10, 10),
Err(SubeventContainmentError::InvalidIntervalPayload)
);
assert_eq!(
EventInterval::new(10, 9),
Err(SubeventContainmentError::InvalidIntervalPayload)
);
assert_eq!(
containment_recovery_rate(&[], &[]),
Err(SubeventContainmentError::InvalidIntervalPayload)
);
assert_eq!(
containment_recovery_rate(&[true], &[]),
Err(SubeventContainmentError::InvalidIntervalPayload)
);
assert_eq!(
containment_recovery_rate(&[true, false], &[true]),
Err(SubeventContainmentError::InvalidIntervalPayload)
);
}
7 changes: 7 additions & 0 deletions crates/subevent_containment/tests/crate_contract.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
//! Integration contract for the `subevent_containment` package identity.

#[test]
fn package_identity_is_stable() {
let observed = std::hint::black_box(env!("CARGO_PKG_NAME"));
assert_eq!(observed, "subevent_containment");
}
2 changes: 1 addition & 1 deletion docs/TRACEABILITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ The full APA 7th standards/literature register remains `docs/research/standards-
| six distinct clocks and uncertain intervals | PRD; ADR 0002 | PR #8 `temporal_core` on protected main; PR #5 historical only | implemented-main |
| Allen relation algebra/bounded closure | ADR 0002; temporal research | PR #9 `temporal_core` path-consistency on protected main | implemented-main |
| forward-only transition subgraph | PRD; ADR 0002/0003 | `relation_graph` on protected main | implemented-main |
| event ontology/evidence mentions | PRD; ADR 0003 | `event_core` mention/instance separation on protected main; `persistence_postgres` mention SQL implemented-main refuses mention-as-instance; event-instance SQL (#39 implemented-main) refuses inverted windows; full intelligence stack remaining | partial |
| event ontology/evidence mentions | PRD; ADR 0003 | `event_core` mention/instance separation on protected main; `subevent_containment` parent-window gate on the active PR; event-instance SQL implemented-main; full intelligence stack remaining | active-PR |
| time-varying cross-classified multiple membership | PRD; ADR 0003 | `membership_core` network on protected main; multilevel estimators remaining | partial |
| leakage-safe availability/cutoff snapshots | PRD; ADR 0002/0013 | `corpus_split` on protected main | implemented-main |
| recovery metrics (RMSE, bias, coverage, graph, temporal order, Monte Carlo SE gates) | PRD; Test Strategy; ADR 0007/0014 | `validation_core` on protected main (PR #19); SE-aware Monte Carlo gates included | implemented-main |
Expand Down
2 changes: 1 addition & 1 deletion docs/adr/0003-relational-event-multiple-membership.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# ADR 0003 — Relational event ontology and time-varying multiple membership

**Decision status:** Accepted
**Implementation maturity:** partial — membership network and event mention/instance separation implemented-main; typed relation graph with forward-only transitions active-PR; multilevel estimators and persistence remain accepted-target
**Implementation maturity:** active-PR — subevent parent-window containment in `subevent_containment` on the active PR; multilevel estimators remain accepted-target
**Date:** 2026-08-05
**Supersedes:** None. ADR 0016 owns TDT/CHRONOS event-intelligence task semantics; this ADR remains authoritative for ontology, relation, role, and membership structure.

Expand Down
2 changes: 1 addition & 1 deletion docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio
|---|---|---|---|---|
| [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. |
| [0002](0002-six-clock-temporal-semantics.md) | Six-clock temporal semantics and fail-closed historical leakage prevention | Accepted | active-PR | Unmerged PR #8 is the canonical Task 3 replacement implementing typed clocks/intervals against the current protected-main lineage; conflicted PR #5 is superseded lineage. Later graph/split enforcement remains target work. |
| [0003](0003-relational-event-multiple-membership.md) | Relational event ontology and time-varying cross-classified multiple membership | Accepted | partial | Weighted time-varying membership network/roles are active-PR (PR #12); full multilevel estimators, graph ontology, and persistence remain accepted-target. ADR 0016 owns event-intelligence tasks. |
| [0003](0003-relational-event-multiple-membership.md) | Relational event ontology and time-varying cross-classified multiple membership | Accepted | active-PR | Subevent parent-window containment in `subevent_containment` on the active PR; multilevel estimators remain accepted-target. |
| [0004](0004-shared-multilingual-latent-space.md) | One shared multilingual latent space with explicit invariance status | Accepted | accepted-target | ADR 0012 owns the full topic-estimator/backend/global-topic contract. |
| [0005](0005-posterior-esem-dsem.md) | Posterior-aware ESEM/DSEM and valid compositional coordinates | Accepted | accepted-target | Downstream psychometric authority; upstream topic/network model is clarified by ADR 0012. |
| [0006](0006-vram-gpu-nvidia-orchestration.md) | VRAM-adaptive GPU compute and model-credential boundary | Accepted | accepted-target | LLM orchestration policy superseded by ADR 0010; autonomous development authority governed by ADR 0015. |
Expand Down
Loading
Loading