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
aien-sovereign-core-mv / crates / cortex-rs / src / handlers.rs
| 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 | use aien_localhttp::Client; |
| 17 | use axum::{ |
| 18 | extract::{Path as AxumPath, Query, State}, |
| 19 | http::StatusCode, |
| 20 | response::{IntoResponse, Response}, |
| 21 | Json, |
| 22 | }; |
| 23 | use serde_json::json; |
| 24 | use std::sync::Arc; |
| 25 | use std::time::{Duration, Instant}; |
| 26 | use tokio::sync::{OwnedSemaphorePermit, Semaphore}; |
| 27 | |
| 28 | use crate::db::Database; |
| 29 | use crate::embeddings::fetch_embedding; |
| 30 | use crate::models::*; |
| 31 | |
| 32 | pub struct AppState { |
| 33 | pub db: Arc<Database>, |
| 34 | pub http_client: Client, |
| 35 | pub encoder_url: String, |
| 36 | pub worker_limit: Arc<Semaphore>, |
| 37 | } |
| 38 | |
| 39 | pub async fn write_handler( |
| 40 | State(state): State<Arc<AppState>>, |
| 41 | Json(payload): Json<WritePayload>, |
| 42 | ) -> Result<Response, (StatusCode, Json<serde_json::Value>)> { |
| 43 | match payload { |
| 44 | WritePayload::Entity { value } => { |
| 45 | let mut emb = None; |
| 46 | let text_to_embed = if !value.content.trim().is_empty() { |
| 47 | format!("{}: {}", value.canonical_name, value.content) |
| 48 | } else { |
| 49 | value.canonical_name.clone() |
| 50 | }; |
| 51 | |
| 52 | match fetch_embedding(&state.http_client, &text_to_embed, &state.encoder_url).await { |
| 53 | Ok(vec) => emb = Some(vec), |
| 54 | Err(e) => { |
| 55 | tracing::warn!( |
| 56 | "Embedding encoder unavailable, proceeding with lexical only: {}", |
| 57 | e |
| 58 | ); |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | match state.db.upsert_entity(&value, emb.as_deref()) { |
| 63 | Ok(receipt) => Ok(( |
| 64 | StatusCode::CREATED, |
| 65 | Json(CortexReceipt { |
| 66 | recorded: true, |
| 67 | receipt, |
| 68 | }), |
| 69 | ) |
| 70 | .into_response()), |
| 71 | Err(e) => Err(( |
| 72 | StatusCode::INTERNAL_SERVER_ERROR, |
| 73 | Json(json!({"error": e.to_string()})), |
| 74 | )), |
| 75 | } |
| 76 | } |
| 77 | WritePayload::Claim { value } => match state.db.upsert_claim(&value) { |
| 78 | Ok(receipt) => Ok(( |
| 79 | StatusCode::CREATED, |
| 80 | Json(CortexReceipt { |
| 81 | recorded: true, |
| 82 | receipt, |
| 83 | }), |
| 84 | ) |
| 85 | .into_response()), |
| 86 | Err(e) => Err(( |
| 87 | StatusCode::INTERNAL_SERVER_ERROR, |
| 88 | Json(json!({"error": e.to_string()})), |
| 89 | )), |
| 90 | }, |
| 91 | WritePayload::Retract { value } => { |
| 92 | match state |
| 93 | .db |
| 94 | .retract_target(&value.target_type, &value.target_id) |
| 95 | { |
| 96 | Ok(receipt) => Ok(( |
| 97 | StatusCode::CREATED, |
| 98 | Json(CortexReceipt { |
| 99 | recorded: true, |
| 100 | receipt, |
| 101 | }), |
| 102 | ) |
| 103 | .into_response()), |
| 104 | Err(e) => Err(( |
| 105 | StatusCode::INTERNAL_SERVER_ERROR, |
| 106 | Json(json!({"error": e.to_string()})), |
| 107 | )), |
| 108 | } |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | pub async fn search_get_handler( |
| 114 | State(state): State<Arc<AppState>>, |
| 115 | Query(params): Query<SearchParams>, |
| 116 | ) -> Result<Json<SearchResponse>, (StatusCode, Json<serde_json::Value>)> { |
| 117 | let start = Instant::now(); |
| 118 | let q = params.q.or(params.query).unwrap_or_default(); |
| 119 | let limit = params.limit.unwrap_or(12).min(50); |
| 120 | let space = params.space.as_deref(); |
| 121 | |
| 122 | match state.db.search_entities(&q, space, limit) { |
| 123 | Ok(results) => { |
| 124 | let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0; |
| 125 | Ok(Json(SearchResponse { |
| 126 | results, |
| 127 | degraded: Vec::new(), |
| 128 | elapsed_ms, |
| 129 | })) |
| 130 | } |
| 131 | Err(e) => Err(( |
| 132 | StatusCode::INTERNAL_SERVER_ERROR, |
| 133 | Json(json!({"error": e.to_string()})), |
| 134 | )), |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | pub async fn search_post_handler( |
| 139 | State(state): State<Arc<AppState>>, |
| 140 | Json(params): Json<SearchParams>, |
| 141 | ) -> Result<Json<SearchResponse>, (StatusCode, Json<serde_json::Value>)> { |
| 142 | let start = Instant::now(); |
| 143 | let q = params.q.or(params.query).unwrap_or_default(); |
| 144 | let limit = params.limit.unwrap_or(12).min(50); |
| 145 | let space = params.space.as_deref(); |
| 146 | |
| 147 | match state.db.search_entities(&q, space, limit) { |
| 148 | Ok(results) => { |
| 149 | let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0; |
| 150 | Ok(Json(SearchResponse { |
| 151 | results, |
| 152 | degraded: Vec::new(), |
| 153 | elapsed_ms, |
| 154 | })) |
| 155 | } |
| 156 | Err(e) => Err(( |
| 157 | StatusCode::INTERNAL_SERVER_ERROR, |
| 158 | Json(json!({"error": e.to_string()})), |
| 159 | )), |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | pub async fn recall_handler( |
| 164 | State(state): State<Arc<AppState>>, |
| 165 | Json(payload): Json<RecallPayload>, |
| 166 | ) -> Result<Json<RecallResponse>, (StatusCode, Json<serde_json::Value>)> { |
| 167 | let start = Instant::now(); |
| 168 | let space = payload.space.as_deref(); |
| 169 | let limit = payload.limit.min(20); |
| 170 | |
| 171 | let mut emb = None; |
| 172 | match fetch_embedding(&state.http_client, &payload.query, &state.encoder_url).await { |
| 173 | Ok(vec) => emb = Some(vec), |
| 174 | Err(e) => { |
| 175 | tracing::warn!("Embedding encoder unavailable for recall: {}", e); |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | match state |
| 180 | .db |
| 181 | .recall_entities(&payload.query, emb.as_deref(), space, limit) |
| 182 | { |
| 183 | Ok(results) => { |
| 184 | let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0; |
| 185 | Ok(Json(RecallResponse { |
| 186 | results, |
| 187 | degraded: Vec::new(), |
| 188 | elapsed_ms, |
| 189 | })) |
| 190 | } |
| 191 | Err(e) => Err(( |
| 192 | StatusCode::INTERNAL_SERVER_ERROR, |
| 193 | Json(json!({"error": e.to_string()})), |
| 194 | )), |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | #[derive(serde::Deserialize)] |
| 199 | pub struct GetParams { |
| 200 | pub id: Option<String>, |
| 201 | pub name: Option<String>, |
| 202 | pub space: Option<String>, |
| 203 | } |
| 204 | |
| 205 | pub async fn get_handler( |
| 206 | State(state): State<Arc<AppState>>, |
| 207 | Query(params): Query<GetParams>, |
| 208 | ) -> Result<Response, (StatusCode, Json<serde_json::Value>)> { |
| 209 | let target = params.id.or(params.name).unwrap_or_default(); |
| 210 | if target.is_empty() { |
| 211 | return Err(( |
| 212 | StatusCode::BAD_REQUEST, |
| 213 | Json(json!({"error": "Missing id or name parameter"})), |
| 214 | )); |
| 215 | } |
| 216 | |
| 217 | match state.db.get_entity(&target, params.space.as_deref()) { |
| 218 | Ok(Some(entity)) => Ok(Json(entity).into_response()), |
| 219 | Ok(None) => Err(( |
| 220 | StatusCode::NOT_FOUND, |
| 221 | Json(json!({"error": "Entity not found"})), |
| 222 | )), |
| 223 | Err(e) => Err(( |
| 224 | StatusCode::INTERNAL_SERVER_ERROR, |
| 225 | Json(json!({"error": e.to_string()})), |
| 226 | )), |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | pub async fn traverse_handler( |
| 231 | State(state): State<Arc<AppState>>, |
| 232 | Json(payload): Json<TraversePayload>, |
| 233 | ) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> { |
| 234 | match state |
| 235 | .db |
| 236 | .traverse_claims(&payload.subject_id, payload.space.as_deref()) |
| 237 | { |
| 238 | Ok(claims) => Ok(Json(json!({"claims": claims}))), |
| 239 | Err(e) => Err(( |
| 240 | StatusCode::INTERNAL_SERVER_ERROR, |
| 241 | Json(json!({"error": e.to_string()})), |
| 242 | )), |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | pub async fn health_handler() -> Json<serde_json::Value> { |
| 247 | Json(json!({ |
| 248 | "status": "ok", |
| 249 | "service": "cortex-rs", |
| 250 | "version": "0.1.0", |
| 251 | "space": "atlas-memory", |
| 252 | "runtime": "native-arm64-rust" |
| 253 | })) |
| 254 | } |
| 255 | |
| 256 | // ========================================================================= |
| 257 | // Episodic Plane Handlers (v2 API) |
| 258 | // ========================================================================= |
| 259 | |
| 260 | #[derive(serde::Deserialize)] |
| 261 | pub struct SessionEventsQuery { |
| 262 | pub branch_id: Option<String>, |
| 263 | pub after_seq: Option<i64>, |
| 264 | pub limit: Option<usize>, |
| 265 | pub recent: Option<bool>, |
| 266 | } |
| 267 | |
| 268 | #[derive(serde::Deserialize)] |
| 269 | pub struct WatermarkQuery { |
| 270 | pub kind: String, |
| 271 | pub version: String, |
| 272 | } |
| 273 | |
| 274 | pub async fn create_session_handler( |
| 275 | State(state): State<Arc<AppState>>, |
| 276 | Json(input): Json<CreateSessionInput>, |
| 277 | ) -> Result<(StatusCode, Json<CortexSession>), (StatusCode, Json<serde_json::Value>)> { |
| 278 | match state.db.create_session(&input) { |
| 279 | Ok(session) => Ok((StatusCode::CREATED, Json(session))), |
| 280 | Err(e) => Err(( |
| 281 | StatusCode::INTERNAL_SERVER_ERROR, |
| 282 | Json(json!({"error": e.to_string()})), |
| 283 | )), |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | pub async fn get_session_handler( |
| 288 | State(state): State<Arc<AppState>>, |
| 289 | AxumPath(session_id): AxumPath<String>, |
| 290 | ) -> Result<Json<CortexSession>, (StatusCode, Json<serde_json::Value>)> { |
| 291 | match state.db.get_session(&session_id) { |
| 292 | Ok(Some(session)) => Ok(Json(session)), |
| 293 | Ok(None) => Err(( |
| 294 | StatusCode::NOT_FOUND, |
| 295 | Json(json!({"error": format!("Session {} not found", session_id)})), |
| 296 | )), |
| 297 | Err(e) => Err(( |
| 298 | StatusCode::INTERNAL_SERVER_ERROR, |
| 299 | Json(json!({"error": e.to_string()})), |
| 300 | )), |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | pub async fn close_session_handler( |
| 305 | State(state): State<Arc<AppState>>, |
| 306 | AxumPath(session_id): AxumPath<String>, |
| 307 | ) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> { |
| 308 | match state.db.close_session(&session_id) { |
| 309 | Ok(()) => Ok(Json(json!({"status": "closed", "sessionId": session_id}))), |
| 310 | Err(e) => Err(( |
| 311 | StatusCode::INTERNAL_SERVER_ERROR, |
| 312 | Json(json!({"error": e.to_string()})), |
| 313 | )), |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | pub async fn batch_append_events_handler( |
| 318 | State(state): State<Arc<AppState>>, |
| 319 | AxumPath(session_id): AxumPath<String>, |
| 320 | Json(payload): Json<BatchAppendEventsInput>, |
| 321 | ) -> Result<(StatusCode, Json<serde_json::Value>), (StatusCode, Json<serde_json::Value>)> { |
| 322 | match state |
| 323 | .db |
| 324 | .batch_append_events(&session_id, &payload.branch_id, &payload.events) |
| 325 | { |
| 326 | Ok(events) => Ok((StatusCode::CREATED, Json(json!({ "events": events })))), |
| 327 | Err(e) => Err(( |
| 328 | StatusCode::INTERNAL_SERVER_ERROR, |
| 329 | Json(json!({"error": e.to_string()})), |
| 330 | )), |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | pub async fn get_session_events_handler( |
| 335 | State(state): State<Arc<AppState>>, |
| 336 | AxumPath(session_id): AxumPath<String>, |
| 337 | Query(params): Query<SessionEventsQuery>, |
| 338 | ) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> { |
| 339 | let branch = params.branch_id.as_deref().unwrap_or("main"); |
| 340 | let limit = params.limit.unwrap_or(50).min(500); |
| 341 | let fetched = if params.recent.unwrap_or(false) && params.after_seq.is_none() { |
| 342 | state |
| 343 | .db |
| 344 | .get_recent_session_events(&session_id, branch, limit) |
| 345 | } else { |
| 346 | state |
| 347 | .db |
| 348 | .get_session_events(&session_id, branch, params.after_seq, limit) |
| 349 | }; |
| 350 | match fetched { |
| 351 | Ok(events) => Ok(Json(json!({ "events": events }))), |
| 352 | Err(e) => Err(( |
| 353 | StatusCode::INTERNAL_SERVER_ERROR, |
| 354 | Json(json!({"error": e.to_string()})), |
| 355 | )), |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | pub async fn get_watermark_handler( |
| 360 | State(state): State<Arc<AppState>>, |
| 361 | AxumPath(session_id): AxumPath<String>, |
| 362 | Query(params): Query<WatermarkQuery>, |
| 363 | ) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> { |
| 364 | match state |
| 365 | .db |
| 366 | .get_watermark(&session_id, ¶ms.kind, ¶ms.version) |
| 367 | { |
| 368 | Ok(Some(seq)) => Ok(Json(json!({ |
| 369 | "sessionId": session_id, |
| 370 | "processorKind": params.kind, |
| 371 | "processorVersion": params.version, |
| 372 | "watermarkSeq": seq |
| 373 | }))), |
| 374 | Ok(None) => Ok(Json(json!({ |
| 375 | "sessionId": session_id, |
| 376 | "processorKind": params.kind, |
| 377 | "processorVersion": params.version, |
| 378 | "watermarkSeq": null |
| 379 | }))), |
| 380 | Err(e) => Err(( |
| 381 | StatusCode::INTERNAL_SERVER_ERROR, |
| 382 | Json(json!({"error": e.to_string()})), |
| 383 | )), |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | pub async fn set_watermark_handler( |
| 388 | State(state): State<Arc<AppState>>, |
| 389 | AxumPath(session_id): AxumPath<String>, |
| 390 | Json(input): Json<SetWatermarkInput>, |
| 391 | ) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> { |
| 392 | match state.db.set_watermark( |
| 393 | &session_id, |
| 394 | &input.processor_kind, |
| 395 | &input.processor_version, |
| 396 | input.watermark_seq, |
| 397 | ) { |
| 398 | Ok(()) => Ok(Json(json!({ |
| 399 | "status": "ok", |
| 400 | "sessionId": session_id, |
| 401 | "processorKind": input.processor_kind, |
| 402 | "processorVersion": input.processor_version, |
| 403 | "watermarkSeq": input.watermark_seq |
| 404 | }))), |
| 405 | Err(e) => Err(( |
| 406 | StatusCode::INTERNAL_SERVER_ERROR, |
| 407 | Json(json!({"error": e.to_string()})), |
| 408 | )), |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | #[derive(serde::Deserialize)] |
| 413 | pub struct CandidatesQuery { |
| 414 | pub space: Option<String>, |
| 415 | pub state: Option<String>, |
| 416 | pub limit: Option<usize>, |
| 417 | } |
| 418 | |
| 419 | #[derive(serde::Deserialize)] |
| 420 | #[serde(rename_all = "camelCase")] |
| 421 | pub struct PromoteCandidatePayload { |
| 422 | pub policy_id: Option<String>, |
| 423 | pub verifier_receipt: Option<String>, |
| 424 | } |
| 425 | |
| 426 | pub async fn get_candidates_handler( |
| 427 | State(state): State<Arc<AppState>>, |
| 428 | Query(params): Query<CandidatesQuery>, |
| 429 | ) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> { |
| 430 | let limit = params.limit.unwrap_or(50); |
| 431 | match state |
| 432 | .db |
| 433 | .get_memory_candidates(params.space.as_deref(), params.state.as_deref(), limit) |
| 434 | { |
| 435 | Ok(candidates) => Ok(Json(json!({ "candidates": candidates }))), |
| 436 | Err(e) => Err(( |
| 437 | StatusCode::INTERNAL_SERVER_ERROR, |
| 438 | Json(json!({ "error": e.to_string() })), |
| 439 | )), |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | pub async fn get_candidate_by_id_handler( |
| 444 | State(state): State<Arc<AppState>>, |
| 445 | AxumPath(candidate_id): AxumPath<String>, |
| 446 | ) -> Result<Json<MemoryCandidate>, (StatusCode, Json<serde_json::Value>)> { |
| 447 | match state.db.get_candidate_by_id(&candidate_id) { |
| 448 | Ok(Some(candidate)) => Ok(Json(candidate)), |
| 449 | Ok(None) => Err(( |
| 450 | StatusCode::NOT_FOUND, |
| 451 | Json(json!({ "error": format!("Candidate {} not found", candidate_id) })), |
| 452 | )), |
| 453 | Err(e) => Err(( |
| 454 | StatusCode::INTERNAL_SERVER_ERROR, |
| 455 | Json(json!({ "error": e.to_string() })), |
| 456 | )), |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | pub async fn promote_candidate_handler( |
| 461 | State(state): State<Arc<AppState>>, |
| 462 | AxumPath(candidate_id): AxumPath<String>, |
| 463 | Json(payload): Json<PromoteCandidatePayload>, |
| 464 | ) -> Result<(StatusCode, Json<PromotionReceipt>), (StatusCode, Json<serde_json::Value>)> { |
| 465 | let input = PromoteCandidateInput { |
| 466 | candidate_id, |
| 467 | policy_id: payload.policy_id, |
| 468 | verifier_receipt: payload.verifier_receipt, |
| 469 | }; |
| 470 | match state.db.promote_candidate(&input) { |
| 471 | Ok(receipt) => Ok((StatusCode::CREATED, Json(receipt))), |
| 472 | Err(e) => Err(( |
| 473 | StatusCode::INTERNAL_SERVER_ERROR, |
| 474 | Json(json!({ "error": e.to_string() })), |
| 475 | )), |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | pub async fn compile_context_handler( |
| 480 | State(state): State<Arc<AppState>>, |
| 481 | Json(query): Json<crate::compiler::MemoryQuery>, |
| 482 | ) -> Result<Json<crate::compiler::MemoryContext>, (StatusCode, Json<serde_json::Value>)> { |
| 483 | let compiler = crate::compiler::MemoryCompiler::new(Arc::clone(&state.db)); |
| 484 | match compiler.compile_context(&query) { |
| 485 | Ok(context) => Ok(Json(context)), |
| 486 | Err(e) => Err(( |
| 487 | StatusCode::INTERNAL_SERVER_ERROR, |
| 488 | Json(json!({ "error": e.to_string() })), |
| 489 | )), |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | pub async fn process_session_handler( |
| 494 | State(state): State<Arc<AppState>>, |
| 495 | AxumPath(session_id): AxumPath<String>, |
| 496 | Query(params): Query<SessionEventsQuery>, |
| 497 | ) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> { |
| 498 | let branch = params.branch_id.as_deref().unwrap_or("main").to_string(); |
| 499 | let branch_for_worker = branch.clone(); |
| 500 | let permit = state |
| 501 | .worker_limit |
| 502 | .clone() |
| 503 | .try_acquire_owned() |
| 504 | .map_err(|_| { |
| 505 | ( |
| 506 | StatusCode::TOO_MANY_REQUESTS, |
| 507 | Json(json!({ "error": "worker capacity exceeded" })), |
| 508 | ) |
| 509 | })?; |
| 510 | let db = Arc::clone(&state.db); |
| 511 | let session_for_worker = session_id.clone(); |
| 512 | let joined = tokio::time::timeout( |
| 513 | Duration::from_secs(30), |
| 514 | tokio::task::spawn_blocking(move || { |
| 515 | let _permit: OwnedSemaphorePermit = permit; |
| 516 | crate::workers::ProcessingScheduler::new(db) |
| 517 | .process_session(&session_for_worker, &branch_for_worker) |
| 518 | }), |
| 519 | ) |
| 520 | .await |
| 521 | .map_err(|_| { |
| 522 | ( |
| 523 | StatusCode::SERVICE_UNAVAILABLE, |
| 524 | Json(json!({ "error": "worker deadline exceeded" })), |
| 525 | ) |
| 526 | })? |
| 527 | .map_err(|e| { |
| 528 | ( |
| 529 | StatusCode::INTERNAL_SERVER_ERROR, |
| 530 | Json(json!({ "error": e.to_string() })), |
| 531 | ) |
| 532 | })?; |
| 533 | match joined { |
| 534 | Ok((summary, candidates)) => Ok(Json(json!({ |
| 535 | "status": "processed", |
| 536 | "sessionId": session_id, |
| 537 | "branchId": branch, |
| 538 | "summary": summary, |
| 539 | "candidates": candidates |
| 540 | }))), |
| 541 | Err(e) => Err(( |
| 542 | StatusCode::INTERNAL_SERVER_ERROR, |
| 543 | Json(json!({ "error": e.to_string() })), |
| 544 | )), |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | #[cfg(test)] |
| 549 | mod tests { |
| 550 | use super::*; |
| 551 | |
| 552 | fn create_test_state() -> Arc<AppState> { |
| 553 | let db = Arc::new(Database::open_in_memory().expect("in memory db")); |
| 554 | Arc::new(AppState { |
| 555 | db, |
| 556 | http_client: Client::new(), |
| 557 | encoder_url: "http://127.0.0.1:18081".to_string(), |
| 558 | worker_limit: Arc::new(Semaphore::new(2)), |
| 559 | }) |
| 560 | } |
| 561 | |
| 562 | #[tokio::test] |
| 563 | async fn test_get_handler_missing_parameter() { |
| 564 | let state = create_test_state(); |
| 565 | let query = GetParams { |
| 566 | id: None, |
| 567 | name: None, |
| 568 | space: None, |
| 569 | }; |
| 570 | let err = get_handler(State(state), Query(query)).await.unwrap_err(); |
| 571 | assert_eq!(err.0, StatusCode::BAD_REQUEST); |
| 572 | assert_eq!(err.1 .0["error"], "Missing id or name parameter"); |
| 573 | } |
| 574 | |
| 575 | #[tokio::test] |
| 576 | async fn test_get_handler_not_found() { |
| 577 | let state = create_test_state(); |
| 578 | let query = GetParams { |
| 579 | id: Some("non_existent_uuid".to_string()), |
| 580 | name: None, |
| 581 | space: Some("atlas-memory".to_string()), |
| 582 | }; |
| 583 | let err = get_handler(State(state), Query(query)).await.unwrap_err(); |
| 584 | assert_eq!(err.0, StatusCode::NOT_FOUND); |
| 585 | assert_eq!(err.1 .0["error"], "Entity not found"); |
| 586 | } |
| 587 | |
| 588 | #[tokio::test] |
| 589 | async fn test_get_handler_success_and_unknown_space() { |
| 590 | let state = create_test_state(); |
| 591 | let input = EntityWriteInput { |
| 592 | id: None, |
| 593 | space: "atlas-memory".to_string(), |
| 594 | entity_type: "discovery".to_string(), |
| 595 | canonical_name: "test_entity_get".to_string(), |
| 596 | content: "Payload content".to_string(), |
| 597 | aliases: vec![], |
| 598 | metadata: json!({"key": "val"}), |
| 599 | confidence: 1.0, |
| 600 | valid_from: None, |
| 601 | valid_to: None, |
| 602 | external_id: None, |
| 603 | }; |
| 604 | state.db.upsert_entity(&input, None).unwrap(); |
| 605 | |
| 606 | // 1. Success fetch |
| 607 | let query_ok = GetParams { |
| 608 | id: None, |
| 609 | name: Some("test_entity_get".to_string()), |
| 610 | space: Some("atlas-memory".to_string()), |
| 611 | }; |
| 612 | let resp = get_handler(State(state.clone()), Query(query_ok)).await; |
| 613 | assert!(resp.is_ok()); |
| 614 | |
| 615 | // 2. Unknown space fetch returns 404 |
| 616 | let query_unknown_space = GetParams { |
| 617 | id: None, |
| 618 | name: Some("test_entity_get".to_string()), |
| 619 | space: Some("non_existent_space".to_string()), |
| 620 | }; |
| 621 | let err_unknown = get_handler(State(state), Query(query_unknown_space)) |
| 622 | .await |
| 623 | .unwrap_err(); |
| 624 | assert_eq!(err_unknown.0, StatusCode::NOT_FOUND); |
| 625 | } |
| 626 | |
| 627 | #[tokio::test] |
| 628 | async fn test_search_unknown_space_returns_empty() { |
| 629 | let state = create_test_state(); |
| 630 | let params = SearchParams { |
| 631 | q: Some("anything".to_string()), |
| 632 | query: None, |
| 633 | space: Some("completely_unknown_space_slug".to_string()), |
| 634 | limit: Some(10), |
| 635 | include_retracted: Some(false), |
| 636 | }; |
| 637 | let Json(res) = search_get_handler(State(state), Query(params)) |
| 638 | .await |
| 639 | .unwrap(); |
| 640 | assert_eq!(res.results.len(), 0); |
| 641 | } |
| 642 | |
| 643 | #[tokio::test] |
| 644 | async fn test_write_entity_and_retract_lifecycle() { |
| 645 | let state = create_test_state(); |
| 646 | |
| 647 | // 1. Write entity |
| 648 | let write_payload = WritePayload::Entity { |
| 649 | value: EntityWriteInput { |
| 650 | id: None, |
| 651 | space: "atlas-memory".to_string(), |
| 652 | entity_type: "lesson".to_string(), |
| 653 | canonical_name: "lifecycle_test".to_string(), |
| 654 | content: "Lifecycle verification".to_string(), |
| 655 | aliases: vec![], |
| 656 | metadata: json!({}), |
| 657 | confidence: 1.0, |
| 658 | valid_from: None, |
| 659 | valid_to: None, |
| 660 | external_id: None, |
| 661 | }, |
| 662 | }; |
| 663 | let write_res = write_handler(State(state.clone()), Json(write_payload)).await; |
| 664 | assert!(write_res.is_ok()); |
| 665 | |
| 666 | let entity = state |
| 667 | .db |
| 668 | .get_entity("lifecycle_test", Some("atlas-memory")) |
| 669 | .unwrap() |
| 670 | .unwrap(); |
| 671 | assert_eq!(entity.canonical_name, "lifecycle_test"); |
| 672 | |
| 673 | // 2. Retract entity |
| 674 | let retract_payload = WritePayload::Retract { |
| 675 | value: RetractInput { |
| 676 | target_type: "entity".to_string(), |
| 677 | target_id: entity.id.clone(), |
| 678 | reason: Some("Obsolescence".to_string()), |
| 679 | }, |
| 680 | }; |
| 681 | let retract_res = write_handler(State(state.clone()), Json(retract_payload)).await; |
| 682 | assert!(retract_res.is_ok()); |
| 683 | |
| 684 | let after = state |
| 685 | .db |
| 686 | .get_entity("lifecycle_test", Some("atlas-memory")) |
| 687 | .unwrap(); |
| 688 | assert!(after.is_none()); |
| 689 | } |
| 690 | |
| 691 | #[tokio::test] |
| 692 | async fn test_health_handler_structure() { |
| 693 | let Json(health) = health_handler().await; |
| 694 | assert_eq!(health["status"], "ok"); |
| 695 | assert_eq!(health["service"], "cortex-rs"); |
| 696 | assert_eq!(health["space"], "atlas-memory"); |
| 697 | } |
| 698 | |
| 699 | #[tokio::test] |
| 700 | async fn test_v2_session_and_events_api_lifecycle() { |
| 701 | let state = create_test_state(); |
| 702 | |
| 703 | // 1. Create session |
| 704 | let session_input = CreateSessionInput { |
| 705 | id: None, |
| 706 | space: "atlas-memory".to_string(), |
| 707 | agent_id: Some("agent-atlas".to_string()), |
| 708 | world_id: Some("world-01".to_string()), |
| 709 | parent_session_id: None, |
| 710 | fork_event_id: None, |
| 711 | retention_class: "standard".to_string(), |
| 712 | metadata: json!({"task": "concurrency_test"}), |
| 713 | }; |
| 714 | |
| 715 | let (status, Json(session)) = |
| 716 | create_session_handler(State(state.clone()), Json(session_input)) |
| 717 | .await |
| 718 | .unwrap(); |
| 719 | assert_eq!(status, StatusCode::CREATED); |
| 720 | assert_eq!(session.status, "active"); |
| 721 | assert_eq!(session.agent_id, Some("agent-atlas".to_string())); |
| 722 | |
| 723 | let session_id = session.id; |
| 724 | |
| 725 | // 2. Get session |
| 726 | let Json(fetched_session) = |
| 727 | get_session_handler(State(state.clone()), AxumPath(session_id.clone())) |
| 728 | .await |
| 729 | .unwrap(); |
| 730 | assert_eq!(fetched_session.id, session_id); |
| 731 | assert_eq!(fetched_session.status, "active"); |
| 732 | |
| 733 | // 3. Append events |
| 734 | let batch_input = BatchAppendEventsInput { |
| 735 | branch_id: "main".to_string(), |
| 736 | events: vec![ |
| 737 | SessionEventInput { |
| 738 | id: Some("ev-001".to_string()), |
| 739 | branch_id: Some("main".to_string()), |
| 740 | parent_event_id: None, |
| 741 | event_type: "user_message".to_string(), |
| 742 | role: Some("user".to_string()), |
| 743 | content: Some("Deploy the memory engine.".to_string()), |
| 744 | payload: json!({}), |
| 745 | sensitivity: None, |
| 746 | }, |
| 747 | SessionEventInput { |
| 748 | id: Some("ev-002".to_string()), |
| 749 | branch_id: Some("main".to_string()), |
| 750 | parent_event_id: Some("ev-001".to_string()), |
| 751 | event_type: "assistant_message".to_string(), |
| 752 | role: Some("assistant".to_string()), |
| 753 | content: Some("Initializing Cortex multi-plane architecture.".to_string()), |
| 754 | payload: json!({}), |
| 755 | sensitivity: None, |
| 756 | }, |
| 757 | ], |
| 758 | }; |
| 759 | |
| 760 | let (status, Json(batch_res)) = batch_append_events_handler( |
| 761 | State(state.clone()), |
| 762 | AxumPath(session_id.clone()), |
| 763 | Json(batch_input), |
| 764 | ) |
| 765 | .await |
| 766 | .unwrap(); |
| 767 | assert_eq!(status, StatusCode::CREATED); |
| 768 | let events = batch_res["events"].as_array().unwrap(); |
| 769 | assert_eq!(events.len(), 2); |
| 770 | assert_eq!(events[0]["sequence"], 1); |
| 771 | assert_eq!(events[1]["sequence"], 2); |
| 772 | |
| 773 | // 4. Test idempotency: re-append ev-001 |
| 774 | let replay_input = BatchAppendEventsInput { |
| 775 | branch_id: "main".to_string(), |
| 776 | events: vec![SessionEventInput { |
| 777 | id: Some("ev-001".to_string()), |
| 778 | branch_id: Some("main".to_string()), |
| 779 | parent_event_id: None, |
| 780 | event_type: "user_message".to_string(), |
| 781 | role: Some("user".to_string()), |
| 782 | content: Some("Deploy the memory engine.".to_string()), |
| 783 | payload: json!({}), |
| 784 | sensitivity: None, |
| 785 | }], |
| 786 | }; |
| 787 | let (_, Json(replay_res)) = batch_append_events_handler( |
| 788 | State(state.clone()), |
| 789 | AxumPath(session_id.clone()), |
| 790 | Json(replay_input), |
| 791 | ) |
| 792 | .await |
| 793 | .unwrap(); |
| 794 | let replayed = replay_res["events"].as_array().unwrap(); |
| 795 | assert_eq!(replayed[0]["id"], "ev-001"); |
| 796 | assert_eq!(replayed[0]["sequence"], 1); |
| 797 | |
| 798 | // 5. Query events |
| 799 | let query = SessionEventsQuery { |
| 800 | branch_id: Some("main".to_string()), |
| 801 | after_seq: Some(0), |
| 802 | limit: Some(10), |
| 803 | recent: None, |
| 804 | }; |
| 805 | let Json(queried) = get_session_events_handler( |
| 806 | State(state.clone()), |
| 807 | AxumPath(session_id.clone()), |
| 808 | Query(query), |
| 809 | ) |
| 810 | .await |
| 811 | .unwrap(); |
| 812 | assert_eq!(queried["events"].as_array().unwrap().len(), 2); |
| 813 | |
| 814 | // 6. Watermarks |
| 815 | let set_wm = SetWatermarkInput { |
| 816 | processor_kind: "summary".to_string(), |
| 817 | processor_version: "v1".to_string(), |
| 818 | watermark_seq: 2, |
| 819 | }; |
| 820 | let Json(wm_res) = set_watermark_handler( |
| 821 | State(state.clone()), |
| 822 | AxumPath(session_id.clone()), |
| 823 | Json(set_wm), |
| 824 | ) |
| 825 | .await |
| 826 | .unwrap(); |
| 827 | assert_eq!(wm_res["status"], "ok"); |
| 828 | |
| 829 | let wm_query = WatermarkQuery { |
| 830 | kind: "summary".to_string(), |
| 831 | version: "v1".to_string(), |
| 832 | }; |
| 833 | let Json(get_wm) = get_watermark_handler( |
| 834 | State(state.clone()), |
| 835 | AxumPath(session_id.clone()), |
| 836 | Query(wm_query), |
| 837 | ) |
| 838 | .await |
| 839 | .unwrap(); |
| 840 | assert_eq!(get_wm["watermarkSeq"], 2); |
| 841 | |
| 842 | // 7. Close session |
| 843 | let Json(close_res) = |
| 844 | close_session_handler(State(state.clone()), AxumPath(session_id.clone())) |
| 845 | .await |
| 846 | .unwrap(); |
| 847 | assert_eq!(close_res["status"], "closed"); |
| 848 | |
| 849 | let Json(closed_session) = |
| 850 | get_session_handler(State(state.clone()), AxumPath(session_id.clone())) |
| 851 | .await |
| 852 | .unwrap(); |
| 853 | assert_eq!(closed_session.status, "closed"); |
| 854 | assert!(closed_session.closed_at.is_some()); |
| 855 | } |
| 856 | |
| 857 | #[tokio::test] |
| 858 | async fn test_v2_compiler_and_process_api_e2e() { |
| 859 | let state = create_test_state(); |
| 860 | |
| 861 | // 1. Create session |
| 862 | let (status, Json(session)) = create_session_handler( |
| 863 | State(state.clone()), |
| 864 | Json(CreateSessionInput { |
| 865 | id: Some("sess-e2e-compiler".to_string()), |
| 866 | space: "atlas-memory".to_string(), |
| 867 | agent_id: Some("atlas-prime".to_string()), |
| 868 | world_id: None, |
| 869 | parent_session_id: None, |
| 870 | fork_event_id: None, |
| 871 | retention_class: "standard".to_string(), |
| 872 | metadata: json!({}), |
| 873 | }), |
| 874 | ) |
| 875 | .await |
| 876 | .unwrap(); |
| 877 | assert_eq!(status, StatusCode::CREATED); |
| 878 | |
| 879 | // 2. Append events (user preference + tool discovery) |
| 880 | let batch = BatchAppendEventsInput { |
| 881 | branch_id: "main".to_string(), |
| 882 | events: vec![ |
| 883 | SessionEventInput { |
| 884 | id: Some("ev-e2e-1".to_string()), |
| 885 | branch_id: Some("main".to_string()), |
| 886 | parent_event_id: None, |
| 887 | event_type: "user_message".to_string(), |
| 888 | role: Some("user".to_string()), |
| 889 | content: Some("I prefer Rust for the sovereign stack.".to_string()), |
| 890 | payload: json!({}), |
| 891 | sensitivity: None, |
| 892 | }, |
| 893 | SessionEventInput { |
| 894 | id: Some("ev-e2e-2".to_string()), |
| 895 | branch_id: Some("main".to_string()), |
| 896 | parent_event_id: Some("ev-e2e-1".to_string()), |
| 897 | event_type: "tool_result".to_string(), |
| 898 | role: Some("tool".to_string()), |
| 899 | content: Some("Verified SQLite WAL mode active on Boston.".to_string()), |
| 900 | payload: json!({"verified": true}), |
| 901 | sensitivity: None, |
| 902 | }, |
| 903 | ], |
| 904 | }; |
| 905 | let _ = batch_append_events_handler( |
| 906 | State(state.clone()), |
| 907 | AxumPath(session.id.clone()), |
| 908 | Json(batch), |
| 909 | ) |
| 910 | .await |
| 911 | .unwrap(); |
| 912 | |
| 913 | // 3. Trigger asynchronous workers on session |
| 914 | let query_proc = SessionEventsQuery { |
| 915 | branch_id: Some("main".to_string()), |
| 916 | after_seq: None, |
| 917 | limit: Some(50), |
| 918 | recent: None, |
| 919 | }; |
| 920 | let Json(proc_res) = process_session_handler( |
| 921 | State(state.clone()), |
| 922 | AxumPath(session.id.clone()), |
| 923 | Query(query_proc), |
| 924 | ) |
| 925 | .await |
| 926 | .unwrap(); |
| 927 | assert_eq!(proc_res["status"], "processed"); |
| 928 | assert!(proc_res["summary"].is_object()); |
| 929 | let candidates = proc_res["candidates"].as_array().unwrap(); |
| 930 | assert_eq!(candidates.len(), 2); |
| 931 | |
| 932 | // 4. Query candidates list |
| 933 | let Json(cands_list) = get_candidates_handler( |
| 934 | State(state.clone()), |
| 935 | Query(CandidatesQuery { |
| 936 | space: Some("atlas-memory".to_string()), |
| 937 | state: Some("pending".to_string()), |
| 938 | limit: Some(10), |
| 939 | }), |
| 940 | ) |
| 941 | .await |
| 942 | .unwrap(); |
| 943 | assert!(!cands_list["candidates"].as_array().unwrap().is_empty()); |
| 944 | |
| 945 | let cand_id = candidates[0]["id"].as_str().unwrap(); |
| 946 | |
| 947 | // 5. Promote candidate |
| 948 | let (p_status, Json(p_receipt)) = promote_candidate_handler( |
| 949 | State(state.clone()), |
| 950 | AxumPath(cand_id.to_string()), |
| 951 | Json(PromoteCandidatePayload { |
| 952 | policy_id: Some("e2e-policy".to_string()), |
| 953 | verifier_receipt: Some("e2e-verified".to_string()), |
| 954 | }), |
| 955 | ) |
| 956 | .await |
| 957 | .unwrap(); |
| 958 | assert_eq!(p_status, StatusCode::CREATED); |
| 959 | assert_eq!(p_receipt.candidate_id, cand_id); |
| 960 | |
| 961 | // 6. Compile Context |
| 962 | let mem_query = crate::compiler::MemoryQuery { |
| 963 | query: "user".to_string(), |
| 964 | session_id: Some(session.id.clone()), |
| 965 | branch_id: Some("main".to_string()), |
| 966 | space: "atlas-memory".to_string(), |
| 967 | intent: crate::compiler::MemoryIntent::Conversation, |
| 968 | token_budget: 1024, |
| 969 | include_candidates: true, |
| 970 | minimum_verification: None, |
| 971 | }; |
| 972 | |
| 973 | let Json(context) = compile_context_handler(State(state.clone()), Json(mem_query)) |
| 974 | .await |
| 975 | .unwrap(); |
| 976 | |
| 977 | assert!(!context.episodic.is_empty()); |
| 978 | assert!(!context.canonical.is_empty()); |
| 979 | assert!(context.rendered_prompt.contains("<CORTEX_MEMORY>")); |
| 980 | assert!(context.rendered_prompt.contains("<EPISODIC_CONTEXT>")); |
| 981 | assert!(context.rendered_prompt.contains("<VERIFIED_KNOWLEDGE>")); |
| 982 | } |
| 983 | } |