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 / spark-adapters / tests / challenger_m1_concurrency_bounds.rs

534 lines · 20221 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
16// Challenger Milestone 1 Adversarial Stress Suite:
17// Concurrency Caching, Fallback Behavior, Payload Bounds, and Dynamic Cortex Auth
18// Strictly adheres to sovereign unslop invariants: zero em dashes, zero en dashes.
19
20use spark_adapters::distill::DistillationEngine;
21use spark_adapters::models::ChatMessage;
22use spark_adapters::providers::openai::{
23 format_openai_payload, format_openai_payload_bounded, DEFAULT_MAX_TOKENS,
24};
25use spark_adapters::vault::{
26 get_scrub_targets, is_secret_present, list_vault_keys, register_test_secret,
27 remove_test_secret, resolve_secret, sanitize_outbound_prompt,
28};
29use std::fs;
30use std::io::{Read, Write};
31use std::net::TcpListener;
32use std::path::PathBuf;
33use std::sync::{Arc, Barrier};
34use std::thread;
35use std::time::{Duration, Instant};
36
37// ============================================================================
38// Challenge 1: Concurrency and TTL Cache Invalidation (50 threads)
39// ============================================================================
40
41#[test]
42fn test_challenge1_concurrency_50_threads_sub_millisecond_reads() {
43 let _concurrency_guard = VAULT_CONCURRENCY_LOCK.lock().unwrap();
44 // Prime and warm the cache with known secrets
45 register_test_secret(
46 "CONCURRENCY_TEST_KEY_1",
47 "initial_concurrency_secret_value_1",
48 );
49 register_test_secret(
50 "CONCURRENCY_TEST_KEY_2",
51 "initial_concurrency_secret_value_2",
52 );
53
54 // Warm-up pass to ensure cached state is populated prior to concurrent execution
55 let _ = resolve_secret("CONCURRENCY_TEST_KEY_1");
56 let _ = resolve_secret("CONCURRENCY_TEST_KEY_2");
57 let _ = get_scrub_targets();
58
59 let num_threads = 50;
60 // Each thread times many short batches instead of one long run. A thread that the OS
61 // deschedules (busy judge, other builds) loses the time inside the batch it was paused in,
62 // but a slow or lock-blocked read slows EVERY batch. The median batch tells the two apart.
63 let batches_per_thread = 20;
64 let iterations_per_batch = 5;
65 let barrier = Arc::new(Barrier::new(num_threads));
66
67 let mut handles = Vec::with_capacity(num_threads);
68
69 for thread_idx in 0..num_threads {
70 let b = Arc::clone(&barrier);
71 handles.push(thread::spawn(move || {
72 // Synchronize all 50 threads to fire at the exact same moment
73 b.wait();
74
75 let start = Instant::now();
76 let mut batch_avg_micros = Vec::with_capacity(batches_per_thread);
77
78 for _ in 0..batches_per_thread {
79 let batch_start = Instant::now();
80 for i in 0..iterations_per_batch {
81 let key = if i % 2 == 0 {
82 "CONCURRENCY_TEST_KEY_1"
83 } else {
84 "CONCURRENCY_TEST_KEY_2"
85 };
86
87 let secret = resolve_secret(key);
88 assert!(
89 secret.is_some(),
90 "Secret must resolve in thread {}",
91 thread_idx
92 );
93
94 let targets = get_scrub_targets();
95 assert!(
96 !targets.is_empty(),
97 "Scrub targets must not be empty in thread {}",
98 thread_idx
99 );
100 }
101 let batch_ops = iterations_per_batch * 2;
102 batch_avg_micros.push(batch_start.elapsed().as_micros() as f64 / batch_ops as f64);
103 }
104
105 let elapsed = start.elapsed();
106 batch_avg_micros.sort_by(|a, b| a.total_cmp(b));
107 let median_op_micros = batch_avg_micros[batches_per_thread / 2];
108
109 (thread_idx, elapsed, median_op_micros)
110 }));
111 }
112
113 let mut total_duration = Duration::from_secs(0);
114 let mut max_median_micros: f64 = 0.0;
115
116 for h in handles {
117 let (t_idx, elapsed, median_micros) = h.join().expect("Thread must not panic or deadlock");
118 if elapsed > total_duration {
119 total_duration = elapsed;
120 }
121 if median_micros > max_median_micros {
122 max_median_micros = median_micros;
123 }
124 assert!(
125 median_micros < 1000.0,
126 "Thread {} median batch operation time ({:.2} us) must be sub-millisecond (< 1000 us)",
127 t_idx,
128 median_micros
129 );
130 }
131
132 println!(
133 "Challenge 1 Pass: 50 concurrent threads completed {} operations in {:.2?}. Max median latency: {:.2} us/op (sub-millisecond invariant verified).",
134 num_threads * batches_per_thread * iterations_per_batch * 2,
135 total_duration,
136 max_median_micros
137 );
138}
139
140#[test]
141fn test_challenge1_concurrency_50_threads_mixed_read_write_invalidation() {
142 let _concurrency_guard = VAULT_CONCURRENCY_LOCK.lock().unwrap();
143 let num_threads = 50;
144 let iterations = 20;
145 let barrier = Arc::new(Barrier::new(num_threads));
146
147 let mut handles = Vec::with_capacity(num_threads);
148
149 for thread_idx in 0..num_threads {
150 let b = Arc::clone(&barrier);
151 handles.push(thread::spawn(move || {
152 b.wait();
153
154 if thread_idx < 10 {
155 // Writer thread: continuously registers new secrets and invalidates cache
156 for i in 0..iterations {
157 let key = format!("DYN_KEY_{}_{}", thread_idx, i);
158 let val = format!("dyn_secret_token_val_{}_{}_secure", thread_idx, i);
159 register_test_secret(&key, &val);
160 thread::sleep(Duration::from_micros(100));
161 }
162 } else if thread_idx < 30 {
163 // Reader thread: verifies resolve_secret under concurrent invalidation
164 for i in 0..iterations {
165 let key = format!("DYN_KEY_{}_{}", thread_idx % 10, i);
166 let _ = resolve_secret(&key);
167 let _ = resolve_secret("CONCURRENCY_TEST_KEY_1");
168 }
169 } else {
170 // Sanitizer thread: verifies prompt scrubbing under concurrent invalidation
171 for i in 0..iterations {
172 let raw_prompt = format!(
173 "Host spark at 127.0.0.1 for Drake Stapleton with DYN_KEY_{}_{}",
174 thread_idx % 10,
175 i
176 );
177 let cleaned = sanitize_outbound_prompt(&raw_prompt);
178 assert!(
179 !cleaned.contains("Drake Stapleton"),
180 "Operator name must be scrubbed"
181 );
182 assert!(!cleaned.contains("127.0.0.1"), "Local IP must be scrubbed");
183 }
184 }
185 }));
186 }
187
188 for h in handles {
189 h.join()
190 .expect("Concurrent read-write thread must not deadlock or panic");
191 }
192
193 // Verify final state consistency
194 let final_targets = get_scrub_targets();
195 assert!(
196 final_targets.len() >= 10,
197 "Scrub targets must incorporate dynamically registered secrets"
198 );
199 println!("Challenge 1 Mixed Read/Write Pass: 50 threads executed without deadlock or race conditions.");
200}
201
202// ============================================================================
203// Challenge 2: Fallback Behavior (Present vs Missing / Absent)
204// ============================================================================
205
206#[test]
207fn test_challenge2_fallback_graceful_missing_and_empty_keys() {
208 // Missing key resolution must return None gracefully without panic
209 let missing_secret = resolve_secret("DEFINITELY_NON_EXISTENT_KEY_998877");
210 assert_eq!(missing_secret, None);
211
212 // Empty key string must return None gracefully
213 let empty_secret = resolve_secret("");
214 assert_eq!(empty_secret, None);
215
216 // Missing key presence check must return false gracefully
217 let presence = is_secret_present("DEFINITELY_NON_EXISTENT_KEY_998877");
218 assert!(!presence);
219
220 // Empty key presence check must return false
221 let empty_presence = is_secret_present("");
222 assert!(!empty_presence);
223
224 // list_vault_keys must succeed even if no keys match
225 let keys = list_vault_keys();
226 assert!(keys.iter().all(|k| !k.is_empty()));
227 println!(
228 "Challenge 2 Fallback Pass: Missing and empty keys handled gracefully with zero panics."
229 );
230}
231
232#[test]
233fn test_challenge2_fallback_physical_tpm_or_cached_keys() {
234 let _guard = CORTEX_CHALLENGE_LOCK.blocking_lock();
235 // Physical TPM key presence on DGX Spark
236 let keys = list_vault_keys();
237 let has_cortex = keys.iter().any(|k| k == "CORTEX_TOKEN");
238 if has_cortex {
239 let cortex_tok = resolve_secret("CORTEX_TOKEN");
240 assert!(
241 cortex_tok.is_some(),
242 "CORTEX_TOKEN present in vault list must resolve"
243 );
244 let presence = is_secret_present("CORTEX_TOKEN");
245 assert!(
246 presence,
247 "is_secret_present must return true for CORTEX_TOKEN"
248 );
249 println!(
250 "Challenge 2 Physical TPM Pass: CORTEX_TOKEN successfully resolved from TPM vault."
251 );
252 } else {
253 println!("Challenge 2 Physical TPM Note: CORTEX_TOKEN not currently registered in physical vault.");
254 }
255}
256
257// ============================================================================
258// Challenge 3: Generation Bounding on OpenAI and Reasoning Models
259// ============================================================================
260
261#[test]
262fn test_challenge3_openai_payload_bounds_never_unconstrained() {
263 let dummy_messages = vec![
264 ChatMessage {
265 role: "system".to_string(),
266 content: "You are a compiler assistant.".to_string(),
267 reasoning: None,
268 },
269 ChatMessage {
270 role: "user".to_string(),
271 content: "Write a high-performance hash map in Rust.".to_string(),
272 reasoning: None,
273 },
274 ];
275
276 // 1. Verify default bounds
277 assert_eq!(DEFAULT_MAX_TOKENS, 4096);
278
279 let standard_models = [
280 "gpt-4o",
281 "gpt-4o-mini",
282 "gpt-4-turbo",
283 "atlas-lightning-omni",
284 "deepseek-chat",
285 "claude-3-7-sonnet",
286 ];
287
288 for model in standard_models {
289 // Default format
290 let p_default = format_openai_payload(model, &dummy_messages, None, false);
291 assert_eq!(
292 p_default["max_tokens"], 4096,
293 "Standard model {} must have max_tokens 4096 by default",
294 model
295 );
296 assert!(
297 p_default.get("max_completion_tokens").is_none(),
298 "Standard model {} must NOT have max_completion_tokens",
299 model
300 );
301
302 // Bounded with None (should fall back to DEFAULT_MAX_TOKENS, never unbounded)
303 let p_none = format_openai_payload_bounded(model, &dummy_messages, None, None, false);
304 assert_eq!(
305 p_none["max_tokens"], 4096,
306 "Standard model {} with None bound must fall back to default limit",
307 model
308 );
309
310 // Bounded with custom override
311 let p_custom =
312 format_openai_payload_bounded(model, &dummy_messages, None, Some(1024), false);
313 assert_eq!(
314 p_custom["max_tokens"], 1024,
315 "Standard model {} must respect custom max_tokens 1024",
316 model
317 );
318 }
319
320 // 2. Reasoning models: o1, o3 series
321 let reasoning_models = ["o1", "o1-preview", "o1-mini", "o3", "o3-mini", "o3-high"];
322
323 for model in reasoning_models {
324 // Default format
325 let p_default = format_openai_payload(model, &dummy_messages, None, false);
326 assert_eq!(
327 p_default["max_completion_tokens"], 4096,
328 "Reasoning model {} must have max_completion_tokens 4096 by default",
329 model
330 );
331 assert!(
332 p_default.get("max_tokens").is_none(),
333 "Reasoning model {} must NOT have max_tokens field",
334 model
335 );
336
337 // Bounded with None
338 let p_none = format_openai_payload_bounded(model, &dummy_messages, None, None, false);
339 assert_eq!(
340 p_none["max_completion_tokens"], 4096,
341 "Reasoning model {} with None bound must fall back to default limit",
342 model
343 );
344
345 // Bounded with custom override
346 let p_custom =
347 format_openai_payload_bounded(model, &dummy_messages, None, Some(8192), false);
348 assert_eq!(
349 p_custom["max_completion_tokens"], 8192,
350 "Reasoning model {} must respect custom max_completion_tokens 8192",
351 model
352 );
353 }
354
355 // 3. Extreme boundary values: Some(1), Some(65536)
356 let p_boundary_low =
357 format_openai_payload_bounded("gpt-4o", &dummy_messages, None, Some(1), false);
358 assert_eq!(p_boundary_low["max_tokens"], 1);
359
360 let p_boundary_high =
361 format_openai_payload_bounded("o3-mini", &dummy_messages, None, Some(65536), false);
362 assert_eq!(p_boundary_high["max_completion_tokens"], 65536);
363
364 println!("Challenge 3 Payload Bounding Pass: All models bounded strictly; reasoning models correctly map to max_completion_tokens.");
365}
366
367// ============================================================================
368// Challenge 4: Cortex Dynamic Auth and Zero Disk Touches
369// ============================================================================
370
371static CORTEX_CHALLENGE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
372static VAULT_CONCURRENCY_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
373
374#[tokio::test]
375async fn test_challenge4_cortex_commit_missing_token_fails_gracefully() {
376 let _guard = CORTEX_CHALLENGE_LOCK.lock().await;
377 // Explicitly simulate empty/missing token in test registry
378 register_test_secret("CORTEX_TOKEN", "");
379
380 let engine = DistillationEngine::new();
381 let res = engine
382 .commit_to_cortex(
383 "test_entity_missing",
384 "canonical_missing",
385 "content here",
386 "task_missing_1",
387 0.9,
388 )
389 .await;
390
391 // Must return Err indicating token missing, with zero panics
392 assert!(res.is_err(), "Must return error when token is missing");
393 let err_msg = res.unwrap_err();
394 assert!(
395 err_msg.contains("CORTEX_TOKEN not found"),
396 "Error must explicitly mention CORTEX_TOKEN not found, got: {}",
397 err_msg
398 );
399 remove_test_secret("CORTEX_TOKEN");
400 println!(
401 "Challenge 4 Missing Token Pass: Gracefully returned error: {}",
402 err_msg
403 );
404}
405
406#[tokio::test]
407async fn test_challenge4_cortex_dynamic_auth_and_zero_disk_touches() {
408 let _guard = CORTEX_CHALLENGE_LOCK.lock().await;
409 let mock_vault_token = "atlas_dynamic_vault_token_verification_secret_7718";
410 register_test_secret("CORTEX_TOKEN", mock_vault_token);
411
412 // Bind local ephemeral TCP listener for mock Cortex server
413 let listener = TcpListener::bind("127.0.0.1:0").expect("Bind ephemeral port for mock Cortex");
414 let port = listener.local_addr().expect("Local addr").port();
415 listener.set_nonblocking(false).expect("Blocking listener");
416
417 // Spawn server thread to capture incoming request and serve valid JSON receipt
418 let server_handle = thread::spawn(move || {
419 let (mut stream, _) = listener.accept().expect("Accept incoming connection");
420 stream
421 .set_read_timeout(Some(Duration::from_secs(5)))
422 .expect("Read timeout");
423
424 let mut raw_data = Vec::new();
425 let mut buf = [0u8; 1024];
426 loop {
427 let n = stream.read(&mut buf).expect("Read HTTP request");
428 if n == 0 {
429 break;
430 }
431 raw_data.extend_from_slice(&buf[..n]);
432 if let Some(pos) = raw_data.windows(4).position(|w| w == b"\r\n\r\n") {
433 let headers = String::from_utf8_lossy(&raw_data[..pos]);
434 let mut content_len = 0;
435 for line in headers.lines() {
436 if line.to_ascii_lowercase().starts_with("content-length:") {
437 if let Some(val) = line.split_once(58 as char).map(|x| x.1) {
438 content_len = val.trim().parse::<usize>().unwrap_or(0);
439 }
440 }
441 }
442 if raw_data.len() >= pos + 4 + content_len {
443 break;
444 }
445 }
446 }
447
448 let req_text = String::from_utf8_lossy(&raw_data).to_string();
449
450 let json_body = "{\"receipt\":{\"targetId\":\"cortex_entity_777\"}}";
451 let resp = format!(
452 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
453 json_body.len(),
454 json_body
455 );
456 stream
457 .write_all(resp.as_bytes())
458 .expect("Write HTTP response");
459 stream.flush().expect("Flush response");
460
461 req_text
462 });
463
464 // Create decoy disk file ~/.config/cortex/token with bogus content if not present
465 let home = std::env::var("HOME")
466 .unwrap_or_else(|_| std::env::temp_dir().to_string_lossy().into_owned());
467 let cortex_dir = PathBuf::from(&home).join(".config/cortex");
468 let decoy_file = cortex_dir.join("token");
469 let decoy_token = "BOGUS_DEPRECATED_DISK_TOKEN_NEVER_USE";
470
471 let had_decoy = decoy_file.exists();
472 if !had_decoy {
473 let _ = fs::create_dir_all(&cortex_dir);
474 let _ = fs::write(&decoy_file, decoy_token);
475 }
476
477 let mut engine = DistillationEngine::new();
478 engine.cortex_endpoint = format!("http://127.0.0.1:{}", port);
479
480 let result = engine
481 .commit_to_cortex(
482 "test_learned_entity",
483 "test_canonical_procedure",
484 "Optimized kernel execution with zero-copy KV blocks",
485 "task_distill_9918",
486 0.98,
487 )
488 .await;
489
490 // Clean up decoy file immediately if we created it
491 if !had_decoy && decoy_file.exists() {
492 let _ = fs::remove_file(&decoy_file);
493 }
494
495 assert!(
496 result.is_ok(),
497 "commit_to_cortex must succeed against mock server: {:?}",
498 result.err()
499 );
500 let entity_id = result.unwrap();
501 assert_eq!(entity_id, "cortex_entity_777");
502
503 let received_http_req = server_handle
504 .join()
505 .expect("Mock server thread must complete");
506
507 // Verify 1: Dynamic vault token was sent, NOT decoy disk token
508 let expected_auth_header = format!("authorization: bearer {}", mock_vault_token);
509 assert!(
510 received_http_req
511 .to_lowercase()
512 .contains(&expected_auth_header),
513 "Request must contain dynamic vault token Authorization header. Received:\n{}",
514 received_http_req
515 );
516 assert!(
517 !received_http_req.contains(decoy_token),
518 "Request must NEVER contain decoy disk token!"
519 );
520
521 // Verify 2: Space is atlas-memory
522 assert!(
523 received_http_req.contains("\"space\":\"atlas-memory\"")
524 || received_http_req.contains("\"space\": \"atlas-memory\""),
525 "Payload must target atlas-memory space"
526 );
527
528 // Verify 3: Payload attributes
529 assert!(received_http_req.contains("test_canonical_procedure"));
530 assert!(received_http_req.contains("learned_procedure"));
531
532 remove_test_secret("CORTEX_TOKEN");
533 println!("Challenge 4 Dynamic Auth Pass: Cortex request verified with dynamic vault token and atlas-memory space; zero disk token leakage.");
534}