interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / cortex-path-m1 / tests / m1.rs

275 lines · 10119 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use chrono::{TimeZone, Utc};
17use cortex_path_m1::config::ExperimentConfig;
18use cortex_path_m1::fixture::{self, EvalCase, EvalFixture};
19use cortex_path_m1::metrics::{self, ci_excludes_zero};
20use cortex_path_m1::run::{self, RunOutcome};
21use cortex_path_m1::score::{self, EdgeView, WalkEdge};
22use cortex_rs::{ClaimStatus, ClaimWriteInput, Database, EntityWriteInput, VerificationTier};
23use rusqlite::Connection;
24use serde_json::json;
25use std::collections::{BTreeMap, BTreeSet};
26use std::path::Path;
27
28fn snapshot_time() -> chrono::DateTime<Utc> {
29 Utc.with_ymd_and_hms(2026, 9, 22, 0, 0, 0).unwrap()
30}
31
32fn entity(id: &str, name: &str) -> EntityWriteInput {
33 EntityWriteInput {
34 id: Some(id.to_string()),
35 space: "atlas-memory".to_string(),
36 entity_type: "discovery".to_string(),
37 canonical_name: name.to_string(),
38 content: String::new(),
39 aliases: Vec::new(),
40 metadata: json!({}),
41 confidence: 1.0,
42 valid_from: None,
43 valid_to: None,
44 external_id: None,
45 }
46}
47
48fn claim(id: &str, subject: &str, object: &str) -> ClaimWriteInput {
49 ClaimWriteInput {
50 id: Some(id.to_string()),
51 space: "atlas-memory".to_string(),
52 subject_entity_id: subject.to_string(),
53 predicate: "links".to_string(),
54 object_entity_id: Some(object.to_string()),
55 literal_value: None,
56 confidence: 1.0,
57 metadata: json!({}),
58 }
59}
60
61fn edge(status: ClaimStatus, retracted: bool, object: Option<&str>) -> EdgeView {
62 EdgeView {
63 claim_id: "c".to_string(),
64 subject: "a".to_string(),
65 object: object.unwrap_or("b").to_string(),
66 confidence: 1.0,
67 tier: VerificationTier::T0Direct,
68 evidence_count: 0,
69 created_at: snapshot_time().to_rfc3339(),
70 status,
71 retracted,
72 subject_space: "atlas-memory".to_string(),
73 object_space: "atlas-memory".to_string(),
74 claim_space: "atlas-memory".to_string(),
75 }
76}
77
78#[test]
79fn admission_keeps_active_same_space_entity_edges() {
80 let active = edge(ClaimStatus::Active, false, Some("b"));
81 assert!(score::is_admitted(&active, "atlas-memory"));
82 assert!(!score::is_admitted(
83 &edge(ClaimStatus::Superseded, false, Some("b")),
84 "atlas-memory"
85 ));
86 assert!(!score::is_admitted(
87 &edge(ClaimStatus::Disputed, false, Some("b")),
88 "atlas-memory"
89 ));
90 assert!(!score::is_admitted(
91 &edge(ClaimStatus::Invalidated, false, Some("b")),
92 "atlas-memory"
93 ));
94 assert!(!score::is_admitted(
95 &edge(ClaimStatus::Active, true, Some("b")),
96 "atlas-memory"
97 ));
98 let mut literal = edge(ClaimStatus::Active, false, Some("b"));
99 literal.object.clear();
100 assert!(!score::is_admitted(&literal, "atlas-memory"));
101 let mut other_space = edge(ClaimStatus::Active, false, Some("b"));
102 other_space.object_space = "other".to_string();
103 assert!(!score::is_admitted(&other_space, "atlas-memory"));
104}
105
106#[test]
107fn edge_weight_uses_tier_evidence_and_age() {
108 let config = ExperimentConfig::default();
109 let mut view = edge(ClaimStatus::Active, false, Some("b"));
110 view.tier = VerificationTier::T2Verified;
111 view.evidence_count = 0;
112 view.confidence = 1.0;
113 let fresh = score::edge_weight(&config, &view, snapshot_time());
114 assert!((fresh - 0.4).abs() < 1e-9);
115 view.created_at = "2025-09-22T00:00:00+00:00".to_string();
116 let aged = score::edge_weight(&config, &view, snapshot_time());
117 assert!(aged < fresh);
118 assert!(aged >= config.freshness_floor * 0.4);
119}
120
121#[test]
122fn two_hops_score_and_the_third_does_not() {
123 let config = ExperimentConfig::default();
124 let mut adj = BTreeMap::new();
125 let mut link = |from: &str, to: &str, claim: &str| {
126 adj.entry(from.to_string())
127 .or_insert_with(Vec::new)
128 .push(WalkEdge {
129 claim_id: claim.to_string(),
130 neighbor: to.to_string(),
131 weight: 1.0,
132 });
133 };
134 link("a", "b", "ab");
135 link("b", "c", "bc");
136 link("c", "d", "cd");
137 let walked = score::walk_paths(&config, &[("a".to_string(), 1.0)], &adj, &BTreeSet::new());
138 assert!(walked.graph_score.contains_key("b"));
139 assert!(walked.graph_score.contains_key("c"));
140 assert!(!walked.graph_score.contains_key("d"));
141 assert!((walked.graph_score["c"] - 0.5).abs() < 1e-9);
142}
143
144#[test]
145fn zero_graph_fusion_keeps_baseline_order_and_breaks_ties_by_id() {
146 let config = ExperimentConfig::default();
147 let ranked = score::fuse_and_rank(
148 &config,
149 &[
150 ("b".to_string(), 0.2),
151 ("a".to_string(), 0.2),
152 ("c".to_string(), 0.9),
153 ],
154 &BTreeMap::new(),
155 );
156 let ids: Vec<_> = ranked.iter().map(|item| item.id.as_str()).collect();
157 assert_eq!(ids, vec!["c", "a", "b"]);
158 assert!((ranked[1].final_score - 0.2).abs() < 1e-12);
159}
160
161#[test]
162fn indirect_anchor_pair_is_a_suggestion_until_a_direct_edge_exists() {
163 let config = ExperimentConfig::default();
164 let mut adj = BTreeMap::new();
165 for (from, to, claim) in [
166 ("a", "c", "ac"),
167 ("c", "b", "cb"),
168 ("b", "c", "cb"),
169 ("c", "a", "ac"),
170 ] {
171 adj.entry(from.to_string())
172 .or_insert_with(Vec::new)
173 .push(WalkEdge {
174 claim_id: claim.to_string(),
175 neighbor: to.to_string(),
176 weight: 1.0,
177 });
178 }
179 let anchors = vec![("a".to_string(), 0.9), ("b".to_string(), 0.9)];
180 let open = score::walk_paths(&config, &anchors, &adj, &BTreeSet::new());
181 assert_eq!(open.suggestions.len(), 1);
182 let mut direct = BTreeSet::new();
183 direct.insert(score::ordered_pair("a", "b"));
184 let closed = score::walk_paths(&config, &anchors, &adj, &direct);
185 assert!(closed.suggestions.is_empty());
186}
187
188#[test]
189fn ndcg_recall_and_bootstrap_match_the_contract() {
190 let relevant = vec!["a".to_string()];
191 let perfect = metrics::ndcg_at_k(&["a".to_string(), "b".to_string()], &relevant, 10);
192 assert!((perfect - 1.0).abs() < 1e-12);
193 let second = metrics::ndcg_at_k(&["b".to_string(), "a".to_string()], &relevant, 10);
194 assert!((second - (1.0 / 3.0_f64.log2())).abs() < 1e-12);
195 assert!(
196 (metrics::recall_at_k(&["b".to_string(), "a".to_string()], &relevant, 10) - 1.0).abs()
197 < 1e-12
198 );
199 let positive = metrics::bootstrap_mean_ci(&[0.2, 0.2, 0.2, 0.2], 200, 0x504541524C).unwrap();
200 assert!(ci_excludes_zero(positive));
201 let flat = metrics::bootstrap_mean_ci(&[0.0, 0.0, 0.0, 0.0], 200, 0x504541524C).unwrap();
202 assert!(!ci_excludes_zero(flat));
203 let once = metrics::bootstrap_mean_ci(&[0.1, 0.4], 100, 0x504541524C).unwrap();
204 let twice = metrics::bootstrap_mean_ci(&[0.1, 0.4], 100, 0x504541524C).unwrap();
205 assert_eq!(once, twice);
206}
207
208#[test]
209fn example_fixture_is_not_a_scientific_verdict() {
210 let bytes =
211 include_bytes!("../../../experiments/fixtures/pearl_cortex_m1_entities.example.json");
212 let fixture = fixture::load_fixture(bytes).unwrap();
213 let rejection = fixture::structural_rejection(&fixture);
214 assert!(!rejection.reasons.is_empty());
215}
216
217#[test]
218fn scoring_does_not_insert_a_candidate_and_leaves_the_source_hash() {
219 let dir = std::env::temp_dir().join(format!("cortex-path-m1-test-{}", std::process::id()));
220 let _ = std::fs::remove_dir_all(&dir);
221 std::fs::create_dir_all(&dir).unwrap();
222 let source = dir.join("source.sqlite");
223 {
224 let db = Database::open(&source).unwrap();
225 db.upsert_entity(&entity("a", "hit-a"), None).unwrap();
226 db.upsert_entity(&entity("b", "hit-b"), None).unwrap();
227 db.upsert_entity(&entity("c", "bridge"), None).unwrap();
228 db.upsert_claim(&claim("ac", "a", "c")).unwrap();
229 db.upsert_claim(&claim("cb", "c", "b")).unwrap();
230 }
231 checkpoint(&source);
232 let before = run::sha256_file(&source).unwrap();
233 let mut cases = Vec::new();
234 for index in 0..50 {
235 let relevant = if index < 15 {
236 vec!["c".to_string()]
237 } else {
238 vec!["a".to_string()]
239 };
240 cases.push(EvalCase {
241 id: format!("q{index}"),
242 space_slug: "atlas-memory".to_string(),
243 query: "hit".to_string(),
244 relevant_entity_ids: relevant,
245 query_embedding: vec![1.0, 0.0],
246 });
247 }
248 let fixture = EvalFixture {
249 kind: "unit".to_string(),
250 cases,
251 };
252 let bytes = serde_json::to_vec(&fixture).unwrap();
253 let outcome = run::run_experiment(&source, &bytes, snapshot_time(), b"test-binary").unwrap();
254 match outcome {
255 RunOutcome::Report(report) => {
256 assert_eq!(report.writes, 0);
257 assert!(!report.queries[0].suggestions.is_empty());
258 }
259 RunOutcome::Rejected(rejection) => panic!("expected a scored run: {:?}", rejection.reasons),
260 }
261 assert_eq!(run::sha256_file(&source).unwrap(), before);
262 let _ = std::fs::remove_dir_all(&dir);
263}
264
265fn checkpoint(path: &Path) {
266 let conn = Connection::open(path).unwrap();
267 let _: (i64, i64, i64) = conn
268 .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
269 Ok((row.get(0)?, row.get(1)?, row.get(2)?))
270 })
271 .unwrap();
272 drop(conn);
273 let _ = std::fs::remove_file(format!("{}-wal", path.display()));
274 let _ = std::fs::remove_file(format!("{}-shm", path.display()));
275}