| /* | |
| * Licensed to the Apache Software Foundation (ASF) under one | |
| * or more contributor license agreements. See the NOTICE file | |
| * distributed with this work for additional information | |
| * regarding copyright ownership. The ASF licenses this file | |
| * to you under the Apache License, Version 2.0 (the | |
| * "License"); you may not use this file except in compliance | |
| * with the License. You may obtain a copy of the License at | |
| * | |
| * http://www.apache.org/licenses/LICENSE-2.0 | |
| * | |
| * Unless required by applicable law or agreed to in writing, | |
| * software distributed under the License is distributed on an | |
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | |
| * KIND, either express or implied. See the License for the | |
| * specific language governing permissions and limitations | |
| * under the License. | |
| */ | |
| //! Canonical Agent facts and deterministic transactional indexes on the original Root. | |
| //! This crate does not choose a next action, schedule work, or recreate live grants. | |
| pub mod artifacts; | |
| pub mod cells; | |
| pub mod computer; | |
| pub mod cross_root; | |
| pub mod diagnostics; | |
| pub mod external_effects; | |
| pub mod external_publication; | |
| pub mod external_steering; | |
| pub mod fold; | |
| pub mod interactions; | |
| pub mod memory; | |
| mod namespace; | |
| pub mod operation; | |
| pub mod queue; | |
| pub mod recall; | |
| pub mod room; | |
| pub mod session_catalog; | |
| pub mod session_history; | |
| mod sql; | |
| mod store; | |
| pub mod usage; | |
| pub use store::{ | |
| Admission, AdmissionGuard, AnswerPage, CallerFence, CallerStatus, CellChildAdmission, | |
| CellChildAdmissionOutcome, Change, CleanupFrontier, Commit, ContentBlob, DriverClaim, | |
| DriverDomain, DriverPurpose, Head, ImmutableContentBody, LiveAuthority, LocalResult, | |
| ModelCleanupItem, NotificationAttention, NotificationState, ProviderToolLookup, | |
| PublicationRead, ReadyCause, ReadyRun, RunObservation, SessionObligation, SessionQuiescence, | |
| SessionQuiescenceGuard, StopOutcome, StopRun, Store, | |
| }; | |
| pub const MIGRATIONS: &[maka_event_log::migration::Migration] = &[ | |
| maka_event_log::migration::Migration { | |
| version: 2, | |
| description: "agent canonical execution", | |
| sql: include_str!("../migrations/0002_agent.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 3, | |
| description: "agent request queue", | |
| sql: include_str!("../migrations/0003_queue.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 4, | |
| description: "agent interactions", | |
| sql: include_str!("../migrations/0004_interactions.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 5, | |
| description: "agent artifact manifests", | |
| sql: include_str!("../migrations/0005_artifacts.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 6, | |
| description: "agent session history", | |
| sql: include_str!("../migrations/0006_session_history.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 7, | |
| description: "agent session catalog", | |
| sql: include_str!("../migrations/0007_session_catalog.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 8, | |
| description: "durable cells", | |
| sql: include_str!("../migrations/0008_cells.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 9, | |
| description: "agent computer observations", | |
| sql: include_str!("../migrations/0009_computer.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 10, | |
| description: "external Host effects", | |
| sql: include_str!("../migrations/0010_external_effects.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 11, | |
| description: "agent usage and recall", | |
| sql: include_str!("../migrations/0011_usage_recall.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 12, | |
| description: "external task steering", | |
| sql: include_str!("../migrations/0012_external_steering.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 13, | |
| description: "immutable history snapshots", | |
| sql: include_str!("../migrations/0013_history_snapshot.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 14, | |
| description: "canonical continuation successor references", | |
| sql: include_str!("../migrations/0014_continuation.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 16, | |
| description: "immutable history snapshot ingestion", | |
| sql: include_str!("../migrations/0016_snapshot_ingest.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 17, | |
| description: "external workspace publication", | |
| sql: include_str!("../migrations/0017_external_publication.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 18, | |
| description: "immutable history snapshot positions", | |
| sql: include_str!("../migrations/0018_snapshot_positions.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 19, | |
| description: "immutable history snapshot navigation", | |
| sql: include_str!("../migrations/0019_snapshot_navigation.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 20, | |
| description: "safe canonical diagnostic projection", | |
| sql: include_str!("../migrations/0020_diagnostics.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 21, | |
| description: "immutable history snapshot catalog metadata", | |
| sql: include_str!("../migrations/0021_snapshot_catalog.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 22, | |
| description: "sparse historical source and diagnostic read indexes", | |
| sql: include_str!("../migrations/0022_read_indexes.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 24, | |
| description: "native input source and turn interruption indexes", | |
| sql: include_str!("../migrations/0024_native_turn_fence.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 25, | |
| description: "immutable snapshot model fact metadata", | |
| sql: include_str!("../migrations/0025_snapshot_model_metadata.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 26, | |
| description: "canonical transport and successful finish projections", | |
| sql: include_str!("../migrations/0026_execution_fences.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 27, | |
| description: "indexed material reference lookups", | |
| sql: include_str!("../migrations/0027_material_reference_indexes.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 28, | |
| description: "indexed ingest content foreign keys", | |
| sql: include_str!("../migrations/0028_ingest_content_reference_indexes.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 29, | |
| description: "original external task cleanup frontier", | |
| sql: include_str!("../migrations/0029_external_cleanup.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 30, | |
| description: "indexed original model cleanup and final settlement", | |
| sql: include_str!("../migrations/0030_model_cleanup.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 31, | |
| description: "indexed imported history positions", | |
| sql: include_str!("../migrations/0031_imported_history_position.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 32, | |
| description: "compact history search", | |
| sql: include_str!("../migrations/0032_compact_history_search.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 33, | |
| description: "derive adopted Run content", | |
| sql: include_str!("../migrations/0033_derived_snapshot_adoption.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 34, | |
| description: "locate immutable inventory pages", | |
| sql: include_str!("../migrations/0034_snapshot_inventory_pages.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 35, | |
| description: "own executor profile contents", | |
| sql: include_str!("../migrations/0035_profile_content_owners.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 37, | |
| description: "track proactive summary attempts", | |
| sql: include_str!("../migrations/0037_proactive_summary.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 38, | |
| description: "subagent presets", | |
| sql: include_str!("../migrations/0038_subagent_presets.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 39, | |
| description: "index external assistant messages in the session catalog", | |
| sql: include_str!("../migrations/0039_external_catalog_messages.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 40, | |
| description: "session rooms and messages", | |
| sql: include_str!("../migrations/0040_rooms.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 41, | |
| description: "index history tool result metadata", | |
| sql: include_str!("../migrations/0041_history_tool_metadata.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 43, | |
| description: "scoped ordinary memory", | |
| sql: include_str!("../migrations/0043_memory.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 44, | |
| description: "memory assertion metadata", | |
| sql: include_str!("../migrations/0044_memory_metadata.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 45, | |
| description: "memory version evidence", | |
| sql: include_str!("../migrations/0045_memory_evidence.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 46, | |
| description: "memory write resolution", | |
| sql: include_str!("../migrations/0046_memory_resolution.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 47, | |
| description: "missing external tool returns", | |
| sql: include_str!("../migrations/0047_missing_external_returns.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 48, | |
| description: "permission grant sources", | |
| sql: include_str!("../migrations/0048_permission_grant_sources.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 49, | |
| description: "session removal foreign-key indexes", | |
| sql: include_str!("../migrations/0049_session_removal_fk_indexes.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 50, | |
| description: "persist run output-limit continuation count", | |
| sql: include_str!("../migrations/0050_output_limit_continuations.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 51, | |
| description: "current memory recall and restricted evidence", | |
| sql: include_str!("../migrations/0051_memory_recall.sql"), | |
| configure: Some(memory::recall::configure_writer), | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 52, | |
| description: "room members, topic, reactions, pins, edits, and full-text search", | |
| sql: include_str!("../migrations/0052_room_overhaul.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 53, | |
| description: "persist consecutive retry streak state on runs", | |
| sql: include_str!("../migrations/0053_retry_streak.sql"), | |
| configure: None, | |
| data: Some(sql::migrate_retry_streak), | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 54, | |
| description: "repair reordered queue projections", | |
| sql: include_str!("../migrations/0054_queue_reorder_projection.sql"), | |
| configure: None, | |
| data: Some(queue::rebuild_queue_projections), | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 55, | |
| description: "index ended-unknown external effect observations and redaction links", | |
| sql: include_str!("../migrations/0055_external_effect_ended_unknown.sql"), | |
| configure: None, | |
| data: Some(recall::migrate_external_effect_observations), | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 56, | |
| description: "session-scoped message submission keys", | |
| sql: include_str!("../migrations/0056_message_submissions.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 57, | |
| description: "track pinned memory, source visibility and legacy read provenance", | |
| sql: include_str!("../migrations/0057_pinned_memory.sql"), | |
| configure: None, | |
| data: Some(memory::migrate_pinned::migrate), | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 58, | |
| description: "drop session visibility taint tracking and simplify memory replay", | |
| sql: include_str!("../migrations/0058_simplify_memory_replay.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 59, | |
| description: "drop redundant duplicate and prefix indexes", | |
| sql: include_str!("../migrations/0059_drop_duplicate_indexes.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 60, | |
| description: "drop stored folded column from agent_recall_messages", | |
| sql: include_str!("../migrations/0060_drop_recall_folded.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 61, | |
| description: "deduplicate Recall indexing at source and coalesce external streaming deltas", | |
| sql: include_str!("../migrations/0061_dedup_recall_index.sql"), | |
| configure: None, | |
| data: Some(recall::migrate_v58::run), | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 62, | |
| description: "intern namespace surrogate keys for history and recall", | |
| sql: include_str!("../migrations/0062_namespace_surrogate_keys.sql"), | |
| configure: None, | |
| data: Some(namespace::migrate_namespace_surrogate_keys), | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 64, | |
| description: "decode compressed contents in agent views and triggers", | |
| sql: include_str!("../migrations/0064_agent_views_content_decode.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 66, | |
| description: "compress agent_cells bodies and intern usage JSON blobs", | |
| sql: include_str!("../migrations/0066_compress_cells_and_usage.sql"), | |
| configure: Some(maka_event_log::content::register_sql_functions), | |
| data: Some(cells::migrate_v66::migrate_compress_cells_and_usage), | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 67, | |
| description: "index live catalog runs for active child lookups", | |
| sql: include_str!("../migrations/0067_catalog_live_runs_index.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 68, | |
| description: "retire session recap storage and configuration field", | |
| sql: include_str!("../migrations/0068_retire_session_recap.sql"), | |
| configure: None, | |
| data: Some(retire_session_recap), | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 69, | |
| description: "index agent_facts by (run, sequence) for cursor inspection", | |
| sql: include_str!("../migrations/0069_agent_facts_run_sequence_index.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 70, | |
| description: "index local message and checkpoint handoff admissions by session", | |
| sql: include_str!("../migrations/0070_message_backend_index.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 71, | |
| description: "remove memory hidden-span, archive taint, and cross-run replay restriction schema", | |
| sql: include_str!("../migrations/0071_remove_memory_read_walls.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 73, | |
| description: "cross-Root Room delivery and receipts", | |
| sql: include_str!("../migrations/0073_cross_root_rooms.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 74, | |
| description: "cross-Root outbox per-root backoff, completion state, and remote member titles", | |
| sql: include_str!("../migrations/0074_cross_root_room_upgrade.sql"), | |
| configure: None, | |
| data: None, | |
| }, | |
| maka_event_log::migration::Migration { | |
| version: 75, | |
| description: "migrate persisted appliedPreset snapshots to appliedRole", | |
| sql: include_str!("../migrations/0075_agent_roles.sql"), | |
| configure: None, | |
| data: Some(migrate_applied_preset_to_role), | |
| }, | |
| ]; | |
| fn strip_agent_recaps(value: &mut serde_json::Value) -> bool { | |
| let mut changed = false; | |
| match value { | |
| serde_json::Value::Object(map) => { | |
| let is_agent = map | |
| .get("package") | |
| .and_then(|p| p.get("id")) | |
| .and_then(serde_json::Value::as_str) | |
| == Some("maka.agent"); | |
| if is_agent | |
| && let Some(values) = map | |
| .get_mut("configuration") | |
| .and_then(|c| c.get_mut("values")) | |
| .and_then(serde_json::Value::as_object_mut) | |
| && values.remove("recaps").is_some() | |
| { | |
| changed = true; | |
| } | |
| if let Some(overrides) = map | |
| .get_mut("overrides") | |
| .and_then(serde_json::Value::as_array_mut) | |
| { | |
| for item in overrides { | |
| if let Some(obj) = item.as_object_mut() { | |
| if let Some(cfg) = obj | |
| .get_mut("configuration") | |
| .and_then(serde_json::Value::as_object_mut) | |
| && cfg.remove("recaps").is_some() | |
| { | |
| changed = true; | |
| } | |
| if let Some(fields) = obj | |
| .get_mut("configurationFields") | |
| .and_then(serde_json::Value::as_array_mut) | |
| { | |
| let before = fields.len(); | |
| fields.retain(|f| { | |
| f.get("path") | |
| .and_then(serde_json::Value::as_array) | |
| .and_then(|p| p.first()) | |
| .and_then(serde_json::Value::as_str) | |
| != Some("recaps") | |
| }); | |
| if fields.len() != before { | |
| changed = true; | |
| } | |
| } | |
| } | |
| } | |
| } | |
| for child in map.values_mut() { | |
| changed |= strip_agent_recaps(child); | |
| } | |
| } | |
| serde_json::Value::Array(items) => { | |
| for item in items { | |
| changed |= strip_agent_recaps(item); | |
| } | |
| } | |
| _ => {} | |
| } | |
| changed | |
| } | |
| fn retire_session_recap(c: &rusqlite::Connection) -> Result<(), maka_event_log::StoreError> { | |
| let mut stmt = c.prepare( | |
| r#"SELECT deployment, revision, input_json FROM application_sources WHERE instr(input_json, '"recaps"') > 0"#, | |
| )?; | |
| let rows: Vec<(String, i64, String)> = stmt | |
| .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))? | |
| .collect::<Result<_, _>>()?; | |
| drop(stmt); | |
| let mut update = c.prepare( | |
| "UPDATE application_sources SET input_json = ?1 WHERE deployment = ?2 AND revision = ?3", | |
| )?; | |
| for (deployment, revision, raw) in rows { | |
| let mut parsed: serde_json::Value = serde_json::from_str(&raw)?; | |
| if strip_agent_recaps(&mut parsed) { | |
| let updated = serde_json::to_string(&parsed)?; | |
| update.execute(rusqlite::params![updated, deployment, revision])?; | |
| } | |
| } | |
| Ok(()) | |
| } | |
| fn role_slug_from_name(name: &str) -> String { | |
| let mut slug = String::new(); | |
| let mut last_dash = true; | |
| for ch in name.trim().chars() { | |
| let lower = ch.to_ascii_lowercase(); | |
| if lower.is_ascii_lowercase() || lower.is_ascii_digit() { | |
| slug.push(lower); | |
| last_dash = false; | |
| } else if !last_dash && !slug.is_empty() { | |
| slug.push('-'); | |
| last_dash = true; | |
| } | |
| if slug.len() >= 48 { | |
| break; | |
| } | |
| } | |
| while slug.ends_with('-') { | |
| slug.pop(); | |
| } | |
| if !slug.is_empty() | |
| && slug | |
| .chars() | |
| .next() | |
| .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) | |
| { | |
| return slug; | |
| } | |
| let mut hash: u64 = 0xcbf29ce484222325; | |
| for byte in name.as_bytes() { | |
| hash ^= u64::from(*byte); | |
| hash = hash.wrapping_mul(0x100000001b3); | |
| } | |
| format!("role-{hash:08x}") | |
| } | |
| fn migrate_applied_preset_to_role( | |
| c: &rusqlite::Connection, | |
| ) -> Result<(), maka_event_log::StoreError> { | |
| let mut stmt = c.prepare( | |
| r#"SELECT id, configuration FROM session_control WHERE instr(configuration, '"appliedPreset"') > 0"#, | |
| )?; | |
| let rows: Vec<(String, String)> = stmt | |
| .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))? | |
| .collect::<Result<_, _>>()?; | |
| drop(stmt); | |
| let mut update = c.prepare("UPDATE session_control SET configuration = ?1 WHERE id = ?2")?; | |
| for (id, raw) in rows { | |
| let mut parsed: serde_json::Value = serde_json::from_str(&raw)?; | |
| let Some(obj) = parsed.as_object_mut() else { | |
| continue; | |
| }; | |
| let Some(legacy) = obj.remove("appliedPreset") else { | |
| continue; | |
| }; | |
| if let Some(preset) = legacy.as_object() { | |
| let name = preset | |
| .get("name") | |
| .and_then(serde_json::Value::as_str) | |
| .unwrap_or("Role") | |
| .to_owned(); | |
| let instruction = preset | |
| .get("instruction") | |
| .and_then(serde_json::Value::as_str) | |
| .unwrap_or("") | |
| .to_owned(); | |
| let backend = preset | |
| .get("model") | |
| .and_then(serde_json::Value::as_object) | |
| .and_then(|model| { | |
| let connection_id = model.get("connectionId")?.as_str()?; | |
| let model_id = model.get("modelId")?.as_str()?; | |
| let mut map = serde_json::Map::new(); | |
| map.insert("kind".into(), serde_json::Value::String("model".into())); | |
| map.insert( | |
| "connectionId".into(), | |
| serde_json::Value::String(connection_id.into()), | |
| ); | |
| map.insert("modelId".into(), serde_json::Value::String(model_id.into())); | |
| if let Some(tier) = model.get("serviceTier").filter(|v| !v.is_null()) { | |
| map.insert("serviceTier".into(), tier.clone()); | |
| } | |
| if let Some(thinking) = preset.get("thinkingLevel").filter(|v| !v.is_null()) { | |
| map.insert("thinkingLevel".into(), thinking.clone()); | |
| } | |
| Some(serde_json::Value::Object(map)) | |
| }); | |
| let mut role = serde_json::Map::new(); | |
| role.insert( | |
| "slug".into(), | |
| serde_json::Value::String(role_slug_from_name(&name)), | |
| ); | |
| role.insert("name".into(), serde_json::Value::String(name)); | |
| role.insert( | |
| "description".into(), | |
| serde_json::Value::String(String::new()), | |
| ); | |
| role.insert("instruction".into(), serde_json::Value::String(instruction)); | |
| if let Some(backend) = backend { | |
| role.insert("backend".into(), backend); | |
| } | |
| role.insert( | |
| "permissions".into(), | |
| serde_json::Value::String("inherit".into()), | |
| ); | |
| role.insert("workspace".into(), serde_json::Value::String("same".into())); | |
| role.insert("skills".into(), serde_json::Value::Array(Vec::new())); | |
| obj.insert("appliedRole".into(), serde_json::Value::Object(role)); | |
| } | |
| let updated = serde_json::to_string(&parsed)?; | |
| update.execute(rusqlite::params![updated, id])?; | |
| } | |
| Ok(()) | |
| } | |
| #[cfg(test)] | |
| mod migration_tests { | |
| #[test] | |
| fn composed_product_migrations_initialize_upgrade_and_reopen() { | |
| let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS | |
| .iter() | |
| .chain(super::MIGRATIONS) | |
| .copied() | |
| .collect(); | |
| for through in [0, 41].into_iter().chain(46..=69) { | |
| let directory = tempfile::tempdir().unwrap(); | |
| let path = directory.path().join("root.sqlite"); | |
| let db = rusqlite::Connection::open(&path).unwrap(); | |
| if through > 0 { | |
| let previous: Vec<_> = catalog | |
| .iter() | |
| .filter(|m| m.version <= through) | |
| .copied() | |
| .collect(); | |
| maka_event_log::migration::run(&db, &previous).unwrap(); | |
| } | |
| maka_event_log::migration::run(&db, &catalog).unwrap(); | |
| drop(db); | |
| let db = rusqlite::Connection::open(&path).unwrap(); | |
| maka_event_log::migration::run(&db, &catalog).unwrap(); | |
| let identities: i64 = db | |
| .query_row( | |
| "SELECT COUNT(*) FROM checkpoint_repository_sessions", | |
| [], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(); | |
| assert_eq!(identities, 0); | |
| for table in [ | |
| "agent_session_history", | |
| "agent_recall_messages", | |
| "agent_recall_external_segments", | |
| "agent_usage_calls", | |
| ] { | |
| let has_ns_id: bool = db | |
| .query_row( | |
| &format!( | |
| "SELECT EXISTS(SELECT 1 FROM pragma_table_info('{table}') WHERE name='namespace_id')" | |
| ), | |
| [], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(); | |
| assert!(has_ns_id, "migration 61 must add namespace_id to {table}"); | |
| let has_owner: bool = db | |
| .query_row( | |
| &format!( | |
| "SELECT EXISTS(SELECT 1 FROM pragma_table_info('{table}') WHERE name IN ('owner','session'))" | |
| ), | |
| [], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(); | |
| assert!( | |
| !has_owner, | |
| "migration 61 must drop owner/session from {table}" | |
| ); | |
| } | |
| for dropped in [ | |
| "agent_session_history_run_fk", | |
| "agent_session_history_result", | |
| "agent_memory_run_termination", | |
| "agent_usage_call_session_time", | |
| ] { | |
| let exists: bool = db | |
| .query_row( | |
| "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='index' AND name=?)", | |
| [dropped], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(); | |
| assert!(!exists, "migration 61 must drop redundant index {dropped}"); | |
| } | |
| for col in ["encoding", "logical_bytes"] { | |
| let exists: bool = db | |
| .query_row( | |
| &format!( | |
| "SELECT EXISTS(SELECT 1 FROM pragma_table_info('contents') WHERE name='{col}')" | |
| ), | |
| [], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(); | |
| assert!(exists, "migration 63 must add {col} to contents"); | |
| } | |
| let count: i64 = db | |
| .query_row( | |
| "SELECT COUNT(*) FROM agent_history_tool_metadata_source", | |
| [], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(); | |
| assert_eq!(count, 0, "migration 64 view must query cleanly"); | |
| for (kind, name) in [ | |
| ("table", "agent_memory_cell_candidates"), | |
| ("table", "agent_memory_cell_observations"), | |
| ("table", "agent_memory_cell_events"), | |
| ("table", "agent_memory_run_restrictions"), | |
| ("table", "agent_memory_shared_fields"), | |
| ("table", "agent_memory_recall_attachments"), | |
| ("table", "agent_memory_recall_calls"), | |
| ("table", "agent_memory_imported_tools"), | |
| ("table", "agent_memory_snapshot_outputs"), | |
| ("table", "agent_memory_indexed_snapshots"), | |
| ("table", "agent_memory_read_aliases"), | |
| ("table", "agent_memory_history_boundary"), | |
| ("table", "agent_memory_legacy_recap_history"), | |
| ("table", "agent_memory_tool_inputs"), | |
| ("view", "agent_memory_hidden_spans"), | |
| ("view", "agent_memory_operation_field_source"), | |
| ("view", "agent_memory_failed_terminations"), | |
| ("view", "agent_memory_termination_receipts"), | |
| ("view", "agent_memory_recall_outputs"), | |
| ("index", "agent_memory_interruption_attempt"), | |
| ("trigger", "agent_memory_recall_call_insert"), | |
| ("trigger", "agent_memory_snapshot_index"), | |
| ] { | |
| let exists: bool = db | |
| .query_row( | |
| "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type=?1 AND name=?2)", | |
| [kind, name], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(); | |
| assert!(!exists, "migration 71 must drop {kind} {name}"); | |
| } | |
| for (kind, name) in [ | |
| ("table", "agent_memories"), | |
| ("table", "agent_memory_versions"), | |
| ("table", "agent_memory_evidence"), | |
| ("table", "agent_memory_scopes"), | |
| ("table", "agent_memory_matches"), | |
| ("table", "agent_memory_relations"), | |
| ("table", "agent_memory_search"), | |
| ("table", "agent_memory_recall_keys"), | |
| ("table", "agent_memory_recall_terms"), | |
| ("view", "agent_memory_recall_current"), | |
| ("trigger", "agent_memory_recall_version"), | |
| ("trigger", "agent_memory_recall_change"), | |
| ("trigger", "agent_memory_run_insert"), | |
| ] { | |
| let exists: bool = db | |
| .query_row( | |
| "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type=?1 AND name=?2)", | |
| [kind, name], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(); | |
| assert!(exists, "migration 71 must preserve core {kind} {name}"); | |
| } | |
| } | |
| } | |
| #[tokio::test] | |
| async fn compressed_contents_survive_store_reads_views_and_seekable_chunks() { | |
| use crate::artifacts::{ArtifactReadScope, ArtifactStore, SessionScope, Upload}; | |
| use crate::store::{Admission, Change}; | |
| use maka_agent_facts::{ | |
| artifact::{Artifact, ArtifactKind, ArtifactSource}, | |
| durable::{Fact, FactId, RunId, Terminal, UnixMillis}, | |
| input::{MessageInput, RunInput}, | |
| }; | |
| use maka_event_log::{ | |
| RootStore, | |
| root::{RootNamespaces, RootOwner}, | |
| }; | |
| use std::io::{Read, Seek, SeekFrom}; | |
| use std::sync::Arc; | |
| let dir = tempfile::tempdir().unwrap(); | |
| let namespaces = RootNamespaces { | |
| ownership: dir.path().join("owners"), | |
| control: dir.path().join("control"), | |
| }; | |
| let root_path = dir.path().join("root"); | |
| let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS | |
| .iter() | |
| .chain(super::MIGRATIONS) | |
| .copied() | |
| .collect(); | |
| // Seed a pre-v63 database with an uncompressed compressible blob first. | |
| let through_62: Vec<_> = catalog | |
| .iter() | |
| .filter(|m| m.version <= 62) | |
| .copied() | |
| .collect(); | |
| let legacy_payload = "legacy-uncompressed-payload-".repeat(120).into_bytes(); | |
| let legacy_blob = crate::ContentBlob::new(legacy_payload.clone()); | |
| let legacy_digest = legacy_blob.reference().digest.clone(); | |
| { | |
| let owner = Arc::new(RootOwner::create(&root_path, &namespaces).unwrap()); | |
| let pre_root = RootStore::open(owner, &through_62).await.unwrap(); | |
| pre_root.close().await.unwrap(); | |
| let db = | |
| rusqlite::Connection::open(root_path.join(maka_event_log::root::ROOT_DATABASE)) | |
| .unwrap(); | |
| legacy_blob.store_legacy(&db).unwrap(); | |
| } | |
| // Reopen through the real RootStore so v63 + v64 migrate forward in place. | |
| let owner = Arc::new(RootOwner::open_existing(&root_path, &namespaces).unwrap()); | |
| let root = RootStore::open(owner, &catalog).await.unwrap(); | |
| let data = root.data_writer().unwrap(); | |
| let store = crate::Store::new( | |
| data.clone(), | |
| crate::DriverDomain::new(data.clone()).unwrap(), | |
| ) | |
| .unwrap(); | |
| let artifacts = ArtifactStore::new(data.clone()); | |
| // Admit a run with a large compressible user message so new rows land compressed. | |
| let (mut spec, mut blobs) = crate::store::stop_tests::spec(); | |
| let long_text = "compressed-agent-message-segment-".repeat(80); | |
| let input_blob = crate::ContentBlob::json(&RunInput::Message { | |
| content: MessageInput::from(long_text.as_str()), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| }) | |
| .unwrap(); | |
| spec.input = input_blob.reference().clone(); | |
| blobs.push(input_blob); | |
| let run = RunId::new(); | |
| let committed = store | |
| .admit(Admission::with_identity( | |
| run, | |
| spec.clone(), | |
| UnixMillis(1_700_000_000_000), | |
| blobs, | |
| )) | |
| .await | |
| .unwrap(); | |
| let claim = store.claim(run).await.unwrap(); | |
| store | |
| .append( | |
| &claim, | |
| committed.head, | |
| vec![Change { | |
| id: FactId::new(), | |
| at: UnixMillis(1_700_000_000_100), | |
| fact: Fact::RunTerminated { | |
| terminal: Terminal::Failed, | |
| diagnostic: Some("failure-diagnostic-".repeat(40)), | |
| }, | |
| }], | |
| vec![], | |
| ) | |
| .await | |
| .unwrap(); | |
| drop(claim); | |
| // Upload a compressible artifact and read it via both chunk() and with_content(). | |
| let artifact_bytes = "artifact-chunk-boundary-data-0123456789\n" | |
| .repeat(120) | |
| .into_bytes(); | |
| let scope = SessionScope { | |
| owner: spec.owner.clone(), | |
| session: spec.session_id.clone(), | |
| }; | |
| let artifact_id = | |
| maka_agent_facts::artifact::upload_artifact_id(&spec.session_id, "art-compress-1"); | |
| let uploaded = artifacts | |
| .upload(Upload::new( | |
| scope.clone(), | |
| "op-compress-1".into(), | |
| "art-compress-1".into(), | |
| Artifact { | |
| id: artifact_id.clone(), | |
| session_id: spec.session_id.clone(), | |
| turn_id: spec.turn_id.clone(), | |
| created_at: 1_700_000_000_200, | |
| name: "notes.txt".into(), | |
| kind: ArtifactKind::File, | |
| size_bytes: artifact_bytes.len() as u64, | |
| mime_type: Some("text/plain".into()), | |
| source: ArtifactSource::UserUpload, | |
| summary: Some(maka_agent_facts::artifact::content_digest(&artifact_bytes)), | |
| }, | |
| artifact_bytes.clone(), | |
| )) | |
| .await | |
| .unwrap(); | |
| assert_eq!(uploaded.payload.bytes, artifact_bytes.len() as u64); | |
| let read_scope = ArtifactReadScope::Session { | |
| scope: scope.clone(), | |
| }; | |
| let chunk = artifacts | |
| .chunk(read_scope.clone(), artifact_id.clone(), 137, 250) | |
| .await | |
| .unwrap() | |
| .expect("artifact chunk"); | |
| assert_eq!(chunk.bytes, &artifact_bytes[137..387]); | |
| assert_eq!(chunk.total_bytes, artifact_bytes.len() as u64); | |
| let full = artifacts | |
| .with_content(read_scope, artifact_id, |_art, reader| { | |
| let mut buf = Vec::new(); | |
| reader.read_to_end(&mut buf).unwrap(); | |
| buf | |
| }) | |
| .await | |
| .unwrap() | |
| .expect("artifact full read"); | |
| assert_eq!(full, artifact_bytes); | |
| // Verify on-disk compression, ContentReader seeking, v64 views, and incremental re-encoding. | |
| let db_path = root_path.join(maka_event_log::root::ROOT_DATABASE); | |
| let db = rusqlite::Connection::open(&db_path).unwrap(); | |
| maka_event_log::content::register_sql_functions(&db).unwrap(); | |
| let (cid, enc, phys_len, log_len): (i64, i64, i64, Option<i64>) = db | |
| .query_row( | |
| "SELECT id, encoding, length(payload), logical_bytes FROM contents WHERE content_sha256=?", | |
| [&uploaded.payload.digest], | |
| |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), | |
| ) | |
| .unwrap(); | |
| assert_eq!(enc, 1, "compressible artifact must be zstd-encoded"); | |
| assert_eq!(log_len, Some(artifact_bytes.len() as i64)); | |
| assert!(phys_len < artifact_bytes.len() as i64); | |
| let mut reader = maka_event_log::content::open_by_id(&db, cid).unwrap(); | |
| assert_eq!(reader.len(), artifact_bytes.len() as u64); | |
| reader.seek(SeekFrom::Start(50)).unwrap(); | |
| let mut slice = [0_u8; 64]; | |
| reader.read_exact(&mut slice).unwrap(); | |
| assert_eq!(&slice, &artifact_bytes[50..114]); | |
| reader.close().unwrap(); | |
| crate::recall::index::catch_up_session( | |
| &db, | |
| &spec.owner, | |
| &serde_json::to_string(&spec.owner).unwrap(), | |
| &spec.session_id, | |
| ) | |
| .unwrap(); | |
| let decoded_term: String = db | |
| .query_row( | |
| "SELECT maka_content_text(c.payload, c.encoding) | |
| FROM agent_session_history h | |
| JOIN agent_facts f ON f.sequence = h.sequence | |
| JOIN contents c ON c.id = f.body_content_id | |
| WHERE h.run=? AND h.kind='run_terminated'", | |
| [run.to_string()], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(); | |
| assert!( | |
| decoded_term.contains("failure-diagnostic-"), | |
| "maka_content_text must decode compressed termination fact" | |
| ); | |
| // Pre-v63 blob must actually be recompressed in place by RootStore's background | |
| // maintenance worker, shrink physically, record logical_bytes, and remain verbatim readable. | |
| let legacy_id: i64 = db | |
| .query_row( | |
| "SELECT id FROM contents WHERE content_sha256=?", | |
| [&legacy_digest], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(); | |
| let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); | |
| let (legacy_enc, legacy_phys, legacy_logical) = loop { | |
| let row: (i64, i64, Option<i64>) = db | |
| .query_row( | |
| "SELECT encoding, length(payload), logical_bytes FROM contents WHERE id=?", | |
| [legacy_id], | |
| |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), | |
| ) | |
| .unwrap(); | |
| if row.0 != maka_event_log::content::ENCODING_RAW | |
| || std::time::Instant::now() >= deadline | |
| { | |
| break row; | |
| } | |
| tokio::time::sleep(std::time::Duration::from_millis(25)).await; | |
| }; | |
| assert_ne!( | |
| legacy_enc, | |
| maka_event_log::content::ENCODING_RAW, | |
| "RootStore background maintenance must recompress legacy raw compressible blobs" | |
| ); | |
| assert_eq!(legacy_logical, Some(legacy_payload.len() as i64)); | |
| assert!(legacy_phys < legacy_payload.len() as i64); | |
| assert_eq!( | |
| maka_event_log::content::read(&db, &legacy_digest) | |
| .unwrap() | |
| .as_deref(), | |
| Some(legacy_payload.as_slice()) | |
| ); | |
| assert!( | |
| db.execute("UPDATE contents SET encoding=1 WHERE id=?", [legacy_id]) | |
| .is_err(), | |
| "content_immutable must reject invalid encoding updates" | |
| ); | |
| // Large (> 64 KiB) new artifact uses seekable framed zstd (encoding = 2) and supports | |
| // cross-frame chunk reads via Artifacts::chunk. | |
| let seekable_bytes: Vec<u8> = (0..5000) | |
| .flat_map(|i| { | |
| format!( | |
| "seekable-artifact-line-{i:05}-compressible-segment | |
| " | |
| ) | |
| .into_bytes() | |
| }) | |
| .collect(); | |
| assert!(seekable_bytes.len() > maka_event_log::content::SEEKABLE_FRAME_BYTES * 3); | |
| let seekable_art_id = | |
| maka_agent_facts::artifact::upload_artifact_id(&spec.session_id, "art-seekable-1"); | |
| let seekable_uploaded = artifacts | |
| .upload(Upload::new( | |
| scope.clone(), | |
| "op-seekable-1".into(), | |
| "art-seekable-1".into(), | |
| Artifact { | |
| id: seekable_art_id.clone(), | |
| session_id: spec.session_id.clone(), | |
| turn_id: spec.turn_id.clone(), | |
| created_at: 1_700_000_000_300, | |
| name: "large.log".into(), | |
| kind: ArtifactKind::File, | |
| size_bytes: seekable_bytes.len() as u64, | |
| mime_type: Some("text/plain".into()), | |
| source: ArtifactSource::UserUpload, | |
| summary: Some(maka_agent_facts::artifact::content_digest(&seekable_bytes)), | |
| }, | |
| seekable_bytes.clone(), | |
| )) | |
| .await | |
| .unwrap(); | |
| let (seek_enc, seek_phys, seek_logical): (i64, i64, Option<i64>) = db | |
| .query_row( | |
| "SELECT encoding, length(payload), logical_bytes FROM contents WHERE content_sha256=?", | |
| [&seekable_uploaded.payload.digest], | |
| |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), | |
| ) | |
| .unwrap(); | |
| assert_eq!(seek_enc, maka_event_log::content::ENCODING_ZSTD_SEEKABLE); | |
| assert_eq!(seek_logical, Some(seekable_bytes.len() as i64)); | |
| assert!(seek_phys < seekable_bytes.len() as i64); | |
| let cross_frame_off = (maka_event_log::content::SEEKABLE_FRAME_BYTES - 128) as u64; | |
| let seek_chunk = artifacts | |
| .chunk( | |
| ArtifactReadScope::Session { | |
| scope: scope.clone(), | |
| }, | |
| seekable_art_id, | |
| cross_frame_off, | |
| 512, | |
| ) | |
| .await | |
| .unwrap() | |
| .expect("seekable artifact chunk"); | |
| assert_eq!( | |
| seek_chunk.bytes, | |
| &seekable_bytes[cross_frame_off as usize..cross_frame_off as usize + 512] | |
| ); | |
| // Verify recall message index decoded the compressed input blob. | |
| let recall_hits: i64 = db | |
| .query_row( | |
| "SELECT COUNT(*) FROM agent_recall_messages m | |
| JOIN agent_namespaces ns ON ns.id = m.namespace_id | |
| WHERE ns.session = ? AND m.body LIKE '%compressed-agent-message-segment%'", | |
| [&spec.session_id], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(); | |
| assert_eq!(recall_hits, 1, "recall must index compressed input message"); | |
| drop(db); | |
| root.close().await.unwrap(); | |
| } | |
| #[test] | |
| fn migration_68_retires_session_recap_data_and_config() { | |
| let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS | |
| .iter() | |
| .chain(super::MIGRATIONS) | |
| .copied() | |
| .collect(); | |
| let before: Vec<_> = catalog.iter().filter(|m| m.version < 68).copied().collect(); | |
| let db = rusqlite::Connection::open_in_memory().unwrap(); | |
| maka_event_log::migration::run(&db, &before).unwrap(); | |
| db.execute( | |
| r#"INSERT INTO plugin_data(package_id, scope_id, key, revision, value_json) VALUES('maka.session-recap', 'profile', 'sess-1', 1, '{"kind":"ready"}')"#, | |
| [], | |
| ) | |
| .unwrap(); | |
| let input = serde_json::json!({ | |
| "instances": { | |
| "agent": { | |
| "package": { "id": "maka.agent" }, | |
| "configuration": { "values": { "automaticTitles": true, "recaps": true } }, | |
| "overrides": [{ | |
| "path": ["agent"], | |
| "configuration": { "recaps": false, "recall": true }, | |
| "configurationFields": [ | |
| { "path": ["recaps"], "value": false }, | |
| { "path": ["recall"], "value": true } | |
| ] | |
| }] | |
| }, | |
| "other": { | |
| "package": { "id": "maka.other" }, | |
| "configuration": { "values": { "recaps": true } } | |
| } | |
| } | |
| }); | |
| db.execute( | |
| "INSERT INTO application_sources(deployment, revision, input_json, remote_exports_json) VALUES('default', 1, ?, '{}')", | |
| [input.to_string()], | |
| ) | |
| .unwrap(); | |
| maka_event_log::migration::run(&db, &catalog).unwrap(); | |
| let remaining_recap_rows: i64 = db | |
| .query_row( | |
| "SELECT COUNT(*) FROM plugin_data WHERE package_id = 'maka.session-recap'", | |
| [], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(); | |
| assert_eq!(remaining_recap_rows, 0); | |
| let migrated: serde_json::Value = serde_json::from_str( | |
| &db.query_row::<String, _, _>( | |
| "SELECT input_json FROM application_sources WHERE deployment = 'default' AND revision = 1", | |
| [], | |
| |r| r.get(0), | |
| ) | |
| .unwrap(), | |
| ) | |
| .unwrap(); | |
| assert!( | |
| migrated["instances"]["agent"]["configuration"]["values"] | |
| .get("recaps") | |
| .is_none() | |
| ); | |
| assert_eq!( | |
| migrated["instances"]["agent"]["configuration"]["values"]["automaticTitles"], | |
| true | |
| ); | |
| assert!( | |
| migrated["instances"]["agent"]["overrides"][0]["configuration"] | |
| .get("recaps") | |
| .is_none() | |
| ); | |
| assert_eq!( | |
| migrated["instances"]["agent"]["overrides"][0]["configuration"]["recall"], | |
| true | |
| ); | |
| assert_eq!( | |
| migrated["instances"]["agent"]["overrides"][0]["configurationFields"] | |
| .as_array() | |
| .unwrap() | |
| .len(), | |
| 1 | |
| ); | |
| assert_eq!( | |
| migrated["instances"]["other"]["configuration"]["values"]["recaps"], | |
| true | |
| ); | |
| } | |
| #[tokio::test] | |
| async fn deferred_projections_stay_off_hot_path_and_catch_up_live_and_after_cold_reopen() { | |
| use crate::{Admission, Change}; | |
| use maka_agent_facts::{ | |
| artifact::ToolReturn, | |
| diagnostics::TitleFailureCause, | |
| durable::{ | |
| AcceptedResult, Fact, ModelAttemptId, RunId, StepId, StopRequester, Terminal, | |
| ToolDecision, ToolKey, UnixMillis, | |
| }, | |
| input::{MessageInput, RunInput}, | |
| model::{ModelFinishReason, ModelPart, ModelToolCall, ToolInput}, | |
| tool_call::ToolSettlement, | |
| tool_output::{ | |
| AcceptedToolResult, DurableToolProjection, StoredToolResult, ToolOutput, | |
| }, | |
| tools::ToolSemantics, | |
| }; | |
| use maka_event_log::{ | |
| RootStore, | |
| root::{RootNamespaces, RootOwner}, | |
| }; | |
| use std::sync::Arc; | |
| let dir = tempfile::tempdir().unwrap(); | |
| let namespaces = RootNamespaces { | |
| ownership: dir.path().join("owners"), | |
| control: dir.path().join("control"), | |
| }; | |
| let root_path = dir.path().join("root"); | |
| let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS | |
| .iter() | |
| .chain(super::MIGRATIONS) | |
| .copied() | |
| .collect(); | |
| let owner = Arc::new(RootOwner::create(&root_path, &namespaces).unwrap()); | |
| let root = RootStore::open(owner, &catalog).await.unwrap(); | |
| let data = root.data_writer().unwrap(); | |
| let store = crate::Store::new( | |
| data.clone(), | |
| crate::DriverDomain::new(data.clone()).unwrap(), | |
| ) | |
| .unwrap(); | |
| // Run 1: full Model -> Tool (coalesced Boundary 4) -> Diagnostic fact on hot path. | |
| let (mut spec1, mut blobs1) = crate::store::stop_tests::spec(); | |
| spec1.session_id = "ma_proto_session_1".into(); | |
| { | |
| let db = | |
| rusqlite::Connection::open(root_path.join(maka_event_log::root::ROOT_DATABASE)) | |
| .unwrap(); | |
| db.execute( | |
| "INSERT INTO session_control(id,fingerprint,revision,created_at,updated_at,archived,configuration) VALUES(?1,'fp',1,1,1,0,'{}')", | |
| [&spec1.session_id], | |
| ) | |
| .unwrap(); | |
| db.execute( | |
| "INSERT INTO session_creations(session_id,creation_id,fingerprint,command,ready,visible) VALUES(?1,?2,'fp',NULL,1,1)", | |
| rusqlite::params![&spec1.session_id, uuid::Uuid::new_v4().to_string()], | |
| ) | |
| .unwrap(); | |
| } | |
| let input1 = crate::ContentBlob::json(&RunInput::Message { | |
| content: MessageInput::from("alpha-live-recall-needle"), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| }) | |
| .unwrap(); | |
| spec1.input = input1.reference().clone(); | |
| blobs1.push(input1); | |
| let run1 = RunId::new(); | |
| store | |
| .admit(Admission::with_identity( | |
| run1, | |
| spec1.clone(), | |
| UnixMillis(1_700_000_001_000), | |
| blobs1, | |
| )) | |
| .await | |
| .unwrap(); | |
| let claim1 = store.claim(run1).await.unwrap(); | |
| let view1 = store.frontier(run1).await.unwrap(); | |
| let empty_blob = | |
| crate::ContentBlob::json(&maka_agent_facts::composition::CompositionSurface { | |
| system_prompt: None, | |
| tools: vec![], | |
| sources: vec![], | |
| }) | |
| .unwrap(); | |
| let make_req_blob = |step: StepId| { | |
| let empty_ref = empty_blob.reference().clone(); | |
| crate::ContentBlob::json(&maka_agent_facts::durable::RequestSpec { | |
| schema_version: maka_agent_facts::durable::SCHEMA_VERSION, | |
| step, | |
| composition: maka_agent_facts::composition::RequestComposition { | |
| surface: empty_ref.clone(), | |
| dynamic_context: vec![], | |
| tool_catalog_digest: empty_ref.digest.clone(), | |
| provider_options: None, | |
| max_output_tokens: None, | |
| }, | |
| summary_repair_of: None, | |
| compaction_recovery: None, | |
| source_capture: empty_ref.clone(), | |
| source_digest: empty_ref.digest.clone(), | |
| effective_source_digest: empty_ref.digest.clone(), | |
| provenance: empty_ref.clone(), | |
| tool_contracts: None, | |
| projection: None, | |
| adjudications: vec![], | |
| steering: vec![], | |
| request: empty_ref.clone(), | |
| protocol: "test".into(), | |
| protocol_version: 1, | |
| recovery_contract: empty_ref, | |
| request_contents: vec![], | |
| accounting: maka_agent_facts::accounting::ModelEvidence { | |
| purpose: maka_agent_facts::context::ModelPurpose::Main, | |
| model_id: "test-model".into(), | |
| binding: maka_agent_facts::execution::ModelBinding { | |
| connection_id: "conn-1".into(), | |
| connection_slug: "test".into(), | |
| model: "test-model".into(), | |
| }, | |
| quote: None, | |
| }, | |
| }) | |
| .unwrap() | |
| }; | |
| let step1 = StepId::new(); | |
| let attempt1 = ModelAttemptId::new(); | |
| let req_blob = make_req_blob(step1); | |
| let tool_key = ToolKey { | |
| attempt: attempt1, | |
| call: "call-b4".into(), | |
| }; | |
| let tool_input = crate::ContentBlob::json(&serde_json::json!({"k": 1})).unwrap(); | |
| store | |
| .append( | |
| &claim1, | |
| (&view1).into(), | |
| vec![ | |
| Change::new( | |
| Fact::StepPrepared { | |
| step: step1, | |
| request: req_blob.reference().clone(), | |
| adjudications: vec![], | |
| }, | |
| UnixMillis(1_700_000_001_010), | |
| ), | |
| Change::new( | |
| Fact::ModelAttemptPrepared { | |
| attempt: attempt1, | |
| step: step1, | |
| }, | |
| UnixMillis(1_700_000_001_010), | |
| ), | |
| Change::new( | |
| Fact::ModelAttemptAdmitted { | |
| attempt: attempt1, | |
| upstream: serde_json::json!({}), | |
| }, | |
| UnixMillis(1_700_000_001_010), | |
| ), | |
| Change::new( | |
| Fact::ModelObserved { | |
| attempt: attempt1, | |
| index: 0, | |
| part: ModelPart::ToolCall { | |
| call: ModelToolCall { | |
| id: tool_key.call.clone(), | |
| name: "read".into(), | |
| input: ToolInput::Json(serde_json::json!({"k": 1})), | |
| provider_options: None, | |
| provider_executed: false, | |
| }, | |
| }, | |
| continuation: None, | |
| }, | |
| UnixMillis(1_700_000_001_020), | |
| ), | |
| Change::new( | |
| Fact::ModelClosed { | |
| attempt: attempt1, | |
| outcome: maka_agent_facts::accounting::Outcome::Success, | |
| diagnostic: None, | |
| usage: Default::default(), | |
| protocol: serde_json::json!({"finishReason": ModelFinishReason::ToolCalls}), | |
| }, | |
| UnixMillis(1_700_000_001_020), | |
| ), | |
| Change::new( | |
| Fact::ModelCleanupObserved { | |
| attempt: attempt1, | |
| cleanup: maka_plugin_core::operation::OperationCleanup::Confirmed, | |
| }, | |
| UnixMillis(1_700_000_001_020), | |
| ), | |
| Change::new( | |
| Fact::ToolDecided { | |
| tool: tool_key.clone(), | |
| decision: ToolDecision::Approved { | |
| semantics: ToolSemantics::Parallel, | |
| input: tool_input.reference().clone(), | |
| resources: vec![], | |
| approval: None, | |
| display: Default::default(), | |
| }, | |
| }, | |
| UnixMillis(1_700_000_001_030), | |
| ), | |
| Change::new( | |
| Fact::ToolAdmitted { | |
| tool: tool_key.clone(), | |
| }, | |
| UnixMillis(1_700_000_001_030), | |
| ), | |
| ], | |
| vec![empty_blob.clone(), req_blob, tool_input], | |
| ) | |
| .await | |
| .unwrap(); | |
| // Boundary 4: coalesced [LocalToolReturned, ToolResultAccepted] via append_driver_result. | |
| let ret_blob = crate::ContentBlob::json(&ToolReturn { | |
| schema_version: maka_agent_facts::durable::SCHEMA_VERSION, | |
| artifacts: vec![], | |
| body: StoredToolResult::from_local( | |
| ToolOutput::Json(serde_json::json!({"ok": true})), | |
| None, | |
| DurableToolProjection::Json { | |
| value: serde_json::json!({"ok": true}), | |
| }, | |
| false, | |
| Default::default(), | |
| None, | |
| ), | |
| }) | |
| .unwrap(); | |
| let acc_blob = crate::ContentBlob::json(&AcceptedToolResult::Local { | |
| result: ret_blob.reference().clone(), | |
| }) | |
| .unwrap(); | |
| let b4_rev_before = store.frontier(run1).await.unwrap().revision; | |
| let b4_commit = store | |
| .append_driver_result( | |
| &claim1, | |
| vec![ | |
| Change::new( | |
| Fact::LocalToolReturned { | |
| tool: tool_key.clone(), | |
| result: ret_blob.reference().clone(), | |
| is_error: false, | |
| settlement: ToolSettlement::Returned, | |
| cell_observation: None, | |
| }, | |
| UnixMillis(1_700_000_001_040), | |
| ), | |
| Change::new( | |
| Fact::ToolResultAccepted { | |
| tool: tool_key.clone(), | |
| result: acc_blob.reference().clone(), | |
| outcome: AcceptedResult::Succeeded, | |
| }, | |
| UnixMillis(1_700_000_001_040), | |
| ), | |
| ], | |
| vec![ret_blob, acc_blob], | |
| ) | |
| .await | |
| .unwrap(); | |
| assert_eq!(b4_commit.facts.len(), 2); | |
| let after_b4 = store.frontier(run1).await.unwrap(); | |
| assert_eq!(after_b4.revision, b4_rev_before + 2); | |
| assert!( | |
| after_b4.tools.is_empty(), | |
| "coalesced ToolResultAccepted must settle tool" | |
| ); | |
| // Record a diagnostic-producing fact (SessionTitleFailed) + terminal. | |
| store | |
| .append( | |
| &claim1, | |
| (&after_b4).into(), | |
| vec![ | |
| Change::new( | |
| Fact::SessionTitleFailed { | |
| cause: TitleFailureCause::InvalidOutput, | |
| }, | |
| UnixMillis(1_700_000_001_050), | |
| ), | |
| Change::new( | |
| Fact::RunTerminated { | |
| terminal: Terminal::Completed, | |
| diagnostic: None, | |
| }, | |
| UnixMillis(1_700_000_001_055), | |
| ), | |
| ], | |
| vec![], | |
| ) | |
| .await | |
| .unwrap(); | |
| // Confirm hot writes left Recall & Diagnostics deferred (0 rows written on hot path!). | |
| { | |
| let db = | |
| rusqlite::Connection::open(root_path.join(maka_event_log::root::ROOT_DATABASE)) | |
| .unwrap(); | |
| let recall_rows: i64 = db | |
| .query_row("SELECT COUNT(*) FROM agent_recall_messages", [], |r| { | |
| r.get(0) | |
| }) | |
| .unwrap(); | |
| let diag_rows: i64 = db | |
| .query_row("SELECT COUNT(*) FROM agent_diagnostics", [], |r| r.get(0)) | |
| .unwrap(); | |
| assert_eq!( | |
| recall_rows, 0, | |
| "Recall must stay deferred during hot writes" | |
| ); | |
| assert_eq!( | |
| diag_rows, 0, | |
| "Diagnostics must stay deferred during hot writes" | |
| ); | |
| } | |
| // Live visibility: RecallStore & DiagnosticsStore catch up automatically on read. | |
| let recall = | |
| crate::recall::RecallStore::new(data.clone(), spec1.owner.clone(), "ma_".into()) | |
| .unwrap(); | |
| let search1 = recall | |
| .search( | |
| crate::recall::SearchQuery { | |
| session_id: Some(spec1.session_id.clone()), | |
| terms: vec!["alpha-live-recall-needle".into()], | |
| since: None, | |
| until: None, | |
| exclude: None, | |
| limit: None, | |
| transcript_only: false, | |
| }, | |
| 0, | |
| 0, | |
| tokio_util::sync::CancellationToken::new(), | |
| ) | |
| .await | |
| .unwrap(); | |
| assert!( | |
| !search1.hits.is_empty(), | |
| "live RecallStore::search must catch up and return Run 1 message" | |
| ); | |
| let diag = crate::diagnostics::DiagnosticsStore::new( | |
| data.clone(), | |
| spec1.owner.clone(), | |
| spec1.session_id.clone(), | |
| ) | |
| .unwrap(); | |
| let diag_page1 = diag.page(None, None, 16, 48 * 1024).await.unwrap(); | |
| assert_eq!(diag_page1.entries.len(), 1); | |
| // Run 2: test Boundary 4 Stop fence + cold reopen deferred projection visibility. | |
| let (mut spec2, mut blobs2) = crate::store::stop_tests::spec(); | |
| spec2.session_id = spec1.session_id.clone(); | |
| spec2.turn_id = "turn-2".into(); | |
| spec2.trigger = maka_agent_facts::durable::Trigger::Message { | |
| message_id: "message-2".into(), | |
| }; | |
| spec2.owner = spec1.owner.clone(); | |
| let input2 = crate::ContentBlob::json(&RunInput::Message { | |
| content: MessageInput::from("beta-cold-reopen-recall-needle"), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| }) | |
| .unwrap(); | |
| spec2.input = input2.reference().clone(); | |
| blobs2.push(input2); | |
| let run2 = RunId::new(); | |
| store | |
| .admit(Admission::with_identity( | |
| run2, | |
| spec2.clone(), | |
| UnixMillis(1_700_000_002_000), | |
| blobs2, | |
| )) | |
| .await | |
| .unwrap(); | |
| let claim2 = store.claim(run2).await.unwrap(); | |
| let v2 = store.frontier(run2).await.unwrap(); | |
| let step2 = StepId::new(); | |
| let attempt2 = ModelAttemptId::new(); | |
| let req2 = make_req_blob(step2); | |
| let key2 = ToolKey { | |
| attempt: attempt2, | |
| call: "call-stop-fence".into(), | |
| }; | |
| let in2 = crate::ContentBlob::json(&serde_json::json!({})).unwrap(); | |
| store | |
| .append( | |
| &claim2, | |
| (&v2).into(), | |
| vec![ | |
| Change::new( | |
| Fact::StepPrepared { | |
| step: step2, | |
| request: req2.reference().clone(), | |
| adjudications: vec![], | |
| }, | |
| UnixMillis(1_700_000_002_010), | |
| ), | |
| Change::new( | |
| Fact::ModelAttemptPrepared { | |
| attempt: attempt2, | |
| step: step2, | |
| }, | |
| UnixMillis(1_700_000_002_010), | |
| ), | |
| Change::new( | |
| Fact::ModelAttemptAdmitted { | |
| attempt: attempt2, | |
| upstream: serde_json::json!({}), | |
| }, | |
| UnixMillis(1_700_000_002_010), | |
| ), | |
| Change::new( | |
| Fact::ModelObserved { | |
| attempt: attempt2, | |
| index: 0, | |
| part: ModelPart::ToolCall { | |
| call: ModelToolCall { | |
| id: key2.call.clone(), | |
| name: "read".into(), | |
| input: ToolInput::Json(serde_json::json!({})), | |
| provider_options: None, | |
| provider_executed: false, | |
| }, | |
| }, | |
| continuation: None, | |
| }, | |
| UnixMillis(1_700_000_002_020), | |
| ), | |
| Change::new( | |
| Fact::ModelClosed { | |
| attempt: attempt2, | |
| outcome: maka_agent_facts::accounting::Outcome::Success, | |
| diagnostic: None, | |
| usage: Default::default(), | |
| protocol: serde_json::json!({"finishReason": ModelFinishReason::ToolCalls}), | |
| }, | |
| UnixMillis(1_700_000_002_020), | |
| ), | |
| Change::new( | |
| Fact::ModelCleanupObserved { | |
| attempt: attempt2, | |
| cleanup: maka_plugin_core::operation::OperationCleanup::Confirmed, | |
| }, | |
| UnixMillis(1_700_000_002_020), | |
| ), | |
| Change::new( | |
| Fact::ToolDecided { | |
| tool: key2.clone(), | |
| decision: ToolDecision::Approved { | |
| semantics: ToolSemantics::Parallel, | |
| input: in2.reference().clone(), | |
| resources: vec![], | |
| approval: None, | |
| display: Default::default(), | |
| }, | |
| }, | |
| UnixMillis(1_700_000_002_030), | |
| ), | |
| Change::new( | |
| Fact::ToolAdmitted { tool: key2.clone() }, | |
| UnixMillis(1_700_000_002_030), | |
| ), | |
| ], | |
| vec![empty_blob, req2, in2], | |
| ) | |
| .await | |
| .unwrap(); | |
| // Race StopRequested before coalesced Boundary 4 acceptance! | |
| let v2_pre_stop = store.frontier(run2).await.unwrap(); | |
| store | |
| .control( | |
| run2, | |
| (&v2_pre_stop).into(), | |
| vec![Change::new( | |
| Fact::StopRequested { | |
| diagnostic: "user-stop".into(), | |
| requester: StopRequester::User, | |
| }, | |
| UnixMillis(1_700_000_002_035), | |
| )], | |
| vec![], | |
| ) | |
| .await | |
| .unwrap(); | |
| let ret2 = crate::ContentBlob::json(&ToolReturn { | |
| schema_version: maka_agent_facts::durable::SCHEMA_VERSION, | |
| artifacts: vec![], | |
| body: StoredToolResult::from_local( | |
| ToolOutput::Json(serde_json::json!({"ok": 2})), | |
| None, | |
| DurableToolProjection::Json { | |
| value: serde_json::json!({"ok": 2}), | |
| }, | |
| false, | |
| Default::default(), | |
| None, | |
| ), | |
| }) | |
| .unwrap(); | |
| let acc2 = crate::ContentBlob::json(&AcceptedToolResult::Local { | |
| result: ret2.reference().clone(), | |
| }) | |
| .unwrap(); | |
| let orig_return = Change::new( | |
| Fact::LocalToolReturned { | |
| tool: key2.clone(), | |
| result: ret2.reference().clone(), | |
| is_error: false, | |
| settlement: ToolSettlement::Returned, | |
| cell_observation: None, | |
| }, | |
| UnixMillis(1_700_000_002_040), | |
| ); | |
| let orig_return_id = orig_return.id; | |
| // Coalesced Boundary 4 MUST reject on stopped run! | |
| let fenced = store | |
| .append_driver_result( | |
| &claim2, | |
| vec![ | |
| orig_return.clone(), | |
| Change::new( | |
| Fact::ToolResultAccepted { | |
| tool: key2.clone(), | |
| result: acc2.reference().clone(), | |
| outcome: AcceptedResult::Succeeded, | |
| }, | |
| UnixMillis(1_700_000_002_040), | |
| ), | |
| ], | |
| vec![ret2.clone(), acc2], | |
| ) | |
| .await; | |
| assert!( | |
| fenced.is_err(), | |
| "Boundary 4 coalesced ToolResultAccepted must reject after StopRequested" | |
| ); | |
| // Late fallback with exact same original FactId succeeds without ToolResultAccepted. | |
| let late = store | |
| .observe_artifacts(run2, vec![orig_return], vec![ret2], vec![]) | |
| .await | |
| .unwrap(); | |
| assert_eq!(late.facts.len(), 1); | |
| assert_eq!(late.facts[0].id, orig_return_id); | |
| // Add Run 2 diagnostic fact, then close RootStore COLD without reading Recall/Diagnostics. | |
| let v2_after = store.frontier(run2).await.unwrap(); | |
| store | |
| .append( | |
| &claim2, | |
| (&v2_after).into(), | |
| vec![Change::new( | |
| Fact::SessionTitleFailed { | |
| cause: TitleFailureCause::EmptyOutput, | |
| }, | |
| UnixMillis(1_700_000_002_050), | |
| )], | |
| vec![], | |
| ) | |
| .await | |
| .unwrap(); | |
| drop((recall, diag, claim1, claim2, store, data)); | |
| root.close().await.unwrap(); | |
| // Cold reopen with ZERO extra writes: both Recall and Diagnostics must catch up & see Run 2! | |
| let reopened_owner = Arc::new(RootOwner::open_existing(&root_path, &namespaces).unwrap()); | |
| let reopened_root = RootStore::open(reopened_owner, &catalog).await.unwrap(); | |
| let reopened_data = reopened_root.data_writer().unwrap(); | |
| let reopened_recall = crate::recall::RecallStore::new( | |
| reopened_data.clone(), | |
| spec2.owner.clone(), | |
| "ma_".into(), | |
| ) | |
| .unwrap(); | |
| let search2 = reopened_recall | |
| .search( | |
| crate::recall::SearchQuery { | |
| session_id: Some(spec2.session_id.clone()), | |
| terms: vec!["beta-cold-reopen-recall-needle".into()], | |
| since: None, | |
| until: None, | |
| exclude: None, | |
| limit: None, | |
| transcript_only: false, | |
| }, | |
| 0, | |
| 0, | |
| tokio_util::sync::CancellationToken::new(), | |
| ) | |
| .await | |
| .unwrap(); | |
| assert!( | |
| !search2.hits.is_empty(), | |
| "cold reopen RecallStore::search must catch up and return Run 2 without extra writes" | |
| ); | |
| let reopened_diag = crate::diagnostics::DiagnosticsStore::new( | |
| reopened_data.clone(), | |
| spec2.owner.clone(), | |
| spec2.session_id.clone(), | |
| ) | |
| .unwrap(); | |
| let diag_page2 = reopened_diag.page(None, None, 16, 48 * 1024).await.unwrap(); | |
| assert_eq!( | |
| diag_page2.entries.len(), | |
| 2, | |
| "cold reopen DiagnosticsStore must see both Run 1 and Run 2 diagnostics" | |
| ); | |
| // Corrupt recall head past authoritative history must still fail explicitly (no silent fallback). | |
| { | |
| let db = | |
| rusqlite::Connection::open(root_path.join(maka_event_log::root::ROOT_DATABASE)) | |
| .unwrap(); | |
| db.execute( | |
| "UPDATE agent_recall_heads SET sequence = sequence + 9999", | |
| [], | |
| ) | |
| .unwrap(); | |
| } | |
| let corrupt = reopened_recall | |
| .search( | |
| crate::recall::SearchQuery { | |
| session_id: Some(spec2.session_id.clone()), | |
| terms: vec!["beta-cold-reopen-recall-needle".into()], | |
| since: None, | |
| until: None, | |
| exclude: None, | |
| limit: None, | |
| transcript_only: false, | |
| }, | |
| 0, | |
| 0, | |
| tokio_util::sync::CancellationToken::new(), | |
| ) | |
| .await; | |
| assert!( | |
| corrupt.is_err(), | |
| "corrupt recall watermark must fail explicitly rather than silently falling back" | |
| ); | |
| drop((reopened_recall, reopened_diag, reopened_data)); | |
| reopened_root.close().await.unwrap(); | |
| } | |
| #[tokio::test] | |
| async fn diagnostics_reads_succeed_under_concurrent_writes_and_reject_corrupt_coverage() { | |
| use crate::{Admission, Change}; | |
| use maka_agent_facts::{ | |
| diagnostics::TitleFailureCause, | |
| durable::{Fact, RunId, UnixMillis}, | |
| }; | |
| use maka_event_log::{ | |
| RootStore, | |
| root::{RootNamespaces, RootOwner}, | |
| }; | |
| use std::sync::Arc; | |
| let dir = tempfile::tempdir().unwrap(); | |
| let namespaces = RootNamespaces { | |
| ownership: dir.path().join("owners"), | |
| control: dir.path().join("control"), | |
| }; | |
| let root_path = dir.path().join("root"); | |
| let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS | |
| .iter() | |
| .chain(super::MIGRATIONS) | |
| .copied() | |
| .collect(); | |
| let root_owner = Arc::new(RootOwner::create(&root_path, &namespaces).unwrap()); | |
| let root = RootStore::open(root_owner, &catalog).await.unwrap(); | |
| let data = root.data_writer().unwrap(); | |
| let store = crate::Store::new( | |
| data.clone(), | |
| crate::DriverDomain::new(data.clone()).unwrap(), | |
| ) | |
| .unwrap(); | |
| let (mut spec, blobs) = crate::store::stop_tests::spec(); | |
| spec.session_id = "ma_diag_concurrent".into(); | |
| let run = RunId::new(); | |
| let owner = spec.owner.clone(); | |
| let session = spec.session_id.clone(); | |
| store | |
| .admit(Admission::with_identity( | |
| run, | |
| spec, | |
| UnixMillis(1_700_000_000_000), | |
| blobs, | |
| )) | |
| .await | |
| .unwrap(); | |
| let claim = store.claim(run).await.unwrap(); | |
| let diag = | |
| crate::diagnostics::DiagnosticsStore::new(data.clone(), owner.clone(), session.clone()) | |
| .unwrap(); | |
| let writer_store = store.clone(); | |
| let total_diagnostics = 24usize; | |
| let writer = tokio::spawn(async move { | |
| let mut expected = writer_store.frontier(run).await.unwrap(); | |
| for i in 0..total_diagnostics { | |
| let ts = UnixMillis(1_700_000_001_000 + i as i64 * 10); | |
| writer_store | |
| .append( | |
| &claim, | |
| (&expected).into(), | |
| vec![ | |
| Change::new( | |
| Fact::SessionTitleFailed { | |
| cause: TitleFailureCause::InvalidOutput, | |
| }, | |
| ts, | |
| ), | |
| Change::new(Fact::BudgetCharged { tokens: 1 }, UnixMillis(ts.0 + 1)), | |
| ], | |
| vec![], | |
| ) | |
| .await | |
| .unwrap(); | |
| expected = writer_store.frontier(run).await.unwrap(); | |
| } | |
| }); | |
| let mut prev_through = 0u64; | |
| while !writer.is_finished() { | |
| let head = diag | |
| .head() | |
| .await | |
| .expect("concurrent DiagnosticsStore::head must not fail with rebuild race"); | |
| assert!(head.through >= prev_through); | |
| prev_through = head.through; | |
| let page = diag | |
| .page(None, None, 16, 48 * 1024) | |
| .await | |
| .expect("concurrent DiagnosticsStore::page must not fail with rebuild race"); | |
| assert!(page.through >= prev_through); | |
| prev_through = page.through; | |
| } | |
| writer.await.unwrap(); | |
| let final_page = diag.page(None, None, 64, 48 * 1024).await.unwrap(); | |
| assert_eq!(final_page.entries.len(), total_diagnostics); | |
| // Corrupt coverage past canonical tail must still fail explicitly. | |
| { | |
| let db = | |
| rusqlite::Connection::open(root_path.join(maka_event_log::root::ROOT_DATABASE)) | |
| .unwrap(); | |
| db.execute_batch( | |
| "PRAGMA foreign_keys = OFF; UPDATE agent_diagnostic_coverage SET revision = revision + 100;", | |
| ) | |
| .unwrap(); | |
| } | |
| assert!( | |
| diag.head().await.is_err(), | |
| "corrupt diagnostic coverage must fail head() explicitly" | |
| ); | |
| assert!( | |
| diag.page(None, None, 16, 48 * 1024).await.is_err(), | |
| "corrupt diagnostic coverage must fail page() explicitly" | |
| ); | |
| drop((diag, store, data)); | |
| root.close().await.unwrap(); | |
| } | |
| #[tokio::test] | |
| async fn cold_recall_catch_up_chunks_batches_and_allows_concurrent_stop() { | |
| use crate::{Admission, Change}; | |
| use maka_agent_facts::{ | |
| durable::{Fact, RunId, StopRequester, Terminal, UnixMillis}, | |
| input::{MessageInput, RunInput}, | |
| }; | |
| use maka_event_log::{ | |
| RootStore, | |
| root::{RootNamespaces, RootOwner}, | |
| }; | |
| use std::sync::Arc; | |
| let dir = tempfile::tempdir().unwrap(); | |
| let namespaces = RootNamespaces { | |
| ownership: dir.path().join("owners"), | |
| control: dir.path().join("control"), | |
| }; | |
| let root_path = dir.path().join("root"); | |
| let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS | |
| .iter() | |
| .chain(super::MIGRATIONS) | |
| .copied() | |
| .collect(); | |
| let root_owner = Arc::new(RootOwner::create(&root_path, &namespaces).unwrap()); | |
| let root = RootStore::open(root_owner, &catalog).await.unwrap(); | |
| let data = root.data_writer().unwrap(); | |
| let store = crate::Store::new( | |
| data.clone(), | |
| crate::DriverDomain::new(data.clone()).unwrap(), | |
| ) | |
| .unwrap(); | |
| // Register sessions in session_control / session_creations for Recall catalog joins. | |
| { | |
| let db = | |
| rusqlite::Connection::open(root_path.join(maka_event_log::root::ROOT_DATABASE)) | |
| .unwrap(); | |
| for sid in ["ma_recall_cold_a", "ma_recall_stop_b"] { | |
| db.execute( | |
| "INSERT INTO session_control(id,fingerprint,revision,created_at,updated_at,archived,configuration) VALUES(?1,'fp',1,1,1,0,'{}')", | |
| [sid], | |
| ) | |
| .unwrap(); | |
| db.execute( | |
| "INSERT INTO session_creations(session_id,creation_id,fingerprint,command,ready,visible) VALUES(?1,?2,'fp',NULL,1,1)", | |
| rusqlite::params![sid, uuid::Uuid::new_v4().to_string()], | |
| ) | |
| .unwrap(); | |
| } | |
| } | |
| // Seed session A with > 3x CATCH_UP_BATCH_LIMIT history facts kept cold in Recall. | |
| let (base_spec, _) = crate::store::stop_tests::spec(); | |
| let owner = base_spec.owner.clone(); | |
| let rounds = crate::recall::index::CATCH_UP_BATCH_LIMIT * 2 + 10; | |
| for i in 0..rounds { | |
| let (mut spec, mut blobs) = crate::store::stop_tests::spec(); | |
| spec.owner = owner.clone(); | |
| spec.session_id = "ma_recall_cold_a".into(); | |
| spec.turn_id = format!("turn-{i}"); | |
| spec.trigger = maka_agent_facts::durable::Trigger::Message { | |
| message_id: format!("cold-msg-{i}"), | |
| }; | |
| let msg = format!("cold-recall-chunk-row-{i}-tail-marker"); | |
| let input = crate::ContentBlob::json(&RunInput::Message { | |
| content: MessageInput::from(msg), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| }) | |
| .unwrap(); | |
| spec.input = input.reference().clone(); | |
| blobs.push(input); | |
| let run = RunId::new(); | |
| store | |
| .admit(Admission::with_identity( | |
| run, | |
| spec, | |
| UnixMillis(1_700_000_000_000 + i as i64 * 10), | |
| blobs, | |
| )) | |
| .await | |
| .unwrap(); | |
| let claim = store.claim(run).await.unwrap(); | |
| let view = store.frontier(run).await.unwrap(); | |
| store | |
| .append( | |
| &claim, | |
| (&view).into(), | |
| vec![Change::new( | |
| Fact::RunTerminated { | |
| terminal: Terminal::Completed, | |
| diagnostic: None, | |
| }, | |
| UnixMillis(1_700_000_000_005 + i as i64 * 10), | |
| )], | |
| vec![], | |
| ) | |
| .await | |
| .unwrap(); | |
| } | |
| // Verify a single catch-up step is bounded and leaves has_more = true. | |
| { | |
| let db = | |
| rusqlite::Connection::open(root_path.join(maka_event_log::root::ROOT_DATABASE)) | |
| .unwrap(); | |
| maka_event_log::content::register_sql_functions(&db).unwrap(); | |
| let owner_json = serde_json::to_string(&owner).unwrap(); | |
| let step = crate::recall::index::catch_up_session_step( | |
| &db, | |
| &owner, | |
| &owner_json, | |
| "ma_recall_cold_a", | |
| None, | |
| ) | |
| .unwrap(); | |
| assert!(step.changed); | |
| assert!( | |
| step.has_more, | |
| "cold catch-up step must yield after a bounded batch" | |
| ); | |
| } | |
| // Seed active session B to receive a concurrent Stop during cold Recall catch-up. | |
| let (mut spec_b, blobs_b) = crate::store::stop_tests::spec(); | |
| spec_b.owner = owner.clone(); | |
| spec_b.session_id = "ma_recall_stop_b".into(); | |
| let run_b = RunId::new(); | |
| store | |
| .admit(Admission::with_identity( | |
| run_b, | |
| spec_b, | |
| UnixMillis(1_700_000_050_000), | |
| blobs_b, | |
| )) | |
| .await | |
| .unwrap(); | |
| let recall = | |
| crate::recall::RecallStore::new(data.clone(), owner.clone(), "ma_".into()).unwrap(); | |
| // Pre-cancelled token must abort before running catch-up. | |
| let cancelled = tokio_util::sync::CancellationToken::new(); | |
| cancelled.cancel(); | |
| let cancelled_res = recall | |
| .search( | |
| crate::recall::SearchQuery { | |
| session_id: Some("ma_recall_cold_a".into()), | |
| terms: vec![format!("cold-recall-chunk-row-{}-tail-marker", rounds - 1)], | |
| since: None, | |
| until: None, | |
| exclude: None, | |
| limit: None, | |
| transcript_only: false, | |
| }, | |
| 0, | |
| 0, | |
| cancelled, | |
| ) | |
| .await; | |
| assert!(cancelled_res.is_err()); | |
| // Run cold Recall search concurrently with stopping session B. | |
| let needle = format!("cold-recall-chunk-row-{}-tail-marker", rounds - 1); | |
| let search_fut = recall.search( | |
| crate::recall::SearchQuery { | |
| session_id: Some("ma_recall_cold_a".into()), | |
| terms: vec![needle], | |
| since: None, | |
| until: None, | |
| exclude: None, | |
| limit: None, | |
| transcript_only: false, | |
| }, | |
| 0, | |
| 0, | |
| tokio_util::sync::CancellationToken::new(), | |
| ); | |
| let stop_fut = async { | |
| let v_b = store.frontier(run_b).await.unwrap(); | |
| store | |
| .control( | |
| run_b, | |
| (&v_b).into(), | |
| vec![Change::new( | |
| Fact::StopRequested { | |
| diagnostic: "concurrent stop during cold recall".into(), | |
| requester: StopRequester::User, | |
| }, | |
| UnixMillis(1_700_000_060_000), | |
| )], | |
| vec![], | |
| ) | |
| .await | |
| }; | |
| let (search_res, stop_res) = tokio::join!(search_fut, stop_fut); | |
| let batch = search_res.unwrap(); | |
| assert!( | |
| !batch.hits.is_empty(), | |
| "chunked cold Recall catch-up must index through the tail fact" | |
| ); | |
| stop_res.unwrap(); | |
| assert!(store.frontier(run_b).await.unwrap().stopped); | |
| drop((recall, store, data)); | |
| root.close().await.unwrap(); | |
| } | |
| #[tokio::test] | |
| async fn run_rebuild_preserves_earlier_run_visibility_in_recall() { | |
| use crate::{Admission, Change}; | |
| use maka_agent_facts::{ | |
| durable::{Fact, RunId, Terminal, UnixMillis}, | |
| input::{MessageInput, RunInput}, | |
| }; | |
| use maka_event_log::{ | |
| RootStore, | |
| root::{RootNamespaces, RootOwner}, | |
| }; | |
| use std::sync::Arc; | |
| let dir = tempfile::tempdir().unwrap(); | |
| let namespaces = RootNamespaces { | |
| ownership: dir.path().join("owners"), | |
| control: dir.path().join("control"), | |
| }; | |
| let root_path = dir.path().join("root"); | |
| let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS | |
| .iter() | |
| .chain(super::MIGRATIONS) | |
| .copied() | |
| .collect(); | |
| let root_owner = Arc::new(RootOwner::create(&root_path, &namespaces).unwrap()); | |
| let root = RootStore::open(root_owner, &catalog).await.unwrap(); | |
| let data = root.data_writer().unwrap(); | |
| let store = crate::Store::new( | |
| data.clone(), | |
| crate::DriverDomain::new(data.clone()).unwrap(), | |
| ) | |
| .unwrap(); | |
| let session_id = "ma_rebuild_recall_session"; | |
| { | |
| let db = | |
| rusqlite::Connection::open(root_path.join(maka_event_log::root::ROOT_DATABASE)) | |
| .unwrap(); | |
| db.execute( | |
| "INSERT INTO session_control(id,fingerprint,revision,created_at,updated_at,archived,configuration) VALUES(?1,'fp',1,1,1,0,'{}')", | |
| [session_id], | |
| ) | |
| .unwrap(); | |
| db.execute( | |
| "INSERT INTO session_creations(session_id,creation_id,fingerprint,command,ready,visible) VALUES(?1,?2,'fp',NULL,1,1)", | |
| rusqlite::params![session_id, uuid::Uuid::new_v4().to_string()], | |
| ) | |
| .unwrap(); | |
| } | |
| let (base_spec, _) = crate::store::stop_tests::spec(); | |
| let owner = base_spec.owner.clone(); | |
| // Admit Run A with a unique marker (kept cold in Recall) and terminate it. | |
| let (mut spec_a, mut blobs_a) = crate::store::stop_tests::spec(); | |
| spec_a.owner = owner.clone(); | |
| spec_a.session_id = session_id.into(); | |
| spec_a.turn_id = "turn-a".into(); | |
| spec_a.trigger = maka_agent_facts::durable::Trigger::Message { | |
| message_id: "msg-run-a".into(), | |
| }; | |
| let input_a = crate::ContentBlob::json(&RunInput::Message { | |
| content: MessageInput::from("run-a-unique-recall-marker"), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| }) | |
| .unwrap(); | |
| spec_a.input = input_a.reference().clone(); | |
| blobs_a.push(input_a); | |
| let run_a = RunId::new(); | |
| store | |
| .admit(Admission::with_identity( | |
| run_a, | |
| spec_a, | |
| UnixMillis(1_700_000_000_000), | |
| blobs_a, | |
| )) | |
| .await | |
| .unwrap(); | |
| let claim_a = store.claim(run_a).await.unwrap(); | |
| let view_a = store.frontier(run_a).await.unwrap(); | |
| store | |
| .append( | |
| &claim_a, | |
| (&view_a).into(), | |
| vec![Change::new( | |
| Fact::RunTerminated { | |
| terminal: Terminal::Completed, | |
| diagnostic: None, | |
| }, | |
| UnixMillis(1_700_000_000_010), | |
| )], | |
| vec![], | |
| ) | |
| .await | |
| .unwrap(); | |
| // Admit Run B in the same Session, then call Store::rebuild(run_b). | |
| let (mut spec_b, mut blobs_b) = crate::store::stop_tests::spec(); | |
| spec_b.owner = owner.clone(); | |
| spec_b.session_id = session_id.into(); | |
| spec_b.turn_id = "turn-b".into(); | |
| spec_b.trigger = maka_agent_facts::durable::Trigger::Message { | |
| message_id: "msg-run-b".into(), | |
| }; | |
| let input_b = crate::ContentBlob::json(&RunInput::Message { | |
| content: MessageInput::from("run-b-message"), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| }) | |
| .unwrap(); | |
| spec_b.input = input_b.reference().clone(); | |
| blobs_b.push(input_b); | |
| let run_b = RunId::new(); | |
| store | |
| .admit(Admission::with_identity( | |
| run_b, | |
| spec_b, | |
| UnixMillis(1_700_000_001_000), | |
| blobs_b, | |
| )) | |
| .await | |
| .unwrap(); | |
| // Rebuilding Run B alone must not advance Session-level Recall head past Run A. | |
| store.rebuild(run_b).await.unwrap(); | |
| let recall = | |
| crate::recall::RecallStore::new(data.clone(), owner.clone(), "ma_".into()).unwrap(); | |
| let batch = recall | |
| .search( | |
| crate::recall::SearchQuery { | |
| session_id: Some(session_id.into()), | |
| terms: vec!["run-a-unique-recall-marker".into()], | |
| since: None, | |
| until: None, | |
| exclude: None, | |
| limit: None, | |
| transcript_only: false, | |
| }, | |
| 0, | |
| 0, | |
| tokio_util::sync::CancellationToken::new(), | |
| ) | |
| .await | |
| .unwrap(); | |
| assert_eq!(batch.hits.len(), 1, "Run A marker must stay searchable"); | |
| assert!(batch.gaps.is_empty(), "{:?}", batch.gaps); | |
| drop((recall, store, data)); | |
| root.close().await.unwrap(); | |
| } | |
| #[tokio::test] | |
| async fn recall_search_and_context_keep_existing_hits_across_concurrent_admit() { | |
| use crate::{Admission, Change}; | |
| use maka_agent_facts::{ | |
| durable::{Fact, RunId, Terminal, UnixMillis}, | |
| input::{MessageInput, RunInput}, | |
| }; | |
| use maka_event_log::{ | |
| RootStore, | |
| root::{RootNamespaces, RootOwner}, | |
| }; | |
| use std::sync::Arc; | |
| let dir = tempfile::tempdir().unwrap(); | |
| let namespaces = RootNamespaces { | |
| ownership: dir.path().join("owners"), | |
| control: dir.path().join("control"), | |
| }; | |
| let root_path = dir.path().join("root"); | |
| let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS | |
| .iter() | |
| .chain(super::MIGRATIONS) | |
| .copied() | |
| .collect(); | |
| let root_owner = Arc::new(RootOwner::create(&root_path, &namespaces).unwrap()); | |
| let root = RootStore::open(root_owner, &catalog).await.unwrap(); | |
| let data = root.data_writer().unwrap(); | |
| let store = crate::Store::new( | |
| data.clone(), | |
| crate::DriverDomain::new(data.clone()).unwrap(), | |
| ) | |
| .unwrap(); | |
| let session_id = "ma_recall_concurrent_admit"; | |
| { | |
| let db = | |
| rusqlite::Connection::open(root_path.join(maka_event_log::root::ROOT_DATABASE)) | |
| .unwrap(); | |
| db.execute( | |
| "INSERT INTO session_control(id,fingerprint,revision,created_at,updated_at,archived,configuration) VALUES(?1,'fp',1,1,1,0,'{}')", | |
| [session_id], | |
| ) | |
| .unwrap(); | |
| db.execute( | |
| "INSERT INTO session_creations(session_id,creation_id,fingerprint,command,ready,visible) VALUES(?1,?2,'fp',NULL,1,1)", | |
| rusqlite::params![session_id, uuid::Uuid::new_v4().to_string()], | |
| ) | |
| .unwrap(); | |
| } | |
| let (base_spec, _) = crate::store::stop_tests::spec(); | |
| let owner = base_spec.owner.clone(); | |
| // Seed Run 1 containing the search needle. | |
| let (mut spec1, mut blobs1) = crate::store::stop_tests::spec(); | |
| spec1.owner = owner.clone(); | |
| spec1.session_id = session_id.into(); | |
| spec1.turn_id = "turn-1".into(); | |
| spec1.trigger = maka_agent_facts::durable::Trigger::Message { | |
| message_id: "msg-initial-hit".into(), | |
| }; | |
| let input1 = crate::ContentBlob::json(&RunInput::Message { | |
| content: MessageInput::from("stable-concurrent-recall-needle"), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| }) | |
| .unwrap(); | |
| spec1.input = input1.reference().clone(); | |
| blobs1.push(input1); | |
| let run1 = RunId::new(); | |
| store | |
| .admit(Admission::with_identity( | |
| run1, | |
| spec1, | |
| UnixMillis(1_700_000_000_000), | |
| blobs1, | |
| )) | |
| .await | |
| .unwrap(); | |
| let claim1 = store.claim(run1).await.unwrap(); | |
| let view1 = store.frontier(run1).await.unwrap(); | |
| store | |
| .append( | |
| &claim1, | |
| (&view1).into(), | |
| vec![Change::new( | |
| Fact::RunTerminated { | |
| terminal: Terminal::Completed, | |
| diagnostic: None, | |
| }, | |
| UnixMillis(1_700_000_000_010), | |
| )], | |
| vec![], | |
| ) | |
| .await | |
| .unwrap(); | |
| let recall = | |
| crate::recall::RecallStore::new(data.clone(), owner.clone(), "ma_".into()).unwrap(); | |
| // Continuously admit new runs while concurrently running search() and context(cut=None). | |
| let writer_store = store.clone(); | |
| let writer_owner = owner.clone(); | |
| let writer = tokio::spawn(async move { | |
| for i in 0..20 { | |
| let (mut spec, mut blobs) = crate::store::stop_tests::spec(); | |
| spec.owner = writer_owner.clone(); | |
| spec.session_id = session_id.into(); | |
| spec.turn_id = format!("turn-concurrent-{i}"); | |
| spec.trigger = maka_agent_facts::durable::Trigger::Message { | |
| message_id: format!("msg-concurrent-{i}"), | |
| }; | |
| let input = crate::ContentBlob::json(&RunInput::Message { | |
| content: MessageInput::from(format!("concurrent-admit-{i}")), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| }) | |
| .unwrap(); | |
| spec.input = input.reference().clone(); | |
| blobs.push(input); | |
| let run = RunId::new(); | |
| writer_store | |
| .admit(Admission::with_identity( | |
| run, | |
| spec, | |
| UnixMillis(1_700_000_001_000 + i * 10), | |
| blobs, | |
| )) | |
| .await | |
| .unwrap(); | |
| let claim = writer_store.claim(run).await.unwrap(); | |
| let view = writer_store.frontier(run).await.unwrap(); | |
| writer_store | |
| .append( | |
| &claim, | |
| (&view).into(), | |
| vec![Change::new( | |
| Fact::RunTerminated { | |
| terminal: Terminal::Completed, | |
| diagnostic: None, | |
| }, | |
| UnixMillis(1_700_000_001_005 + i * 10), | |
| )], | |
| vec![], | |
| ) | |
| .await | |
| .unwrap(); | |
| } | |
| }); | |
| while !writer.is_finished() { | |
| let batch = recall | |
| .search( | |
| crate::recall::SearchQuery { | |
| session_id: Some(session_id.into()), | |
| terms: vec!["stable-concurrent-recall-needle".into()], | |
| since: None, | |
| until: None, | |
| exclude: None, | |
| limit: None, | |
| transcript_only: false, | |
| }, | |
| 0, | |
| 0, | |
| tokio_util::sync::CancellationToken::new(), | |
| ) | |
| .await | |
| .unwrap(); | |
| assert_eq!(batch.hits.len(), 1, "existing hit must never disappear"); | |
| assert!( | |
| batch.gaps.is_empty(), | |
| "concurrent admit must not produce gaps: {:?}", | |
| batch.gaps | |
| ); | |
| let ctx = recall | |
| .context( | |
| session_id.into(), | |
| "msg-initial-hit".into(), | |
| crate::recall::ContextWindow { | |
| before: 1, | |
| after: 1, | |
| }, | |
| None, | |
| None, | |
| tokio_util::sync::CancellationToken::new(), | |
| ) | |
| .await | |
| .expect("context(cut=None) must stay valid across concurrent admits"); | |
| assert_eq!(ctx.anchor.message_id, "msg-initial-hit"); | |
| } | |
| writer.await.unwrap(); | |
| drop((recall, store, data)); | |
| root.close().await.unwrap(); | |
| } | |
| #[tokio::test] | |
| async fn invalid_cut_fails_fast_and_fixed_cut_recovers_superseded_rows() { | |
| use crate::{Admission, Change}; | |
| use maka_agent_facts::{ | |
| artifact::ToolReturn, | |
| durable::{ | |
| AcceptedResult, Fact, ModelAttemptId, RunId, StepId, Terminal, ToolDecision, | |
| ToolKey, UnixMillis, | |
| }, | |
| input::{MessageInput, RunInput}, | |
| model::{ModelFinishReason, ModelPart, ModelToolCall, ToolInput}, | |
| tool_call::ToolSettlement, | |
| tool_output::{ | |
| AcceptedToolResult, DurableToolProjection, StoredToolResult, ToolOutput, | |
| }, | |
| tools::ToolSemantics, | |
| }; | |
| use maka_event_log::{ | |
| RootStore, | |
| root::{RootNamespaces, RootOwner}, | |
| }; | |
| use std::sync::Arc; | |
| let dir = tempfile::tempdir().unwrap(); | |
| let namespaces = RootNamespaces { | |
| ownership: dir.path().join("owners"), | |
| control: dir.path().join("control"), | |
| }; | |
| let root_path = dir.path().join("root"); | |
| let catalog: Vec<_> = maka_event_log::ROOT_MIGRATIONS | |
| .iter() | |
| .chain(super::MIGRATIONS) | |
| .copied() | |
| .collect(); | |
| let root_owner = Arc::new(RootOwner::create(&root_path, &namespaces).unwrap()); | |
| let root = RootStore::open(root_owner, &catalog).await.unwrap(); | |
| let data = root.data_writer().unwrap(); | |
| let store = crate::Store::new( | |
| data.clone(), | |
| crate::DriverDomain::new(data.clone()).unwrap(), | |
| ) | |
| .unwrap(); | |
| let (base_spec, _) = crate::store::stop_tests::spec(); | |
| let owner = base_spec.owner.clone(); | |
| for sid in ["ma_cut_sess_a", "ma_cut_sess_b"] { | |
| let db = | |
| rusqlite::Connection::open(root_path.join(maka_event_log::root::ROOT_DATABASE)) | |
| .unwrap(); | |
| db.execute( | |
| "INSERT INTO session_control(id,fingerprint,revision,created_at,updated_at,archived,configuration) VALUES(?1,'fp',1,1,1,0,'{}')", | |
| [sid], | |
| ) | |
| .unwrap(); | |
| db.execute( | |
| "INSERT INTO session_creations(session_id,creation_id,fingerprint,command,ready,visible) VALUES(?1,?2,'fp',NULL,1,1)", | |
| rusqlite::params![sid, uuid::Uuid::new_v4().to_string()], | |
| ) | |
| .unwrap(); | |
| } | |
| // Interleave session A fact 1 -> session B fact -> session A fact 2 so B's sequence falls between A's facts. | |
| let admit_msg = |sid: &str, turn: &str, msg_id: &str, text: &str, ts: i64| { | |
| let (mut spec, mut blobs) = crate::store::stop_tests::spec(); | |
| spec.owner = owner.clone(); | |
| spec.session_id = sid.into(); | |
| spec.turn_id = turn.into(); | |
| spec.trigger = maka_agent_facts::durable::Trigger::Message { | |
| message_id: msg_id.into(), | |
| }; | |
| let input = crate::ContentBlob::json(&RunInput::Message { | |
| content: MessageInput::from(text), | |
| request_fingerprint: None, | |
| source_messages: vec![], | |
| }) | |
| .unwrap(); | |
| spec.input = input.reference().clone(); | |
| blobs.push(input); | |
| (RunId::new(), spec, blobs, UnixMillis(ts)) | |
| }; | |
| let (run_a1, spec_a1, blobs_a1, ts_a1) = admit_msg( | |
| "ma_cut_sess_a", | |
| "t-a1", | |
| "m-a1", | |
| "sess-a-first", | |
| 1_700_000_000_000, | |
| ); | |
| store | |
| .admit(Admission::with_identity(run_a1, spec_a1, ts_a1, blobs_a1)) | |
| .await | |
| .unwrap(); | |
| let claim_a1 = store.claim(run_a1).await.unwrap(); | |
| let view_a1 = store.frontier(run_a1).await.unwrap(); | |
| store | |
| .append( | |
| &claim_a1, | |
| (&view_a1).into(), | |
| vec![Change::new( | |
| Fact::RunTerminated { | |
| terminal: Terminal::Completed, | |
| diagnostic: None, | |
| }, | |
| UnixMillis(1_700_000_000_010), | |
| )], | |
| vec![], | |
| ) | |
| .await | |
| .unwrap(); | |
| let (run_b, spec_b, blobs_b, ts_b) = admit_msg( | |
| "ma_cut_sess_b", | |
| "t-b", | |
| "m-b", | |
| "sess-b-middle", | |
| 1_700_000_000_020, | |
| ); | |
| store | |
| .admit(Admission::with_identity(run_b, spec_b, ts_b, blobs_b)) | |
| .await | |
| .unwrap(); | |
| let (run_a2, spec_a2, blobs_a2, ts_a2) = admit_msg( | |
| "ma_cut_sess_a", | |
| "t-a2", | |
| "m-a2", | |
| "sess-a-second", | |
| 1_700_000_000_030, | |
| ); | |
| store | |
| .admit(Admission::with_identity(run_a2, spec_a2, ts_a2, blobs_a2)) | |
| .await | |
| .unwrap(); | |
| let recall = | |
| crate::recall::RecallStore::new(data.clone(), owner.clone(), "ma_".into()).unwrap(); | |
| let cut_b = recall.capture("ma_cut_sess_b".into(), None).await.unwrap(); | |
| // 1. Cross-session cut on context() must fail immediately, never spin in catch-up. | |
| let ctx_err = match tokio::time::timeout( | |
| std::time::Duration::from_secs(2), | |
| recall.context( | |
| "ma_cut_sess_a".into(), | |
| "m-a1".into(), | |
| crate::recall::ContextWindow { | |
| before: 1, | |
| after: 1, | |
| }, | |
| Some(cut_b.clone()), | |
| None, | |
| tokio_util::sync::CancellationToken::new(), | |
| ), | |
| ) | |
| .await | |
| .expect("cross-session cut must not spin") | |
| { | |
| Err(err) => err, | |
| Ok(_) => panic!("cross-session cut must be rejected"), | |
| }; | |
| assert!(matches!(ctx_err, maka_event_log::StoreError::EventConflict)); | |
| // 2. Non-member sequence (B's sequence on A's session) on landmarks() must also fail fast. | |
| let mut bad_a_cut = recall.capture("ma_cut_sess_a".into(), None).await.unwrap(); | |
| bad_a_cut.through_sequence = cut_b.through_sequence; | |
| let lm_err = match tokio::time::timeout( | |
| std::time::Duration::from_secs(2), | |
| recall.landmarks(bad_a_cut, 10, tokio_util::sync::CancellationToken::new()), | |
| ) | |
| .await | |
| .expect("non-member sequence cut must not spin in catch-up") | |
| { | |
| Err(err) => err, | |
| Ok(_) => panic!("non-member sequence cut must fail validation"), | |
| }; | |
| assert!( | |
| matches!( | |
| lm_err, | |
| maka_event_log::StoreError::InvalidTransition(_) | |
| | maka_event_log::StoreError::EventConflict | |
| ), | |
| "{lm_err}" | |
| ); | |
| // 3. Fixed-cut search must still recover a LocalToolReturned row whose FTS posting was | |
| // later pruned when ToolResultAccepted was projected past the fixed cut. | |
| let claim_a2 = store.claim(run_a2).await.unwrap(); | |
| let v = store.frontier(run_a2).await.unwrap(); | |
| let step_id = StepId::new(); | |
| let attempt_id = ModelAttemptId::new(); | |
| let empty_blob = | |
| crate::ContentBlob::json(&maka_agent_facts::composition::CompositionSurface { | |
| system_prompt: None, | |
| tools: vec![], | |
| sources: vec![], | |
| }) | |
| .unwrap(); | |
| let empty_ref = empty_blob.reference().clone(); | |
| let req_blob = crate::ContentBlob::json(&maka_agent_facts::durable::RequestSpec { | |
| schema_version: maka_agent_facts::durable::SCHEMA_VERSION, | |
| step: step_id, | |
| composition: maka_agent_facts::composition::RequestComposition { | |
| surface: empty_ref.clone(), | |
| dynamic_context: vec![], | |
| tool_catalog_digest: empty_ref.digest.clone(), | |
| provider_options: None, | |
| max_output_tokens: None, | |
| }, | |
| summary_repair_of: None, | |
| compaction_recovery: None, | |
| source_capture: empty_ref.clone(), | |
| source_digest: empty_ref.digest.clone(), | |
| effective_source_digest: empty_ref.digest.clone(), | |
| provenance: empty_ref.clone(), | |
| tool_contracts: None, | |
| projection: None, | |
| adjudications: vec![], | |
| steering: vec![], | |
| request: empty_ref.clone(), | |
| protocol: "test".into(), | |
| protocol_version: 1, | |
| recovery_contract: empty_ref, | |
| request_contents: vec![], | |
| accounting: maka_agent_facts::accounting::ModelEvidence { | |
| purpose: maka_agent_facts::context::ModelPurpose::Main, | |
| model_id: "test-model".into(), | |
| binding: maka_agent_facts::execution::ModelBinding { | |
| connection_id: "conn-1".into(), | |
| connection_slug: "test".into(), | |
| model: "test-model".into(), | |
| }, | |
| quote: None, | |
| }, | |
| }) | |
| .unwrap(); | |
| let tool_key = ToolKey { | |
| attempt: attempt_id, | |
| call: "call-supersede-1".into(), | |
| }; | |
| let in_blob = crate::ContentBlob::json(&serde_json::json!({})).unwrap(); | |
| let needle = "superseded-local-tool-return-unique-marker"; | |
| let ret_blob = crate::ContentBlob::json(&ToolReturn { | |
| schema_version: maka_agent_facts::durable::SCHEMA_VERSION, | |
| artifacts: vec![], | |
| body: StoredToolResult::from_local( | |
| ToolOutput::Json(serde_json::json!({"marker": needle})), | |
| None, | |
| DurableToolProjection::Json { | |
| value: serde_json::json!({"marker": needle}), | |
| }, | |
| false, | |
| Default::default(), | |
| None, | |
| ), | |
| }) | |
| .unwrap(); | |
| store | |
| .append( | |
| &claim_a2, | |
| (&v).into(), | |
| vec![ | |
| Change::new( | |
| Fact::StepPrepared { | |
| step: step_id, | |
| request: req_blob.reference().clone(), | |
| adjudications: vec![], | |
| }, | |
| UnixMillis(1_700_000_001_000), | |
| ), | |
| Change::new( | |
| Fact::ModelAttemptPrepared { | |
| attempt: attempt_id, | |
| step: step_id, | |
| }, | |
| UnixMillis(1_700_000_001_000), | |
| ), | |
| Change::new( | |
| Fact::ModelAttemptAdmitted { | |
| attempt: attempt_id, | |
| upstream: serde_json::json!({}), | |
| }, | |
| UnixMillis(1_700_000_001_000), | |
| ), | |
| Change::new( | |
| Fact::ModelObserved { | |
| attempt: attempt_id, | |
| index: 0, | |
| part: ModelPart::ToolCall { | |
| call: ModelToolCall { | |
| id: tool_key.call.clone(), | |
| name: "read".into(), | |
| input: ToolInput::Json(serde_json::json!({})), | |
| provider_options: None, | |
| provider_executed: false, | |
| }, | |
| }, | |
| continuation: None, | |
| }, | |
| UnixMillis(1_700_000_001_010), | |
| ), | |
| Change::new( | |
| Fact::ModelClosed { | |
| attempt: attempt_id, | |
| outcome: maka_agent_facts::accounting::Outcome::Success, | |
| diagnostic: None, | |
| usage: Default::default(), | |
| protocol: serde_json::json!({"finishReason": ModelFinishReason::ToolCalls}), | |
| }, | |
| UnixMillis(1_700_000_001_010), | |
| ), | |
| Change::new( | |
| Fact::ModelCleanupObserved { | |
| attempt: attempt_id, | |
| cleanup: maka_plugin_core::operation::OperationCleanup::Confirmed, | |
| }, | |
| UnixMillis(1_700_000_001_010), | |
| ), | |
| Change::new( | |
| Fact::ToolDecided { | |
| tool: tool_key.clone(), | |
| decision: ToolDecision::Approved { | |
| semantics: ToolSemantics::Parallel, | |
| input: in_blob.reference().clone(), | |
| resources: vec![], | |
| approval: None, | |
| display: Default::default(), | |
| }, | |
| }, | |
| UnixMillis(1_700_000_001_020), | |
| ), | |
| Change::new( | |
| Fact::ToolAdmitted { | |
| tool: tool_key.clone(), | |
| }, | |
| UnixMillis(1_700_000_001_020), | |
| ), | |
| Change::new( | |
| Fact::LocalToolReturned { | |
| tool: tool_key.clone(), | |
| result: ret_blob.reference().clone(), | |
| is_error: false, | |
| settlement: ToolSettlement::Returned, | |
| cell_observation: None, | |
| }, | |
| UnixMillis(1_700_000_001_030), | |
| ), | |
| ], | |
| vec![empty_blob, req_blob, in_blob, ret_blob.clone()], | |
| ) | |
| .await | |
| .unwrap(); | |
| // Capture the fixed cut right after LocalToolReturned (before ToolResultAccepted). | |
| let cut_before_accept = recall.capture("ma_cut_sess_a".into(), None).await.unwrap(); | |
| // Now append ToolResultAccepted with identical output and let another reader project it | |
| // (which prunes the old LocalToolReturned FTS posting and sets body_ref_sequence). | |
| let v2 = store.frontier(run_a2).await.unwrap(); | |
| let acc_blob = crate::ContentBlob::json(&AcceptedToolResult::Local { | |
| result: ret_blob.reference().clone(), | |
| }) | |
| .unwrap(); | |
| store | |
| .append( | |
| &claim_a2, | |
| (&v2).into(), | |
| vec![Change::new( | |
| Fact::ToolResultAccepted { | |
| tool: tool_key, | |
| result: acc_blob.reference().clone(), | |
| outcome: AcceptedResult::Succeeded, | |
| }, | |
| UnixMillis(1_700_000_001_040), | |
| )], | |
| vec![acc_blob], | |
| ) | |
| .await | |
| .unwrap(); | |
| // Another reader catches Recall up through ToolResultAccepted. | |
| let latest_batch = recall | |
| .search( | |
| crate::recall::SearchQuery { | |
| session_id: Some("ma_cut_sess_a".into()), | |
| terms: vec![needle.into()], | |
| since: None, | |
| until: None, | |
| exclude: None, | |
| limit: None, | |
| transcript_only: false, | |
| }, | |
| 0, | |
| 0, | |
| tokio_util::sync::CancellationToken::new(), | |
| ) | |
| .await | |
| .unwrap(); | |
| assert_eq!(latest_batch.hits.len(), 1); | |
| // Now run the search query directly against the earlier fixed cut_before_accept: | |
| // it must still recover the superseded LocalToolReturned row with 1 hit and 0 gaps. | |
| let mut fixed_cuts = std::collections::BTreeMap::new(); | |
| fixed_cuts.insert("ma_cut_sess_a".to_owned(), cut_before_accept.clone()); | |
| let q = crate::recall::SearchQuery { | |
| session_id: Some("ma_cut_sess_a".into()), | |
| terms: vec![needle.into()], | |
| since: None, | |
| until: None, | |
| exclude: None, | |
| limit: None, | |
| transcript_only: false, | |
| }; | |
| let older_batch = recall | |
| .search_at_cuts( | |
| q, | |
| fixed_cuts, | |
| 0, | |
| 0, | |
| tokio_util::sync::CancellationToken::new(), | |
| ) | |
| .await | |
| .unwrap(); | |
| assert_eq!( | |
| older_batch.hits.len(), | |
| 1, | |
| "fixed older cut must still find superseded LocalToolReturned row" | |
| ); | |
| assert!(older_batch.gaps.is_empty(), "{:?}", older_batch.gaps); | |
| // 4. If session A advances past its fixed cut and then enters removal before the final | |
| // owner search read, owner search with limit=1 must exclude A up front and return B | |
| // instead of failing with SessionNotFound or letting A crowd out B's limit slot. | |
| let (run_b2, spec_b2, blobs_b2, ts_b2) = admit_msg( | |
| "ma_cut_sess_b", | |
| "t-b-shared", | |
| "m-b-shared", | |
| needle, | |
| 1_700_000_001_050, | |
| ); | |
| store | |
| .admit(Admission::with_identity(run_b2, spec_b2, ts_b2, blobs_b2)) | |
| .await | |
| .unwrap(); | |
| // Catch up B so both A (at cut_before_accept) and B are indexed for the shared needle. | |
| let _ = recall | |
| .search( | |
| crate::recall::SearchQuery { | |
| session_id: Some("ma_cut_sess_b".into()), | |
| terms: vec![needle.into()], | |
| since: None, | |
| until: None, | |
| exclude: None, | |
| limit: None, | |
| transcript_only: false, | |
| }, | |
| 0, | |
| 0, | |
| tokio_util::sync::CancellationToken::new(), | |
| ) | |
| .await | |
| .unwrap(); | |
| let cut_b_shared = recall.capture("ma_cut_sess_b".into(), None).await.unwrap(); | |
| // Mark session A as removing (retired with remove_session = 1) while its Recall head | |
| // is already ahead of cut_before_accept. | |
| { | |
| let db = | |
| rusqlite::Connection::open(root_path.join(maka_event_log::root::ROOT_DATABASE)) | |
| .unwrap(); | |
| db.execute( | |
| "INSERT INTO session_retirements(session_id,remove_session,completed) VALUES(?1,1,0)", | |
| ["ma_cut_sess_a"], | |
| ) | |
| .unwrap(); | |
| } | |
| let mut owner_cuts = std::collections::BTreeMap::new(); | |
| owner_cuts.insert("ma_cut_sess_a".to_owned(), cut_before_accept); | |
| owner_cuts.insert("ma_cut_sess_b".to_owned(), cut_b_shared); | |
| let owner_batch = recall | |
| .search_at_cuts( | |
| crate::recall::SearchQuery { | |
| session_id: None, | |
| terms: vec![needle.into()], | |
| since: None, | |
| until: None, | |
| exclude: None, | |
| limit: Some(1), | |
| transcript_only: false, | |
| }, | |
| owner_cuts, | |
| 0, | |
| 0, | |
| tokio_util::sync::CancellationToken::new(), | |
| ) | |
| .await | |
| .expect("removing session must not fail owner search with SessionNotFound"); | |
| assert_eq!(owner_batch.hits.len(), 1); | |
| assert_eq!(owner_batch.hits[0].session.metadata.id, "ma_cut_sess_b"); | |
| assert!(owner_batch.gaps.is_empty(), "{:?}", owner_batch.gaps); | |
| drop((recall, store, data)); | |
| root.close().await.unwrap(); | |
| } | |
| } |