Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/patches/06837b870ebeef27 # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aien-sovereign-core-mv#59 (code only) closed derived `06837b870ebeef27` #59 Imported from GitHub aien-dev/aien-sovereign-core-mv#59 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `2f500140d5e577d0de66b48f6b385dde276e7671` · Head `7171eed1d5518bb728a0a6880131a8fd167eea52` ### Apply it ``` git checkout -b patch-06837b870ebeef27 2f500140d5e577d0de66b48f6b385dde276e7671 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/06837b870ebeef27.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-sovereign-core-mv 59 7171eed1d5518bb728a0a6880131a8fd167eea52 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":59,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/59","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:35Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/Cargo.lock b/Cargo.lock index 9da24f52..854cc58d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -76,6 +76,15 @@ dependencies = [ "spin", ] +[[package]] +name = "aien-platform-linux" +version = "0.1.0" +dependencies = [ + "aien-platform", + "libc", + "parking_lot", +] + [[package]] name = "aien-scheduler" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 35c927ca..65350197 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ members = [ "crates/aien-scheduler", "crates/aien-security", "crates/aien-platform", + "crates/aien-platform-linux", ] [workspace.package] diff --git a/crates/aien-platform-linux/Cargo.toml b/crates/aien-platform-linux/Cargo.toml new file mode 100644 index 00000000..0fa8a736 --- /dev/null +++ b/crates/aien-platform-linux/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "aien-platform-linux" +version = "0.1.0" +edition = "2021" +authors = ["Drake Stapleton "] +description = "Linux and Grace Blackwell GB10 platform driver cell for the AIEN runtime" +license = "Apache-2.0" + +[dependencies] +aien-platform = { path = "../aien-platform" } +libc = "0.2" +parking_lot = "0.12" diff --git a/crates/aien-platform-linux/build.rs b/crates/aien-platform-linux/build.rs new file mode 100644 index 00000000..b6ca1652 --- /dev/null +++ b/crates/aien-platform-linux/build.rs @@ -0,0 +1,9 @@ +fn main() { + println!("cargo:rustc-check-cfg=cfg(has_blackwell_cuda)"); + let nvcc = std::path::PathBuf::from("/usr/local/cuda/bin/nvcc"); + if nvcc.exists() { + println!("cargo:rustc-link-search=native=/usr/local/cuda/lib64"); + println!("cargo:rustc-link-lib=dylib=cudart"); + println!("cargo:rustc-cfg=has_blackwell_cuda"); + } +} diff --git a/crates/aien-platform-linux/src/buffer.rs b/crates/aien-platform-linux/src/buffer.rs new file mode 100644 index 00000000..ad29bd3e --- /dev/null +++ b/crates/aien-platform-linux/src/buffer.rs @@ -0,0 +1,196 @@ +//! Linux Unified Buffer implementation for Grace Blackwell GB10 and Linux host. +//! Allocates anonymous page-aligned mmap with ATS hardware coherency on GB10. + +use aien_platform::{BufferLayout, DeviceAddress, PlatformError, UnifiedBuffer}; +use core::mem::align_of; +use core::ptr::NonNull; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LinuxMemoryKind { + AtsSystem, + HmmSystem, + CudaManagedFallback, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ResidencyPolicy { + Pageable, + FaultIn, + Locked, +} + +pub struct LinuxUnifiedBuffer { + ptr: NonNull, + mapping_base: NonNull, + mapping_len: usize, + len: usize, + align: usize, + kind: LinuxMemoryKind, + device_address: DeviceAddress, +} + +unsafe impl Send for LinuxUnifiedBuffer {} +unsafe impl Sync for LinuxUnifiedBuffer {} + +impl LinuxUnifiedBuffer { + pub fn allocate( + layout: BufferLayout, + kind: LinuxMemoryKind, + policy: ResidencyPolicy, + ) -> Result { + if layout.size == 0 { + return Err(PlatformError::InvalidLayout); + } + + let align = layout.align.max(align_of::()).max(64); + let mapping_len = layout + .size + .checked_add(align) + .ok_or(PlatformError::OutOfMemory)?; + + let (mapping_base_ptr, actual_kind) = match kind { + LinuxMemoryKind::AtsSystem | LinuxMemoryKind::HmmSystem => { + let p = unsafe { + libc::mmap( + core::ptr::null_mut(), + mapping_len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + if p == libc::MAP_FAILED || p.is_null() { + return Err(PlatformError::OutOfMemory); + } + (p as *mut u8, kind) + } + LinuxMemoryKind::CudaManagedFallback => { + #[cfg(has_blackwell_cuda)] + { + let mut p: *mut libc::c_void = core::ptr::null_mut(); + let res = unsafe { cudaMallocManaged(&mut p, mapping_len, 1) }; + if res == 0 && !p.is_null() { + (p as *mut u8, LinuxMemoryKind::CudaManagedFallback) + } else { + let fallback_ptr = unsafe { + libc::mmap( + core::ptr::null_mut(), + mapping_len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + if fallback_ptr == libc::MAP_FAILED || fallback_ptr.is_null() { + return Err(PlatformError::OutOfMemory); + } + (fallback_ptr as *mut u8, LinuxMemoryKind::AtsSystem) + } + } + #[cfg(not(has_blackwell_cuda))] + { + let p = unsafe { + libc::mmap( + core::ptr::null_mut(), + mapping_len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANONYMOUS, + -1, + 0, + ) + }; + if p == libc::MAP_FAILED || p.is_null() { + return Err(PlatformError::OutOfMemory); + } + (p as *mut u8, LinuxMemoryKind::AtsSystem) + } + } + }; + + let mapping_base = NonNull::new(mapping_base_ptr).ok_or(PlatformError::OutOfMemory)?; + let base_addr = mapping_base_ptr as usize; + let aligned_addr = (base_addr + align - 1) & !(align - 1); + let ptr = NonNull::new(aligned_addr as *mut u8).ok_or(PlatformError::OutOfMemory)?; + + if policy == ResidencyPolicy::FaultIn { + let page_size = 4096; + for offset in (0..layout.size).step_by(page_size) { + unsafe { + core::ptr::write_volatile(ptr.as_ptr().add(offset), 0); + } + } + } + + let device_address = DeviceAddress(aligned_addr as u64); + + Ok(Self { + ptr, + mapping_base, + mapping_len, + len: layout.size, + align, + kind: actual_kind, + device_address, + }) + } + + pub fn kind(&self) -> LinuxMemoryKind { + self.kind + } + + pub fn alignment(&self) -> usize { + self.align + } +} + +impl UnifiedBuffer for LinuxUnifiedBuffer { + fn len(&self) -> usize { + self.len + } + + fn device_address(&self) -> DeviceAddress { + self.device_address + } + + fn as_ptr(&self) -> *const u8 { + self.ptr.as_ptr() + } + + fn as_mut_ptr(&mut self) -> *mut u8 { + self.ptr.as_ptr() + } +} + +impl Drop for LinuxUnifiedBuffer { + fn drop(&mut self) { + match self.kind { + LinuxMemoryKind::AtsSystem | LinuxMemoryKind::HmmSystem => unsafe { + libc::munmap( + self.mapping_base.as_ptr() as *mut libc::c_void, + self.mapping_len, + ); + }, + LinuxMemoryKind::CudaManagedFallback => { + #[cfg(has_blackwell_cuda)] + unsafe { + cudaFree(self.mapping_base.as_ptr() as *mut libc::c_void); + } + #[cfg(not(has_blackwell_cuda))] + unsafe { + libc::munmap( + self.mapping_base.as_ptr() as *mut libc::c_void, + self.mapping_len, + ); + } + } + } + } +} + +#[cfg(has_blackwell_cuda)] +extern "C" { + fn cudaMallocManaged(dev_ptr: *mut *mut libc::c_void, size: usize, flags: u32) -> i32; + fn cudaFree(dev_ptr: *mut libc::c_void) -> i32; +} diff --git a/crates/aien-platform-linux/src/device.rs b/crates/aien-platform-linux/src/device.rs new file mode 100644 index 00000000..4d3a7db8 --- /dev/null +++ b/crates/aien-platform-linux/src/device.rs @@ -0,0 +1,146 @@ +//! Linux Compute Device implementation for Grace Blackwell GB10. +//! Binds to GB10 GPU with ATS coherency, or provides Linux host execution. + +use crate::buffer::{LinuxMemoryKind, LinuxUnifiedBuffer, ResidencyPolicy}; +use aien_platform::{BufferLayout, ComputeDevice, ComputeWork, Fence, PlatformError}; +use core::sync::atomic::{AtomicU64, Ordering}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LinuxCudaCapabilities { + pub concurrent_managed_access: bool, + pub pageable_memory_access: bool, + pub uses_host_page_tables: bool, + pub direct_managed_access_from_host: bool, + pub host_native_atomics: bool, +} + +impl LinuxCudaCapabilities { + pub fn detect() -> Self { + #[cfg(has_blackwell_cuda)] + { + let mut caps = Self { + concurrent_managed_access: false, + pageable_memory_access: false, + uses_host_page_tables: false, + direct_managed_access_from_host: false, + host_native_atomics: false, + }; + + let get_attr = |attr: i32| -> i32 { + let mut val = 0; + let res = unsafe { cudaDeviceGetAttribute(&mut val, attr, 0) }; + if res == 0 { + val + } else { + 0 + } + }; + + caps.concurrent_managed_access = get_attr(89) != 0; + caps.pageable_memory_access = get_attr(97) != 0; + caps.uses_host_page_tables = get_attr(100) != 0; + caps.direct_managed_access_from_host = get_attr(98) != 0; + caps.host_native_atomics = get_attr(99) != 0; + + caps + } + #[cfg(not(has_blackwell_cuda))] + { + Self { + concurrent_managed_access: false, + pageable_memory_access: false, + uses_host_page_tables: false, + direct_managed_access_from_host: false, + host_native_atomics: false, + } + } + } + + pub fn is_ats_hardware_coherent(&self) -> bool { + self.pageable_memory_access && self.uses_host_page_tables + } +} + +pub struct LinuxComputeDevice { + device_id: u32, + capabilities: LinuxCudaCapabilities, + fence_counter: AtomicU64, +} + +impl LinuxComputeDevice { + pub fn new() -> Self { + Self::with_device_id(0) + } + + pub fn with_device_id(device_id: u32) -> Self { + #[cfg(has_blackwell_cuda)] + unsafe { + let _ = cudaSetDevice(device_id as i32); + } + + let capabilities = LinuxCudaCapabilities::detect(); + Self { + device_id, + capabilities, + fence_counter: AtomicU64::new(1), + } + } + + pub fn device_id(&self) -> u32 { + self.device_id + } + + pub fn capabilities(&self) -> &LinuxCudaCapabilities { + &self.capabilities + } + + pub fn preferred_memory_kind(&self) -> LinuxMemoryKind { + if self.capabilities.is_ats_hardware_coherent() { + LinuxMemoryKind::AtsSystem + } else if self.capabilities.pageable_memory_access { + LinuxMemoryKind::HmmSystem + } else { + LinuxMemoryKind::CudaManagedFallback + } + } +} + +impl Default for LinuxComputeDevice { + fn default() -> Self { + Self::new() + } +} + +impl ComputeDevice for LinuxComputeDevice { + type Buffer = LinuxUnifiedBuffer; + + fn alloc(&self, layout: BufferLayout) -> Result { + let kind = self.preferred_memory_kind(); + LinuxUnifiedBuffer::allocate(layout, kind, ResidencyPolicy::FaultIn) + } + + fn submit(&self, _work: ComputeWork<'_>) -> Result { + let id = self.fence_counter.fetch_add(1, Ordering::SeqCst); + Ok(Fence(id)) + } + + fn synchronize(&self, _fence: Fence) -> Result<(), PlatformError> { + #[cfg(has_blackwell_cuda)] + unsafe { + let res = cudaDeviceSynchronize(); + if res != 0 { + return Err(PlatformError::HardwareFault( + "cudaDeviceSynchronize failed".into(), + )); + } + } + Ok(()) + } +} + +#[cfg(has_blackwell_cuda)] +extern "C" { + fn cudaDeviceGetAttribute(value: *mut i32, attr: i32, device: i32) -> i32; + fn cudaSetDevice(device: i32) -> i32; + fn cudaDeviceSynchronize() -> i32; +} diff --git a/crates/aien-platform-linux/src/lib.rs b/crates/aien-platform-linux/src/lib.rs new file mode 100644 index 00000000..753371a9 --- /dev/null +++ b/crates/aien-platform-linux/src/lib.rs @@ -0,0 +1,133 @@ +//! Linux and Grace Blackwell GB10 platform driver cell for the AIEN runtime. + +pub mod buffer; +pub mod device; +pub mod queue; +pub mod telemetry; + +pub use buffer::{LinuxMemoryKind, LinuxUnifiedBuffer, ResidencyPolicy}; +pub use device::{LinuxComputeDevice, LinuxCudaCapabilities}; +pub use queue::LinuxWorkQueue; +pub use telemetry::LinuxTelemetrySource; + +#[cfg(test)] +mod tests { + use super::*; + use aien_platform::{ + BufferLayout, ComputeDevice, InferenceWork, KvHandle, ModelHandle, Priority, + TelemetrySource, UnifiedBuffer, WorkQueue, + }; + + #[test] + fn test_linux_unified_buffer_allocation_and_read_write() { + let layout = BufferLayout::new(65536, 128); + let mut buf = LinuxUnifiedBuffer::allocate( + layout, + LinuxMemoryKind::AtsSystem, + ResidencyPolicy::FaultIn, + ) + .expect("Failed to allocate LinuxUnifiedBuffer"); + + assert_eq!(buf.len(), 65536); + assert!(buf.device_address().0 != 0); + assert_eq!(buf.device_address().0 % 128, 0); + + unsafe { + let p = buf.as_mut_ptr(); + *p = 42; + *p.add(65535) = 99; + assert_eq!(*buf.as_ptr(), 42); + assert_eq!(*buf.as_ptr().add(65535), 99); + } + } + + #[test] + fn test_linux_compute_device_allocation() { + let device = LinuxComputeDevice::new(); + let layout = BufferLayout::new(1024 * 1024, 256); + let buf = device + .alloc(layout) + .expect("Failed to allocate from LinuxComputeDevice"); + + assert_eq!(buf.len(), 1024 * 1024); + assert_eq!(buf.device_address().0 % 256, 0); + } + + #[test] + fn test_linux_work_queue_priority_and_deadline() { + let queue = LinuxWorkQueue::new(64); + let w_bg = InferenceWork { + sequence: 1, + model: ModelHandle(1), + kv: KvHandle(1), + priority: Priority::Background, + deadline: None, + branch_parent: None, + next_token_budget: 16, + }; + let w_rt = InferenceWork { + sequence: 2, + model: ModelHandle(1), + kv: KvHandle(2), + priority: Priority::Realtime, + deadline: Some(100), + branch_parent: None, + next_token_budget: 16, + }; + let w_rt_earlier = InferenceWork { + sequence: 3, + model: ModelHandle(1), + kv: KvHandle(3), + priority: Priority::Realtime, + deadline: Some(50), + branch_parent: None, + next_token_budget: 16, + }; + + queue.push(w_bg).expect("Push background failed"); + queue.push(w_rt).expect("Push realtime failed"); + queue + .push(w_rt_earlier) + .expect("Push earlier realtime failed"); + + assert_eq!(queue.len(), 3); + + let first = queue.pop().expect("Pop first"); + assert_eq!(first.sequence, 3); + + let second = queue.pop().expect("Pop second"); + assert_eq!(second.sequence, 2); + + let third = queue.pop().expect("Pop third"); + assert_eq!(third.sequence, 1); + + assert!(queue.is_empty()); + } + + #[test] + fn test_linux_gb10_ats_capabilities_if_available() { + let device = LinuxComputeDevice::new(); + let caps = device.capabilities(); + eprintln!("LinuxComputeDevice detected capabilities: {:?}", caps); + eprintln!( + "Preferred memory kind: {:?}", + device.preferred_memory_kind() + ); + + #[cfg(has_blackwell_cuda)] + { + if caps.is_ats_hardware_coherent() { + assert_eq!(device.preferred_memory_kind(), LinuxMemoryKind::AtsSystem); + } + } + } + + #[test] + fn test_linux_telemetry_source_snapshot() { + let source = LinuxTelemetrySource::new(); + let snap = source.snapshot().expect("Snapshot failed"); + assert!(!snap.architecture.is_empty()); + assert!(!snap.target.is_empty()); + assert!(snap.clock_ticks > 0); + } +} diff --git a/crates/aien-platform-linux/src/queue.rs b/crates/aien-platform-linux/src/queue.rs new file mode 100644 index 00000000..18bfedec --- /dev/null +++ b/crates/aien-platform-linux/src/queue.rs @@ -0,0 +1,73 @@ +//! Priority-deadline concurrent WorkQueue for the Linux platform. + +use aien_platform::{InferenceWork, QueueError, WorkQueue}; +use parking_lot::Mutex; +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +#[derive(Debug, Clone, PartialEq, Eq)] +struct ScheduledWorkItem(InferenceWork); + +impl Ord for ScheduledWorkItem { + fn cmp(&self, other: &Self) -> Ordering { + match self.0.priority.cmp(&other.0.priority) { + Ordering::Equal => match (self.0.deadline, other.0.deadline) { + (Some(d1), Some(d2)) => d2.cmp(&d1), + (Some(_), None) => Ordering::Greater, + (None, Some(_)) => Ordering::Less, + (None, None) => Ordering::Equal, + }, + ord => ord, + } + } +} + +impl PartialOrd for ScheduledWorkItem { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +pub struct LinuxWorkQueue { + capacity: usize, + items: Mutex>, +} + +impl LinuxWorkQueue { + pub fn new(capacity: usize) -> Self { + Self { + capacity, + items: Mutex::new(BinaryHeap::with_capacity(capacity)), + } + } + + pub fn with_default_capacity() -> Self { + Self::new(4096) + } +} + +impl Default for LinuxWorkQueue { + fn default() -> Self { + Self::with_default_capacity() + } +} + +impl WorkQueue for LinuxWorkQueue { + fn push(&self, work: InferenceWork) -> Result<(), QueueError> { + let mut heap = self.items.lock(); + if heap.len() >= self.capacity { + return Err(QueueError::Full); + } + heap.push(ScheduledWorkItem(work)); + Ok(()) + } + + fn pop(&self) -> Option { + let mut heap = self.items.lock(); + heap.pop().map(|item| item.0) + } + + fn len(&self) -> usize { + self.items.lock().len() + } +} diff --git a/crates/aien-platform-linux/src/telemetry.rs b/crates/aien-platform-linux/src/telemetry.rs new file mode 100644 index 00000000..02dad645 --- /dev/null +++ b/crates/aien-platform-linux/src/telemetry.rs @@ -0,0 +1,58 @@ +//! Telemetry source for Linux and DGX Spark GB10. + +use aien_platform::{PlatformError, TelemetrySnapshot, TelemetrySource}; +use std::fs; + +pub struct LinuxTelemetrySource; + +impl LinuxTelemetrySource { + pub fn new() -> Self { + Self + } +} + +impl Default for LinuxTelemetrySource { + fn default() -> Self { + Self::new() + } +} + +impl TelemetrySource for LinuxTelemetrySource { + fn snapshot(&self) -> Result { + let mut total_mem = 0usize; + let mut avail_mem = 0usize; + + if let Ok(meminfo) = fs::read_to_string("/proc/meminfo") { + for line in meminfo.lines() { + if line.starts_with("MemTotal:") { + if let Some(val) = line.split_whitespace().nth(1) { + total_mem = val.parse::().unwrap_or(0) * 1024; + } + } else if line.starts_with("MemAvailable:") { + if let Some(val) = line.split_whitespace().nth(1) { + avail_mem = val.parse::().unwrap_or(0) * 1024; + } + } + } + } + + let used_mem = total_mem.saturating_sub(avail_mem); + let target = if cfg!(target_arch = "aarch64") { + "gb10" + } else { + "x86_64-linux" + }; + + Ok(TelemetrySnapshot { + architecture: std::env::consts::ARCH.to_string(), + target: target.to_string(), + clock_ticks: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0), + memory_used_bytes: used_mem, + memory_total_bytes: total_mem, + active_sequences: 0, + }) + } +} diff --git a/crates/cortex-rs/src/auth.rs b/crates/cortex-rs/src/auth.rs index 660c9019..6afe941b 100644 --- a/crates/cortex-rs/src/auth.rs +++ b/crates/cortex-rs/src/auth.rs @@ -29,7 +29,10 @@ pub fn load_cortex_token() -> String { } } -pub fn validate_auth_header(auth_header: Option<&str>, expected_token: &str) -> Result<(), StatusCode> { +pub fn validate_auth_header( + auth_header: Option<&str>, + expected_token: &str, +) -> Result<(), StatusCode> { if expected_token.is_empty() { return Err(StatusCode::SERVICE_UNAVAILABLE); } @@ -48,7 +51,10 @@ pub fn validate_auth_header(auth_header: Option<&str>, expected_token: &str) -> pub async fn auth_middleware(req: Request, next: Next) -> Result { let expected = load_cortex_token(); - let auth_header = req.headers().get("Authorization").and_then(|h| h.to_str().ok()); + let auth_header = req + .headers() + .get("Authorization") + .and_then(|h| h.to_str().ok()); match validate_auth_header(auth_header, &expected) { Ok(()) => Ok(next.run(req).await), @@ -63,7 +69,8 @@ pub async fn auth_middleware(req: Request, next: Next) -> Result Result<(), Box> { let tmp_path = std::env::temp_dir().join(format!("cortex_bench_{}.db", std::process::id())); @@ -35,7 +35,10 @@ pub fn run_benchmark(records: usize) -> Result<(), Box> { for i in 0..records { let (domain, desc) = sample_domains[i % sample_domains.len()]; let canonical_name = format!("{}:entity_{:05}", domain, i); - let content = format!("{} Record ID {} generated for production deployment telemetry verification.", desc, i); + let content = format!( + "{} Record ID {} generated for production deployment telemetry verification.", + desc, i + ); let input = EntityWriteInput { id: None, space: "atlas-memory".to_string(), @@ -60,7 +63,10 @@ pub fn run_benchmark(records: usize) -> Result<(), Box> { let ingest_qps = records as f64 / total_ingest_time.as_secs_f64(); // 2. Search Benchmark - println!("[2/3] Benchmarking FTS5 Lexical Search across {} records...", records); + println!( + "[2/3] Benchmarking FTS5 Lexical Search across {} records...", + records + ); let search_queries = [ "tpm vault", "unified memory", @@ -161,8 +167,14 @@ pub fn run_benchmark(records: usize) -> Result<(), Box> { traverse_qps ); println!("--------------------------------------------------------------------------------"); - println!("Search p50 in milliseconds: {:.3} ms", percentile(&search_latencies_us, 50.0) / 1000.0); - println!("Search p99 in milliseconds: {:.3} ms", percentile(&search_latencies_us, 99.0) / 1000.0); + println!( + "Search p50 in milliseconds: {:.3} ms", + percentile(&search_latencies_us, 50.0) / 1000.0 + ); + println!( + "Search p99 in milliseconds: {:.3} ms", + percentile(&search_latencies_us, 99.0) / 1000.0 + ); println!("================================================================================"); // Cleanup diff --git a/crates/cortex-rs/src/db.rs b/crates/cortex-rs/src/db.rs index a81c18dc..807949a2 100644 --- a/crates/cortex-rs/src/db.rs +++ b/crates/cortex-rs/src/db.rs @@ -122,17 +122,25 @@ impl Database { Ok(new_id) } - pub fn upsert_entity(&self, input: &EntityWriteInput, embedding: Option<&[f32]>) -> Result { + pub fn upsert_entity( + &self, + input: &EntityWriteInput, + embedding: Option<&[f32]>, + ) -> Result { let space_id = self.ensure_space(&input.space)?; let conn = self.conn.lock().unwrap(); let now = Utc::now().to_rfc3339(); let embedding_blob = embedding.map(embedding_to_bytes); - let aliases_json = serde_json::to_string(&input.aliases).unwrap_or_else(|_| "[]".to_string()); - let metadata_json = serde_json::to_string(&input.metadata).unwrap_or_else(|_| "{}".to_string()); + let aliases_json = + serde_json::to_string(&input.aliases).unwrap_or_else(|_| "[]".to_string()); + let metadata_json = + serde_json::to_string(&input.metadata).unwrap_or_else(|_| "{}".to_string()); // Check if entity exists by canonical_name in space - let mut stmt = conn.prepare("SELECT id, revision FROM entities WHERE space_slug = ?1 AND canonical_name = ?2")?; + let mut stmt = conn.prepare( + "SELECT id, revision FROM entities WHERE space_slug = ?1 AND canonical_name = ?2", + )?; let mut rows = stmt.query(params![input.space, input.canonical_name])?; let (target_id, revision) = if let Some(row) = rows.next()? { @@ -140,7 +148,10 @@ impl Database { let rev: i64 = row.get(1)?; (existing_id, rev + 1) } else { - let new_id = input.id.clone().unwrap_or_else(|| Uuid::new_v4().to_string()); + let new_id = input + .id + .clone() + .unwrap_or_else(|| Uuid::new_v4().to_string()); (new_id, 1) }; drop(rows); @@ -199,9 +210,16 @@ impl Database { let space_id = self.ensure_space(&input.space)?; let conn = self.conn.lock().unwrap(); let now = Utc::now().to_rfc3339(); - let claim_id = input.id.clone().unwrap_or_else(|| Uuid::new_v4().to_string()); - let literal_json = input.literal_value.as_ref().map(|v| serde_json::to_string(v).unwrap_or_default()); - let metadata_json = serde_json::to_string(&input.metadata).unwrap_or_else(|_| "{}".to_string()); + let claim_id = input + .id + .clone() + .unwrap_or_else(|| Uuid::new_v4().to_string()); + let literal_json = input + .literal_value + .as_ref() + .map(|v| serde_json::to_string(v).unwrap_or_default()); + let metadata_json = + serde_json::to_string(&input.metadata).unwrap_or_else(|_| "{}".to_string()); conn.execute( "INSERT INTO claims (id, space_id, space_slug, subject_entity_id, predicate, object_entity_id, literal_value_json, confidence, metadata_json, retracted, created_at) @@ -241,10 +259,16 @@ impl Database { let now = Utc::now().to_rfc3339(); if target_type == "entity" { - conn.execute("UPDATE entities SET retracted = 1 WHERE id = ?1", params![target_id])?; + conn.execute( + "UPDATE entities SET retracted = 1 WHERE id = ?1", + params![target_id], + )?; conn.execute("DELETE FROM entities_fts WHERE id = ?1", params![target_id])?; } else if target_type == "claim" { - conn.execute("UPDATE claims SET retracted = 1 WHERE id = ?1", params![target_id])?; + conn.execute( + "UPDATE claims SET retracted = 1 WHERE id = ?1", + params![target_id], + )?; } Ok(ReceiptDetails { @@ -256,7 +280,11 @@ impl Database { }) } - pub fn get_entity(&self, id_or_name: &str, space: Option<&str>) -> Result> { + pub fn get_entity( + &self, + id_or_name: &str, + space: Option<&str>, + ) -> Result> { let conn = self.conn.lock().unwrap(); let target_space = space.unwrap_or("atlas-memory"); @@ -292,7 +320,12 @@ impl Database { } } - pub fn search_entities(&self, query: &str, space: Option<&str>, limit: usize) -> Result> { + pub fn search_entities( + &self, + query: &str, + space: Option<&str>, + limit: usize, + ) -> Result> { let conn = self.conn.lock().unwrap(); let target_space = space.unwrap_or("atlas-memory"); let query_trimmed = query.trim(); @@ -317,7 +350,8 @@ impl Database { canonical_name: row.get(4)?, content: row.get(5)?, aliases: serde_json::from_str(&aliases_str).unwrap_or_default(), - metadata: serde_json::from_str(&meta_str).unwrap_or_else(|_| serde_json::json!({})), + metadata: serde_json::from_str(&meta_str) + .unwrap_or_else(|_| serde_json::json!({})), confidence: row.get(8)?, revision: row.get(9)?, retracted: row.get::<_, i64>(10)? != 0, @@ -359,34 +393,37 @@ impl Database { LIMIT ?3" ).ok()?; - let rows = stmt.query_map(params![query_str, target_space, limit], |row| { - let aliases_str: String = row.get(6)?; - let meta_str: String = row.get(7)?; - let bm25_rank: f64 = row.get(14)?; - let lexical_score = 1.0 / (1.0 + bm25_rank.abs()); - Ok(SearchResult { - entity: CortexEntity { - id: row.get(0)?, - space_id: row.get(1)?, - space_slug: row.get(2)?, - entity_type: row.get(3)?, - canonical_name: row.get(4)?, - content: row.get(5)?, - aliases: serde_json::from_str(&aliases_str).unwrap_or_default(), - metadata: serde_json::from_str(&meta_str).unwrap_or_else(|_| serde_json::json!({})), - confidence: row.get(8)?, - revision: row.get(9)?, - retracted: row.get::<_, i64>(10)? != 0, - valid_from: row.get(11)?, - valid_to: row.get(12)?, - created_at: row.get(13)?, - }, - lexical_score, - graph_score: 0.0, - semantic_score: 0.0, - score: lexical_score, + let rows = stmt + .query_map(params![query_str, target_space, limit], |row| { + let aliases_str: String = row.get(6)?; + let meta_str: String = row.get(7)?; + let bm25_rank: f64 = row.get(14)?; + let lexical_score = 1.0 / (1.0 + bm25_rank.abs()); + Ok(SearchResult { + entity: CortexEntity { + id: row.get(0)?, + space_id: row.get(1)?, + space_slug: row.get(2)?, + entity_type: row.get(3)?, + canonical_name: row.get(4)?, + content: row.get(5)?, + aliases: serde_json::from_str(&aliases_str).unwrap_or_default(), + metadata: serde_json::from_str(&meta_str) + .unwrap_or_else(|_| serde_json::json!({})), + confidence: row.get(8)?, + revision: row.get(9)?, + retracted: row.get::<_, i64>(10)? != 0, + valid_from: row.get(11)?, + valid_to: row.get(12)?, + created_at: row.get(13)?, + }, + lexical_score, + graph_score: 0.0, + semantic_score: 0.0, + score: lexical_score, + }) }) - }).ok()?; + .ok()?; let mut out = Vec::new(); for r in rows.flatten() { @@ -439,7 +476,8 @@ impl Database { canonical_name: row.get(4)?, content: row.get(5)?, aliases: serde_json::from_str(&aliases_str).unwrap_or_default(), - metadata: serde_json::from_str(&meta_str).unwrap_or_else(|_| serde_json::json!({})), + metadata: serde_json::from_str(&meta_str) + .unwrap_or_else(|_| serde_json::json!({})), confidence: row.get(8)?, revision: row.get(9)?, retracted: row.get::<_, i64>(10)? != 0, @@ -455,7 +493,10 @@ impl Database { })?; for r in sub_rows { let sr = r?; - if !results.iter().any(|existing| existing.entity.id == sr.entity.id) { + if !results + .iter() + .any(|existing| existing.entity.id == sr.entity.id) + { results.push(sr); } } @@ -465,7 +506,13 @@ impl Database { Ok(results) } - pub fn recall_entities(&self, query_text: &str, query_embedding: Option<&[f32]>, space: Option<&str>, limit: usize) -> Result> { + pub fn recall_entities( + &self, + query_text: &str, + query_embedding: Option<&[f32]>, + space: Option<&str>, + limit: usize, + ) -> Result> { let conn = self.conn.lock().unwrap(); let target_space = space.unwrap_or("atlas-memory"); @@ -538,12 +585,20 @@ impl Database { }); } - candidates.sort_by(|a, b| b.final_score.partial_cmp(&a.final_score).unwrap_or(std::cmp::Ordering::Equal)); + candidates.sort_by(|a, b| { + b.final_score + .partial_cmp(&a.final_score) + .unwrap_or(std::cmp::Ordering::Equal) + }); candidates.truncate(limit); Ok(candidates) } - pub fn traverse_claims(&self, subject_id: &str, space: Option<&str>) -> Result> { + pub fn traverse_claims( + &self, + subject_id: &str, + space: Option<&str>, + ) -> Result> { let conn = self.conn.lock().unwrap(); let target_space = space.unwrap_or("atlas-memory"); @@ -578,11 +633,17 @@ impl Database { Ok(claims) } - pub fn import_entity_raw(&self, entity: &CortexEntity, embedding: Option<&[f32]>) -> Result<()> { + pub fn import_entity_raw( + &self, + entity: &CortexEntity, + embedding: Option<&[f32]>, + ) -> Result<()> { let conn = self.conn.lock().unwrap(); let embedding_blob = embedding.map(embedding_to_bytes); - let aliases_json = serde_json::to_string(&entity.aliases).unwrap_or_else(|_| "[]".to_string()); - let metadata_json = serde_json::to_string(&entity.metadata).unwrap_or_else(|_| "{}".to_string()); + let aliases_json = + serde_json::to_string(&entity.aliases).unwrap_or_else(|_| "[]".to_string()); + let metadata_json = + serde_json::to_string(&entity.metadata).unwrap_or_else(|_| "{}".to_string()); conn.execute( "INSERT INTO entities (id, space_id, space_slug, entity_type, canonical_name, content, aliases_json, metadata_json, confidence, revision, retracted, valid_from, valid_to, created_at, embedding) @@ -651,20 +712,31 @@ mod tests { }; let dummy_emb = vec![0.5f32; 768]; - let receipt = db.upsert_entity(&input, Some(&dummy_emb)).expect("upsert entity"); + let receipt = db + .upsert_entity(&input, Some(&dummy_emb)) + .expect("upsert entity"); assert_eq!(receipt.operation, "entity.upsert"); - let fetched = db.get_entity("test_cortex_rebuild", Some("atlas-memory")).expect("get entity"); + let fetched = db + .get_entity("test_cortex_rebuild", Some("atlas-memory")) + .expect("get entity"); assert!(fetched.is_some()); let entity = fetched.unwrap(); assert_eq!(entity.canonical_name, "test_cortex_rebuild"); assert_eq!(entity.aliases.len(), 1); - let search_results = db.search_entities("Rust", Some("atlas-memory"), 10).expect("search"); + let search_results = db + .search_entities("Rust", Some("atlas-memory"), 10) + .expect("search"); assert!(!search_results.is_empty()); - assert_eq!(search_results[0].entity.canonical_name, "test_cortex_rebuild"); + assert_eq!( + search_results[0].entity.canonical_name, + "test_cortex_rebuild" + ); - let recall_results = db.recall_entities("Rust", Some(&dummy_emb), Some("atlas-memory"), 5).expect("recall"); + let recall_results = db + .recall_entities("Rust", Some(&dummy_emb), Some("atlas-memory"), 5) + .expect("recall"); assert!(!recall_results.is_empty()); assert!(recall_results[0].final_score > 0.5); } @@ -681,7 +753,9 @@ mod tests { // Verify WAL mode is active { let conn = db.conn.lock().unwrap(); - let mode: String = conn.query_row("PRAGMA journal_mode", [], |r| r.get(0)).unwrap(); + let mode: String = conn + .query_row("PRAGMA journal_mode", [], |r| r.get(0)) + .unwrap(); assert_eq!(mode.to_lowercase(), "wal"); } @@ -705,7 +779,9 @@ mod tests { valid_to: None, external_id: None, }; - let receipt = db_clone.upsert_entity(&input, None).expect("concurrent entity upsert"); + let receipt = db_clone + .upsert_entity(&input, None) + .expect("concurrent entity upsert"); assert_eq!(receipt.operation, "entity.upsert"); // Also write a claim @@ -719,7 +795,9 @@ mod tests { confidence: 1.0, metadata: serde_json::json!({}), }; - let claim_receipt = db_clone.upsert_claim(&claim_input).expect("concurrent claim upsert"); + let claim_receipt = db_clone + .upsert_claim(&claim_input) + .expect("concurrent claim upsert"); assert_eq!(claim_receipt.operation, "claim.upsert"); } })); @@ -751,11 +829,20 @@ mod tests { for t in 0..4 { for i in 0..10 { let name = format!("entity_t{}_i{}", t, i); - let ent = reopened.get_entity(&name, Some("atlas-memory")).expect("get persisted entity"); - assert!(ent.is_some(), "Entity {} must persist across restarts", name); + let ent = reopened + .get_entity(&name, Some("atlas-memory")) + .expect("get persisted entity"); + assert!( + ent.is_some(), + "Entity {} must persist across restarts", + name + ); let e = ent.unwrap(); assert_eq!(e.canonical_name, name); - assert_eq!(e.content, format!("Content from thread {} iteration {}", t, i)); + assert_eq!( + e.content, + format!("Content from thread {} iteration {}", t, i) + ); } } @@ -767,11 +854,31 @@ mod tests { let db = Database::open_in_memory().expect("open in memory db"); let items = vec![ - ("NVFP4_Loader", "High throughput native NVFP4 checkpoint loader for vLLM and MAX", "discovery"), - ("Qwen3_Parser", "Llama cpp tokenizer and grammar parser for Qwen3 models", "learned_procedure"), - ("TPM_Vault", "Hardware TPM bound key vault with zero plaintext secrets on disk", "lesson"), - ("Sovereign_Covenant", "Frontier AI Anti Enclosure mandate and sovereign defense network", "discovery"), - ("Memory_Optimizer", "Memory architecture optimization for memory engines with memory reuse", "lesson"), + ( + "NVFP4_Loader", + "High throughput native NVFP4 checkpoint loader for vLLM and MAX", + "discovery", + ), + ( + "Qwen3_Parser", + "Llama cpp tokenizer and grammar parser for Qwen3 models", + "learned_procedure", + ), + ( + "TPM_Vault", + "Hardware TPM bound key vault with zero plaintext secrets on disk", + "lesson", + ), + ( + "Sovereign_Covenant", + "Frontier AI Anti Enclosure mandate and sovereign defense network", + "discovery", + ), + ( + "Memory_Optimizer", + "Memory architecture optimization for memory engines with memory reuse", + "lesson", + ), ]; for (name, content, etype) in items { @@ -792,49 +899,72 @@ mod tests { } // 1. Exact term matching - let exact_res = db.search_entities("NVFP4", Some("atlas-memory"), 10).expect("search exact"); + let exact_res = db + .search_entities("NVFP4", Some("atlas-memory"), 10) + .expect("search exact"); assert_eq!(exact_res.len(), 1); assert_eq!(exact_res[0].entity.canonical_name, "NVFP4_Loader"); - let exact_tpm = db.search_entities("TPM", Some("atlas-memory"), 10).expect("search exact TPM"); + let exact_tpm = db + .search_entities("TPM", Some("atlas-memory"), 10) + .expect("search exact TPM"); assert_eq!(exact_tpm.len(), 1); assert_eq!(exact_tpm[0].entity.canonical_name, "TPM_Vault"); // 2. Prefix queries - let prefix_res = db.search_entities("NVF*", Some("atlas-memory"), 10).expect("search prefix"); + let prefix_res = db + .search_entities("NVF*", Some("atlas-memory"), 10) + .expect("search prefix"); assert_eq!(prefix_res.len(), 1); assert_eq!(prefix_res[0].entity.canonical_name, "NVFP4_Loader"); - let prefix_hard = db.search_entities("hardw*", Some("atlas-memory"), 10).expect("search prefix hardw*"); + let prefix_hard = db + .search_entities("hardw*", Some("atlas-memory"), 10) + .expect("search prefix hardw*"); assert_eq!(prefix_hard.len(), 1); assert_eq!(prefix_hard[0].entity.canonical_name, "TPM_Vault"); - let prefix_token = db.search_entities("token*", Some("atlas-memory"), 10).expect("search prefix token*"); + let prefix_token = db + .search_entities("token*", Some("atlas-memory"), 10) + .expect("search prefix token*"); assert_eq!(prefix_token.len(), 1); assert_eq!(prefix_token[0].entity.canonical_name, "Qwen3_Parser"); // 3. Boolean AND - let and_res = db.search_entities("NVFP4 AND vLLM", Some("atlas-memory"), 10).expect("search AND"); + let and_res = db + .search_entities("NVFP4 AND vLLM", Some("atlas-memory"), 10) + .expect("search AND"); assert_eq!(and_res.len(), 1); assert_eq!(and_res[0].entity.canonical_name, "NVFP4_Loader"); - let and_mismatch = db.search_entities("NVFP4 AND non_existent_token", Some("atlas-memory"), 10).expect("search AND mismatch"); + let and_mismatch = db + .search_entities("NVFP4 AND non_existent_token", Some("atlas-memory"), 10) + .expect("search AND mismatch"); assert_eq!(and_mismatch.len(), 0); // 4. Boolean OR - let or_res = db.search_entities("Qwen3 OR TPM", Some("atlas-memory"), 10).expect("search OR"); + let or_res = db + .search_entities("Qwen3 OR TPM", Some("atlas-memory"), 10) + .expect("search OR"); assert_eq!(or_res.len(), 2); - let names: Vec = or_res.into_iter().map(|r| r.entity.canonical_name).collect(); + let names: Vec = or_res + .into_iter() + .map(|r| r.entity.canonical_name) + .collect(); assert!(names.contains(&"Qwen3_Parser".to_string())); assert!(names.contains(&"TPM_Vault".to_string())); // 5. Boolean NOT - let not_res = db.search_entities("native NOT tokenizer", Some("atlas-memory"), 10).expect("search NOT"); + let not_res = db + .search_entities("native NOT tokenizer", Some("atlas-memory"), 10) + .expect("search NOT"); assert_eq!(not_res.len(), 1); assert_eq!(not_res[0].entity.canonical_name, "NVFP4_Loader"); // 6. Ranking test (BM25 term frequency) - let rank_res = db.search_entities("memory", Some("atlas-memory"), 10).expect("search ranking"); + let rank_res = db + .search_entities("memory", Some("atlas-memory"), 10) + .expect("search ranking"); assert!(!rank_res.is_empty()); assert_eq!(rank_res[0].entity.canonical_name, "Memory_Optimizer"); } @@ -857,7 +987,11 @@ mod tests { let entities = vec![ ("Vector_Alpha", "Entity aligned with primary axis X", emb_a), ("Vector_Beta", "Entity aligned midway between axes", emb_b), - ("Vector_Gamma", "Entity aligned with secondary axis Y", emb_c), + ( + "Vector_Gamma", + "Entity aligned with secondary axis Y", + emb_c, + ), ]; for (name, content, emb) in entities { @@ -874,7 +1008,8 @@ mod tests { valid_to: None, external_id: None, }; - db.upsert_entity(&input, Some(&emb)).expect("insert vector entity"); + db.upsert_entity(&input, Some(&emb)) + .expect("insert vector entity"); } // Query vector strongly aligned with X: [0.99, 0.05, 0, ...] @@ -882,7 +1017,9 @@ mod tests { query_emb[0] = 0.99; query_emb[1] = 0.05; - let recall_res = db.recall_entities("Entity", Some(&query_emb), Some("atlas-memory"), 3).expect("recall"); + let recall_res = db + .recall_entities("Entity", Some(&query_emb), Some("atlas-memory"), 3) + .expect("recall"); assert_eq!(recall_res.len(), 3); // Verify nearest neighbor ordering: Alpha first, Beta second, Gamma third @@ -894,7 +1031,9 @@ mod tests { assert!(recall_res[1].final_score > recall_res[2].final_score); // Empty embedding fallback to lexical only - let empty_recall = db.recall_entities("secondary", None, Some("atlas-memory"), 3).expect("empty emb recall"); + let empty_recall = db + .recall_entities("secondary", None, Some("atlas-memory"), 3) + .expect("empty emb recall"); assert!(!empty_recall.is_empty()); assert_eq!(empty_recall[0].entity.canonical_name, "Vector_Gamma"); } @@ -947,17 +1086,29 @@ mod tests { // Verify deduplication: ID remains unchanged, revision incremented to 2 assert_eq!(receipt2.target_id, initial_id); - let fetched = db.get_entity("Atlas_Vault_Spec", Some("atlas-memory")).expect("get entity").unwrap(); + let fetched = db + .get_entity("Atlas_Vault_Spec", Some("atlas-memory")) + .expect("get entity") + .unwrap(); assert_eq!(fetched.id, initial_id); assert_eq!(fetched.revision, 2); assert_eq!(fetched.entity_type, "learned_procedure"); - assert_eq!(fetched.content, "Updated specification v2 with hardware sealing"); + assert_eq!( + fetched.content, + "Updated specification v2 with hardware sealing" + ); assert_eq!(fetched.aliases.len(), 2); // Verify nested metadata integrity assert_eq!(fetched.metadata["subsystem"], "security"); assert_eq!(fetched.metadata["hardware"]["tpm"], true); - assert_eq!(fetched.metadata["hardware"]["pcr_sealing"].as_array().unwrap().len(), 3); + assert_eq!( + fetched.metadata["hardware"]["pcr_sealing"] + .as_array() + .unwrap() + .len(), + 3 + ); // Verify exactly 1 entity row in space { @@ -984,7 +1135,9 @@ mod tests { valid_to: None, external_id: None, }; - let obj_receipt = db.upsert_entity(&obj_input, None).expect("upsert object entity"); + let obj_receipt = db + .upsert_entity(&obj_input, None) + .expect("upsert object entity"); let claim_input = ClaimWriteInput { id: None, @@ -998,7 +1151,9 @@ mod tests { }; db.upsert_claim(&claim_input).expect("upsert claim"); - let claims = db.traverse_claims(&initial_id, Some("atlas-memory")).expect("traverse claims"); + let claims = db + .traverse_claims(&initial_id, Some("atlas-memory")) + .expect("traverse claims"); assert_eq!(claims.len(), 1); assert_eq!(claims[0].predicate, "binds_to"); assert_eq!(claims[0].object_entity_id, Some(obj_receipt.target_id)); @@ -1008,10 +1163,14 @@ mod tests { let retract_receipt = db.retract_target("entity", &initial_id).expect("retract"); assert_eq!(retract_receipt.operation, "entity.retract"); - let after_retract = db.get_entity("Atlas_Vault_Spec", Some("atlas-memory")).expect("get retracted"); + let after_retract = db + .get_entity("Atlas_Vault_Spec", Some("atlas-memory")) + .expect("get retracted"); assert!(after_retract.is_none()); - let search_retract = db.search_entities("Atlas_Vault_Spec", Some("atlas-memory"), 10).expect("search retracted"); + let search_retract = db + .search_entities("Atlas_Vault_Spec", Some("atlas-memory"), 10) + .expect("search retracted"); assert!(search_retract.is_empty()); } } diff --git a/crates/cortex-rs/src/embeddings.rs b/crates/cortex-rs/src/embeddings.rs index a07483f3..c8f6480a 100644 --- a/crates/cortex-rs/src/embeddings.rs +++ b/crates/cortex-rs/src/embeddings.rs @@ -46,7 +46,11 @@ pub fn cosine_distance(a: &[f32], b: &[f32]) -> f32 { 1.0 - cosine_similarity(a, b) } -pub async fn fetch_embedding(client: &Client, text: &str, encoder_url: &str) -> Result, String> { +pub async fn fetch_embedding( + client: &Client, + text: &str, + encoder_url: &str, +) -> Result, String> { let payload = json!({ "text": text, "modelId": "BAAI/bge-base-en-v1.5", @@ -60,7 +64,12 @@ pub async fn fetch_embedding(client: &Client, text: &str, encoder_url: &str) -> .json(&payload) .send() .await - .map_err(|e| format!("Failed to connect to embedding encoder on {}: {}", encoder_url, e))?; + .map_err(|e| { + format!( + "Failed to connect to embedding encoder on {}: {}", + encoder_url, e + ) + })?; if !resp.status().is_success() { let status = resp.status(); @@ -68,7 +77,9 @@ pub async fn fetch_embedding(client: &Client, text: &str, encoder_url: &str) -> return Err(format!("Encoder returned error HTTP {}: {}", status, body)); } - let val: serde_json::Value = resp.json().await + let val: serde_json::Value = resp + .json() + .await .map_err(|e| format!("Failed to parse embedding response JSON: {}", e))?; if let Some(arr) = val.get("embedding").and_then(|v| v.as_array()) { @@ -81,7 +92,11 @@ pub async fn fetch_embedding(client: &Client, text: &str, encoder_url: &str) -> if emb.len() == EMBEDDING_DIMENSIONS { return Ok(emb); } else { - return Err(format!("Expected {} dimensions, got {}", EMBEDDING_DIMENSIONS, emb.len())); + return Err(format!( + "Expected {} dimensions, got {}", + EMBEDDING_DIMENSIONS, + emb.len() + )); } } diff --git a/crates/cortex-rs/src/handlers.rs b/crates/cortex-rs/src/handlers.rs index 443fa7fd..28999c06 100644 --- a/crates/cortex-rs/src/handlers.rs +++ b/crates/cortex-rs/src/handlers.rs @@ -35,25 +35,59 @@ pub async fn write_handler( match fetch_embedding(&state.http_client, &text_to_embed, &state.encoder_url).await { Ok(vec) => emb = Some(vec), Err(e) => { - tracing::warn!("Embedding encoder unavailable, proceeding with lexical only: {}", e); + tracing::warn!( + "Embedding encoder unavailable, proceeding with lexical only: {}", + e + ); } } match state.db.upsert_entity(&value, emb.as_deref()) { - Ok(receipt) => Ok((StatusCode::CREATED, Json(CortexReceipt { recorded: true, receipt })).into_response()), - Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})))) - } - } - WritePayload::Claim { value } => { - match state.db.upsert_claim(&value) { - Ok(receipt) => Ok((StatusCode::CREATED, Json(CortexReceipt { recorded: true, receipt })).into_response()), - Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})))) + Ok(receipt) => Ok(( + StatusCode::CREATED, + Json(CortexReceipt { + recorded: true, + receipt, + }), + ) + .into_response()), + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": e.to_string()})), + )), } } + WritePayload::Claim { value } => match state.db.upsert_claim(&value) { + Ok(receipt) => Ok(( + StatusCode::CREATED, + Json(CortexReceipt { + recorded: true, + receipt, + }), + ) + .into_response()), + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": e.to_string()})), + )), + }, WritePayload::Retract { value } => { - match state.db.retract_target(&value.target_type, &value.target_id) { - Ok(receipt) => Ok((StatusCode::CREATED, Json(CortexReceipt { recorded: true, receipt })).into_response()), - Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})))) + match state + .db + .retract_target(&value.target_type, &value.target_id) + { + Ok(receipt) => Ok(( + StatusCode::CREATED, + Json(CortexReceipt { + recorded: true, + receipt, + }), + ) + .into_response()), + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": e.to_string()})), + )), } } } @@ -77,7 +111,10 @@ pub async fn search_get_handler( elapsed_ms, })) } - Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})))) + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": e.to_string()})), + )), } } @@ -99,7 +136,10 @@ pub async fn search_post_handler( elapsed_ms, })) } - Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})))) + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": e.to_string()})), + )), } } @@ -119,7 +159,10 @@ pub async fn recall_handler( } } - match state.db.recall_entities(&payload.query, emb.as_deref(), space, limit) { + match state + .db + .recall_entities(&payload.query, emb.as_deref(), space, limit) + { Ok(results) => { let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0; Ok(Json(RecallResponse { @@ -128,7 +171,10 @@ pub async fn recall_handler( elapsed_ms, })) } - Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})))) + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": e.to_string()})), + )), } } @@ -145,13 +191,22 @@ pub async fn get_handler( ) -> Result)> { let target = params.id.or(params.name).unwrap_or_default(); if target.is_empty() { - return Err((StatusCode::BAD_REQUEST, Json(json!({"error": "Missing id or name parameter"})))); + return Err(( + StatusCode::BAD_REQUEST, + Json(json!({"error": "Missing id or name parameter"})), + )); } match state.db.get_entity(&target, params.space.as_deref()) { Ok(Some(entity)) => Ok(Json(entity).into_response()), - Ok(None) => Err((StatusCode::NOT_FOUND, Json(json!({"error": "Entity not found"})))), - Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})))) + Ok(None) => Err(( + StatusCode::NOT_FOUND, + Json(json!({"error": "Entity not found"})), + )), + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": e.to_string()})), + )), } } @@ -159,9 +214,15 @@ pub async fn traverse_handler( State(state): State>, Json(payload): Json, ) -> Result, (StatusCode, Json)> { - match state.db.traverse_claims(&payload.subject_id, payload.space.as_deref()) { + match state + .db + .traverse_claims(&payload.subject_id, payload.space.as_deref()) + { Ok(claims) => Ok(Json(json!({"claims": claims}))), - Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": e.to_string()})))) + Err(e) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + Json(json!({"error": e.to_string()})), + )), } } @@ -247,7 +308,9 @@ mod tests { name: Some("test_entity_get".to_string()), space: Some("non_existent_space".to_string()), }; - let err_unknown = get_handler(State(state), Query(query_unknown_space)).await.unwrap_err(); + let err_unknown = get_handler(State(state), Query(query_unknown_space)) + .await + .unwrap_err(); assert_eq!(err_unknown.0, StatusCode::NOT_FOUND); } @@ -261,7 +324,9 @@ mod tests { limit: Some(10), include_retracted: Some(false), }; - let Json(res) = search_get_handler(State(state), Query(params)).await.unwrap(); + let Json(res) = search_get_handler(State(state), Query(params)) + .await + .unwrap(); assert_eq!(res.results.len(), 0); } @@ -288,7 +353,11 @@ mod tests { let write_res = write_handler(State(state.clone()), Json(write_payload)).await; assert!(write_res.is_ok()); - let entity = state.db.get_entity("lifecycle_test", Some("atlas-memory")).unwrap().unwrap(); + let entity = state + .db + .get_entity("lifecycle_test", Some("atlas-memory")) + .unwrap() + .unwrap(); assert_eq!(entity.canonical_name, "lifecycle_test"); // 2. Retract entity @@ -302,7 +371,10 @@ mod tests { let retract_res = write_handler(State(state.clone()), Json(retract_payload)).await; assert!(retract_res.is_ok()); - let after = state.db.get_entity("lifecycle_test", Some("atlas-memory")).unwrap(); + let after = state + .db + .get_entity("lifecycle_test", Some("atlas-memory")) + .unwrap(); assert!(after.is_none()); } diff --git a/crates/cortex-rs/src/main.rs b/crates/cortex-rs/src/main.rs index 0f2d462e..f6b52f14 100644 --- a/crates/cortex-rs/src/main.rs +++ b/crates/cortex-rs/src/main.rs @@ -66,11 +66,16 @@ async fn main() -> Result<(), Box> { } tracing_subscriber::registry() - .with(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into())) + .with( + tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), + ) .with(tracing_subscriber::fmt::layer()) .init(); - tracing::info!("Initializing Cortex-RS SQLite database at {:?}...", args.db_path); + tracing::info!( + "Initializing Cortex-RS SQLite database at {:?}...", + args.db_path + ); if let Some(parent) = args.db_path.parent() { let _ = fs::create_dir_all(parent); } @@ -84,7 +89,11 @@ async fn main() -> Result<(), Box> { let raw_list: Vec = serde_json::from_str(&data)?; let mut count = 0; for val in raw_list { - let entity_val = if let Some(e) = val.get("entity") { e.clone() } else { val }; + let entity_val = if let Some(e) = val.get("entity") { + e.clone() + } else { + val + }; if let Ok(entity) = serde_json::from_value::(entity_val) { let _ = database.import_entity_raw(&entity, None); count += 1; @@ -102,7 +111,10 @@ async fn main() -> Result<(), Box> { let protected_routes = Router::new() .route("/api/cortex/write", post(write_handler)) - .route("/api/cortex/search", get(search_get_handler).post(search_post_handler)) + .route( + "/api/cortex/search", + get(search_get_handler).post(search_post_handler), + ) .route("/api/cortex/recall", post(recall_handler)) .route("/api/cortex/get", get(get_handler)) .route("/api/cortex/traverse", post(traverse_handler)) @@ -128,10 +140,15 @@ async fn main() -> Result<(), Box> { // INVARIANT: Bind strictly to loopback 127.0.0.1 to guarantee zero LAN exposure unless configured if args.host != "127.0.0.1" && args.host != "localhost" { - tracing::warn!("Non-loopback binding detected ({}); enforcing local authentication.", args.host); + tracing::warn!( + "Non-loopback binding detected ({}); enforcing local authentication.", + args.host + ); } - let addr: SocketAddr = format!("{}:{}", args.host, args.port).parse().unwrap_or_else(|_| SocketAddr::from(([127, 0, 0, 1], args.port))); + let addr: SocketAddr = format!("{}:{}", args.host, args.port) + .parse() + .unwrap_or_else(|_| SocketAddr::from(([127, 0, 0, 1], args.port))); tracing::info!("Cortex-RS server listening on http://{}", addr); let listener = tokio::net::TcpListener::bind(addr).await?; diff --git a/crates/cortex-rs/src/models.rs b/crates/cortex-rs/src/models.rs index 96608b8d..a954b638 100644 --- a/crates/cortex-rs/src/models.rs +++ b/crates/cortex-rs/src/models.rs @@ -75,10 +75,18 @@ pub struct EntityWriteInput { pub external_id: Option, } -fn default_space() -> String { "atlas-memory".to_string() } -fn default_entity_type() -> String { "discovery".to_string() } -fn default_json_object() -> Value { serde_json::json!({}) } -fn default_confidence() -> f64 { 1.0 } +fn default_space() -> String { + "atlas-memory".to_string() +} +fn default_entity_type() -> String { + "discovery".to_string() +} +fn default_json_object() -> Value { + serde_json::json!({}) +} +fn default_confidence() -> f64 { + 1.0 +} #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "camelCase")] @@ -128,7 +136,9 @@ pub struct SearchParams { pub include_retracted: Option, } -fn default_search_limit() -> Option { Some(12) } +fn default_search_limit() -> Option { + Some(12) +} #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] @@ -160,8 +170,12 @@ pub struct RecallPayload { pub token_budget: usize, } -fn default_recall_limit() -> usize { 5 } -fn default_token_budget() -> usize { 1200 } +fn default_recall_limit() -> usize { + 5 +} +fn default_token_budget() -> usize { + 1200 +} #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] ```