| 1 | //! Durable thread/turn/item runtime for the HTTP API and background tasks. |
| 2 | //! |
| 3 | //! Execution follows the configured provider route while exposing Codex-like |
| 4 | //! lifecycle semantics (threads, turns, items, interrupt/steer, and replayable |
| 5 | //! events). |
| 6 | |
| 7 | // Background-task runtime — runs alongside the TUI. Raw stdio prints |
| 8 | // here would still land in the alt-screen on whichever terminal the |
| 9 | // foreground TUI happens to own. Route everything through `tracing::*` |
| 10 | // instead — see `runtime_log` for the rationale. |
| 11 | #![deny(clippy::print_stdout)] |
| 12 | #![deny(clippy::print_stderr)] |
| 13 | |
| 14 | use std::collections::{HashMap, HashSet, VecDeque}; |
| 15 | use std::fs::{self, File, OpenOptions}; |
| 16 | use std::io::{self, BufRead, BufReader, Read, Seek, SeekFrom, Write}; |
| 17 | use std::path::{Component, Path, PathBuf}; |
| 18 | use std::sync::Arc; |
| 19 | use std::time::{Duration, Instant}; |
| 20 | |
| 21 | use anyhow::{Context, Result, anyhow, bail}; |
| 22 | use chrono::{DateTime, Utc}; |
| 23 | use serde::{Deserialize, Serialize}; |
| 24 | use serde_json::{Value, json}; |
| 25 | use sha2::{Digest, Sha256}; |
| 26 | use tokio::sync::{Mutex, Notify, RwLock as AsyncRwLock, broadcast, mpsc, oneshot, watch}; |
| 27 | use tokio_util::sync::CancellationToken; |
| 28 | use uuid::Uuid; |
| 29 | |
| 30 | use crate::compaction::CompactionConfig; |
| 31 | use crate::core::engine::handle::SteerOutcome; |
| 32 | use crate::core::engine::{EngineConfig, EngineHandle}; |
| 33 | use crate::core::events::{Event as EngineEvent, TurnOutcomeStatus}; |
| 34 | use crate::core::ops::{Op, TurnSpec}; |
| 35 | use crate::cost_status::{ |
| 36 | EffectiveRouteEnvelope, EffectiveRouteUsage, RouteBillingMode, RuntimeUsageDropRecord, |
| 37 | RuntimeUsageRecord, |
| 38 | }; |
| 39 | use crate::provider_catalog_live::ProviderLivePricingQuote; |
| 40 | use crate::route_budget::{ |
| 41 | auto_compact_default_for_route, known_route_limits, route_context_window_tokens, |
| 42 | }; |
| 43 | use crate::route_runtime::{ResolvedRuntimeRoute, resolve_runtime_route_for_identity}; |
| 44 | use crate::tools::plan::new_shared_plan_state; |
| 45 | use crate::tools::shell::{SharedShellManager, new_shared_shell_manager}; |
| 46 | use crate::tools::subagent::{ |
| 47 | SharedSubAgentManager, SubAgentStatus, new_shared_runtime_subagent_manager, |
| 48 | }; |
| 49 | use crate::tools::todo::new_shared_todo_list; |
| 50 | use codewhale_app_server_protocol::runtime::{ |
| 51 | DynamicToolCallContent, DynamicToolCallParams, DynamicToolCallResult, DynamicToolSpec, |
| 52 | TurnEnvironmentParams, |
| 53 | }; |
| 54 | #[cfg(test)] |
| 55 | use codewhale_config::AppMode; |
| 56 | use codewhale_config::ProviderKind; |
| 57 | #[cfg(test)] |
| 58 | use codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL; |
| 59 | use codewhale_execpolicy::ApprovalMode; |
| 60 | use codewhale_models::Role; |
| 61 | use codewhale_models::{ContentBlock, Message, SystemPrompt, ToolCallKey, ToolCaller, Usage}; |
| 62 | use codewhale_protocol::agent_mail::{ |
| 63 | AGENT_MAIL_EVENT_CANCELED, AGENT_MAIL_EVENT_DELIVERED, AGENT_MAIL_EVENT_DELIVERING, |
| 64 | AGENT_MAIL_EVENT_DELIVERY_FAILED, AGENT_MAIL_EVENT_QUEUED, AGENT_MAIL_EVENT_READ, |
| 65 | AGENT_MAIL_SCHEMA_VERSION, AgentMailAddress, AgentMailDeliveryMode, AgentMailEnvelope, |
| 66 | AgentMailEventPayload, AgentMailFailureCode, AgentMailFailureReceipt, AgentMailMessageId, |
| 67 | AgentMailSendRequest, AgentMailSendResponse, AgentMailStatus, MAX_AGENT_MAIL_DELIVERY_ATTEMPTS, |
| 68 | MAX_AGENT_MAIL_SUMMARY_BYTES, |
| 69 | }; |
| 70 | use codewhale_runtime::config::{Config, MAX_SUBAGENTS, ProviderIdentity}; |
| 71 | use codewhale_runtime::runtime_policy::RuntimePolicyProjection; |
| 72 | pub const RUNTIME_EVENT_REPLAY_BATCH_SIZE: usize = 256; |
| 73 | pub const MAX_RUNTIME_EVENT_REPLAY_TAIL: usize = 4096; |
| 74 | pub const MAX_RUNTIME_TURN_OPERATION_KEY_BYTES: usize = 128; |
| 75 | const EVENT_TRANSACTION_LOCK_TIMEOUT: Duration = Duration::from_secs(25); |
| 76 | const EVENT_TRANSACTION_LOCK_POLL: Duration = Duration::from_millis(5); |
| 77 | const EVENT_TRANSACTION_LOCK_FILE: &str = "events.lock"; |
| 78 | pub(crate) const RUNTIME_PROCESS_OWNER_LOCK_FILE: &str = "runtime-process.owner.lock"; |
| 79 | const RUNTIME_PROCESS_OWNER_LOCK_HELD: &str = "This runtime is already active in another process. Close the other Codewhale session and try again, or set CODEWHALE_RUNTIME_DIR to a different directory."; |
| 80 | const AGENT_MAIL_OWNER_FILE: &str = "owner.json"; |
| 81 | /// Every directory `RuntimeThreadStore::open` creates to hold work. Emptiness |
| 82 | /// across all of them is what lets a switch adopt an existing store (#6207); |
| 83 | /// `adoptable_empty_store_reports_nothing_to_abandon` pins this list against |
| 84 | /// `open` by asserting each directory is load-bearing on its own. |
| 85 | const RUNTIME_STORE_WORK_DIRS: [&str; 8] = [ |
| 86 | "threads", |
| 87 | "turns", |
| 88 | "items", |
| 89 | "events", |
| 90 | "goals", |
| 91 | "agent-mail", |
| 92 | "turn-operations", |
| 93 | "job-operations", |
| 94 | ]; |
| 95 | const TURN_OPERATION_BINDING_SCHEMA_VERSION: u32 = 2; |
| 96 | const RUNTIME_USAGE_PARTITION_SUMMARY: &str = "Provider usage receipt partition"; |
| 97 | |
| 98 | pub fn runtime_usage_partition_parent(turn: &TurnRecord) -> Option<&str> { |
| 99 | if !turn.routing_settlement || turn.input_summary != RUNTIME_USAGE_PARTITION_SUMMARY { |
| 100 | return None; |
| 101 | } |
| 102 | let (parent, source) = turn.id.strip_prefix("turn_usage_")?.rsplit_once('_')?; |
| 103 | if source.len() != 64 |
| 104 | || !source.bytes().all(|byte| byte.is_ascii_hexdigit()) |
| 105 | || validated_record_id(parent, "usage partition parent").is_err() |
| 106 | { |
| 107 | return None; |
| 108 | } |
| 109 | Some(parent) |
| 110 | } |
| 111 | |
| 112 | fn runtime_usage_partition_id(parent: &str, source_id: &str) -> Result<String> { |
| 113 | validated_record_id(parent, "usage partition parent")?; |
| 114 | Ok(format!( |
| 115 | "turn_usage_{parent}_{}", |
| 116 | routed_usage_source_fingerprint(source_id) |
| 117 | )) |
| 118 | } |
| 119 | |
| 120 | #[cfg(any(test, feature = "test-support"))] |
| 121 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 122 | pub enum EventAppendTestFault { |
| 123 | AfterFlush, |
| 124 | AfterSync, |
| 125 | } |
| 126 | |
| 127 | #[cfg(any(test, feature = "test-support"))] |
| 128 | static TEST_EVENT_APPEND_FAULTS: std::sync::Mutex<Vec<(String, EventAppendTestFault, usize)>> = |
| 129 | std::sync::Mutex::new(Vec::new()); |
| 130 | |
| 131 | #[cfg(any(test, feature = "test-support"))] |
| 132 | pub type EventAppendTestFaultRestore = (String, Option<(EventAppendTestFault, usize)>); |
| 133 | |
| 134 | #[cfg(any(test, feature = "test-support"))] |
| 135 | pub fn set_test_event_append_fault( |
| 136 | thread_id: &str, |
| 137 | fault: EventAppendTestFault, |
| 138 | remaining: usize, |
| 139 | ) -> EventAppendTestFaultRestore { |
| 140 | assert!(remaining > 0, "event append fault count must be positive"); |
| 141 | let mut pending = TEST_EVENT_APPEND_FAULTS |
| 142 | .lock() |
| 143 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 144 | let previous = pending |
| 145 | .iter() |
| 146 | .position(|(target, _, _)| target == thread_id) |
| 147 | .map(|index| { |
| 148 | let (_, previous_fault, previous_remaining) = pending.remove(index); |
| 149 | (previous_fault, previous_remaining) |
| 150 | }); |
| 151 | pending.push((thread_id.to_string(), fault, remaining)); |
| 152 | (thread_id.to_string(), previous) |
| 153 | } |
| 154 | |
| 155 | #[cfg(any(test, feature = "test-support"))] |
| 156 | pub fn restore_test_event_append_fault(restore: EventAppendTestFaultRestore) { |
| 157 | let (thread_id, previous) = restore; |
| 158 | let mut pending = TEST_EVENT_APPEND_FAULTS |
| 159 | .lock() |
| 160 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 161 | if let Some(index) = pending |
| 162 | .iter() |
| 163 | .position(|(target, _, _)| target == &thread_id) |
| 164 | { |
| 165 | pending.remove(index); |
| 166 | } |
| 167 | if let Some((fault, remaining)) = previous { |
| 168 | pending.push((thread_id, fault, remaining)); |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | #[cfg(any(test, feature = "test-support"))] |
| 173 | fn take_test_event_append_fault(thread_id: &str, expected: EventAppendTestFault) -> bool { |
| 174 | let mut pending = TEST_EVENT_APPEND_FAULTS |
| 175 | .lock() |
| 176 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 177 | let Some(index) = pending |
| 178 | .iter() |
| 179 | .position(|(target, fault, _)| target == thread_id && *fault == expected) |
| 180 | else { |
| 181 | return false; |
| 182 | }; |
| 183 | if pending[index].2 > 1 { |
| 184 | pending[index].2 -= 1; |
| 185 | } else { |
| 186 | pending.remove(index); |
| 187 | } |
| 188 | true |
| 189 | } |
| 190 | |
| 191 | fn validated_record_id<'a>(id: &'a str, label: &str) -> Result<&'a str> { |
| 192 | let trimmed = id.trim(); |
| 193 | if trimmed.is_empty() { |
| 194 | bail!("{label} cannot be empty"); |
| 195 | } |
| 196 | if trimmed != id { |
| 197 | bail!("{label} cannot contain leading or trailing whitespace"); |
| 198 | } |
| 199 | if !trimmed |
| 200 | .chars() |
| 201 | .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') |
| 202 | { |
| 203 | bail!("{label} contains unsupported characters"); |
| 204 | } |
| 205 | Ok(trimmed) |
| 206 | } |
| 207 | |
| 208 | fn sort_turn_items_by_start(items: &mut [TurnItemRecord]) { |
| 209 | let fallback = Utc::now(); |
| 210 | items.sort_by(|a, b| { |
| 211 | let left = a.started_at.unwrap_or(fallback); |
| 212 | let right = b.started_at.unwrap_or(fallback); |
| 213 | left.cmp(&right) |
| 214 | }); |
| 215 | } |
| 216 | |
| 217 | /// Bumped to 2 for v0.6.6 after live engine semantics changed. The persisted |
| 218 | /// thread/turn/item records did not change shape, but a v1 reader on a v2 |
| 219 | /// session should still fail closed rather than silently mis-replay. |
| 220 | // Text-only writes retain v2. Image-bearing records require v3 so an older |
| 221 | // binary refuses recovery instead of silently dropping accepted attachments. |
| 222 | const CURRENT_RUNTIME_SCHEMA_VERSION: u32 = 2; |
| 223 | const IMAGE_RUNTIME_SCHEMA_VERSION: u32 = 3; |
| 224 | // Explicit allowances need a newer reader so old binaries cannot retry uncapped. |
| 225 | const OUTPUT_LIMIT_RUNTIME_SCHEMA_VERSION: u32 = 4; |
| 226 | const PREFIX_CHECKPOINT_RUNTIME_SCHEMA_VERSION: u32 = 5; |
| 227 | const SOURCE_ACCOUNTING_RUNTIME_SCHEMA_VERSION: u32 = 6; |
| 228 | const DISALLOWED_TOOLS_RUNTIME_SCHEMA_VERSION: u32 = 7; |
| 229 | const WHALE_RUNTIME_SCHEMA_VERSION: u32 = 8; |
| 230 | const MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION: u32 = WHALE_RUNTIME_SCHEMA_VERSION; |
| 231 | |
| 232 | pub(crate) const fn required_thread_schema_version( |
| 233 | disallowed_tools: &[String], |
| 234 | whale_policy: bool, |
| 235 | ) -> u32 { |
| 236 | if whale_policy { |
| 237 | WHALE_RUNTIME_SCHEMA_VERSION |
| 238 | } else if disallowed_tools.is_empty() { |
| 239 | CURRENT_RUNTIME_SCHEMA_VERSION |
| 240 | } else { |
| 241 | DISALLOWED_TOOLS_RUNTIME_SCHEMA_VERSION |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | fn is_zero_u64(value: &u64) -> bool { |
| 246 | *value == 0 |
| 247 | } |
| 248 | |
| 249 | fn serialize_route_label_option<S>( |
| 250 | value: &Option<String>, |
| 251 | serializer: S, |
| 252 | ) -> std::result::Result<S::Ok, S::Error> |
| 253 | where |
| 254 | S: serde::Serializer, |
| 255 | { |
| 256 | value |
| 257 | .as_deref() |
| 258 | .map(codewhale_runtime::safe_label::sanitize_persisted_route_label) |
| 259 | .serialize(serializer) |
| 260 | } |
| 261 | |
| 262 | fn serialize_endpoint_fingerprint_option<S>( |
| 263 | value: &Option<String>, |
| 264 | serializer: S, |
| 265 | ) -> std::result::Result<S::Ok, S::Error> |
| 266 | where |
| 267 | S: serde::Serializer, |
| 268 | { |
| 269 | value |
| 270 | .as_deref() |
| 271 | .filter(|fingerprint| { |
| 272 | fingerprint.len() == 64 && fingerprint.bytes().all(|byte| byte.is_ascii_hexdigit()) |
| 273 | }) |
| 274 | .map(str::to_ascii_lowercase) |
| 275 | .serialize(serializer) |
| 276 | } |
| 277 | |
| 278 | fn serialize_routed_usage_source_ids<S>( |
| 279 | values: &[String], |
| 280 | serializer: S, |
| 281 | ) -> std::result::Result<S::Ok, S::Error> |
| 282 | where |
| 283 | S: serde::Serializer, |
| 284 | { |
| 285 | values |
| 286 | .iter() |
| 287 | .map(|value| routed_usage_source_fingerprint(value)) |
| 288 | .collect::<Vec<_>>() |
| 289 | .serialize(serializer) |
| 290 | } |
| 291 | |
| 292 | fn routed_usage_source_fingerprint(source_id: &str) -> String { |
| 293 | let source_id = source_id.trim(); |
| 294 | if source_id.len() == 64 && source_id.bytes().all(|byte| byte.is_ascii_hexdigit()) { |
| 295 | source_id.to_ascii_lowercase() |
| 296 | } else { |
| 297 | crate::cost_status::usage_source_fingerprint(source_id) |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | fn serialize_routed_usage_drop_records<S>( |
| 302 | values: &[RuntimeUsageDropRecord], |
| 303 | serializer: S, |
| 304 | ) -> std::result::Result<S::Ok, S::Error> |
| 305 | where |
| 306 | S: serde::Serializer, |
| 307 | { |
| 308 | values |
| 309 | .iter() |
| 310 | .map(|record| RuntimeUsageDropRecord { |
| 311 | reason: record.reason, |
| 312 | source_id: routed_usage_source_fingerprint(&record.source_id), |
| 313 | route: record.route.sanitized_for_persistence(), |
| 314 | }) |
| 315 | .collect::<Vec<_>>() |
| 316 | .serialize(serializer) |
| 317 | } |
| 318 | fn serialize_decision_receipts<S>( |
| 319 | values: &[crate::cost_status::RuntimeDecisionReceipt], |
| 320 | serializer: S, |
| 321 | ) -> std::result::Result<S::Ok, S::Error> |
| 322 | where |
| 323 | S: serde::Serializer, |
| 324 | { |
| 325 | values |
| 326 | .iter() |
| 327 | .map(crate::cost_status::RuntimeDecisionReceipt::sanitized) |
| 328 | .collect::<Vec<_>>() |
| 329 | .serialize(serializer) |
| 330 | } |
| 331 | |
| 332 | const fn default_runtime_schema_version() -> u32 { |
| 333 | CURRENT_RUNTIME_SCHEMA_VERSION |
| 334 | } |
| 335 | |
| 336 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 337 | #[serde(rename_all = "snake_case")] |
| 338 | pub enum RuntimeTurnStatus { |
| 339 | Queued, |
| 340 | InProgress, |
| 341 | Completed, |
| 342 | Failed, |
| 343 | Interrupted, |
| 344 | Canceled, |
| 345 | } |
| 346 | |
| 347 | impl RuntimeTurnStatus { |
| 348 | /// Queued or in-progress — the statuses `GET /v1/threads/running` counts. |
| 349 | pub const fn is_active_work(self) -> bool { |
| 350 | matches!(self, Self::Queued | Self::InProgress) |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 355 | #[serde(rename_all = "snake_case")] |
| 356 | pub enum TurnItemKind { |
| 357 | UserMessage, |
| 358 | AgentMessage, |
| 359 | AgentReasoning, |
| 360 | ToolCall, |
| 361 | FileChange, |
| 362 | CommandExecution, |
| 363 | ContextCompaction, |
| 364 | Status, |
| 365 | Error, |
| 366 | } |
| 367 | |
| 368 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 369 | #[serde(rename_all = "snake_case")] |
| 370 | pub enum TurnItemLifecycleStatus { |
| 371 | Queued, |
| 372 | InProgress, |
| 373 | Completed, |
| 374 | Failed, |
| 375 | Interrupted, |
| 376 | Canceled, |
| 377 | } |
| 378 | |
| 379 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 380 | pub struct ThreadRecord { |
| 381 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 382 | pub origin: Option<ThreadOrigin>, |
| 383 | #[serde(default = "default_runtime_schema_version")] |
| 384 | pub schema_version: u32, |
| 385 | pub id: String, |
| 386 | pub created_at: DateTime<Utc>, |
| 387 | pub updated_at: DateTime<Utc>, |
| 388 | pub model: String, |
| 389 | /// Generic provider kind for this thread's model route. Named custom |
| 390 | /// routes remain `custom` for compatibility with enum-only consumers. |
| 391 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 392 | pub model_provider: Option<String>, |
| 393 | /// Exact non-secret configured provider key. |
| 394 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 395 | pub model_provider_id: Option<String>, |
| 396 | /// Optional thread-level reasoning preference. A turn may override this; |
| 397 | /// when absent, the Runtime falls back to the configured preference. |
| 398 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 399 | pub reasoning_effort: Option<String>, |
| 400 | /// Optional thread-level model-visible tool allowlist. `None` keeps the |
| 401 | /// normal configured tool catalog; `Some([])` deliberately exposes none. |
| 402 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 403 | pub allowed_tools: Option<Vec<String>>, |
| 404 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 405 | pub disallowed_tools: Vec<String>, |
| 406 | /// Extra roots the file tools may read and write outside the workspace. |
| 407 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 408 | pub add_dirs: Vec<PathBuf>, |
| 409 | pub workspace: PathBuf, |
| 410 | pub mode: String, |
| 411 | /// Named default permission posture for new turns. Absent on legacy |
| 412 | /// records, whose effective posture is derived from the old fields. |
| 413 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 414 | pub permission_posture: Option<String>, |
| 415 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 416 | pub whale_id: Option<String>, |
| 417 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 418 | pub child_posture: Option<String>, |
| 419 | pub allow_shell: bool, |
| 420 | pub trust_mode: bool, |
| 421 | pub auto_approve: bool, |
| 422 | #[serde(skip_serializing_if = "Option::is_none")] |
| 423 | pub latest_turn_id: Option<String>, |
| 424 | #[serde(skip_serializing_if = "Option::is_none")] |
| 425 | pub latest_response_bookmark: Option<String>, |
| 426 | #[serde(default)] |
| 427 | pub archived: bool, |
| 428 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 429 | pub system_prompt: Option<String>, |
| 430 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 431 | pub task_id: Option<String>, |
| 432 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 433 | pub parent_thread_id: Option<String>, |
| 434 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 435 | pub parent_edge_kind: Option<ThreadEdgeKind>, |
| 436 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 437 | pub run_id: Option<String>, |
| 438 | /// User-set title for the thread. When `None`, consumers fall back to a |
| 439 | /// derived title (typically the latest turn's input summary). Added in |
| 440 | /// v0.8.10 (#562); old runtime records simply have no `title` and behave |
| 441 | /// as before. Schema version is not bumped because this field is purely |
| 442 | /// additive metadata — older readers ignore it without misinterpretation. |
| 443 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 444 | pub title: Option<String>, |
| 445 | /// Full-fidelity saved history prefix. Engine recovery verifies its checkpoint |
| 446 | /// and appends later durable Runtime turns without duplicating saved messages. |
| 447 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 448 | pub session_id: Option<String>, |
| 449 | /// Exact saved transcript and the last Runtime turn it already contains. |
| 450 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 451 | pub saved_session_checkpoint: Option<SavedSessionCheckpoint>, |
| 452 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 453 | pub last_read: Option<ThreadReadMarker>, |
| 454 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 455 | pub executor: Option<ExecutorRecord>, |
| 456 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 457 | pub environment: Option<ThreadEnvironment>, |
| 458 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 459 | pub agent_preset: Option<String>, |
| 460 | } |
| 461 | |
| 462 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 463 | #[serde(tag = "kind", rename_all = "snake_case")] |
| 464 | pub enum ThreadOrigin { |
| 465 | Automation, |
| 466 | Conversation, |
| 467 | Fork, |
| 468 | FleetCoordinator, |
| 469 | FleetWorker, |
| 470 | Subagent, |
| 471 | } |
| 472 | |
| 473 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 474 | #[serde(rename_all = "snake_case")] |
| 475 | pub enum ThreadEdgeKind { |
| 476 | Fork, |
| 477 | Spawned, |
| 478 | Coordinates, |
| 479 | ResumedFrom, |
| 480 | } |
| 481 | |
| 482 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 483 | pub struct ThreadEnvironment { |
| 484 | pub id: String, |
| 485 | pub provider_kind: String, |
| 486 | } |
| 487 | |
| 488 | impl ThreadEnvironment { |
| 489 | pub fn refusal(&self) -> crate::fleet::agents::ExecutorUnavailable { |
| 490 | crate::fleet::agents::ExecutorUnavailable::new( |
| 491 | crate::fleet::agents::ExecutorUnavailable::ENVIRONMENT_NOT_SUPPORTED, |
| 492 | "This session runs in another environment, which this build of Codewhale cannot serve.", |
| 493 | ) |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | pub const EXECUTOR_RECORD_VERSION: u32 = 1; |
| 498 | pub const EXECUTOR_KIND_ACP: &str = "acp"; |
| 499 | pub const EXECUTOR_KIND_CLI: &str = "cli"; |
| 500 | pub const EXECUTOR_KIND_ENGINE: &str = "engine"; |
| 501 | pub const EXECUTOR_TRANSPORT_ACP: &str = "acp"; |
| 502 | pub const EXECUTOR_TRANSPORT_CLI: &str = "cli"; |
| 503 | |
| 504 | pub fn is_external_executor_kind(kind: &str) -> bool { |
| 505 | matches!(kind, EXECUTOR_KIND_ACP | EXECUTOR_KIND_CLI) |
| 506 | } |
| 507 | |
| 508 | fn default_executor_record_version() -> u32 { |
| 509 | EXECUTOR_RECORD_VERSION |
| 510 | } |
| 511 | |
| 512 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 513 | pub struct ExecutorRecord { |
| 514 | #[serde(default = "default_executor_record_version")] |
| 515 | pub version: u32, |
| 516 | pub kind: String, |
| 517 | pub agent_id: String, |
| 518 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 519 | pub transport: Option<String>, |
| 520 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 521 | pub agent_name: Option<String>, |
| 522 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 523 | pub agent_version: Option<String>, |
| 524 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 525 | pub protocol_version: Option<u64>, |
| 526 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 527 | pub foreign_session_id: Option<String>, |
| 528 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 529 | pub model: Option<String>, |
| 530 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 531 | pub thought_level: Option<String>, |
| 532 | } |
| 533 | |
| 534 | impl ExecutorRecord { |
| 535 | pub fn validate(&self) -> Result<()> { |
| 536 | use crate::fleet::agents::ExecutorUnavailable; |
| 537 | if self.version > EXECUTOR_RECORD_VERSION { |
| 538 | return Err(ExecutorUnavailable::new( |
| 539 | ExecutorUnavailable::EXECUTOR_NOT_SUPPORTED, |
| 540 | format!( |
| 541 | "This session's executor record (version {}) is newer than this build of Codewhale.", |
| 542 | self.version |
| 543 | ), |
| 544 | ) |
| 545 | .into()); |
| 546 | } |
| 547 | if !is_external_executor_kind(&self.kind) { |
| 548 | let kind: String = self.kind.chars().take(32).collect(); |
| 549 | return Err(ExecutorUnavailable::new( |
| 550 | ExecutorUnavailable::EXECUTOR_NOT_SUPPORTED, |
| 551 | format!("Sessions run by `{kind}` are not supported in this build of Codewhale."), |
| 552 | ) |
| 553 | .into()); |
| 554 | } |
| 555 | if let Some(transport) = self.transport.as_deref() |
| 556 | && !matches!(transport, EXECUTOR_TRANSPORT_ACP | EXECUTOR_TRANSPORT_CLI) |
| 557 | { |
| 558 | let transport: String = transport.chars().take(32).collect(); |
| 559 | return Err(ExecutorUnavailable::new( |
| 560 | ExecutorUnavailable::EXECUTOR_NOT_SUPPORTED, |
| 561 | format!( |
| 562 | "External agent transport `{transport}` is not supported in this build of Codewhale." |
| 563 | ), |
| 564 | ) |
| 565 | .into()); |
| 566 | } |
| 567 | if let Some(level) = self.thought_level.as_deref() { |
| 568 | anyhow::ensure!( |
| 569 | !level.is_empty() |
| 570 | && level.len() <= crate::external_agents::acp::MAX_VALUE_BYTES |
| 571 | && !level.chars().any(char::is_control), |
| 572 | "executor thought_level must be the agent's own option value" |
| 573 | ); |
| 574 | } |
| 575 | Ok(()) |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 580 | pub struct ThreadReadMarker { |
| 581 | pub item_id: String, |
| 582 | pub last_in_turn: bool, |
| 583 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 584 | pub watermark_item_id: Option<String>, |
| 585 | } |
| 586 | |
| 587 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 588 | pub struct SavedSessionCheckpoint { |
| 589 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 590 | pub publication_observation: Option<crate::session_manager::SessionObservation>, |
| 591 | pub covered_turn_id: Option<String>, |
| 592 | /// Fingerprint of the document's first `messages_len` messages. |
| 593 | pub messages_sha256: String, |
| 594 | /// How many leading document messages the fingerprint covers (#6144). |
| 595 | /// |
| 596 | /// The document is the conversation's own record, and other writers |
| 597 | /// append to it legitimately — a TUI autosave of the same id, a later |
| 598 | /// `PUT /v1/sessions`. A fingerprint of the *whole* document turned every |
| 599 | /// such append into "changed after this thread's checkpoint" and stranded |
| 600 | /// the thread. Fingerprinting a prefix keeps the thread's history exact |
| 601 | /// (document prefix + its own later turns) while the document grows. |
| 602 | /// `None` is a checkpoint written before this field; it is migrated on |
| 603 | /// read by finding the prefix its whole-document fingerprint names. |
| 604 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 605 | pub messages_len: Option<usize>, |
| 606 | /// A backtracked fork may retain only a prefix of the verified snapshot. |
| 607 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 608 | pub retained_messages: Option<usize>, |
| 609 | } |
| 610 | |
| 611 | fn session_messages_sha256(messages: &[Message]) -> Result<String> { |
| 612 | Ok(hex_digest(Sha256::digest(serde_json::to_vec(messages)?))) |
| 613 | } |
| 614 | |
| 615 | fn hex_digest(digest: impl AsRef<[u8]>) -> String { |
| 616 | digest |
| 617 | .as_ref() |
| 618 | .iter() |
| 619 | .map(|byte| format!("{byte:02x}")) |
| 620 | .collect() |
| 621 | } |
| 622 | |
| 623 | /// How many leading `messages` the checkpoint's fingerprint covers, or `None` |
| 624 | /// when no prefix of this document is the one the thread was bound to. |
| 625 | /// |
| 626 | /// A checkpoint with `messages_len` is checked directly. A legacy one |
| 627 | /// fingerprinted the whole document at bind time, and the document may have |
| 628 | /// grown since, so every prefix is a candidate. `serde_json` writes a slice as |
| 629 | /// `[` + elements joined by `,` + `]`, so one pass that serializes each message |
| 630 | /// once can fingerprint every prefix — no quadratic re-serialization. |
| 631 | pub fn checkpoint_prefix_len( |
| 632 | checkpoint: &SavedSessionCheckpoint, |
| 633 | messages: &[Message], |
| 634 | ) -> Result<Option<usize>> { |
| 635 | if let Some(len) = checkpoint.messages_len { |
| 636 | if len > messages.len() { |
| 637 | return Ok(None); |
| 638 | } |
| 639 | return Ok( |
| 640 | (session_messages_sha256(&messages[..len])? == checkpoint.messages_sha256) |
| 641 | .then_some(len), |
| 642 | ); |
| 643 | } |
| 644 | let mut hasher = Sha256::new(); |
| 645 | hasher.update(b"["); |
| 646 | let close = |hasher: &Sha256| hex_digest(hasher.clone().chain_update(b"]").finalize()); |
| 647 | if close(&hasher) == checkpoint.messages_sha256 { |
| 648 | return Ok(Some(0)); |
| 649 | } |
| 650 | for (index, message) in messages.iter().enumerate() { |
| 651 | if index > 0 { |
| 652 | hasher.update(b","); |
| 653 | } |
| 654 | hasher.update(serde_json::to_vec(message)?); |
| 655 | if close(&hasher) == checkpoint.messages_sha256 { |
| 656 | return Ok(Some(index + 1)); |
| 657 | } |
| 658 | } |
| 659 | Ok(None) |
| 660 | } |
| 661 | |
| 662 | pub fn checkpoint_covers_every_turn( |
| 663 | checkpoint: &SavedSessionCheckpoint, |
| 664 | turns: &[TurnRecord], |
| 665 | ) -> bool { |
| 666 | match checkpoint.covered_turn_id.as_deref() { |
| 667 | Some(id) => turns.last().is_some_and(|turn| turn.id == id), |
| 668 | None => turns.is_empty(), |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | /// A thread's saved-session binding no longer describes any readable |
| 673 | /// document: the document is gone, or its prefix is not the one the thread |
| 674 | /// was bound to. The thread still owns its turns, so the binding is dropped |
| 675 | /// (with a receipt) and the thread hydrates from them instead of failing. |
| 676 | #[derive(Debug)] |
| 677 | pub struct StaleSessionBinding { |
| 678 | pub reason: String, |
| 679 | } |
| 680 | |
| 681 | impl std::fmt::Display for StaleSessionBinding { |
| 682 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 683 | f.write_str(&self.reason) |
| 684 | } |
| 685 | } |
| 686 | |
| 687 | impl std::error::Error for StaleSessionBinding {} |
| 688 | |
| 689 | /// The session document a Runtime thread writes under when nothing bound it |
| 690 | /// to one yet (#6144). |
| 691 | /// |
| 692 | /// A Runtime thread's engine used to mint a random conversation id every time |
| 693 | /// it was loaded, so everything it kept under its session directory — |
| 694 | /// compaction transfers, background-shell evidence, truncation spills — went |
| 695 | /// to a directory no document would ever name, and even the thread lost it at |
| 696 | /// the next load. Exporting the thread (`POST /v1/sessions`) minted yet |
| 697 | /// another id. Deriving the id from the thread makes all three agree, and |
| 698 | /// makes the export idempotent: a retry after a crash between "save the |
| 699 | /// document" and "bind the checkpoint" finds the document it already wrote. |
| 700 | pub fn thread_session_id(thread_id: &str) -> String { |
| 701 | // The thread's own id: the same id its engine runs under (see |
| 702 | // `ensure_engine_loaded`, #6621), so the export, the engine's session |
| 703 | // directory and the thread all name one conversation, and the export |
| 704 | // stays idempotent because the id is fixed by the thread. |
| 705 | thread_id.to_string() |
| 706 | } |
| 707 | |
| 708 | /// Stored item correlation is a projection of the existing history identity. |
| 709 | /// Explicit executions never fall back to legacy provider ids. New non-model |
| 710 | /// events carry an execution id but no provider id and do not enter history. |
| 711 | #[derive(Clone, Copy)] |
| 712 | struct RuntimeToolIdentity<'a> { |
| 713 | execution_id: Option<&'a str>, |
| 714 | provider_id: &'a str, |
| 715 | } |
| 716 | |
| 717 | impl<'a> RuntimeToolIdentity<'a> { |
| 718 | fn read(metadata: Option<&'a Value>, side: &str) -> Result<Option<Self>> { |
| 719 | let Some(meta) = metadata else { |
| 720 | return Ok(None); |
| 721 | }; |
| 722 | let Some(local) = meta.get(side) else { |
| 723 | return Ok(None); |
| 724 | }; |
| 725 | let local = local.as_str().context("Invalid stored tool correlation")?; |
| 726 | let Some(execution) = meta.get("execution_id") else { |
| 727 | return Ok((!local.is_empty()).then_some(Self { |
| 728 | execution_id: None, |
| 729 | provider_id: local, |
| 730 | })); |
| 731 | }; |
| 732 | let execution = execution |
| 733 | .as_str() |
| 734 | .filter(|id| !id.is_empty()) |
| 735 | .context("Invalid stored tool execution identity")?; |
| 736 | anyhow::ensure!( |
| 737 | local == execution, |
| 738 | "Stored tool execution identity mismatch" |
| 739 | ); |
| 740 | let Some(provider) = meta.get("provider_tool_use_id") else { |
| 741 | return Ok(None); |
| 742 | }; |
| 743 | let provider = provider |
| 744 | .as_str() |
| 745 | .filter(|id| !id.is_empty()) |
| 746 | .context("Invalid stored provider tool identity")?; |
| 747 | Ok(Some(Self { |
| 748 | execution_id: Some(execution), |
| 749 | provider_id: provider, |
| 750 | })) |
| 751 | } |
| 752 | |
| 753 | fn key(self) -> (ToolCallKey<'a>, &'a str) { |
| 754 | ( |
| 755 | self.execution_id.map_or( |
| 756 | ToolCallKey::LegacyProvider(self.provider_id), |
| 757 | ToolCallKey::Execution, |
| 758 | ), |
| 759 | self.provider_id, |
| 760 | ) |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | /// A persisted execution cannot acquire a different provider pairing on a |
| 765 | /// later result, turn, or import block. This is a transient validation index, |
| 766 | /// never a grant or another history store; legacy wire-only keys stay unchanged. |
| 767 | fn check_execution_provider( |
| 768 | bindings: &mut HashMap<String, String>, |
| 769 | execution: Option<&str>, |
| 770 | provider: &str, |
| 771 | ) -> Result<()> { |
| 772 | if let Some(execution) = execution { |
| 773 | anyhow::ensure!( |
| 774 | !execution.is_empty() && !provider.is_empty(), |
| 775 | "Invalid stored tool execution identity" |
| 776 | ); |
| 777 | if let Some(previous) = bindings.get(execution) { |
| 778 | anyhow::ensure!( |
| 779 | previous == provider, |
| 780 | "Stored tool execution has inconsistent provider identity" |
| 781 | ); |
| 782 | } else { |
| 783 | bindings.insert(execution.to_string(), provider.to_string()); |
| 784 | } |
| 785 | } |
| 786 | Ok(()) |
| 787 | } |
| 788 | |
| 789 | /// Legacy item reconstruction covered generic tool rows only. New model |
| 790 | /// correlation survives the UI's shell/file classification as well; a local |
| 791 | /// non-model record is still excluded by RuntimeToolIdentity::read. |
| 792 | fn projects_tool_history(item: &TurnItemRecord) -> bool { |
| 793 | item.kind == TurnItemKind::ToolCall |
| 794 | || (matches!( |
| 795 | item.kind, |
| 796 | TurnItemKind::FileChange | TurnItemKind::CommandExecution |
| 797 | ) && item |
| 798 | .metadata |
| 799 | .as_ref() |
| 800 | .is_some_and(|meta| meta.get("execution_id").is_some())) |
| 801 | } |
| 802 | |
| 803 | /// The result a rebuilt history must give a tool call whose outcome the turn |
| 804 | /// store never recorded, or `None` when nothing is missing. |
| 805 | /// |
| 806 | /// A call that was interrupted or canceled can be persisted as a single |
| 807 | /// `tool_call` item that carries the call alone, and so can a call that failed |
| 808 | /// under a runtime older than #6803, which kept the failure text on the item's |
| 809 | /// own `detail` without marking it `tool_result_for`. (A failure recorded now |
| 810 | /// carries that marker, so the record answers it like any completed call and |
| 811 | /// nothing is missing here.) Rebuilding |
| 812 | /// only the call leaves it unanswered, which a provider rejects outright — |
| 813 | /// `No tool output found for tool call …`. The missing result is also what |
| 814 | /// stopped the first of two responses from flushing, so the rebuild glued them |
| 815 | /// into one assistant message (`thinking`, `call`, `thinking`, `call`) and the |
| 816 | /// provider read *that* as the first call never being answered, even after the |
| 817 | /// request-time repair had answered it. |
| 818 | /// |
| 819 | /// Both are cured by answering the call where its own outcome is known: the |
| 820 | /// item's failure text for a failure, and the repository's interrupted-call |
| 821 | /// notice for a call the process never finished. |
| 822 | /// |
| 823 | /// An answer is only ever paired with a call the rebuild actually emits, so the |
| 824 | /// identity required here is the one the caller needs before it emits the call |
| 825 | /// at all (#5823): a snapshot with no tool name is skipped rather than replayed |
| 826 | /// as an empty shell, and answering it would leave the result on its own. |
| 827 | /// |
| 828 | /// A call still running is deliberately left alone. A rebuild of a live turn |
| 829 | /// must not invent an outcome the engine is still waiting for — the result is |
| 830 | /// coming — so this answers only the terminal failures. |
| 831 | fn unanswered_call_result( |
| 832 | item: &TurnItemRecord, |
| 833 | identity: RuntimeToolIdentity<'_>, |
| 834 | call_name: &str, |
| 835 | recorded_results: &HashSet<(ToolCallKey<'_>, &str)>, |
| 836 | ) -> Option<String> { |
| 837 | if identity.provider_id.is_empty() |
| 838 | || call_name.is_empty() |
| 839 | || recorded_results.contains(&identity.key()) |
| 840 | { |
| 841 | return None; |
| 842 | } |
| 843 | match item.status { |
| 844 | TurnItemLifecycleStatus::Failed => { |
| 845 | Some(item.detail.clone().unwrap_or_else(|| item.summary.clone())) |
| 846 | } |
| 847 | TurnItemLifecycleStatus::Interrupted | TurnItemLifecycleStatus::Canceled => { |
| 848 | Some(codewhale_runtime::tool_history_repair::CRASH_REPAIR_CONTENT.to_string()) |
| 849 | } |
| 850 | TurnItemLifecycleStatus::Queued |
| 851 | | TurnItemLifecycleStatus::InProgress |
| 852 | | TurnItemLifecycleStatus::Completed => None, |
| 853 | } |
| 854 | } |
| 855 | |
| 856 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 857 | pub struct WorkspaceMcpToolEstimate { |
| 858 | pub workspace_identity: String, |
| 859 | pub estimate: crate::tool_inspection::PreparedMcpToolEstimate, |
| 860 | } |
| 861 | |
| 862 | impl WorkspaceMcpToolEstimate { |
| 863 | pub fn workspace_identity(canonical: &Path, directory: &File) -> io::Result<String> { |
| 864 | let mut digest = Sha256::new(); |
| 865 | codewhale_util::path_identity::hash_os_path(&mut digest, b"prepared-mcp-tools", canonical); |
| 866 | #[cfg(unix)] |
| 867 | { |
| 868 | use std::os::unix::fs::MetadataExt; |
| 869 | let metadata = directory.metadata()?; |
| 870 | digest.update(metadata.dev().to_le_bytes()); |
| 871 | digest.update(metadata.ino().to_le_bytes()); |
| 872 | } |
| 873 | #[cfg(windows)] |
| 874 | { |
| 875 | let id = codewhale_util::path_identity::windows_file_identity(directory)?; |
| 876 | digest.update(id.volume.to_le_bytes()); |
| 877 | digest.update(id.index.to_le_bytes()); |
| 878 | } |
| 879 | #[cfg(not(any(unix, windows)))] |
| 880 | let _ = directory; |
| 881 | Ok(hex_digest(digest.finalize())) |
| 882 | } |
| 883 | } |
| 884 | |
| 885 | /// Bounded per-turn request facts copied only from the engine's terminal |
| 886 | /// request snapshot. These are distinct from provider-reported `TurnUsage`: |
| 887 | /// a model-client request and its HTTP retries may have no usage receipt. |
| 888 | /// These counts are observations, never provider invoices. |
| 889 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 890 | #[serde(rename_all = "camelCase")] |
| 891 | pub struct RuntimeTurnRequestDiagnostics { |
| 892 | #[serde(default)] |
| 893 | pub primary_coverage_recorded: bool, |
| 894 | #[serde(default)] |
| 895 | pub primary_usage_reported: u32, |
| 896 | #[serde(default)] |
| 897 | pub primary_usage_unknown: u32, |
| 898 | #[serde(default)] |
| 899 | pub primary_usage_missing: u32, |
| 900 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 901 | pub stop_reason: Option<RuntimeTurnStopReason>, |
| 902 | /// Parent streaming model-client calls, including stream retries. |
| 903 | pub model_requests_started: u32, |
| 904 | /// HTTP retries entered inside the captured streaming request, not invoices. |
| 905 | #[serde(default)] |
| 906 | pub transport_retries: u32, |
| 907 | /// Retries after a stream ended before content was observed. |
| 908 | pub transparent_stream_retries: u32, |
| 909 | /// Retry/resume attempts after an interrupted stream. |
| 910 | pub stream_resumes: u32, |
| 911 | /// Bounded re-requests after a reasoning-only provider response. |
| 912 | #[serde(default)] |
| 913 | pub reasoning_only_reprompts: u32, |
| 914 | /// Bounded re-requests after a clean empty provider stop. |
| 915 | #[serde(default)] |
| 916 | pub empty_stop_retries: u32, |
| 917 | } |
| 918 | |
| 919 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 920 | #[serde(rename_all = "snake_case")] |
| 921 | pub enum RuntimeTurnStopReason { |
| 922 | ProviderNoToolCall, |
| 923 | ProviderToolCallMissing, |
| 924 | StepBudgetExhausted, |
| 925 | NoProgress, |
| 926 | Interrupted, |
| 927 | Failed, |
| 928 | } |
| 929 | |
| 930 | impl From<crate::tool_inspection::TurnStopReason> for RuntimeTurnStopReason { |
| 931 | fn from(reason: crate::tool_inspection::TurnStopReason) -> Self { |
| 932 | match reason { |
| 933 | crate::tool_inspection::TurnStopReason::ProviderNoToolCall => Self::ProviderNoToolCall, |
| 934 | crate::tool_inspection::TurnStopReason::ProviderToolCallMissing => { |
| 935 | Self::ProviderToolCallMissing |
| 936 | } |
| 937 | crate::tool_inspection::TurnStopReason::StepBudgetExhausted => { |
| 938 | Self::StepBudgetExhausted |
| 939 | } |
| 940 | crate::tool_inspection::TurnStopReason::NoProgress => Self::NoProgress, |
| 941 | crate::tool_inspection::TurnStopReason::Interrupted => Self::Interrupted, |
| 942 | crate::tool_inspection::TurnStopReason::Failed => Self::Failed, |
| 943 | } |
| 944 | } |
| 945 | } |
| 946 | |
| 947 | impl From<&crate::tool_inspection::TurnStopDiagnostics> for RuntimeTurnRequestDiagnostics { |
| 948 | fn from(diagnostics: &crate::tool_inspection::TurnStopDiagnostics) -> Self { |
| 949 | Self { |
| 950 | primary_coverage_recorded: false, |
| 951 | primary_usage_reported: 0, |
| 952 | primary_usage_unknown: 0, |
| 953 | primary_usage_missing: 0, |
| 954 | stop_reason: diagnostics.reason.map(RuntimeTurnStopReason::from), |
| 955 | model_requests_started: diagnostics.model_requests_started, |
| 956 | transport_retries: diagnostics.transport_retries, |
| 957 | transparent_stream_retries: diagnostics.transparent_stream_retries, |
| 958 | stream_resumes: diagnostics.stream_resumes, |
| 959 | reasoning_only_reprompts: diagnostics.reasoning_only_reprompts, |
| 960 | empty_stop_retries: diagnostics.empty_stop_retries, |
| 961 | } |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 966 | pub struct RuntimeOperationSpan { |
| 967 | pub span_id: String, |
| 968 | pub activity_kind: codewhale_protocol::engine_owner::OwnerActivityKind, |
| 969 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 970 | pub action_id: Option<String>, |
| 971 | pub started_at: DateTime<Utc>, |
| 972 | } |
| 973 | |
| 974 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 975 | pub struct RuntimeOperationCompletion { |
| 976 | pub span_id: String, |
| 977 | pub activity_kind: codewhale_protocol::engine_owner::OwnerActivityKind, |
| 978 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 979 | pub action_id: Option<String>, |
| 980 | pub completed_at: DateTime<Utc>, |
| 981 | pub outcome: codewhale_protocol::engine_owner::OwnerOperationOutcome, |
| 982 | } |
| 983 | |
| 984 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 985 | pub struct RuntimeOperationActivity { |
| 986 | pub observed_at: DateTime<Utc>, |
| 987 | pub active: Vec<RuntimeOperationSpan>, |
| 988 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 989 | pub last_completed: Option<RuntimeOperationCompletion>, |
| 990 | #[serde(default)] |
| 991 | pub overflowed: bool, |
| 992 | } |
| 993 | |
| 994 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 995 | #[serde(deny_unknown_fields)] |
| 996 | pub struct RuntimePrefixCheckpoint { |
| 997 | checkpoint_id: String, |
| 998 | session_id: String, |
| 999 | agent_id: Option<String>, |
| 1000 | runtime_turn_id: String, |
| 1001 | engine_turn_id: String, |
| 1002 | call_id: String, |
| 1003 | owner_id: String, |
| 1004 | source_sha256: String, |
| 1005 | persisted_sha256: String, |
| 1006 | messages_len: usize, |
| 1007 | projection: String, |
| 1008 | item_ids: Vec<String>, |
| 1009 | covered_items: HashMap<String, String>, |
| 1010 | pending_items: Vec<String>, |
| 1011 | tool_declarations: HashMap<String, String>, |
| 1012 | } |
| 1013 | |
| 1014 | fn checkpoint_item_digest(item: &TurnItemRecord) -> Result<String> { |
| 1015 | Ok(hex_digest(Sha256::digest(serde_json::to_vec(&json!({ |
| 1016 | "kind": item.kind, |
| 1017 | "summary": item.summary, |
| 1018 | "detail": item.detail, |
| 1019 | "metadata": item.metadata, |
| 1020 | }))?))) |
| 1021 | } |
| 1022 | |
| 1023 | fn ordered_turn_items( |
| 1024 | turn: &TurnRecord, |
| 1025 | items_by_turn: &HashMap<String, Vec<TurnItemRecord>>, |
| 1026 | ) -> Result<Vec<TurnItemRecord>> { |
| 1027 | let stored = items_by_turn.get(&turn.id).cloned().unwrap_or_default(); |
| 1028 | let mut by_id = HashMap::new(); |
| 1029 | for item in &stored { |
| 1030 | anyhow::ensure!( |
| 1031 | item.turn_id == turn.id, |
| 1032 | "Stored item belongs to another turn" |
| 1033 | ); |
| 1034 | anyhow::ensure!( |
| 1035 | by_id.insert(item.id.clone(), item.clone()).is_none(), |
| 1036 | "Duplicate stored item" |
| 1037 | ); |
| 1038 | } |
| 1039 | let mut ordered = Vec::with_capacity(stored.len()); |
| 1040 | for id in &turn.item_ids { |
| 1041 | if let Some(item) = by_id.remove(id) { |
| 1042 | ordered.push(item); |
| 1043 | } |
| 1044 | } |
| 1045 | for item in stored { |
| 1046 | if by_id.remove(&item.id).is_some() { |
| 1047 | ordered.push(item); |
| 1048 | } |
| 1049 | } |
| 1050 | Ok(ordered) |
| 1051 | } |
| 1052 | |
| 1053 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1054 | pub struct TurnRecord { |
| 1055 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] |
| 1056 | pub imported_history: bool, |
| 1057 | #[serde(default, skip_serializing)] |
| 1058 | pub prefix_checkpoint: Option<RuntimePrefixCheckpoint>, |
| 1059 | /// Admitted per-request allowance. Older turns have no explicit allowance. |
| 1060 | #[serde( |
| 1061 | default, |
| 1062 | rename = "maxOutputTokens", |
| 1063 | alias = "max_output_tokens", |
| 1064 | skip_serializing_if = "Option::is_none" |
| 1065 | )] |
| 1066 | pub max_output_tokens: Option<std::num::NonZeroU32>, |
| 1067 | #[serde(default = "default_runtime_schema_version")] |
| 1068 | pub schema_version: u32, |
| 1069 | pub id: String, |
| 1070 | pub thread_id: String, |
| 1071 | pub status: RuntimeTurnStatus, |
| 1072 | pub input_summary: String, |
| 1073 | pub created_at: DateTime<Utc>, |
| 1074 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1075 | pub started_at: Option<DateTime<Utc>>, |
| 1076 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1077 | pub ended_at: Option<DateTime<Utc>>, |
| 1078 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1079 | pub duration_ms: Option<u64>, |
| 1080 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1081 | pub usage: Option<Usage>, |
| 1082 | /// Accounting-only receipt for auxiliary work completed before parent |
| 1083 | /// admission. It stays visible in history and cost totals, but never |
| 1084 | /// advances the thread's latest accepted turn, including after restart. |
| 1085 | #[serde(default)] |
| 1086 | pub routing_settlement: bool, |
| 1087 | /// Portion of `usage` served by this turn's persisted effective route. |
| 1088 | /// New records use this for parent cost/token accumulation, then add each |
| 1089 | /// routed child independently. Legacy absence falls back to `usage`. |
| 1090 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1091 | pub effective_route_usage: Option<Usage>, |
| 1092 | /// Canonical posture that governed this turn. New records always carry |
| 1093 | /// this receipt; old records deserialize with no fabricated value. |
| 1094 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1095 | pub permission_posture: Option<String>, |
| 1096 | /// Canonical mode this turn ran in (`agent` / `plan` / `operate`), resolved |
| 1097 | /// from the same policy projection as `permission_posture`. It is the |
| 1098 | /// per-turn record of the mode, which the thread cannot answer: `mode` may |
| 1099 | /// have been switched since, so a client reading the thread at completion |
| 1100 | /// learns how the thread is set up *now*, not how the run it is looking at |
| 1101 | /// ran. New records always carry it; records this runtime did not run (an |
| 1102 | /// imported conversation, a failed settlement for an unaccepted turn) and |
| 1103 | /// pre-existing records have none. |
| 1104 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1105 | pub mode: Option<String>, |
| 1106 | /// Concrete generic provider kind selected for this turn. |
| 1107 | #[serde( |
| 1108 | default, |
| 1109 | skip_serializing_if = "Option::is_none", |
| 1110 | serialize_with = "serialize_route_label_option" |
| 1111 | )] |
| 1112 | pub effective_provider: Option<String>, |
| 1113 | /// Exact non-secret configured provider key selected for this turn. |
| 1114 | #[serde( |
| 1115 | default, |
| 1116 | skip_serializing_if = "Option::is_none", |
| 1117 | serialize_with = "serialize_route_label_option" |
| 1118 | )] |
| 1119 | pub effective_provider_id: Option<String>, |
| 1120 | /// Requested OpenRouter upstream frozen at dispatch, when pinned. |
| 1121 | #[serde( |
| 1122 | default, |
| 1123 | skip_serializing_if = "Option::is_none", |
| 1124 | serialize_with = "serialize_route_label_option" |
| 1125 | )] |
| 1126 | pub effective_openrouter_vendor: Option<String>, |
| 1127 | /// Non-secret discriminator for routes whose provider/model pair spans |
| 1128 | /// different billing systems (for example StepFun PAYG vs Step Plan). |
| 1129 | #[serde( |
| 1130 | default, |
| 1131 | skip_serializing_if = "Option::is_none", |
| 1132 | serialize_with = "serialize_route_label_option" |
| 1133 | )] |
| 1134 | pub effective_billing_surface: Option<String>, |
| 1135 | /// SHA-256 fingerprint of the concrete dispatch endpoint. Raw URLs are |
| 1136 | /// intentionally never persisted. |
| 1137 | #[serde( |
| 1138 | default, |
| 1139 | skip_serializing_if = "Option::is_none", |
| 1140 | serialize_with = "serialize_endpoint_fingerprint_option" |
| 1141 | )] |
| 1142 | pub effective_endpoint_fingerprint: Option<String>, |
| 1143 | /// Immutable provider-live rate receipt frozen at CodeWhale's pre-permit |
| 1144 | /// application-dispatch boundary. Missing on legacy records; Baseten then |
| 1145 | /// stays unpriced while OpenRouter may use only its immutable bundled row. |
| 1146 | #[serde( |
| 1147 | default, |
| 1148 | skip_serializing_if = "Option::is_none", |
| 1149 | deserialize_with = "crate::provider_catalog_live::deserialize_optional_provider_live_pricing" |
| 1150 | )] |
| 1151 | pub effective_provider_live_pricing: Option<ProviderLivePricingQuote>, |
| 1152 | /// Immutable billing classification captured before dispatch. |
| 1153 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1154 | pub effective_billing_mode: Option<RouteBillingMode>, |
| 1155 | /// Dispatch timestamp used for historical/live pricing lookup. |
| 1156 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1157 | pub effective_dispatched_at: Option<DateTime<Utc>>, |
| 1158 | /// Concrete wire model selected for this turn (especially important when |
| 1159 | /// the thread is configured as `auto`). |
| 1160 | #[serde( |
| 1161 | default, |
| 1162 | skip_serializing_if = "Option::is_none", |
| 1163 | serialize_with = "serialize_route_label_option" |
| 1164 | )] |
| 1165 | pub effective_model: Option<String>, |
| 1166 | /// Model calls made beneath this parent turn, each paired with its own |
| 1167 | /// immutable route. These are exclusive of `effective_route_usage`; |
| 1168 | /// `usage` remains the authoritative all-token turn total and may include |
| 1169 | /// inline RLM/guardian calls. |
| 1170 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 1171 | pub routed_usage: Vec<EffectiveRouteUsage>, |
| 1172 | #[serde(default)] |
| 1173 | pub source_accounting: bool, |
| 1174 | #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] |
| 1175 | pub source_usage_records: |
| 1176 | std::collections::BTreeMap<String, crate::cost_status::RuntimeUsageRecord>, |
| 1177 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1178 | pub source_usage_origin_turn_id: Option<String>, |
| 1179 | /// Decision evidence shares this durable origin-turn ledger, including |
| 1180 | /// responses arriving after the parent terminal event. |
| 1181 | #[serde( |
| 1182 | default, |
| 1183 | skip_serializing_if = "Vec::is_empty", |
| 1184 | serialize_with = "serialize_decision_receipts" |
| 1185 | )] |
| 1186 | pub decision_receipts: Vec<crate::cost_status::RuntimeDecisionReceipt>, |
| 1187 | /// Exact missing-usage provider responses paired with their frozen route. |
| 1188 | /// Sources are persisted only as fingerprints, routes are sanitized, and |
| 1189 | /// the shared source ledger bounds usage plus missing-usage records. |
| 1190 | #[serde( |
| 1191 | default, |
| 1192 | skip_serializing_if = "Vec::is_empty", |
| 1193 | serialize_with = "serialize_routed_usage_drop_records" |
| 1194 | )] |
| 1195 | pub routed_usage_drop_records: Vec<RuntimeUsageDropRecord>, |
| 1196 | /// Fingerprints of provider-call identities already settled by this turn. |
| 1197 | /// Primary membership adds no routed amount. This ledger makes mailbox, sink, fallback |
| 1198 | /// recovery, and process restart idempotent without persisting raw ids. |
| 1199 | #[serde( |
| 1200 | default, |
| 1201 | skip_serializing_if = "Vec::is_empty", |
| 1202 | serialize_with = "serialize_routed_usage_source_ids" |
| 1203 | )] |
| 1204 | pub routed_usage_source_ids: Vec<String>, |
| 1205 | /// Background provider calls discarded from the bounded fallback journal. |
| 1206 | /// Non-zero means token/cost aggregation is necessarily incomplete. |
| 1207 | #[serde(default, skip_serializing_if = "is_zero_u64")] |
| 1208 | pub routed_usage_dropped_records: u64, |
| 1209 | /// Terminal facts about parent streaming model-client calls. This is |
| 1210 | /// absent until the engine emits its terminal request snapshot. It counts |
| 1211 | /// model-client calls, not HTTP retries within the client or invoices. |
| 1212 | #[serde( |
| 1213 | default, |
| 1214 | rename = "modelRequestDiagnostics", |
| 1215 | alias = "model_request_diagnostics", |
| 1216 | skip_serializing_if = "Option::is_none" |
| 1217 | )] |
| 1218 | pub model_request_diagnostics: Option<RuntimeTurnRequestDiagnostics>, |
| 1219 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1220 | pub prepared_mcp_tools: Option<WorkspaceMcpToolEstimate>, |
| 1221 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1222 | pub operation_activity: Option<RuntimeOperationActivity>, |
| 1223 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1224 | pub error: Option<String>, |
| 1225 | #[serde(default)] |
| 1226 | pub item_ids: Vec<String>, |
| 1227 | #[serde(default)] |
| 1228 | pub steer_count: usize, |
| 1229 | /// Stable Agent Mail id that caused this turn. This is the durable |
| 1230 | /// idempotency bridge between a claimed mail envelope and the existing |
| 1231 | /// turn queue; ordinary external-user turns leave it unset. |
| 1232 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1233 | pub agent_mail_message_id: Option<String>, |
| 1234 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1235 | pub input_source: Option<String>, |
| 1236 | /// What this turn produced, merged from its items' refs and, once |
| 1237 | /// settled, the workspace snapshot delta. Empty until the turn ends. |
| 1238 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 1239 | pub artifacts: Vec<TurnArtifactRef>, |
| 1240 | /// Where the workspace-level accounting stands. `None` while the turn |
| 1241 | /// runs (and on records written before this field existed). |
| 1242 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1243 | pub workspace: Option<TurnWorkspaceArtifacts>, |
| 1244 | /// Workspace snapshots the engine took while this turn ran, in the order |
| 1245 | /// the engine reported them (one FIFO event channel, one consumer per |
| 1246 | /// turn): the turn's `pre_turn` restore point, one `tool` snapshot before |
| 1247 | /// each file-modifying tool call, and its `post_turn` state. A thread owns |
| 1248 | /// exactly the restore points recorded on its own turns — a fork owns the |
| 1249 | /// ones its cloned turns carry — and turn-scoped undo and file revert |
| 1250 | /// resolve only these. Records written before this field existed, turns |
| 1251 | /// imported from a saved session, and turns that ran with snapshots off |
| 1252 | /// carry none, and so have no restore point. |
| 1253 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 1254 | pub workspace_snapshots: Vec<codewhale_snapshot::WorkspaceSnapshotRef>, |
| 1255 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 1256 | pub delegated_writes: Vec<String>, |
| 1257 | } |
| 1258 | |
| 1259 | impl TurnRecord { |
| 1260 | fn validate_output_token_limit(&self) -> Result<()> { |
| 1261 | if let Some(activity) = &self.operation_activity { |
| 1262 | let safe_id = |
| 1263 | |id: &str| !id.is_empty() && id.len() <= 256 && !id.chars().any(char::is_control); |
| 1264 | anyhow::ensure!( |
| 1265 | activity.active.len() <= 256 |
| 1266 | && activity.active.iter().all(|span| { |
| 1267 | safe_id(&span.span_id) |
| 1268 | && span.action_id.as_deref().is_none_or(safe_id) |
| 1269 | && span.started_at <= activity.observed_at |
| 1270 | }) |
| 1271 | && activity.last_completed.as_ref().is_none_or(|span| { |
| 1272 | safe_id(&span.span_id) |
| 1273 | && span.action_id.as_deref().is_none_or(safe_id) |
| 1274 | && span.completed_at <= activity.observed_at |
| 1275 | }), |
| 1276 | "Turn operation activity exceeds its bound" |
| 1277 | ); |
| 1278 | } |
| 1279 | if self.decision_receipts.iter().any(|r| !r.is_bounded()) { |
| 1280 | bail!("Turn decision evidence exceeds its bound"); |
| 1281 | } |
| 1282 | anyhow::ensure!( |
| 1283 | self.prefix_checkpoint.is_none() |
| 1284 | || self.schema_version >= PREFIX_CHECKPOINT_RUNTIME_SCHEMA_VERSION, |
| 1285 | "Runtime prefix checkpoint requires its recovery schema" |
| 1286 | ); |
| 1287 | anyhow::ensure!( |
| 1288 | (!self.source_accounting |
| 1289 | && self.source_usage_records.is_empty() |
| 1290 | && self.source_usage_origin_turn_id.is_none()) |
| 1291 | || self.schema_version >= SOURCE_ACCOUNTING_RUNTIME_SCHEMA_VERSION, |
| 1292 | "native source accounting requires its recovery schema" |
| 1293 | ); |
| 1294 | anyhow::ensure!( |
| 1295 | self.source_usage_records.is_empty() || self.source_accounting, |
| 1296 | "source records require native accounting reconciliation" |
| 1297 | ); |
| 1298 | anyhow::ensure!( |
| 1299 | self.source_usage_records.is_empty() || self.source_usage_origin_turn_id.is_some(), |
| 1300 | "native source receipts have no original owning turn" |
| 1301 | ); |
| 1302 | if let Some(origin) = self.source_usage_origin_turn_id.as_deref() { |
| 1303 | validated_record_id(origin, "native usage origin turn id")?; |
| 1304 | } |
| 1305 | anyhow::ensure!( |
| 1306 | self.source_usage_records |
| 1307 | .iter() |
| 1308 | .all(|(key, record)| record.settlement.is_some() |
| 1309 | && record.validate().is_ok() |
| 1310 | && *key == crate::cost_status::usage_source_fingerprint(&record.source_id) |
| 1311 | && self.routed_usage_source_ids.contains(key)), |
| 1312 | "native source receipts violate their identity contract" |
| 1313 | ); |
| 1314 | if self.routing_settlement && self.input_summary == RUNTIME_USAGE_PARTITION_SUMMARY { |
| 1315 | let parent = runtime_usage_partition_parent(self) |
| 1316 | .context("Runtime usage partition identity is invalid")?; |
| 1317 | let source = self.id.rsplit_once('_').map(|(_, source)| source); |
| 1318 | anyhow::ensure!( |
| 1319 | parent != self.id |
| 1320 | && self.status == RuntimeTurnStatus::Completed |
| 1321 | && self.error.is_none() |
| 1322 | && self.max_output_tokens.is_none() |
| 1323 | && self.usage.is_none() |
| 1324 | && self.effective_route_usage.is_none() |
| 1325 | && self.effective_route_envelope().is_none() |
| 1326 | && self.prefix_checkpoint.is_none() |
| 1327 | && self.item_ids.is_empty() |
| 1328 | && self.decision_receipts.is_empty() |
| 1329 | && self.model_request_diagnostics.is_none() |
| 1330 | && self.operation_activity.is_none() |
| 1331 | && self.permission_posture.is_none() |
| 1332 | && self.mode.is_none() |
| 1333 | && self.steer_count == 0 |
| 1334 | && self.agent_mail_message_id.is_none() |
| 1335 | && self.input_source.is_none() |
| 1336 | && self.artifacts.is_empty() |
| 1337 | && self.workspace.is_none() |
| 1338 | && self.workspace_snapshots.is_empty() |
| 1339 | && self.delegated_writes.is_empty() |
| 1340 | && self.source_accounting |
| 1341 | && self.source_usage_records.len() == 1 |
| 1342 | && self |
| 1343 | .source_usage_records |
| 1344 | .keys() |
| 1345 | .all(|key| Some(key.as_str()) == source) |
| 1346 | && self.routed_usage_source_ids.len() == 1 |
| 1347 | && self.routed_usage.is_empty() |
| 1348 | && self.routed_usage_drop_records.is_empty() |
| 1349 | && self.routed_usage_dropped_records == 0, |
| 1350 | "Runtime usage partition contains unrelated turn effects or sources" |
| 1351 | ); |
| 1352 | } |
| 1353 | if self.schema_version > MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION { |
| 1354 | bail!( |
| 1355 | "Turn schema v{} is newer than supported v{}", |
| 1356 | self.schema_version, |
| 1357 | MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION |
| 1358 | ); |
| 1359 | } |
| 1360 | if (self.max_output_tokens.is_some() |
| 1361 | && self.schema_version < OUTPUT_LIMIT_RUNTIME_SCHEMA_VERSION) |
| 1362 | || (self.max_output_tokens.is_none() |
| 1363 | && self.schema_version == OUTPUT_LIMIT_RUNTIME_SCHEMA_VERSION) |
| 1364 | { |
| 1365 | bail!("Turn output allowance does not match its schema"); |
| 1366 | } |
| 1367 | Ok(()) |
| 1368 | } |
| 1369 | |
| 1370 | pub fn effective_provider_label(&self) -> Option<&str> { |
| 1371 | self.effective_provider_id |
| 1372 | .as_deref() |
| 1373 | .filter(|identity| !identity.trim().is_empty()) |
| 1374 | .or_else(|| { |
| 1375 | self.effective_provider |
| 1376 | .as_deref() |
| 1377 | .filter(|provider| !provider.trim().is_empty()) |
| 1378 | }) |
| 1379 | } |
| 1380 | |
| 1381 | fn persist_effective_route(&mut self, route: &EffectiveRouteEnvelope) { |
| 1382 | let route = route.sanitized_for_persistence(); |
| 1383 | self.effective_provider = Some(route.provider.as_str().to_string()); |
| 1384 | self.effective_provider_id = Some(route.provider_identity); |
| 1385 | self.effective_openrouter_vendor = route.openrouter_vendor; |
| 1386 | self.effective_billing_surface = route.billing_surface; |
| 1387 | self.effective_endpoint_fingerprint = route.endpoint_fingerprint; |
| 1388 | self.effective_provider_live_pricing = route.provider_live_pricing; |
| 1389 | self.effective_billing_mode = Some(route.billing_mode); |
| 1390 | self.effective_dispatched_at = Some(route.dispatched_at); |
| 1391 | self.effective_model = Some(route.model); |
| 1392 | } |
| 1393 | |
| 1394 | /// Rehydrate only a complete persisted dispatch record. Legacy rows must |
| 1395 | /// not borrow a provider identity or timestamp from the current thread. |
| 1396 | fn effective_route_envelope(&self) -> Option<EffectiveRouteEnvelope> { |
| 1397 | let provider = self |
| 1398 | .effective_provider |
| 1399 | .as_deref() |
| 1400 | .and_then(ProviderKind::parse)?; |
| 1401 | let provider_identity = self |
| 1402 | .effective_provider_id |
| 1403 | .as_deref() |
| 1404 | .filter(|identity| !identity.trim().is_empty())? |
| 1405 | .to_string(); |
| 1406 | let model = self |
| 1407 | .effective_model |
| 1408 | .as_deref() |
| 1409 | .filter(|model| !model.trim().is_empty())? |
| 1410 | .to_string(); |
| 1411 | let dispatched_at = self.effective_dispatched_at?; |
| 1412 | Some( |
| 1413 | EffectiveRouteEnvelope { |
| 1414 | provider, |
| 1415 | provider_identity, |
| 1416 | model, |
| 1417 | openrouter_vendor: self.effective_openrouter_vendor.clone(), |
| 1418 | billing_surface: self.effective_billing_surface.clone(), |
| 1419 | endpoint_fingerprint: self.effective_endpoint_fingerprint.clone(), |
| 1420 | provider_live_pricing: self.effective_provider_live_pricing.clone(), |
| 1421 | billing_mode: self |
| 1422 | .effective_billing_mode |
| 1423 | .unwrap_or(RouteBillingMode::Unknown), |
| 1424 | dispatched_at, |
| 1425 | } |
| 1426 | .sanitized_for_persistence(), |
| 1427 | ) |
| 1428 | } |
| 1429 | } |
| 1430 | |
| 1431 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1432 | pub struct TurnItemRecord { |
| 1433 | #[serde(default = "default_runtime_schema_version")] |
| 1434 | pub schema_version: u32, |
| 1435 | pub id: String, |
| 1436 | pub turn_id: String, |
| 1437 | pub kind: TurnItemKind, |
| 1438 | pub status: TurnItemLifecycleStatus, |
| 1439 | pub summary: String, |
| 1440 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1441 | pub detail: Option<String>, |
| 1442 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1443 | pub metadata: Option<Value>, |
| 1444 | /// Legacy projection of `artifacts`: workspace-relative paths of the |
| 1445 | /// files this item created, changed or renamed (never deleted files, |
| 1446 | /// spills or media). Derived only by `legacy_artifact_refs`. |
| 1447 | #[serde(default)] |
| 1448 | pub artifact_refs: Vec<PathBuf>, |
| 1449 | /// What this item produced, as typed references. The authority for a |
| 1450 | /// single tool call's artifacts; the turn aggregate is merged from these. |
| 1451 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 1452 | pub artifacts: Vec<TurnArtifactRef>, |
| 1453 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1454 | pub started_at: Option<DateTime<Utc>>, |
| 1455 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1456 | pub ended_at: Option<DateTime<Utc>>, |
| 1457 | } |
| 1458 | |
| 1459 | impl TurnItemRecord { |
| 1460 | pub fn recorded_tool_error(&self) -> Option<bool> { |
| 1461 | let metadata = self.metadata.as_ref()?; |
| 1462 | let error = metadata.get("is_error")?.as_bool()?; |
| 1463 | let explicit = metadata.get("is_error_explicit").and_then(Value::as_bool) == Some(true); |
| 1464 | let call = metadata["tool_use_id"].as_str(); |
| 1465 | let live_result = call.is_some() && call == metadata["tool_result_for"].as_str(); |
| 1466 | (error || explicit || live_result).then_some(error) |
| 1467 | } |
| 1468 | |
| 1469 | fn set_image_content(&mut self, content: Vec<ContentBlock>) { |
| 1470 | self.schema_version = IMAGE_RUNTIME_SCHEMA_VERSION; |
| 1471 | let metadata = self.metadata.get_or_insert_with(|| json!({})); |
| 1472 | metadata["runtime_image_content"] = json!(content); |
| 1473 | } |
| 1474 | |
| 1475 | fn user_content(&self) -> Result<Vec<ContentBlock>> { |
| 1476 | if (self.schema_version == IMAGE_RUNTIME_SCHEMA_VERSION |
| 1477 | || (self.schema_version == OUTPUT_LIMIT_RUNTIME_SCHEMA_VERSION |
| 1478 | && self |
| 1479 | .metadata |
| 1480 | .as_ref() |
| 1481 | .is_some_and(|meta| meta.get("runtime_image_content").is_some()))) |
| 1482 | && self.kind == TurnItemKind::UserMessage |
| 1483 | { |
| 1484 | let content = self |
| 1485 | .metadata |
| 1486 | .as_ref() |
| 1487 | .and_then(|meta| meta.get("runtime_image_content")) |
| 1488 | .context("persisted image input is missing its content")?; |
| 1489 | let blocks: Vec<ContentBlock> = |
| 1490 | serde_json::from_value(content.clone()).context("invalid persisted image input")?; |
| 1491 | crate::image_attach::validate_stored_image_content(&blocks)?; |
| 1492 | if self.detail.as_deref().is_some_and(|text| !text.trim().is_empty()) |
| 1493 | && !blocks.iter().any(|block| matches!(block, ContentBlock::Text { text, .. } if !text.trim().is_empty())) |
| 1494 | { |
| 1495 | bail!("persisted image input is missing its prompt"); |
| 1496 | } |
| 1497 | return Ok(blocks); |
| 1498 | } |
| 1499 | let text = self.detail.as_ref().unwrap_or(&self.summary); |
| 1500 | Ok(if text.trim().is_empty() { |
| 1501 | Vec::new() |
| 1502 | } else { |
| 1503 | vec![ContentBlock::Text { |
| 1504 | text: text.clone(), |
| 1505 | cache_control: None, |
| 1506 | }] |
| 1507 | }) |
| 1508 | } |
| 1509 | } |
| 1510 | |
| 1511 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1512 | pub struct RuntimeEventRecord { |
| 1513 | #[serde(default = "default_runtime_schema_version")] |
| 1514 | pub schema_version: u32, |
| 1515 | pub seq: u64, |
| 1516 | pub timestamp: DateTime<Utc>, |
| 1517 | pub thread_id: String, |
| 1518 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1519 | pub turn_id: Option<String>, |
| 1520 | #[serde(skip_serializing_if = "Option::is_none")] |
| 1521 | pub item_id: Option<String>, |
| 1522 | pub event: String, |
| 1523 | pub payload: Value, |
| 1524 | } |
| 1525 | |
| 1526 | /// Event name for a runtime store record the runtime could not read, parse, |
| 1527 | /// or write. Its payload is a [`RuntimeStoreFailureNotice`] (#5931). |
| 1528 | pub const RUNTIME_STORE_FAILURE_EVENT: &str = "runtime.store_failure"; |
| 1529 | |
| 1530 | /// Which runtime store file family failed. The nouns are the store's own |
| 1531 | /// directories (`threads/`, `turns/`, `items/`), so a notice can point at one |
| 1532 | /// file and mean it. |
| 1533 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 1534 | #[serde(rename_all = "snake_case")] |
| 1535 | pub enum RuntimeStoreRecordKind { |
| 1536 | Thread, |
| 1537 | Turn, |
| 1538 | Item, |
| 1539 | } |
| 1540 | |
| 1541 | impl std::fmt::Display for RuntimeStoreRecordKind { |
| 1542 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 1543 | f.write_str(match self { |
| 1544 | Self::Thread => "thread", |
| 1545 | Self::Turn => "turn", |
| 1546 | Self::Item => "item", |
| 1547 | }) |
| 1548 | } |
| 1549 | } |
| 1550 | |
| 1551 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 1552 | #[serde(rename_all = "snake_case")] |
| 1553 | pub enum RuntimeStoreOperation { |
| 1554 | Read, |
| 1555 | Parse, |
| 1556 | Write, |
| 1557 | } |
| 1558 | |
| 1559 | impl std::fmt::Display for RuntimeStoreOperation { |
| 1560 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 1561 | f.write_str(match self { |
| 1562 | Self::Read => "read", |
| 1563 | Self::Parse => "parse", |
| 1564 | Self::Write => "write", |
| 1565 | }) |
| 1566 | } |
| 1567 | } |
| 1568 | |
| 1569 | /// A runtime store record the operator's own disk could not read, parse, or |
| 1570 | /// write. The store's load/save paths attach it as typed `anyhow` context, so |
| 1571 | /// a monitor recognizes a store fault by type instead of by message text and |
| 1572 | /// can name the file and the next action in a visible notice (#5931). |
| 1573 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 1574 | pub struct RuntimeStoreRecordFailure { |
| 1575 | pub operation: RuntimeStoreOperation, |
| 1576 | pub record_kind: RuntimeStoreRecordKind, |
| 1577 | pub record_id: String, |
| 1578 | pub path: PathBuf, |
| 1579 | } |
| 1580 | |
| 1581 | impl RuntimeStoreRecordFailure { |
| 1582 | fn new( |
| 1583 | operation: RuntimeStoreOperation, |
| 1584 | record_kind: RuntimeStoreRecordKind, |
| 1585 | record_id: &str, |
| 1586 | path: &Path, |
| 1587 | ) -> Self { |
| 1588 | Self { |
| 1589 | operation, |
| 1590 | record_kind, |
| 1591 | record_id: record_id.to_string(), |
| 1592 | path: path.to_path_buf(), |
| 1593 | } |
| 1594 | } |
| 1595 | |
| 1596 | /// The typed store fault behind an error, if any layer of it is one. |
| 1597 | #[must_use] |
| 1598 | pub fn from_error(error: &anyhow::Error) -> Option<&Self> { |
| 1599 | error.downcast_ref::<Self>() |
| 1600 | } |
| 1601 | |
| 1602 | /// What the operator can do about it: which file to move aside, or |
| 1603 | /// where to check space and permissions. Nothing here is guessed. |
| 1604 | #[must_use] |
| 1605 | pub fn next_action(&self) -> String { |
| 1606 | match self.operation { |
| 1607 | RuntimeStoreOperation::Read | RuntimeStoreOperation::Parse => format!( |
| 1608 | "Move {} aside (or delete it) and retry; the thread's other records stay in place.", |
| 1609 | self.path.display() |
| 1610 | ), |
| 1611 | RuntimeStoreOperation::Write => format!( |
| 1612 | "Check free space and permissions for {}, then retry; nothing was overwritten.", |
| 1613 | self.path.display() |
| 1614 | ), |
| 1615 | } |
| 1616 | } |
| 1617 | |
| 1618 | /// Build the event payload for this fault. `terminal` says the runtime |
| 1619 | /// already knows the turn can never reach `turn.completed`. |
| 1620 | #[must_use] |
| 1621 | pub fn notice(&self, error: &anyhow::Error, terminal: bool) -> RuntimeStoreFailureNotice { |
| 1622 | let reason = error |
| 1623 | .chain() |
| 1624 | .last() |
| 1625 | .map(ToString::to_string) |
| 1626 | .unwrap_or_default(); |
| 1627 | let next_action = self.next_action(); |
| 1628 | let message = format!( |
| 1629 | "Session runtime store: {} {} at {} could not be {}: {reason}. {next_action}", |
| 1630 | self.record_kind, |
| 1631 | self.record_id, |
| 1632 | self.path.display(), |
| 1633 | match self.operation { |
| 1634 | RuntimeStoreOperation::Read => "read", |
| 1635 | RuntimeStoreOperation::Parse => "parsed", |
| 1636 | RuntimeStoreOperation::Write => "written", |
| 1637 | }, |
| 1638 | ); |
| 1639 | RuntimeStoreFailureNotice { |
| 1640 | failure: self.clone(), |
| 1641 | error: format!("{error:#}"), |
| 1642 | reason, |
| 1643 | next_action, |
| 1644 | message, |
| 1645 | terminal, |
| 1646 | } |
| 1647 | } |
| 1648 | } |
| 1649 | |
| 1650 | impl std::fmt::Display for RuntimeStoreRecordFailure { |
| 1651 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 1652 | write!( |
| 1653 | f, |
| 1654 | "Failed to {} {} {}", |
| 1655 | self.operation, |
| 1656 | self.record_kind, |
| 1657 | self.path.display() |
| 1658 | ) |
| 1659 | } |
| 1660 | } |
| 1661 | |
| 1662 | /// Payload of a `runtime.store_failure` event: the operator's own on-disk |
| 1663 | /// state failed, and every consumer (task timeline, SSE client, TUI toast) |
| 1664 | /// gets the file, the reason, and the next action rather than a log line. |
| 1665 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 1666 | pub struct RuntimeStoreFailureNotice { |
| 1667 | #[serde(flatten)] |
| 1668 | pub failure: RuntimeStoreRecordFailure, |
| 1669 | /// Full error chain, outermost first. |
| 1670 | pub error: String, |
| 1671 | /// Root cause alone (an OS or parser message), for compact surfaces. |
| 1672 | pub reason: String, |
| 1673 | /// What the operator can do about it. |
| 1674 | pub next_action: String, |
| 1675 | /// One-line operator text: record, path, reason, and next action. |
| 1676 | pub message: String, |
| 1677 | /// True when this turn will never reach `turn.completed`: its own record |
| 1678 | /// is unreadable or unwritable, so nothing can be terminalized. Drivers |
| 1679 | /// waiting on the turn should stop waiting. |
| 1680 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] |
| 1681 | pub terminal: bool, |
| 1682 | } |
| 1683 | |
| 1684 | pub struct RuntimeEventReplay { |
| 1685 | /// Cursor immediately before the first replayed event. For a tail-limited |
| 1686 | /// replay this advances past omitted history so continuity remains exact. |
| 1687 | pub base_seq: u64, |
| 1688 | /// Filesystem parsing happens on the blocking pool and publishes bounded |
| 1689 | /// chunks through this small channel, applying backpressure instead of |
| 1690 | /// allocating an unbounded backlog on a Tokio worker. A closed channel |
| 1691 | /// means history is complete; every failure, a worker panic included, |
| 1692 | /// arrives as an `Err` batch first. |
| 1693 | pub batches: mpsc::Receiver<std::result::Result<Vec<RuntimeEventRecord>, String>>, |
| 1694 | } |
| 1695 | |
| 1696 | type RuntimeEventReader = BufReader<std::io::Take<File>>; |
| 1697 | |
| 1698 | enum RuntimeEventMatch { |
| 1699 | ThreadStarted, |
| 1700 | TurnCompleted { |
| 1701 | turn_id: String, |
| 1702 | }, |
| 1703 | DynamicTerminal { |
| 1704 | turn_id: String, |
| 1705 | call_id: String, |
| 1706 | }, |
| 1707 | AgentMail { |
| 1708 | event_name: String, |
| 1709 | message_id: String, |
| 1710 | attempt_count: u8, |
| 1711 | }, |
| 1712 | WorkerLifecycle { |
| 1713 | turn_id: String, |
| 1714 | agent_id: String, |
| 1715 | event_name: String, |
| 1716 | }, |
| 1717 | } |
| 1718 | |
| 1719 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1720 | pub struct RuntimeStoreState { |
| 1721 | #[serde(default = "default_runtime_schema_version")] |
| 1722 | schema_version: u32, |
| 1723 | next_seq: u64, |
| 1724 | } |
| 1725 | |
| 1726 | impl Default for RuntimeStoreState { |
| 1727 | fn default() -> Self { |
| 1728 | Self { |
| 1729 | schema_version: CURRENT_RUNTIME_SCHEMA_VERSION, |
| 1730 | next_seq: 1, |
| 1731 | } |
| 1732 | } |
| 1733 | } |
| 1734 | |
| 1735 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1736 | enum EventAppendFailureDisposition { |
| 1737 | RolledBack, |
| 1738 | Indeterminate, |
| 1739 | } |
| 1740 | |
| 1741 | #[derive(Debug)] |
| 1742 | struct RuntimeEventAppendError { |
| 1743 | disposition: EventAppendFailureDisposition, |
| 1744 | append_error: String, |
| 1745 | rollback_error: Option<String>, |
| 1746 | } |
| 1747 | |
| 1748 | #[derive(Debug, thiserror::Error)] |
| 1749 | #[error("Runtime event lock timed out after {0:?}")] |
| 1750 | struct RuntimeEventLockTimeout(Duration); |
| 1751 | |
| 1752 | impl RuntimeEventAppendError { |
| 1753 | const fn retry_safe(&self) -> bool { |
| 1754 | matches!(self.disposition, EventAppendFailureDisposition::RolledBack) |
| 1755 | } |
| 1756 | } |
| 1757 | |
| 1758 | impl std::fmt::Display for RuntimeEventAppendError { |
| 1759 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 1760 | match &self.rollback_error { |
| 1761 | Some(rollback_error) => write!( |
| 1762 | formatter, |
| 1763 | "Runtime event append is indeterminate after append error ({}) and rollback error ({})", |
| 1764 | self.append_error, rollback_error |
| 1765 | ), |
| 1766 | None => write!( |
| 1767 | formatter, |
| 1768 | "Runtime event append failed and was rolled back: {}", |
| 1769 | self.append_error |
| 1770 | ), |
| 1771 | } |
| 1772 | } |
| 1773 | } |
| 1774 | |
| 1775 | impl std::error::Error for RuntimeEventAppendError {} |
| 1776 | |
| 1777 | #[derive(Default)] |
| 1778 | struct RecoveryCompletionIndex { |
| 1779 | offset: u64, |
| 1780 | completed: HashSet<String>, |
| 1781 | } |
| 1782 | |
| 1783 | #[derive(Debug, Clone)] |
| 1784 | pub struct RuntimeThreadStore { |
| 1785 | threads_dir: PathBuf, |
| 1786 | turns_dir: PathBuf, |
| 1787 | items_dir: PathBuf, |
| 1788 | events_dir: PathBuf, |
| 1789 | goals_dir: PathBuf, |
| 1790 | /// Serializes goal controls and revision-fenced progress transactions. |
| 1791 | /// Acquired after `active` at admission; never held across an await. |
| 1792 | goal_mutation: Arc<parking_lot::Mutex<()>>, |
| 1793 | mail_store: agent_mail_store::AgentMailStore, |
| 1794 | turn_operations_dir: PathBuf, |
| 1795 | job_operations_dir: PathBuf, |
| 1796 | owner_id: String, |
| 1797 | state_path: PathBuf, |
| 1798 | event_lock_path: PathBuf, |
| 1799 | /// Serializes load-modify-save operations on thread records. The guard is |
| 1800 | /// synchronous and must never cross an `.await`; JSON records are small, |
| 1801 | /// and one global guard avoids per-thread lock lifecycle races. |
| 1802 | thread_mutation: Arc<parking_lot::Mutex<()>>, |
| 1803 | /// Serializes load-modify-save operations on turn records. Like the |
| 1804 | /// thread guard, it is synchronous and never crosses an `.await`. |
| 1805 | /// Reentrant so [`Self::save_turn`] can take the guard while an outer |
| 1806 | /// RMW transaction already holds it; every turn write goes through that |
| 1807 | /// path so a store-side settle cannot be stomped by a concurrent monitor |
| 1808 | /// save that loaded a stale in-flight copy. |
| 1809 | turn_mutation: Arc<parking_lot::ReentrantMutex<()>>, |
| 1810 | /// Serializes envelope claim/state transitions. The durable envelope is |
| 1811 | /// the queue; this guard prevents concurrent replay/wake requests from |
| 1812 | /// starting more than one turn for the same message. |
| 1813 | mail_mutation: Arc<parking_lot::Mutex<()>>, |
| 1814 | /// Turn id -> item ids, filled by one items-directory read and kept |
| 1815 | /// current by the item writers; see [`Self::item_ids_for_turns`]. |
| 1816 | item_index: Arc<parking_lot::RwLock<ItemIndex>>, |
| 1817 | /// Serializes the one items-directory read that fills `item_index`. Held |
| 1818 | /// across the whole read, so a caller that arrives while it runs waits for |
| 1819 | /// its result instead of repeating it — and so an item writer can tell |
| 1820 | /// whether a read is running by probing it. A writer never holds it, so a |
| 1821 | /// running turn's write is never behind a store-wide read. |
| 1822 | item_index_seed: Arc<parking_lot::Mutex<()>>, |
| 1823 | /// Whether this handle may write the store's caches. A live engine does; a |
| 1824 | /// read-only open does not, because its whole contract is that reading a |
| 1825 | /// thread never mutates a store another process owns. |
| 1826 | persist_caches: bool, |
| 1827 | /// Set when the index this process built differs from the cached one, so a |
| 1828 | /// later [`Self::cache_item_index`] knows there is something to write. |
| 1829 | item_index_differs_from_cache: Arc<std::sync::atomic::AtomicBool>, |
| 1830 | thread_progress: Arc<parking_lot::Mutex<HashMap<String, DateTime<Utc>>>>, |
| 1831 | /// Files read by whole-directory turn scans (`list_all_turns`). Shared |
| 1832 | /// across store clones so a `spawn_blocking` snapshot still counts against |
| 1833 | /// the manager the test holds. Per-store so parallel tests do not collide. |
| 1834 | #[cfg(any(test, feature = "test-support"))] |
| 1835 | turn_dir_files_read: Arc<std::sync::atomic::AtomicU64>, |
| 1836 | /// Files read by whole-directory item scans (`list_items_for_turn` and |
| 1837 | /// `list_items_for_turns_map`). |
| 1838 | #[cfg(any(test, feature = "test-support"))] |
| 1839 | item_dir_files_read: Arc<std::sync::atomic::AtomicU64>, |
| 1840 | } |
| 1841 | |
| 1842 | #[derive(Debug)] |
| 1843 | pub enum RuntimeDiagnosticRecord { |
| 1844 | Thread(Box<ThreadRecord>), |
| 1845 | Turn(Box<TurnRecord>), |
| 1846 | Item(Box<TurnItemRecord>), |
| 1847 | Event(Box<RuntimeEventRecord>), |
| 1848 | } |
| 1849 | |
| 1850 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1851 | struct RuntimeStoreOwner { |
| 1852 | owner_id: String, |
| 1853 | } |
| 1854 | |
| 1855 | /// Every item id the store holds, grouped by turn. |
| 1856 | /// |
| 1857 | /// An item's filename carries the item id and nothing else, so a reader that |
| 1858 | /// wants one thread's items has no way to ask the filesystem for them: the only |
| 1859 | /// answer is to read every item record. This makes that whole-directory read a |
| 1860 | /// one-time cost per store instead of a per-request one. |
| 1861 | #[derive(Debug, Default)] |
| 1862 | struct ItemIndex { |
| 1863 | /// `None` until the items directory has been read once. |
| 1864 | by_turn: Option<HashMap<String, Vec<String>>>, |
| 1865 | /// Item writes that landed while the directory read was running and may |
| 1866 | /// therefore have been missed by it. Drained into `by_turn` when it is |
| 1867 | /// published. Only writes that race a read are recorded; see |
| 1868 | /// [`RuntimeThreadStore::note_item_in_index`]. |
| 1869 | pending: Vec<(String, String)>, |
| 1870 | } |
| 1871 | |
| 1872 | /// The item index as it is kept between processes: item id to turn id. |
| 1873 | /// |
| 1874 | /// The in-memory index above answers "which items does this turn own", and it |
| 1875 | /// is built by reading every item record because an item's filename carries |
| 1876 | /// only its own id. That read is the cost of the first thread a process opens |
| 1877 | /// (see [`RuntimeThreadStore::ensure_item_index`]), and it is paid again by |
| 1878 | /// every new process — a restarted engine, a `codewhale receipts` run — because |
| 1879 | /// until now the answer lived only in memory. |
| 1880 | /// |
| 1881 | /// This file is that answer on disk. It is a cache and nothing more: an id |
| 1882 | /// names one turn for the life of the record, so an entry can be stale only by |
| 1883 | /// naming an item that is gone, and the directory listing — which costs a |
| 1884 | /// `readdir`, not a record read — is what decides which entries still count. A |
| 1885 | /// missing, unreadable or out-of-date file therefore costs one full read and |
| 1886 | /// nothing worse, exactly what every open used to cost. |
| 1887 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 1888 | struct PersistedItemIndex { |
| 1889 | schema_version: u32, |
| 1890 | /// Item id -> the turn that owns it. |
| 1891 | by_item: HashMap<String, String>, |
| 1892 | } |
| 1893 | |
| 1894 | /// Bumped only if the shape of [`PersistedItemIndex`] changes. A file carrying |
| 1895 | /// another version is ignored and rebuilt, so this is never a migration. |
| 1896 | const ITEM_INDEX_SCHEMA_VERSION: u32 = 1; |
| 1897 | |
| 1898 | /// The cached item index, beside the directories it describes. It is not inside |
| 1899 | /// `items/`: that directory is read as "one file is one item", and a cache in it |
| 1900 | /// would be read as an item. |
| 1901 | const ITEM_INDEX_CACHE_FILE: &str = "item-index.json"; |
| 1902 | |
| 1903 | /// The one field a whole-directory read needs from an item record. Deserializing |
| 1904 | /// into this instead of [`TurnItemRecord`] skips every string in `detail` and |
| 1905 | /// `metadata`, which is most of a tool result's bytes. |
| 1906 | #[derive(Debug, Deserialize)] |
| 1907 | struct ItemTurnReference { |
| 1908 | turn_id: String, |
| 1909 | } |
| 1910 | |
| 1911 | impl RuntimeThreadStore { |
| 1912 | pub fn open(root: PathBuf) -> Result<Self> { |
| 1913 | let root = checked_runtime_store_root(root)?; |
| 1914 | ensure_runtime_store_dir(&root)?; |
| 1915 | let threads_dir = root.join("threads"); |
| 1916 | let turns_dir = root.join("turns"); |
| 1917 | let items_dir = root.join("items"); |
| 1918 | let events_dir = root.join("events"); |
| 1919 | let goals_dir = root.join("goals"); |
| 1920 | let mail_dir = root.join("agent-mail"); |
| 1921 | let turn_operations_dir = root.join("turn-operations"); |
| 1922 | let job_operations_dir = root.join("job-operations"); |
| 1923 | ensure_runtime_store_dir(&threads_dir)?; |
| 1924 | ensure_runtime_store_dir(&turns_dir)?; |
| 1925 | ensure_runtime_store_dir(&items_dir)?; |
| 1926 | ensure_runtime_store_dir(&events_dir)?; |
| 1927 | ensure_runtime_store_dir(&goals_dir)?; |
| 1928 | ensure_runtime_store_dir(&mail_dir)?; |
| 1929 | ensure_runtime_store_dir(&turn_operations_dir)?; |
| 1930 | ensure_runtime_store_dir(&job_operations_dir)?; |
| 1931 | let state_path = root.join("state.json"); |
| 1932 | let owner_path = root.join(AGENT_MAIL_OWNER_FILE); |
| 1933 | let event_lock_path = root.join(EVENT_TRANSACTION_LOCK_FILE); |
| 1934 | // The owner namespaces operation-key fingerprints. Creating it outside |
| 1935 | // a cross-process transaction lets two first-start processes mint |
| 1936 | // different owners, and therefore different operation locks, for the |
| 1937 | // same store. Reuse the root event lock before any owner-derived path |
| 1938 | // is computed so all processes load exactly one durable owner. |
| 1939 | let owner_id = load_or_create_runtime_store_owner(&owner_path, &event_lock_path)?; |
| 1940 | let store = Self { |
| 1941 | threads_dir, |
| 1942 | turns_dir, |
| 1943 | items_dir, |
| 1944 | events_dir, |
| 1945 | goals_dir, |
| 1946 | mail_store: agent_mail_store::AgentMailStore::new(mail_dir), |
| 1947 | turn_operations_dir, |
| 1948 | job_operations_dir, |
| 1949 | owner_id, |
| 1950 | state_path, |
| 1951 | event_lock_path, |
| 1952 | thread_mutation: Arc::new(parking_lot::Mutex::new(())), |
| 1953 | turn_mutation: Arc::new(parking_lot::ReentrantMutex::new(())), |
| 1954 | goal_mutation: Arc::new(parking_lot::Mutex::new(())), |
| 1955 | mail_mutation: Arc::new(parking_lot::Mutex::new(())), |
| 1956 | item_index: Arc::new(parking_lot::RwLock::new(ItemIndex::default())), |
| 1957 | item_index_seed: Arc::new(parking_lot::Mutex::new(())), |
| 1958 | persist_caches: true, |
| 1959 | item_index_differs_from_cache: Arc::new(std::sync::atomic::AtomicBool::new(false)), |
| 1960 | thread_progress: Arc::new(parking_lot::Mutex::new(HashMap::new())), |
| 1961 | #[cfg(any(test, feature = "test-support"))] |
| 1962 | turn_dir_files_read: Arc::new(std::sync::atomic::AtomicU64::new(0)), |
| 1963 | #[cfg(any(test, feature = "test-support"))] |
| 1964 | item_dir_files_read: Arc::new(std::sync::atomic::AtomicU64::new(0)), |
| 1965 | }; |
| 1966 | store.with_event_transaction(EVENT_TRANSACTION_LOCK_TIMEOUT, || { |
| 1967 | repair_torn_event_log_tails(&store.events_dir)?; |
| 1968 | if store.state_path.exists() { |
| 1969 | load_runtime_store_state(&store.state_path)?; |
| 1970 | } else { |
| 1971 | write_json_atomic(&store.state_path, &RuntimeStoreState::default())?; |
| 1972 | } |
| 1973 | Ok(()) |
| 1974 | })?; |
| 1975 | store.recover_incomplete_turn_operations()?; |
| 1976 | store.recover_claimed_agent_mail()?; |
| 1977 | Ok(store) |
| 1978 | } |
| 1979 | |
| 1980 | /// Open an existing store only to read it: no directories, owner file, |
| 1981 | /// torn-tail repair, or recovery. `None` when `root` holds no store. |
| 1982 | /// Offline readers (`codewhale receipts`) use this so reading a thread |
| 1983 | /// never mutates a store a live `codewhale serve` may own. Event reads |
| 1984 | /// still take the shared event lock, so they see only committed records. |
| 1985 | /// |
| 1986 | /// The item index this store builds (see [`Self::ensure_item_index`]) is |
| 1987 | /// a snapshot of one open: a store another process owns keeps writing |
| 1988 | /// items, and those are invisible here until the next open reads the |
| 1989 | /// directory again. That is the contract every caller already lives |
| 1990 | /// under — `codewhale receipts` opens the store once per invocation and |
| 1991 | /// exits — so holding an instance across foreign writes serves no |
| 1992 | /// caller today. If one ever does, invalidate or reopen rather than |
| 1993 | /// serving a stale map silently. |
| 1994 | pub fn open_read_only(root: PathBuf) -> Result<Option<Self>> { |
| 1995 | let root = checked_runtime_store_root(root)?; |
| 1996 | let threads_dir = root.join("threads"); |
| 1997 | if !threads_dir.is_dir() { |
| 1998 | return Ok(None); |
| 1999 | } |
| 2000 | Ok(Some(Self { |
| 2001 | threads_dir, |
| 2002 | turns_dir: root.join("turns"), |
| 2003 | items_dir: root.join("items"), |
| 2004 | events_dir: root.join("events"), |
| 2005 | goals_dir: root.join("goals"), |
| 2006 | mail_store: agent_mail_store::AgentMailStore::new(root.join("agent-mail")), |
| 2007 | turn_operations_dir: root.join("turn-operations"), |
| 2008 | job_operations_dir: root.join("job-operations"), |
| 2009 | owner_id: String::new(), |
| 2010 | state_path: root.join("state.json"), |
| 2011 | event_lock_path: root.join(EVENT_TRANSACTION_LOCK_FILE), |
| 2012 | thread_mutation: Arc::new(parking_lot::Mutex::new(())), |
| 2013 | turn_mutation: Arc::new(parking_lot::ReentrantMutex::new(())), |
| 2014 | goal_mutation: Arc::new(parking_lot::Mutex::new(())), |
| 2015 | mail_mutation: Arc::new(parking_lot::Mutex::new(())), |
| 2016 | item_index: Arc::new(parking_lot::RwLock::new(ItemIndex::default())), |
| 2017 | item_index_seed: Arc::new(parking_lot::Mutex::new(())), |
| 2018 | persist_caches: false, |
| 2019 | item_index_differs_from_cache: Arc::new(std::sync::atomic::AtomicBool::new(false)), |
| 2020 | thread_progress: Arc::new(parking_lot::Mutex::new(HashMap::new())), |
| 2021 | #[cfg(any(test, feature = "test-support"))] |
| 2022 | turn_dir_files_read: Arc::new(std::sync::atomic::AtomicU64::new(0)), |
| 2023 | #[cfg(any(test, feature = "test-support"))] |
| 2024 | item_dir_files_read: Arc::new(std::sync::atomic::AtomicU64::new(0)), |
| 2025 | })) |
| 2026 | } |
| 2027 | |
| 2028 | pub fn recent_mission_mail( |
| 2029 | &self, |
| 2030 | workspace: &Path, |
| 2031 | run_id: &str, |
| 2032 | limit: usize, |
| 2033 | ) -> Result<Vec<codewhale_protocol::agent_mail::MissionMailEvent>> { |
| 2034 | anyhow::ensure!((1..=100).contains(&limit), "Invalid mission mail limit"); |
| 2035 | let root = self |
| 2036 | .threads_dir |
| 2037 | .parent() |
| 2038 | .context("Runtime store has no root")?; |
| 2039 | let owner_path = root.join(AGENT_MAIL_OWNER_FILE); |
| 2040 | let Some(owner_id) = read_runtime_store_owner(&owner_path)? else { |
| 2041 | return Ok(Vec::new()); |
| 2042 | }; |
| 2043 | let scope = format!("{}:{run_id}", manager::agent_mail_workspace_id(workspace)?); |
| 2044 | self.mail_store |
| 2045 | .recent_mission_events(&scope, &owner_id, limit) |
| 2046 | } |
| 2047 | |
| 2048 | fn open_diagnostic_file(&self, path: &Path) -> Result<File> { |
| 2049 | let root = self |
| 2050 | .threads_dir |
| 2051 | .parent() |
| 2052 | .context("Runtime diagnostic store has no root")?; |
| 2053 | let relative = path |
| 2054 | .strip_prefix(root) |
| 2055 | .context("Runtime diagnostic file escaped its store")?; |
| 2056 | let file = codewhale_util::files::WorkspaceFile::open_resolved_root(root, relative, false)? |
| 2057 | .open_file()?; |
| 2058 | runtime_store_file_identity(&file)?; |
| 2059 | Ok(file) |
| 2060 | } |
| 2061 | |
| 2062 | pub fn visit_diagnostic_records( |
| 2063 | &self, |
| 2064 | mut visit: impl FnMut(Result<RuntimeDiagnosticRecord>) -> Result<()>, |
| 2065 | ) -> Result<()> { |
| 2066 | self.visit_diagnostic_records_while(|record| { |
| 2067 | visit(record)?; |
| 2068 | Ok(std::ops::ControlFlow::Continue(())) |
| 2069 | }) |
| 2070 | } |
| 2071 | |
| 2072 | pub fn visit_diagnostic_records_while( |
| 2073 | &self, |
| 2074 | mut visit: impl FnMut(Result<RuntimeDiagnosticRecord>) -> Result<std::ops::ControlFlow<()>>, |
| 2075 | ) -> Result<()> { |
| 2076 | let limit = crate::session_manager::SESSION_METADATA_READ_LIMIT as u64; |
| 2077 | for (directory, kind) in [ |
| 2078 | (&self.threads_dir, RuntimeStoreRecordKind::Thread), |
| 2079 | (&self.turns_dir, RuntimeStoreRecordKind::Turn), |
| 2080 | (&self.items_dir, RuntimeStoreRecordKind::Item), |
| 2081 | ] { |
| 2082 | let entries = match checked_existing_runtime_store_dir(directory) |
| 2083 | .and_then(|directory| fs::read_dir(directory).map_err(anyhow::Error::from)) |
| 2084 | { |
| 2085 | Ok(entries) => entries, |
| 2086 | Err(error) => { |
| 2087 | if visit(Err(error))?.is_break() { |
| 2088 | return Ok(()); |
| 2089 | } |
| 2090 | continue; |
| 2091 | } |
| 2092 | }; |
| 2093 | let mut paths = Vec::new(); |
| 2094 | for entry in entries { |
| 2095 | match entry { |
| 2096 | Ok(entry) => paths.push(entry.path()), |
| 2097 | Err(error) => { |
| 2098 | if visit(Err(error.into()))?.is_break() { |
| 2099 | return Ok(()); |
| 2100 | } |
| 2101 | } |
| 2102 | } |
| 2103 | } |
| 2104 | paths.sort(); |
| 2105 | for path in paths { |
| 2106 | let result = (|| -> Result<Option<RuntimeDiagnosticRecord>> { |
| 2107 | if path.extension().is_none_or(|extension| extension != "json") { |
| 2108 | return Ok(None); |
| 2109 | } |
| 2110 | let file = self.open_diagnostic_file(&path)?; |
| 2111 | let mut raw = Vec::new(); |
| 2112 | file.take(limit + 1).read_to_end(&mut raw)?; |
| 2113 | if raw.len() as u64 > limit { |
| 2114 | return Err(io::Error::new( |
| 2115 | io::ErrorKind::FileTooLarge, |
| 2116 | "Runtime diagnostic record exceeds the session inspection limit", |
| 2117 | ) |
| 2118 | .into()); |
| 2119 | } |
| 2120 | let record = match kind { |
| 2121 | RuntimeStoreRecordKind::Thread => { |
| 2122 | let record: ThreadRecord = serde_json::from_slice(&raw)?; |
| 2123 | if path.file_stem().and_then(|name| name.to_str()) |
| 2124 | != Some(record.id.as_str()) |
| 2125 | { |
| 2126 | bail!("Runtime diagnostic record id does not match its file"); |
| 2127 | } |
| 2128 | if record.schema_version > MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION { |
| 2129 | bail!("unsupported Runtime diagnostic thread schema"); |
| 2130 | } |
| 2131 | RuntimeDiagnosticRecord::Thread(Box::new(record)) |
| 2132 | } |
| 2133 | RuntimeStoreRecordKind::Turn => { |
| 2134 | let record: TurnRecord = serde_json::from_slice(&raw)?; |
| 2135 | if path.file_stem().and_then(|name| name.to_str()) |
| 2136 | != Some(record.id.as_str()) |
| 2137 | { |
| 2138 | bail!("Runtime diagnostic record id does not match its file"); |
| 2139 | } |
| 2140 | record.validate_output_token_limit()?; |
| 2141 | RuntimeDiagnosticRecord::Turn(Box::new(record)) |
| 2142 | } |
| 2143 | RuntimeStoreRecordKind::Item => { |
| 2144 | let record: TurnItemRecord = serde_json::from_slice(&raw)?; |
| 2145 | if path.file_stem().and_then(|name| name.to_str()) |
| 2146 | != Some(record.id.as_str()) |
| 2147 | { |
| 2148 | bail!("Runtime diagnostic record id does not match its file"); |
| 2149 | } |
| 2150 | if record.schema_version > MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION { |
| 2151 | bail!("unsupported Runtime diagnostic item schema"); |
| 2152 | } |
| 2153 | if record.kind == TurnItemKind::UserMessage { |
| 2154 | record.user_content()?; |
| 2155 | } |
| 2156 | RuntimeDiagnosticRecord::Item(Box::new(record)) |
| 2157 | } |
| 2158 | }; |
| 2159 | Ok(Some(record)) |
| 2160 | })(); |
| 2161 | match result { |
| 2162 | Ok(Some(record)) => { |
| 2163 | if visit(Ok(record))?.is_break() { |
| 2164 | return Ok(()); |
| 2165 | } |
| 2166 | } |
| 2167 | Ok(None) => {} |
| 2168 | Err(error) => { |
| 2169 | if visit(Err(error))?.is_break() { |
| 2170 | return Ok(()); |
| 2171 | } |
| 2172 | } |
| 2173 | } |
| 2174 | } |
| 2175 | } |
| 2176 | let directory = match checked_existing_runtime_store_dir(&self.events_dir) { |
| 2177 | Ok(directory) => directory, |
| 2178 | Err(error) => { |
| 2179 | let _ = visit(Err(error))?; |
| 2180 | return Ok(()); |
| 2181 | } |
| 2182 | }; |
| 2183 | let mut event_paths = Vec::new(); |
| 2184 | for entry in fs::read_dir(directory)? { |
| 2185 | match entry { |
| 2186 | Ok(entry) => event_paths.push(entry.path()), |
| 2187 | Err(error) => { |
| 2188 | if visit(Err(error.into()))?.is_break() { |
| 2189 | return Ok(()); |
| 2190 | } |
| 2191 | } |
| 2192 | } |
| 2193 | } |
| 2194 | event_paths.sort(); |
| 2195 | for path in event_paths { |
| 2196 | let result = (|| -> Result<Option<(RuntimeEventReader, String)>> { |
| 2197 | if path |
| 2198 | .extension() |
| 2199 | .is_none_or(|extension| extension != "jsonl") |
| 2200 | { |
| 2201 | return Ok(None); |
| 2202 | } |
| 2203 | let thread_id = path |
| 2204 | .file_stem() |
| 2205 | .and_then(|id| id.to_str()) |
| 2206 | .context("Runtime diagnostic event filename is not a thread id")? |
| 2207 | .to_string(); |
| 2208 | validated_record_id(&thread_id, "diagnostic thread id")?; |
| 2209 | let lock_file = self.open_diagnostic_file(&self.event_lock_path)?; |
| 2210 | let lock = fd_lock::RwLock::new(lock_file); |
| 2211 | let started = Instant::now(); |
| 2212 | loop { |
| 2213 | match lock.try_read() { |
| 2214 | Ok(guard) => { |
| 2215 | validate_same_runtime_store_file_handles( |
| 2216 | &guard, |
| 2217 | &self.open_diagnostic_file(&self.event_lock_path)?, |
| 2218 | &self.event_lock_path, |
| 2219 | )?; |
| 2220 | let file = self.open_diagnostic_file(&path)?; |
| 2221 | let committed = file.metadata()?.len(); |
| 2222 | return Ok(Some((BufReader::new(file.take(committed)), thread_id))); |
| 2223 | } |
| 2224 | Err(error) |
| 2225 | if matches!( |
| 2226 | error.kind(), |
| 2227 | io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted |
| 2228 | ) => |
| 2229 | { |
| 2230 | wait_for_event_lock(started, EVENT_TRANSACTION_LOCK_TIMEOUT)? |
| 2231 | } |
| 2232 | Err(error) => return Err(error.into()), |
| 2233 | } |
| 2234 | } |
| 2235 | })(); |
| 2236 | let (mut reader, thread_id) = match result { |
| 2237 | Ok(Some(reader)) => reader, |
| 2238 | Ok(None) => continue, |
| 2239 | Err(error) => { |
| 2240 | if visit(Err(error))?.is_break() { |
| 2241 | return Ok(()); |
| 2242 | } |
| 2243 | continue; |
| 2244 | } |
| 2245 | }; |
| 2246 | loop { |
| 2247 | let mut raw = Vec::new(); |
| 2248 | let count = reader |
| 2249 | .by_ref() |
| 2250 | .take(limit + 1) |
| 2251 | .read_until(b'\n', &mut raw)?; |
| 2252 | if count == 0 { |
| 2253 | break; |
| 2254 | } |
| 2255 | if raw.len() as u64 > limit { |
| 2256 | if visit(Err(io::Error::new( |
| 2257 | io::ErrorKind::FileTooLarge, |
| 2258 | "Runtime diagnostic event exceeds the session inspection limit", |
| 2259 | ) |
| 2260 | .into()))? |
| 2261 | .is_break() |
| 2262 | { |
| 2263 | return Ok(()); |
| 2264 | } |
| 2265 | break; |
| 2266 | } |
| 2267 | if !raw.ends_with(b"\n") { |
| 2268 | if visit(Err(anyhow!("Runtime diagnostic event tail is incomplete")))? |
| 2269 | .is_break() |
| 2270 | { |
| 2271 | return Ok(()); |
| 2272 | } |
| 2273 | break; |
| 2274 | } |
| 2275 | if raw.iter().all(u8::is_ascii_whitespace) { |
| 2276 | continue; |
| 2277 | } |
| 2278 | let event = serde_json::from_slice::<RuntimeEventRecord>(&raw).and_then(|event| { |
| 2279 | if event.schema_version > MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION { |
| 2280 | return Err(serde::de::Error::custom( |
| 2281 | "unsupported Runtime diagnostic event schema", |
| 2282 | )); |
| 2283 | } |
| 2284 | if event.thread_id != thread_id { |
| 2285 | return Err(serde::de::Error::custom( |
| 2286 | "Runtime diagnostic event thread does not match its file", |
| 2287 | )); |
| 2288 | } |
| 2289 | Ok(RuntimeDiagnosticRecord::Event(Box::new(event))) |
| 2290 | }); |
| 2291 | if visit(event.map_err(anyhow::Error::from))?.is_break() { |
| 2292 | return Ok(()); |
| 2293 | } |
| 2294 | } |
| 2295 | } |
| 2296 | Ok(()) |
| 2297 | } |
| 2298 | |
| 2299 | fn open_event_lock(&self) -> Result<File> { |
| 2300 | let file = |
| 2301 | open_runtime_store_file(&self.event_lock_path, "Runtime event lock", |options| { |
| 2302 | options.create(true).truncate(false).read(true).write(true); |
| 2303 | })?; |
| 2304 | #[cfg(unix)] |
| 2305 | { |
| 2306 | use std::os::unix::fs::PermissionsExt as _; |
| 2307 | file.set_permissions(fs::Permissions::from_mode(0o600)) |
| 2308 | .context("Failed to secure Runtime event lock")?; |
| 2309 | } |
| 2310 | Ok(file) |
| 2311 | } |
| 2312 | |
| 2313 | fn with_event_transaction<T>( |
| 2314 | &self, |
| 2315 | timeout: Duration, |
| 2316 | operation: impl FnOnce() -> Result<T>, |
| 2317 | ) -> Result<T> { |
| 2318 | let mut lock = fd_lock::RwLock::new(self.open_event_lock()?); |
| 2319 | let started = Instant::now(); |
| 2320 | let mut operation = Some(operation); |
| 2321 | loop { |
| 2322 | match lock |
| 2323 | .try_write() |
| 2324 | .map(|_guard| operation.take().expect("event transaction runs once")()) |
| 2325 | { |
| 2326 | Ok(result) => return result, |
| 2327 | Err(error) |
| 2328 | if matches!( |
| 2329 | error.kind(), |
| 2330 | std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted |
| 2331 | ) => |
| 2332 | { |
| 2333 | wait_for_event_lock(started, timeout)?; |
| 2334 | } |
| 2335 | Err(error) => return Err(error).context("Failed to lock Runtime events"), |
| 2336 | } |
| 2337 | } |
| 2338 | } |
| 2339 | |
| 2340 | fn record_path(base: &Path, id: &str, extension: &str, label: &str) -> Result<PathBuf> { |
| 2341 | let id = validated_record_id(id, label)?; |
| 2342 | Ok(base.join(format!("{id}.{extension}"))) |
| 2343 | } |
| 2344 | |
| 2345 | fn thread_path(&self, thread_id: &str) -> Result<PathBuf> { |
| 2346 | Self::record_path(&self.threads_dir, thread_id, "json", "thread id") |
| 2347 | } |
| 2348 | |
| 2349 | fn turn_path(&self, turn_id: &str) -> Result<PathBuf> { |
| 2350 | Self::record_path(&self.turns_dir, turn_id, "json", "turn id") |
| 2351 | } |
| 2352 | |
| 2353 | fn item_path(&self, item_id: &str) -> Result<PathBuf> { |
| 2354 | Self::record_path(&self.items_dir, item_id, "json", "item id") |
| 2355 | } |
| 2356 | |
| 2357 | fn events_path(&self, thread_id: &str) -> Result<PathBuf> { |
| 2358 | Self::record_path(&self.events_dir, thread_id, "jsonl", "thread id") |
| 2359 | } |
| 2360 | |
| 2361 | fn goal_path(&self, thread_id: &str) -> Result<PathBuf> { |
| 2362 | Self::record_path(&self.goals_dir, thread_id, "json", "thread id") |
| 2363 | } |
| 2364 | |
| 2365 | fn turn_operation_path(&self, operation_key_fingerprint: &str) -> Result<PathBuf> { |
| 2366 | validate_sha256_fingerprint(operation_key_fingerprint, "operation key fingerprint")?; |
| 2367 | Self::record_path( |
| 2368 | &self.turn_operations_dir, |
| 2369 | &format!("op_{operation_key_fingerprint}"), |
| 2370 | "json", |
| 2371 | "turn operation binding id", |
| 2372 | ) |
| 2373 | } |
| 2374 | |
| 2375 | fn history_operation_path(&self, fingerprint: &str) -> Result<PathBuf> { |
| 2376 | validate_sha256_fingerprint(fingerprint, "history operation fingerprint")?; |
| 2377 | Self::record_path( |
| 2378 | &self.turn_operations_dir, |
| 2379 | &format!("history_{fingerprint}"), |
| 2380 | "json", |
| 2381 | "history operation", |
| 2382 | ) |
| 2383 | } |
| 2384 | |
| 2385 | fn thread_create_operation_path(&self, fingerprint: &str) -> Result<PathBuf> { |
| 2386 | validate_sha256_fingerprint(fingerprint, "thread creation operation fingerprint")?; |
| 2387 | Self::record_path( |
| 2388 | &self.turn_operations_dir, |
| 2389 | &format!("thread_create_{fingerprint}"), |
| 2390 | "json", |
| 2391 | "thread creation operation", |
| 2392 | ) |
| 2393 | } |
| 2394 | |
| 2395 | fn load_history_operation(&self, fingerprint: &str) -> Result<Option<RuntimeHistoryOperation>> { |
| 2396 | let path = self.history_operation_path(fingerprint)?; |
| 2397 | let raw = match read_store_file(&path) { |
| 2398 | Ok(raw) => raw, |
| 2399 | Err(error) |
| 2400 | if error |
| 2401 | .downcast_ref::<std::io::Error>() |
| 2402 | .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) => |
| 2403 | { |
| 2404 | return Ok(None); |
| 2405 | } |
| 2406 | Err(error) => return Err(error), |
| 2407 | }; |
| 2408 | let operation: RuntimeHistoryOperation = serde_json::from_str(&raw)?; |
| 2409 | operation.validate()?; |
| 2410 | anyhow::ensure!( |
| 2411 | operation.key_fingerprint == fingerprint, |
| 2412 | "history operation filename does not match its binding" |
| 2413 | ); |
| 2414 | Ok(Some(operation)) |
| 2415 | } |
| 2416 | |
| 2417 | fn save_history_operation(&self, operation: &RuntimeHistoryOperation) -> Result<()> { |
| 2418 | operation.validate()?; |
| 2419 | write_json_atomic( |
| 2420 | &self.history_operation_path(&operation.key_fingerprint)?, |
| 2421 | operation, |
| 2422 | ) |
| 2423 | } |
| 2424 | |
| 2425 | fn turn_operation_lock_path(&self, operation_key_fingerprint: &str) -> Result<PathBuf> { |
| 2426 | validate_sha256_fingerprint(operation_key_fingerprint, "operation key fingerprint")?; |
| 2427 | Self::record_path( |
| 2428 | &self.turn_operations_dir, |
| 2429 | &format!("op_{operation_key_fingerprint}"), |
| 2430 | "lock", |
| 2431 | "turn operation claim lock id", |
| 2432 | ) |
| 2433 | } |
| 2434 | |
| 2435 | fn open_turn_operation_claim_lock(&self, operation_key_fingerprint: &str) -> Result<File> { |
| 2436 | let path = self.turn_operation_lock_path(operation_key_fingerprint)?; |
| 2437 | open_runtime_store_file(&path, "Runtime turn operation claim lock", |options| { |
| 2438 | options.create(true).truncate(false).read(true).write(true); |
| 2439 | }) |
| 2440 | } |
| 2441 | |
| 2442 | fn with_turn_operation_claim<T>( |
| 2443 | &self, |
| 2444 | operation_key_fingerprint: Option<&str>, |
| 2445 | operation: impl FnOnce() -> Result<T>, |
| 2446 | ) -> Result<T> { |
| 2447 | let Some(operation_key_fingerprint) = operation_key_fingerprint else { |
| 2448 | return operation(); |
| 2449 | }; |
| 2450 | let mut claim = |
| 2451 | fd_lock::RwLock::new(self.open_turn_operation_claim_lock(operation_key_fingerprint)?); |
| 2452 | let _guard = self.acquire_turn_operation_claim(&mut claim)?; |
| 2453 | operation() |
| 2454 | } |
| 2455 | |
| 2456 | fn acquire_turn_operation_claim<'a>( |
| 2457 | &self, |
| 2458 | claim: &'a mut fd_lock::RwLock<File>, |
| 2459 | ) -> Result<fd_lock::RwLockWriteGuard<'a, File>> { |
| 2460 | match claim.try_write() { |
| 2461 | Ok(guard) => Ok(guard), |
| 2462 | Err(error) |
| 2463 | if matches!( |
| 2464 | error.kind(), |
| 2465 | std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted |
| 2466 | ) => |
| 2467 | { |
| 2468 | bail!("Runtime turn operation is already being claimed; retry") |
| 2469 | } |
| 2470 | Err(error) => Err(error).context("Failed to claim Runtime turn operation"), |
| 2471 | } |
| 2472 | } |
| 2473 | |
| 2474 | fn recover_incomplete_turn_operations(&self) -> Result<()> { |
| 2475 | let operations_dir = checked_existing_runtime_store_dir(&self.turn_operations_dir)?; |
| 2476 | for entry in fs::read_dir(&operations_dir) |
| 2477 | .with_context(|| format!("Failed to read {}", operations_dir.display()))? |
| 2478 | { |
| 2479 | let path = entry?.path(); |
| 2480 | if path.extension().is_none_or(|extension| extension != "json") { |
| 2481 | continue; |
| 2482 | } |
| 2483 | let raw = read_store_file(&path) |
| 2484 | .with_context(|| format!("Failed to read {}", path.display()))?; |
| 2485 | if path |
| 2486 | .file_stem() |
| 2487 | .and_then(|name| name.to_str()) |
| 2488 | .is_some_and(|name| name.starts_with("thread_create_")) |
| 2489 | { |
| 2490 | let binding: RuntimeThreadCreateBinding = serde_json::from_str(&raw)?; |
| 2491 | binding.validate()?; |
| 2492 | anyhow::ensure!( |
| 2493 | path == self |
| 2494 | .thread_create_operation_path(&binding.operation_key_fingerprint)?, |
| 2495 | "thread creation operation path mismatch" |
| 2496 | ); |
| 2497 | continue; |
| 2498 | } |
| 2499 | if path |
| 2500 | .file_stem() |
| 2501 | .and_then(|name| name.to_str()) |
| 2502 | .is_some_and(|name| name.starts_with("history_")) |
| 2503 | { |
| 2504 | let history: RuntimeHistoryOperation = serde_json::from_str(&raw)?; |
| 2505 | history.validate()?; |
| 2506 | anyhow::ensure!( |
| 2507 | path == self.history_operation_path(&history.key_fingerprint)?, |
| 2508 | "history operation path mismatch" |
| 2509 | ); |
| 2510 | // Keep both reserved and committed work: a retry observes this |
| 2511 | // exact identity instead of replaying an uncertain creation. |
| 2512 | continue; |
| 2513 | } |
| 2514 | let observed: RuntimeTurnOperationBinding = serde_json::from_str(&raw) |
| 2515 | .with_context(|| format!("Failed to parse {}", path.display()))?; |
| 2516 | observed.validate()?; |
| 2517 | self.with_turn_operation_claim(Some(&observed.operation_key_fingerprint), || { |
| 2518 | // A live writer may have replaced the file between the |
| 2519 | // directory scan and this claim. Re-read under the same |
| 2520 | // cross-process lock used by `start_turn`. Ambiguous |
| 2521 | // reservations remain available for exact receipt lookup. |
| 2522 | let Some(_binding) = |
| 2523 | self.load_turn_operation_binding(&observed.operation_key_fingerprint)? |
| 2524 | else { |
| 2525 | return Ok(()); |
| 2526 | }; |
| 2527 | Ok(()) |
| 2528 | })?; |
| 2529 | } |
| 2530 | Ok(()) |
| 2531 | } |
| 2532 | |
| 2533 | fn save_turn_operation_binding(&self, binding: &RuntimeTurnOperationBinding) -> Result<()> { |
| 2534 | binding.validate()?; |
| 2535 | write_json_atomic( |
| 2536 | &self.turn_operation_path(&binding.operation_key_fingerprint)?, |
| 2537 | binding, |
| 2538 | ) |
| 2539 | } |
| 2540 | |
| 2541 | fn load_turn_operation_binding( |
| 2542 | &self, |
| 2543 | operation_key_fingerprint: &str, |
| 2544 | ) -> Result<Option<RuntimeTurnOperationBinding>> { |
| 2545 | let path = self.turn_operation_path(operation_key_fingerprint)?; |
| 2546 | let raw = match read_store_file(&path) { |
| 2547 | Ok(raw) => raw, |
| 2548 | Err(error) |
| 2549 | if error |
| 2550 | .downcast_ref::<std::io::Error>() |
| 2551 | .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) => |
| 2552 | { |
| 2553 | return Ok(None); |
| 2554 | } |
| 2555 | Err(error) => { |
| 2556 | return Err(error).with_context(|| { |
| 2557 | format!("Failed to read Runtime turn operation {}", path.display()) |
| 2558 | }); |
| 2559 | } |
| 2560 | }; |
| 2561 | let binding: RuntimeTurnOperationBinding = |
| 2562 | serde_json::from_str(&raw).with_context(|| { |
| 2563 | format!("Failed to parse Runtime turn operation {}", path.display()) |
| 2564 | })?; |
| 2565 | binding.validate()?; |
| 2566 | Ok(Some(binding)) |
| 2567 | } |
| 2568 | |
| 2569 | fn recover_claimed_agent_mail(&self) -> Result<()> { |
| 2570 | let _mail_mutation = self.mail_mutation.lock(); |
| 2571 | for mut mail in self.list_agent_mail()? { |
| 2572 | if mail.status != AgentMailStatus::Delivering { |
| 2573 | continue; |
| 2574 | } |
| 2575 | mail.status = AgentMailStatus::Failed; |
| 2576 | mail.failure = Some(AgentMailFailureReceipt { |
| 2577 | code: AgentMailFailureCode::DeliveryRejected, |
| 2578 | message: "Delivery claim recovered after runtime restart".to_string(), |
| 2579 | retryable: true, |
| 2580 | failed_at: Utc::now(), |
| 2581 | }); |
| 2582 | self.save_agent_mail(&mail)?; |
| 2583 | } |
| 2584 | Ok(()) |
| 2585 | } |
| 2586 | |
| 2587 | fn save_agent_mail(&self, mail: &AgentMailEnvelope) -> Result<()> { |
| 2588 | self.mail_store.save(mail) |
| 2589 | } |
| 2590 | |
| 2591 | fn load_agent_mail(&self, message_id: &AgentMailMessageId) -> Result<AgentMailEnvelope> { |
| 2592 | self.mail_store |
| 2593 | .load(message_id)? |
| 2594 | .with_context(|| format!("Agent Mail message {message_id} not found")) |
| 2595 | } |
| 2596 | |
| 2597 | fn list_agent_mail(&self) -> Result<Vec<AgentMailEnvelope>> { |
| 2598 | self.mail_store.list(None) |
| 2599 | } |
| 2600 | |
| 2601 | /// Persist a goal record for a thread. The goal is stored as a JSON file |
| 2602 | /// in the `goals/` subdirectory; it is independent of the TUI state store |
| 2603 | /// and requires only that the runtime thread exists. |
| 2604 | #[cfg(any(test, feature = "test-support"))] |
| 2605 | pub fn save_goal(&self, goal: &codewhale_protocol::ThreadGoal) -> Result<()> { |
| 2606 | let _guard = self.goal_mutation.lock(); |
| 2607 | self.save_goal_under_lock(goal) |
| 2608 | } |
| 2609 | |
| 2610 | fn save_goal_under_lock(&self, goal: &codewhale_protocol::ThreadGoal) -> Result<()> { |
| 2611 | goal.validate_stall_state().map_err(anyhow::Error::msg)?; |
| 2612 | write_json_atomic(&self.goal_path(&goal.thread_id)?, goal) |
| 2613 | } |
| 2614 | |
| 2615 | /// Load the goal for a thread, returning `None` if no goal has been set. |
| 2616 | /// A corrupt record that is still Active with an exhausted stall window |
| 2617 | /// is restored paused: the engine pauses NoProgress in the same locked |
| 2618 | /// mutation that fills the window, so Active-at-ceiling can only come |
| 2619 | /// from an interrupted write. |
| 2620 | pub fn load_goal(&self, thread_id: &str) -> Result<Option<codewhale_protocol::ThreadGoal>> { |
| 2621 | let path = self.goal_path(thread_id)?; |
| 2622 | if !path.exists() { |
| 2623 | return Ok(None); |
| 2624 | } |
| 2625 | let raw = read_store_file(&path) |
| 2626 | .with_context(|| format!("Failed to read goal {}", path.display()))?; |
| 2627 | let mut goal: codewhale_protocol::ThreadGoal = serde_json::from_str(&raw) |
| 2628 | .with_context(|| format!("Failed to parse goal {}", path.display()))?; |
| 2629 | goal.validate_stall_state().map_err(anyhow::Error::msg)?; |
| 2630 | goal.normalize_restored_stall_state(); |
| 2631 | Ok(Some(goal)) |
| 2632 | } |
| 2633 | |
| 2634 | pub fn thread_exists(&self, thread_id: &str) -> bool { |
| 2635 | self.thread_path(thread_id) |
| 2636 | .map(|path| path.is_file()) |
| 2637 | .unwrap_or(false) |
| 2638 | } |
| 2639 | |
| 2640 | pub fn list_goal_thread_ids(&self) -> Result<Vec<String>> { |
| 2641 | let mut ids = Vec::new(); |
| 2642 | for entry in fs::read_dir(&self.goals_dir) |
| 2643 | .with_context(|| format!("Failed to read {}", self.goals_dir.display()))? |
| 2644 | { |
| 2645 | let path = entry?.path(); |
| 2646 | if path.extension().and_then(|ext| ext.to_str()) != Some("json") { |
| 2647 | continue; |
| 2648 | } |
| 2649 | if let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) { |
| 2650 | ids.push(stem.to_string()); |
| 2651 | } |
| 2652 | } |
| 2653 | Ok(ids) |
| 2654 | } |
| 2655 | |
| 2656 | /// A late turn can only update the revision admitted with that turn. |
| 2657 | /// Load/compare/write share the same guard as explicit save/delete. |
| 2658 | /// Mutate the goal only while it is still the revision the caller read: |
| 2659 | /// the same `goal_id` and, when `expected_status` is given, the same |
| 2660 | /// status. Returns `Ok(None)` without writing when either changed, so a |
| 2661 | /// transition decided against a stale read (for example Blocked computed |
| 2662 | /// while a concurrent Complete landed) can never overwrite the newer state. |
| 2663 | fn update_goal_if_revision( |
| 2664 | &self, |
| 2665 | thread_id: &str, |
| 2666 | goal_id: &str, |
| 2667 | expected_status: Option<codewhale_protocol::ThreadGoalStatus>, |
| 2668 | update: impl FnOnce(&mut codewhale_protocol::ThreadGoal), |
| 2669 | ) -> Result<Option<codewhale_protocol::ThreadGoal>> { |
| 2670 | let _guard = self.goal_mutation.lock(); |
| 2671 | self.update_goal_if_revision_under_lock(thread_id, goal_id, expected_status, update) |
| 2672 | } |
| 2673 | |
| 2674 | fn update_goal_if_revision_under_lock( |
| 2675 | &self, |
| 2676 | thread_id: &str, |
| 2677 | goal_id: &str, |
| 2678 | expected_status: Option<codewhale_protocol::ThreadGoalStatus>, |
| 2679 | update: impl FnOnce(&mut codewhale_protocol::ThreadGoal), |
| 2680 | ) -> Result<Option<codewhale_protocol::ThreadGoal>> { |
| 2681 | let Some(mut goal) = self.load_goal(thread_id)? else { |
| 2682 | return Ok(None); |
| 2683 | }; |
| 2684 | if goal.goal_id != goal_id |
| 2685 | || expected_status.is_some_and(|expected| goal.status != expected) |
| 2686 | { |
| 2687 | return Ok(None); |
| 2688 | } |
| 2689 | update(&mut goal); |
| 2690 | goal.validate_stall_state().map_err(anyhow::Error::msg)?; |
| 2691 | write_json_atomic(&self.goal_path(thread_id)?, &goal)?; |
| 2692 | Ok(Some(goal)) |
| 2693 | } |
| 2694 | |
| 2695 | /// Persist a goal the model created mid-turn through `create_goal`, but |
| 2696 | /// only when the thread still has no durable goal: a concurrent explicit |
| 2697 | /// PUT/DELETE is the newer revision and always wins. Returns the adopted |
| 2698 | /// goal_id when this call created the record, `None` otherwise. |
| 2699 | fn create_goal_from_snapshot_if_absent( |
| 2700 | &self, |
| 2701 | thread_id: &str, |
| 2702 | snapshot: &crate::tools::goal::GoalSnapshot, |
| 2703 | ) -> Result<Option<String>> { |
| 2704 | let _guard = self.goal_mutation.lock(); |
| 2705 | if !snapshot.is_active() || self.load_goal(thread_id)?.is_some() { |
| 2706 | return Ok(None); |
| 2707 | } |
| 2708 | let Some(objective) = snapshot |
| 2709 | .objective |
| 2710 | .as_deref() |
| 2711 | .map(str::trim) |
| 2712 | .filter(|objective| !objective.is_empty()) |
| 2713 | else { |
| 2714 | return Ok(None); |
| 2715 | }; |
| 2716 | let now = chrono::Utc::now().timestamp(); |
| 2717 | let goal_id = snapshot |
| 2718 | .goal_id |
| 2719 | .clone() |
| 2720 | .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); |
| 2721 | let goal = codewhale_protocol::ThreadGoal { |
| 2722 | thread_id: thread_id.to_string(), |
| 2723 | goal_id: goal_id.clone(), |
| 2724 | objective: objective.to_string(), |
| 2725 | status: codewhale_protocol::ThreadGoalStatus::Active, |
| 2726 | token_budget: snapshot.token_budget.map(i64::from), |
| 2727 | tokens_used: 0, |
| 2728 | time_used_seconds: 0, |
| 2729 | continuation_count: 0, |
| 2730 | created_at: now, |
| 2731 | updated_at: now, |
| 2732 | last_gap_fingerprint: None, |
| 2733 | repeated_gap_count: 0, |
| 2734 | last_gap_pass: None, |
| 2735 | pause_reason: None, |
| 2736 | }; |
| 2737 | goal.validate_stall_state().map_err(anyhow::Error::msg)?; |
| 2738 | write_json_atomic(&self.goal_path(thread_id)?, &goal)?; |
| 2739 | Ok(Some(goal_id)) |
| 2740 | } |
| 2741 | |
| 2742 | /// Remove the goal for a thread, returning `true` if one existed. |
| 2743 | fn delete_goal_under_lock(&self, thread_id: &str) -> Result<bool> { |
| 2744 | let path = self.goal_path(thread_id)?; |
| 2745 | if !path.exists() { |
| 2746 | return Ok(false); |
| 2747 | } |
| 2748 | fs::remove_file(&path) |
| 2749 | .with_context(|| format!("Failed to delete goal {}", path.display()))?; |
| 2750 | Ok(true) |
| 2751 | } |
| 2752 | |
| 2753 | pub fn save_thread(&self, thread: &ThreadRecord) -> Result<()> { |
| 2754 | let path = self.thread_path(&thread.id)?; |
| 2755 | let min_version = required_thread_schema_version( |
| 2756 | &thread.disallowed_tools, |
| 2757 | thread.child_posture.is_some() || thread.whale_id.is_some(), |
| 2758 | ); |
| 2759 | if thread.schema_version < min_version { |
| 2760 | let mut updated = thread.clone(); |
| 2761 | updated.schema_version = min_version; |
| 2762 | return write_json_atomic(&path, &updated).with_context(|| { |
| 2763 | RuntimeStoreRecordFailure::new( |
| 2764 | RuntimeStoreOperation::Write, |
| 2765 | RuntimeStoreRecordKind::Thread, |
| 2766 | &updated.id, |
| 2767 | &path, |
| 2768 | ) |
| 2769 | }); |
| 2770 | } |
| 2771 | write_json_atomic(&path, thread).with_context(|| { |
| 2772 | RuntimeStoreRecordFailure::new( |
| 2773 | RuntimeStoreOperation::Write, |
| 2774 | RuntimeStoreRecordKind::Thread, |
| 2775 | &thread.id, |
| 2776 | &path, |
| 2777 | ) |
| 2778 | }) |
| 2779 | } |
| 2780 | |
| 2781 | pub fn save_turn(&self, turn: &TurnRecord) -> Result<()> { |
| 2782 | // Hold the turn mutation guard for every write — including callers that |
| 2783 | // already hold it (reentrant) — so unlocked test/API settles cannot be |
| 2784 | // overwritten by a monitor RMW that loaded an older in-flight snapshot. |
| 2785 | let _turn_mutation = self.turn_mutation.lock(); |
| 2786 | let path = self.turn_path(&turn.id)?; |
| 2787 | let stored = Self::turn_storage_value(turn)?; |
| 2788 | write_json_atomic(&path, &stored).with_context(|| { |
| 2789 | RuntimeStoreRecordFailure::new( |
| 2790 | RuntimeStoreOperation::Write, |
| 2791 | RuntimeStoreRecordKind::Turn, |
| 2792 | &turn.id, |
| 2793 | &path, |
| 2794 | ) |
| 2795 | }) |
| 2796 | } |
| 2797 | |
| 2798 | fn turn_storage_value(turn: &TurnRecord) -> Result<Value> { |
| 2799 | turn.validate_output_token_limit()?; |
| 2800 | validated_record_id(&turn.thread_id, "thread id")?; |
| 2801 | let mut value = serde_json::to_value(turn)?; |
| 2802 | if let Some(checkpoint) = &turn.prefix_checkpoint { |
| 2803 | value["prefix_checkpoint"] = serde_json::to_value(checkpoint)?; |
| 2804 | } |
| 2805 | Ok(value) |
| 2806 | } |
| 2807 | |
| 2808 | fn save_seed_turns_batch(&self, turns: &[TurnRecord]) -> Result<()> { |
| 2809 | let _turn_mutation = self.turn_mutation.lock(); |
| 2810 | let mut files = Vec::with_capacity(turns.len()); |
| 2811 | for turn in turns { |
| 2812 | let path = self.turn_path(&turn.id)?; |
| 2813 | reject_symlinked_store_file(&path)?; |
| 2814 | let payload = serde_json::to_vec_pretty(&Self::turn_storage_value(turn)?)?; |
| 2815 | files.push((format!("{}.json", turn.id), payload)); |
| 2816 | } |
| 2817 | let Some((first, _)) = files.first() else { |
| 2818 | return Ok(()); |
| 2819 | }; |
| 2820 | let root = self |
| 2821 | .turns_dir |
| 2822 | .parent() |
| 2823 | .context("Runtime store root is missing")?; |
| 2824 | let turns_dir = self |
| 2825 | .turns_dir |
| 2826 | .file_name() |
| 2827 | .context("Runtime turn directory is missing")?; |
| 2828 | let batch = codewhale_util::files::WorkspaceFile::open_resolved_root( |
| 2829 | root, |
| 2830 | &Path::new(turns_dir).join(first), |
| 2831 | false, |
| 2832 | )?; |
| 2833 | batch |
| 2834 | .replace_siblings(&files) |
| 2835 | .context("Failed to publish saved-session turns")?; |
| 2836 | #[cfg(unix)] |
| 2837 | codewhale_util::files::WorkspaceFile::open_resolved_root( |
| 2838 | root, |
| 2839 | Path::new(turns_dir), |
| 2840 | false, |
| 2841 | )? |
| 2842 | .sync_parent()?; |
| 2843 | Ok(()) |
| 2844 | } |
| 2845 | |
| 2846 | pub fn save_item(&self, item: &TurnItemRecord) -> Result<()> { |
| 2847 | validated_record_id(&item.turn_id, "turn id")?; |
| 2848 | // Before the write, because the record it replaces is the only thing |
| 2849 | // that still knows which turn owned this id. |
| 2850 | self.forget_cached_item_ownership(item); |
| 2851 | let path = self.item_path(&item.id)?; |
| 2852 | write_json_atomic(&path, item).with_context(|| { |
| 2853 | RuntimeStoreRecordFailure::new( |
| 2854 | RuntimeStoreOperation::Write, |
| 2855 | RuntimeStoreRecordKind::Item, |
| 2856 | &item.id, |
| 2857 | &path, |
| 2858 | ) |
| 2859 | })?; |
| 2860 | self.note_item_in_index(&item.turn_id, &item.id); |
| 2861 | Ok(()) |
| 2862 | } |
| 2863 | |
| 2864 | /// Publish many items at once, paying the items directory's costs once. |
| 2865 | /// |
| 2866 | /// Each `save_item` fsyncs the items directory — right for one record, |
| 2867 | /// ruinous for the hundreds a fork clones. The stale-temp sweep is |
| 2868 | /// throttled per directory inside `write_atomic`; unthrottled it cost 22 ms |
| 2869 | /// of directory scan per item, 34 s for one fork's 771. The per-record |
| 2870 | /// checks and the atomic replace are unchanged; see |
| 2871 | /// [`codewhale_util::utils::write_atomic_batch`]. |
| 2872 | /// |
| 2873 | /// Ordering stays the caller's: items, then their turns, then the thread |
| 2874 | /// record that makes them reachable. |
| 2875 | pub fn save_items_batch(&self, items: &[&TurnItemRecord]) -> Result<()> { |
| 2876 | let mut files = Vec::with_capacity(items.len()); |
| 2877 | for item in items { |
| 2878 | validated_record_id(&item.turn_id, "turn id")?; |
| 2879 | self.forget_cached_item_ownership(item); |
| 2880 | let path = self.item_path(&item.id)?; |
| 2881 | reject_symlinked_store_file(&path)?; |
| 2882 | let payload = serde_json::to_string_pretty(item)?; |
| 2883 | files.push((path, payload.into_bytes())); |
| 2884 | } |
| 2885 | codewhale_util::utils::write_atomic_batch(&files) |
| 2886 | .with_context(|| format!("Failed to write {} store items", files.len()))?; |
| 2887 | for item in items { |
| 2888 | self.note_item_in_index(&item.turn_id, &item.id); |
| 2889 | } |
| 2890 | Ok(()) |
| 2891 | } |
| 2892 | |
| 2893 | /// The engine history a compacting turn settled on, stored once under |
| 2894 | /// its digest beside the items (listings read only `.json`). Forks share |
| 2895 | /// it by reference, so it is never removed. |
| 2896 | fn settled_history_path(&self, digest: &str) -> Result<PathBuf> { |
| 2897 | Self::record_path(&self.items_dir, digest, "history", "settled history digest") |
| 2898 | } |
| 2899 | |
| 2900 | pub fn save_settled_history(&self, messages: &[Message]) -> Result<Value> { |
| 2901 | let bytes = serde_json::to_vec(messages)?; |
| 2902 | let digest = hex_digest(Sha256::digest(&bytes)); |
| 2903 | let path = self.settled_history_path(&digest)?; |
| 2904 | reject_symlinked_store_file(&path)?; |
| 2905 | codewhale_util::utils::write_atomic(&path, &bytes) |
| 2906 | .with_context(|| format!("Failed to write settled history {}", path.display()))?; |
| 2907 | Ok(json!({ "sha256": digest, "messages": messages.len() })) |
| 2908 | } |
| 2909 | |
| 2910 | /// The newest settled history among `turns`, and how many of them it |
| 2911 | /// covers. A reference whose file is missing, altered or unreadable is an |
| 2912 | /// error: replaying the raw turns instead would silently undo compaction. |
| 2913 | fn settled_history( |
| 2914 | &self, |
| 2915 | turns: &[TurnRecord], |
| 2916 | items_by_turn: &HashMap<String, Vec<TurnItemRecord>>, |
| 2917 | ) -> Result<Option<(usize, Vec<Message>)>> { |
| 2918 | for (index, turn) in turns.iter().enumerate().rev() { |
| 2919 | let Some((item, reference)) = items_by_turn |
| 2920 | .get(&turn.id) |
| 2921 | .into_iter() |
| 2922 | .flatten() |
| 2923 | .rev() |
| 2924 | .filter(|item| item.kind == TurnItemKind::ContextCompaction) |
| 2925 | .find_map(|item| { |
| 2926 | let reference = item.metadata.as_ref()?.get("settled_history")?; |
| 2927 | Some((item, reference)) |
| 2928 | }) |
| 2929 | else { |
| 2930 | continue; |
| 2931 | }; |
| 2932 | let digest = reference |
| 2933 | .get("sha256") |
| 2934 | .and_then(Value::as_str) |
| 2935 | .filter(|digest| { |
| 2936 | digest.len() == 64 |
| 2937 | && digest |
| 2938 | .bytes() |
| 2939 | .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) |
| 2940 | }) |
| 2941 | .with_context(|| { |
| 2942 | format!( |
| 2943 | "Compaction item {} on turn {} names an invalid settled history", |
| 2944 | item.id, turn.id |
| 2945 | ) |
| 2946 | })?; |
| 2947 | let expected = reference |
| 2948 | .get("messages") |
| 2949 | .and_then(Value::as_u64) |
| 2950 | .and_then(|count| usize::try_from(count).ok()) |
| 2951 | .with_context(|| { |
| 2952 | format!( |
| 2953 | "Compaction item {} on turn {} names no settled history length", |
| 2954 | item.id, turn.id |
| 2955 | ) |
| 2956 | })?; |
| 2957 | let path = self.settled_history_path(digest)?; |
| 2958 | reject_symlinked_store_file(&path)?; |
| 2959 | let bytes = fs::read(&path).with_context(|| { |
| 2960 | format!( |
| 2961 | "Settled history for turn {} is unreadable: {}", |
| 2962 | turn.id, |
| 2963 | path.display() |
| 2964 | ) |
| 2965 | })?; |
| 2966 | anyhow::ensure!( |
| 2967 | hex_digest(Sha256::digest(&bytes)) == digest, |
| 2968 | "Settled history {} for turn {} does not match its digest", |
| 2969 | path.display(), |
| 2970 | turn.id |
| 2971 | ); |
| 2972 | let messages: Vec<Message> = serde_json::from_slice(&bytes) |
| 2973 | .with_context(|| format!("Failed to parse settled history {}", path.display()))?; |
| 2974 | anyhow::ensure!( |
| 2975 | messages.len() == expected, |
| 2976 | "Settled history {} for turn {} holds {} messages, not {expected}", |
| 2977 | path.display(), |
| 2978 | turn.id, |
| 2979 | messages.len() |
| 2980 | ); |
| 2981 | return Ok(Some((index + 1, messages))); |
| 2982 | } |
| 2983 | Ok(None) |
| 2984 | } |
| 2985 | |
| 2986 | fn load_prefix_history(&self, checkpoint: &RuntimePrefixCheckpoint) -> Result<Vec<Message>> { |
| 2987 | anyhow::ensure!( |
| 2988 | checkpoint.persisted_sha256.len() == 64 |
| 2989 | && checkpoint |
| 2990 | .persisted_sha256 |
| 2991 | .bytes() |
| 2992 | .all(|byte| byte.is_ascii_hexdigit()) |
| 2993 | && checkpoint.projection == "runtime_receipt_redacted", |
| 2994 | "Invalid Runtime prefix checkpoint reference" |
| 2995 | ); |
| 2996 | let path = self.settled_history_path(&checkpoint.persisted_sha256)?; |
| 2997 | reject_symlinked_store_file(&path)?; |
| 2998 | let bytes = fs::read(&path).context("Runtime prefix checkpoint is unreadable")?; |
| 2999 | anyhow::ensure!( |
| 3000 | hex_digest(Sha256::digest(&bytes)) == checkpoint.persisted_sha256, |
| 3001 | "Runtime prefix checkpoint digest mismatch" |
| 3002 | ); |
| 3003 | let messages: Vec<Message> = serde_json::from_slice(&bytes)?; |
| 3004 | anyhow::ensure!( |
| 3005 | messages.len() == checkpoint.messages_len, |
| 3006 | "Runtime prefix checkpoint length mismatch" |
| 3007 | ); |
| 3008 | Ok(messages) |
| 3009 | } |
| 3010 | |
| 3011 | fn checkpoint_tail( |
| 3012 | &self, |
| 3013 | turn: &TurnRecord, |
| 3014 | items_by_turn: &HashMap<String, Vec<TurnItemRecord>>, |
| 3015 | messages: &[Message], |
| 3016 | ) -> Result<HashMap<String, Vec<TurnItemRecord>>> { |
| 3017 | let checkpoint = turn |
| 3018 | .prefix_checkpoint |
| 3019 | .as_ref() |
| 3020 | .context("Missing Runtime prefix checkpoint")?; |
| 3021 | anyhow::ensure!( |
| 3022 | checkpoint.session_id == turn.thread_id |
| 3023 | && checkpoint.runtime_turn_id == turn.id |
| 3024 | && checkpoint.agent_id.is_none() |
| 3025 | && checkpoint.owner_id == self.owner_id |
| 3026 | && !checkpoint.engine_turn_id.is_empty() |
| 3027 | && !checkpoint.call_id.is_empty() |
| 3028 | && !checkpoint.checkpoint_id.is_empty() |
| 3029 | && checkpoint.source_sha256.len() == 64 |
| 3030 | && checkpoint |
| 3031 | .source_sha256 |
| 3032 | .bytes() |
| 3033 | .all(|byte| byte.is_ascii_hexdigit()), |
| 3034 | "Runtime prefix checkpoint owner mismatch" |
| 3035 | ); |
| 3036 | anyhow::ensure!( |
| 3037 | turn.item_ids.starts_with(&checkpoint.item_ids) |
| 3038 | && checkpoint.item_ids.iter().collect::<HashSet<_>>().len() |
| 3039 | == checkpoint.item_ids.len() |
| 3040 | && checkpoint |
| 3041 | .covered_items |
| 3042 | .keys() |
| 3043 | .all(|id| checkpoint.item_ids.contains(id)) |
| 3044 | && checkpoint |
| 3045 | .pending_items |
| 3046 | .iter() |
| 3047 | .all(|id| checkpoint.item_ids.contains(id) |
| 3048 | && !checkpoint.covered_items.contains_key(id)), |
| 3049 | "Runtime prefix checkpoint item cursor changed" |
| 3050 | ); |
| 3051 | let mut calls = HashMap::<(Option<String>, String), ContentBlock>::new(); |
| 3052 | let mut results = HashMap::<(Option<String>, String), ContentBlock>::new(); |
| 3053 | let mut call_order = Vec::new(); |
| 3054 | let mut execution_providers = HashMap::new(); |
| 3055 | for block in messages.iter().flat_map(|message| &message.content) { |
| 3056 | match block { |
| 3057 | ContentBlock::ToolUse { |
| 3058 | execution_id, id, .. |
| 3059 | } => { |
| 3060 | check_execution_provider( |
| 3061 | &mut execution_providers, |
| 3062 | execution_id.as_deref(), |
| 3063 | id, |
| 3064 | )?; |
| 3065 | let key = (execution_id.clone(), id.clone()); |
| 3066 | anyhow::ensure!( |
| 3067 | !calls.contains_key(&key) || results.contains_key(&key), |
| 3068 | "Checkpoint contains duplicate open tool identity" |
| 3069 | ); |
| 3070 | results.remove(&key); |
| 3071 | call_order.retain(|previous| previous != &key); |
| 3072 | call_order.push(key.clone()); |
| 3073 | calls.insert(key, block.clone()); |
| 3074 | } |
| 3075 | ContentBlock::ToolResult { |
| 3076 | execution_id, |
| 3077 | tool_use_id, |
| 3078 | .. |
| 3079 | } => { |
| 3080 | check_execution_provider( |
| 3081 | &mut execution_providers, |
| 3082 | execution_id.as_deref(), |
| 3083 | tool_use_id, |
| 3084 | )?; |
| 3085 | let key = (execution_id.clone(), tool_use_id.clone()); |
| 3086 | anyhow::ensure!( |
| 3087 | calls.contains_key(&key) && results.insert(key, block.clone()).is_none(), |
| 3088 | "Checkpoint contains an unpaired tool result" |
| 3089 | ); |
| 3090 | } |
| 3091 | _ => {} |
| 3092 | } |
| 3093 | } |
| 3094 | anyhow::ensure!( |
| 3095 | calls.len() == checkpoint.tool_declarations.len() |
| 3096 | && calls |
| 3097 | .keys() |
| 3098 | .all( |
| 3099 | |key| serde_json::to_string(key).ok().is_some_and(|key| checkpoint |
| 3100 | .tool_declarations |
| 3101 | .get(&key) |
| 3102 | .is_some_and(|digest| digest.len() == 64 |
| 3103 | && digest.bytes().all(|byte| byte.is_ascii_hexdigit()))) |
| 3104 | ), |
| 3105 | "Runtime prefix checkpoint tool declarations are incomplete" |
| 3106 | ); |
| 3107 | let items = ordered_turn_items(turn, items_by_turn)?; |
| 3108 | let present: HashSet<_> = items.iter().map(|item| item.id.as_str()).collect(); |
| 3109 | anyhow::ensure!( |
| 3110 | checkpoint |
| 3111 | .item_ids |
| 3112 | .iter() |
| 3113 | .all(|id| present.contains(id.as_str())), |
| 3114 | "Runtime prefix checkpoint item is missing" |
| 3115 | ); |
| 3116 | let mut retained = Vec::new(); |
| 3117 | let mut answered = HashSet::new(); |
| 3118 | for mut item in items { |
| 3119 | if let Some(expected) = checkpoint.covered_items.get(&item.id) { |
| 3120 | anyhow::ensure!( |
| 3121 | checkpoint_item_digest(&item)? == *expected |
| 3122 | && (projects_tool_history(&item) |
| 3123 | || !matches!( |
| 3124 | item.status, |
| 3125 | TurnItemLifecycleStatus::Queued | TurnItemLifecycleStatus::Canceled |
| 3126 | )), |
| 3127 | "Runtime prefix checkpoint covered item changed" |
| 3128 | ); |
| 3129 | if !projects_tool_history(&item) { |
| 3130 | continue; |
| 3131 | } |
| 3132 | } |
| 3133 | anyhow::ensure!( |
| 3134 | !checkpoint.item_ids.contains(&item.id) |
| 3135 | || checkpoint.pending_items.contains(&item.id) |
| 3136 | || !matches!( |
| 3137 | item.kind, |
| 3138 | TurnItemKind::UserMessage |
| 3139 | | TurnItemKind::AgentMessage |
| 3140 | | TurnItemKind::AgentReasoning |
| 3141 | ) |
| 3142 | || matches!( |
| 3143 | item.status, |
| 3144 | TurnItemLifecycleStatus::Queued | TurnItemLifecycleStatus::Canceled |
| 3145 | ), |
| 3146 | "Runtime prefix checkpoint covered item reference is missing" |
| 3147 | ); |
| 3148 | if projects_tool_history(&item) { |
| 3149 | let identity = |
| 3150 | RuntimeToolIdentity::read(item.metadata.as_ref(), "tool_use_id")?.or( |
| 3151 | RuntimeToolIdentity::read(item.metadata.as_ref(), "tool_result_for")?, |
| 3152 | ); |
| 3153 | if let Some(identity) = identity { |
| 3154 | check_execution_provider( |
| 3155 | &mut execution_providers, |
| 3156 | identity.execution_id, |
| 3157 | identity.provider_id, |
| 3158 | )?; |
| 3159 | let key = ( |
| 3160 | identity.execution_id.map(str::to_owned), |
| 3161 | identity.provider_id.to_owned(), |
| 3162 | ); |
| 3163 | if calls.contains_key(&key) { |
| 3164 | let declaration = checkpoint |
| 3165 | .tool_declarations |
| 3166 | .get(&serde_json::to_string(&key)?) |
| 3167 | .context("Runtime prefix tool declaration reference is missing")?; |
| 3168 | let mut isolated = turn.clone(); |
| 3169 | isolated.item_ids = vec![item.id.clone()]; |
| 3170 | let projected = reconstruct_messages_from_turns_with( |
| 3171 | &[isolated], |
| 3172 | &HashMap::from([(turn.id.clone(), vec![item.clone()])]), |
| 3173 | )?; |
| 3174 | let mut outcome = None; |
| 3175 | for block in projected.into_iter().flat_map(|message| message.content) { |
| 3176 | match &block { |
| 3177 | ContentBlock::ToolUse { .. } => anyhow::ensure!( |
| 3178 | hex_digest(Sha256::digest(serde_json::to_vec(&block)?)) |
| 3179 | == *declaration, |
| 3180 | "Runtime prefix tool declaration changed" |
| 3181 | ), |
| 3182 | ContentBlock::ToolResult { .. } => outcome = Some(block), |
| 3183 | _ => {} |
| 3184 | } |
| 3185 | } |
| 3186 | if results.contains_key(&key) { |
| 3187 | anyhow::ensure!( |
| 3188 | checkpoint.covered_items.contains_key(&item.id), |
| 3189 | "Runtime prefix completed tool receipt is not bound to its cursor" |
| 3190 | ); |
| 3191 | continue; |
| 3192 | } |
| 3193 | if let Some(outcome) = outcome { |
| 3194 | anyhow::ensure!( |
| 3195 | answered.insert(key.clone()), |
| 3196 | "Duplicate Runtime prefix tool result" |
| 3197 | ); |
| 3198 | let ContentBlock::ToolResult { |
| 3199 | content, |
| 3200 | is_error, |
| 3201 | content_blocks, |
| 3202 | .. |
| 3203 | } = outcome |
| 3204 | else { |
| 3205 | unreachable!() |
| 3206 | }; |
| 3207 | let metadata = item |
| 3208 | .metadata |
| 3209 | .as_mut() |
| 3210 | .and_then(Value::as_object_mut) |
| 3211 | .context("Invalid Runtime prefix tool metadata")?; |
| 3212 | metadata.remove("tool_use_id"); |
| 3213 | metadata.insert( |
| 3214 | "tool_result_for".into(), |
| 3215 | json!(key.0.as_deref().unwrap_or(&key.1)), |
| 3216 | ); |
| 3217 | if let Some(error) = is_error { |
| 3218 | metadata.insert("is_error".into(), json!(error)); |
| 3219 | metadata.insert("is_error_explicit".into(), json!(true)); |
| 3220 | } else { |
| 3221 | metadata.remove("is_error"); |
| 3222 | metadata.remove("is_error_explicit"); |
| 3223 | } |
| 3224 | if let Some(content_blocks) = content_blocks { |
| 3225 | metadata.insert("content_blocks".into(), json!(content_blocks)); |
| 3226 | } |
| 3227 | item.detail = Some(content); |
| 3228 | retained.push(item); |
| 3229 | } |
| 3230 | continue; |
| 3231 | } |
| 3232 | anyhow::ensure!( |
| 3233 | !checkpoint.item_ids.contains(&item.id), |
| 3234 | "Runtime prefix does not contain a covered tool declaration" |
| 3235 | ); |
| 3236 | } |
| 3237 | } |
| 3238 | retained.push(item); |
| 3239 | } |
| 3240 | if !turn.status.is_active_work() { |
| 3241 | let mut missing = Vec::new(); |
| 3242 | for key in call_order |
| 3243 | .iter() |
| 3244 | .filter(|key| !results.contains_key(*key) && !answered.contains(*key)) |
| 3245 | { |
| 3246 | let id = format!("checkpoint_result_{}", missing.len()); |
| 3247 | missing.push(TurnItemRecord { |
| 3248 | schema_version: CURRENT_RUNTIME_SCHEMA_VERSION, |
| 3249 | id, |
| 3250 | turn_id: turn.id.clone(), |
| 3251 | kind: TurnItemKind::ToolCall, |
| 3252 | status: TurnItemLifecycleStatus::Interrupted, |
| 3253 | summary: String::new(), |
| 3254 | detail: Some( |
| 3255 | codewhale_runtime::tool_history_repair::CRASH_REPAIR_CONTENT.to_string(), |
| 3256 | ), |
| 3257 | metadata: Some(match &key.0 { |
| 3258 | Some(execution) => { |
| 3259 | json!({"tool_result_for": execution, "execution_id": execution, |
| 3260 | "provider_tool_use_id": key.1, "is_error": true}) |
| 3261 | } |
| 3262 | None => json!({"tool_result_for": key.1, "is_error": true}), |
| 3263 | }), |
| 3264 | artifact_refs: Vec::new(), |
| 3265 | artifacts: Vec::new(), |
| 3266 | started_at: None, |
| 3267 | ended_at: None, |
| 3268 | }); |
| 3269 | } |
| 3270 | let boundary = retained |
| 3271 | .iter() |
| 3272 | .position(|item| { |
| 3273 | matches!( |
| 3274 | item.kind, |
| 3275 | TurnItemKind::UserMessage |
| 3276 | | TurnItemKind::AgentMessage |
| 3277 | | TurnItemKind::AgentReasoning |
| 3278 | ) |
| 3279 | }) |
| 3280 | .unwrap_or(retained.len()); |
| 3281 | retained.splice(boundary..boundary, missing); |
| 3282 | } |
| 3283 | let mut tail = items_by_turn.clone(); |
| 3284 | tail.insert(turn.id.clone(), retained); |
| 3285 | Ok(tail) |
| 3286 | } |
| 3287 | |
| 3288 | fn history_with_prefix( |
| 3289 | &self, |
| 3290 | turns: &[TurnRecord], |
| 3291 | items_by_turn: &HashMap<String, Vec<TurnItemRecord>>, |
| 3292 | mut messages: Vec<Message>, |
| 3293 | mut covered: usize, |
| 3294 | ) -> Result<Vec<Message>> { |
| 3295 | if let Some((settled, history)) = self.settled_history(&turns[covered..], items_by_turn)? { |
| 3296 | covered += settled; |
| 3297 | messages = history; |
| 3298 | } |
| 3299 | if let Some((index, turn)) = turns |
| 3300 | .iter() |
| 3301 | .enumerate() |
| 3302 | .skip(covered) |
| 3303 | .rev() |
| 3304 | .find(|(_, turn)| turn.prefix_checkpoint.is_some()) |
| 3305 | { |
| 3306 | messages = self.load_prefix_history(turn.prefix_checkpoint.as_ref().unwrap())?; |
| 3307 | let tail = self.checkpoint_tail(turn, items_by_turn, &messages)?; |
| 3308 | let mut remaining = turns[index..].to_vec(); |
| 3309 | remaining[0].item_ids = tail |
| 3310 | .get(&turn.id) |
| 3311 | .into_iter() |
| 3312 | .flatten() |
| 3313 | .map(|item| item.id.clone()) |
| 3314 | .collect(); |
| 3315 | messages.extend(reconstruct_messages_from_turns_with(&remaining, &tail)?); |
| 3316 | } else { |
| 3317 | messages.extend(reconstruct_messages_from_turns_with( |
| 3318 | &turns[covered..], |
| 3319 | items_by_turn, |
| 3320 | )?); |
| 3321 | } |
| 3322 | Ok(messages) |
| 3323 | } |
| 3324 | |
| 3325 | /// The model-visible history the records hold: the newest canonical |
| 3326 | /// checkpoint, then later item outcomes and turns. |
| 3327 | pub fn history_from_records( |
| 3328 | &self, |
| 3329 | turns: &[TurnRecord], |
| 3330 | items_by_turn: &HashMap<String, Vec<TurnItemRecord>>, |
| 3331 | ) -> Result<Vec<Message>> { |
| 3332 | self.history_with_prefix(turns, items_by_turn, Vec::new(), 0) |
| 3333 | } |
| 3334 | |
| 3335 | /// Journal for one history seed into an existing thread (#6555), kept |
| 3336 | /// beside the thread record as `<thread>.seed` (listings read only |
| 3337 | /// `.json`). It names every record the seed will write before the first |
| 3338 | /// one lands; the thread record — the seed's commit record — is written |
| 3339 | /// after them, and the journal is removed last. |
| 3340 | fn seed_journal_path(&self, thread_id: &str) -> Result<PathBuf> { |
| 3341 | Self::record_path(&self.threads_dir, thread_id, "seed", "thread id") |
| 3342 | } |
| 3343 | |
| 3344 | fn save_seed_journal(&self, journal: &SeedJournal) -> Result<()> { |
| 3345 | let path = self.seed_journal_path(&journal.thread_id)?; |
| 3346 | reject_symlinked_store_file(&path)?; |
| 3347 | write_json_atomic(&path, journal) |
| 3348 | .with_context(|| format!("Failed to write seed journal {}", path.display())) |
| 3349 | } |
| 3350 | |
| 3351 | fn remove_seed_journal(&self, thread_id: &str) -> Result<()> { |
| 3352 | remove_file_if_exists(&self.seed_journal_path(thread_id)?) |
| 3353 | } |
| 3354 | |
| 3355 | /// Remove every record an uncommitted seed named, then its journal. Ids in |
| 3356 | /// a journal were minted fresh for that seed, so nothing else is touched. |
| 3357 | fn discard_seed(&self, journal: &SeedJournal) -> Result<()> { |
| 3358 | // Validate the whole deletion set first. A damaged journal must not |
| 3359 | // retire records from another thread, even when some earlier records |
| 3360 | // in its list were legitimate members of this seed. |
| 3361 | for turn_id in &journal.turn_ids { |
| 3362 | match self.load_turn(turn_id) { |
| 3363 | Ok(turn) if turn.id == *turn_id && turn.thread_id == journal.thread_id => {} |
| 3364 | Ok(_) => anyhow::bail!("seed journal names a turn outside its thread"), |
| 3365 | Err(error) if store_record_missing(&error) => {} |
| 3366 | Err(error) => { |
| 3367 | return Err(error).context("cannot validate seed turn before cleanup"); |
| 3368 | } |
| 3369 | } |
| 3370 | } |
| 3371 | for item_id in &journal.item_ids { |
| 3372 | match self.load_item(item_id) { |
| 3373 | Ok(item) if item.id == *item_id && journal.turn_ids.contains(&item.turn_id) => {} |
| 3374 | Ok(_) => anyhow::bail!("seed journal names an item outside its turns"), |
| 3375 | Err(error) if store_record_missing(&error) => {} |
| 3376 | Err(error) => { |
| 3377 | return Err(error).context("cannot validate seed item before cleanup"); |
| 3378 | } |
| 3379 | } |
| 3380 | } |
| 3381 | for turn_id in &journal.turn_ids { |
| 3382 | self.remove_turn(turn_id)?; |
| 3383 | } |
| 3384 | for item_id in &journal.item_ids { |
| 3385 | self.remove_item(item_id)?; |
| 3386 | } |
| 3387 | self.remove_seed_journal(&journal.thread_id) |
| 3388 | } |
| 3389 | |
| 3390 | /// Startup half of the seed transaction: a journal whose thread pointer |
| 3391 | /// still matches the one it recorded is an unpublished partial seed and |
| 3392 | /// is discarded, so recovery can never restore it as history. A journal |
| 3393 | /// whose seed provably committed is simply removed. |
| 3394 | /// |
| 3395 | /// Uncertainty is per thread, like [`Self::list_threads_lenient`] |
| 3396 | /// (#6144 P7): a journal whose intent or ownership cannot be proven |
| 3397 | /// quarantines only its thread. Nothing of that thread is deleted or |
| 3398 | /// rewritten, the journal stays for repair, and the returned ids are held |
| 3399 | /// out of recovery so their pointers are not recomputed over a seed that |
| 3400 | /// may be partial. Every other thread in the store recovers normally. |
| 3401 | /// |
| 3402 | /// Known limitation: a quarantined thread stays exactly as recorded until |
| 3403 | /// its journal is repaired or removed by hand — including a turn that was |
| 3404 | /// in flight when the process stopped, which is not terminalized. |
| 3405 | /// Listings and thread detail still read its records as stored. |
| 3406 | fn settle_seed_journals(&self) -> Result<HashSet<String>> { |
| 3407 | let mut quarantined = HashSet::new(); |
| 3408 | for path in self.seed_journal_paths()? { |
| 3409 | match self.judge_seed_journal(&path) { |
| 3410 | SeedJournalVerdict::Committed { thread_id } => { |
| 3411 | if let Err(error) = self.remove_seed_journal(&thread_id) { |
| 3412 | // History is committed either way; the next start |
| 3413 | // judges the journal again. |
| 3414 | tracing::warn!( |
| 3415 | target: "runtime", |
| 3416 | thread_id = %thread_id, |
| 3417 | "committed seed journal not removed: {error:#}" |
| 3418 | ); |
| 3419 | } |
| 3420 | } |
| 3421 | SeedJournalVerdict::Uncommitted(journal) => { |
| 3422 | if let Err(error) = self.discard_seed(&journal) { |
| 3423 | tracing::error!( |
| 3424 | target: "runtime", |
| 3425 | thread_id = %journal.thread_id, |
| 3426 | journal = %path.display(), |
| 3427 | "partial seed not discarded; thread held out of recovery and its \ |
| 3428 | journal kept for repair: {error:#}" |
| 3429 | ); |
| 3430 | quarantined.insert(journal.thread_id); |
| 3431 | } |
| 3432 | } |
| 3433 | SeedJournalVerdict::Quarantined { thread_ids, reason } => { |
| 3434 | tracing::error!( |
| 3435 | target: "runtime", |
| 3436 | thread_ids = ?thread_ids, |
| 3437 | journal = %path.display(), |
| 3438 | "seed journal cannot be settled ({reason}); thread held out of recovery \ |
| 3439 | and every record preserved for repair" |
| 3440 | ); |
| 3441 | quarantined.extend(thread_ids); |
| 3442 | } |
| 3443 | } |
| 3444 | } |
| 3445 | Ok(quarantined) |
| 3446 | } |
| 3447 | |
| 3448 | /// Every `<thread>.seed` journal in the store. |
| 3449 | fn seed_journal_paths(&self) -> Result<Vec<PathBuf>> { |
| 3450 | let threads_dir = checked_existing_runtime_store_dir(&self.threads_dir)?; |
| 3451 | let mut paths = Vec::new(); |
| 3452 | for entry in fs::read_dir(&threads_dir) |
| 3453 | .with_context(|| format!("Failed to read {}", threads_dir.display()))? |
| 3454 | { |
| 3455 | let path = entry?.path(); |
| 3456 | if path.extension().is_some_and(|ext| ext == "seed") { |
| 3457 | paths.push(path); |
| 3458 | } |
| 3459 | } |
| 3460 | Ok(paths) |
| 3461 | } |
| 3462 | |
| 3463 | /// What one seed journal proves, without changing anything. Both the |
| 3464 | /// startup settle and the read-only reconcile reader |
| 3465 | /// ([`HeldRuntimeStore::recoverable_threads`]) judge journals here, so |
| 3466 | /// they agree on what counts as history. |
| 3467 | fn judge_seed_journal(&self, path: &Path) -> SeedJournalVerdict { |
| 3468 | let stem = path |
| 3469 | .file_stem() |
| 3470 | .map(|stem| stem.to_string_lossy().into_owned()) |
| 3471 | .unwrap_or_default(); |
| 3472 | let journal = match read_store_file(path).and_then(|raw| { |
| 3473 | serde_json::from_str::<SeedJournal>(&raw) |
| 3474 | .with_context(|| format!("Failed to parse {}", path.display())) |
| 3475 | }) { |
| 3476 | Ok(journal) => journal, |
| 3477 | Err(error) => { |
| 3478 | // Without readable intent an unpublished seed cannot be told |
| 3479 | // from accepted history. |
| 3480 | return SeedJournalVerdict::Quarantined { |
| 3481 | thread_ids: vec![stem], |
| 3482 | reason: format!("journal unreadable: {error:#}"), |
| 3483 | }; |
| 3484 | } |
| 3485 | }; |
| 3486 | let owned = self |
| 3487 | .seed_journal_path(&journal.thread_id) |
| 3488 | .is_ok_and(|expected| expected.file_name() == path.file_name()); |
| 3489 | if !owned { |
| 3490 | return SeedJournalVerdict::Quarantined { |
| 3491 | thread_ids: vec![stem, journal.thread_id], |
| 3492 | reason: "journal names another thread".to_string(), |
| 3493 | }; |
| 3494 | } |
| 3495 | // A seed that names no records has nothing to publish or withhold. |
| 3496 | if journal.turn_ids.is_empty() && journal.item_ids.is_empty() { |
| 3497 | return SeedJournalVerdict::Uncommitted(journal); |
| 3498 | } |
| 3499 | let thread = match self.load_thread(&journal.thread_id) { |
| 3500 | Ok(thread) => thread, |
| 3501 | // The thread is gone; nothing can publish its seed records. |
| 3502 | Err(error) if store_record_missing(&error) => { |
| 3503 | return SeedJournalVerdict::Uncommitted(journal); |
| 3504 | } |
| 3505 | Err(error) => { |
| 3506 | return SeedJournalVerdict::Quarantined { |
| 3507 | thread_ids: vec![journal.thread_id], |
| 3508 | reason: format!("thread record unreadable: {error:#}"), |
| 3509 | }; |
| 3510 | } |
| 3511 | }; |
| 3512 | if thread.latest_turn_id == journal.previous_latest_turn_id { |
| 3513 | return SeedJournalVerdict::Uncommitted(journal); |
| 3514 | } |
| 3515 | if journal.turn_ids.last() == thread.latest_turn_id.as_ref() { |
| 3516 | return SeedJournalVerdict::Committed { |
| 3517 | thread_id: journal.thread_id, |
| 3518 | }; |
| 3519 | } |
| 3520 | match self.seed_complete_beneath_later_turn(&journal, &thread) { |
| 3521 | Ok(true) => SeedJournalVerdict::Committed { |
| 3522 | thread_id: journal.thread_id, |
| 3523 | }, |
| 3524 | Ok(false) => SeedJournalVerdict::Quarantined { |
| 3525 | thread_ids: vec![journal.thread_id], |
| 3526 | reason: "thread pointer names neither the pre-seed turn nor the seed, and the \ |
| 3527 | complete seed is not provably beneath it" |
| 3528 | .to_string(), |
| 3529 | }, |
| 3530 | Err(error) => SeedJournalVerdict::Quarantined { |
| 3531 | thread_ids: vec![journal.thread_id], |
| 3532 | reason: format!("seed records unreadable: {error:#}"), |
| 3533 | }, |
| 3534 | } |
| 3535 | } |
| 3536 | |
| 3537 | /// True when a journal was left behind by a seed that committed and the |
| 3538 | /// thread then moved on: the journal removal after the commit failed and |
| 3539 | /// later turns advanced the pointer. `thread_mutation` serializes seeding |
| 3540 | /// against every other pointer move, so a pointer that names a turn of |
| 3541 | /// this thread created after the seed's last turn, while every record the |
| 3542 | /// seed journaled is still present and still its own, sits above the |
| 3543 | /// complete seed. A seed with a missing or foreign record is never |
| 3544 | /// proven here — that thread is quarantined instead. |
| 3545 | fn seed_complete_beneath_later_turn( |
| 3546 | &self, |
| 3547 | journal: &SeedJournal, |
| 3548 | thread: &ThreadRecord, |
| 3549 | ) -> Result<bool> { |
| 3550 | let Some(pointer) = thread.latest_turn_id.as_deref() else { |
| 3551 | return Ok(false); |
| 3552 | }; |
| 3553 | if journal.turn_ids.iter().any(|turn_id| turn_id == pointer) { |
| 3554 | return Ok(false); |
| 3555 | } |
| 3556 | let later = match self.load_turn(pointer) { |
| 3557 | Ok(turn) => turn, |
| 3558 | Err(error) if store_record_missing(&error) => return Ok(false), |
| 3559 | Err(error) => return Err(error), |
| 3560 | }; |
| 3561 | if later.id != pointer || later.thread_id != journal.thread_id { |
| 3562 | return Ok(false); |
| 3563 | } |
| 3564 | let mut last_seeded_at = None; |
| 3565 | for turn_id in &journal.turn_ids { |
| 3566 | let turn = match self.load_turn(turn_id) { |
| 3567 | Ok(turn) => turn, |
| 3568 | Err(error) if store_record_missing(&error) => return Ok(false), |
| 3569 | Err(error) => return Err(error), |
| 3570 | }; |
| 3571 | if turn.id != *turn_id || turn.thread_id != journal.thread_id { |
| 3572 | return Ok(false); |
| 3573 | } |
| 3574 | last_seeded_at = Some(turn.created_at); |
| 3575 | } |
| 3576 | for item_id in &journal.item_ids { |
| 3577 | let item = match self.load_item(item_id) { |
| 3578 | Ok(item) => item, |
| 3579 | Err(error) if store_record_missing(&error) => return Ok(false), |
| 3580 | Err(error) => return Err(error), |
| 3581 | }; |
| 3582 | if item.id != *item_id || !journal.turn_ids.contains(&item.turn_id) { |
| 3583 | return Ok(false); |
| 3584 | } |
| 3585 | } |
| 3586 | Ok(last_seeded_at.is_some_and(|seeded_at| later.created_at > seeded_at)) |
| 3587 | } |
| 3588 | |
| 3589 | fn remove_turn(&self, turn_id: &str) -> Result<()> { |
| 3590 | remove_file_if_exists(&self.turn_path(turn_id)?) |
| 3591 | } |
| 3592 | |
| 3593 | fn remove_thread(&self, thread_id: &str) -> Result<()> { |
| 3594 | remove_file_if_exists(&self.thread_path(thread_id)?) |
| 3595 | } |
| 3596 | |
| 3597 | fn remove_item(&self, item_id: &str) -> Result<()> { |
| 3598 | let path = self.item_path(item_id)?; |
| 3599 | // An id that disappears can come back under another turn, and the cache |
| 3600 | // would still name the one it left. |
| 3601 | if self.persist_caches && path.exists() { |
| 3602 | self.drop_persisted_item_index(); |
| 3603 | } |
| 3604 | remove_file_if_exists(&path) |
| 3605 | } |
| 3606 | |
| 3607 | pub fn rebuild_thread_from_event_log(&self, thread_id: &str) -> Result<Option<ThreadRecord>> { |
| 3608 | validated_record_id(thread_id, "thread id")?; |
| 3609 | if self |
| 3610 | .seed_journal_path(thread_id) |
| 3611 | .is_ok_and(|journal_path| journal_path.exists()) |
| 3612 | { |
| 3613 | return Ok(None); |
| 3614 | } |
| 3615 | let mut rebuilt: Option<ThreadRecord> = None; |
| 3616 | let mut latest_turn_id: Option<String> = None; |
| 3617 | let mut latest_ts: Option<DateTime<Utc>> = None; |
| 3618 | self.for_each_event(thread_id, |event| { |
| 3619 | latest_ts = Some(match latest_ts { |
| 3620 | Some(prev) => prev.max(event.timestamp), |
| 3621 | None => event.timestamp, |
| 3622 | }); |
| 3623 | if let Some(turn_id) = event.turn_id.as_deref() |
| 3624 | && !turn_id.trim().is_empty() |
| 3625 | { |
| 3626 | latest_turn_id = Some(turn_id.to_string()); |
| 3627 | } |
| 3628 | if matches!(event.event.as_str(), "thread.started" | "thread.updated") |
| 3629 | && let Some(raw_thread) = event.payload.get("thread") |
| 3630 | && let Ok(candidate) = serde_json::from_value::<ThreadRecord>(raw_thread.clone()) |
| 3631 | && candidate.id == thread_id |
| 3632 | { |
| 3633 | if candidate.schema_version > MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION { |
| 3634 | bail!( |
| 3635 | "Thread schema v{} is newer than supported v{}", |
| 3636 | candidate.schema_version, |
| 3637 | MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION |
| 3638 | ); |
| 3639 | } |
| 3640 | rebuilt = Some(candidate); |
| 3641 | } |
| 3642 | Ok(()) |
| 3643 | })?; |
| 3644 | let Some(mut record) = rebuilt else { |
| 3645 | return Ok(None); |
| 3646 | }; |
| 3647 | if let Some(turn_id) = latest_turn_id { |
| 3648 | record.latest_turn_id = Some(turn_id); |
| 3649 | } |
| 3650 | if let Some(ts) = latest_ts { |
| 3651 | record.updated_at = record.updated_at.max(ts); |
| 3652 | } |
| 3653 | Ok(Some(record)) |
| 3654 | } |
| 3655 | |
| 3656 | fn check_newer_thread_schema_version(raw: &str) -> Result<()> { |
| 3657 | if let Ok(value) = serde_json::from_str::<serde_json::Value>(raw) |
| 3658 | && let Some(version) = value.get("schema_version").and_then(Value::as_u64) |
| 3659 | && version > u64::from(MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION) |
| 3660 | { |
| 3661 | bail!( |
| 3662 | "Thread schema v{version} is newer than supported v{MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION}" |
| 3663 | ); |
| 3664 | } |
| 3665 | Ok(()) |
| 3666 | } |
| 3667 | |
| 3668 | pub fn load_thread(&self, thread_id: &str) -> Result<ThreadRecord> { |
| 3669 | self.read_thread(thread_id, true) |
| 3670 | } |
| 3671 | |
| 3672 | fn read_thread(&self, thread_id: &str, repair: bool) -> Result<ThreadRecord> { |
| 3673 | let path = self.thread_path(thread_id)?; |
| 3674 | let raw = read_store_file(&path).with_context(|| { |
| 3675 | RuntimeStoreRecordFailure::new( |
| 3676 | RuntimeStoreOperation::Read, |
| 3677 | RuntimeStoreRecordKind::Thread, |
| 3678 | thread_id, |
| 3679 | &path, |
| 3680 | ) |
| 3681 | })?; |
| 3682 | let record: ThreadRecord = match serde_json::from_str(&raw) { |
| 3683 | Ok(record) => record, |
| 3684 | Err(parse_err) => { |
| 3685 | Self::check_newer_thread_schema_version(&raw)?; |
| 3686 | match if repair { |
| 3687 | self.rebuild_thread_from_event_log(thread_id) |
| 3688 | } else { |
| 3689 | Ok(None) |
| 3690 | } { |
| 3691 | Ok(Some(rebuilt)) => { |
| 3692 | tracing::warn!( |
| 3693 | target: "runtime", |
| 3694 | thread_id, |
| 3695 | "rebuilt damaged thread record from event log" |
| 3696 | ); |
| 3697 | let _ = self.save_thread(&rebuilt); |
| 3698 | return Ok(rebuilt); |
| 3699 | } |
| 3700 | Err(err) if err.to_string().contains("is newer than supported") => { |
| 3701 | return Err(err); |
| 3702 | } |
| 3703 | Ok(None) | Err(_) => { |
| 3704 | return Err(parse_err).with_context(|| { |
| 3705 | RuntimeStoreRecordFailure::new( |
| 3706 | RuntimeStoreOperation::Parse, |
| 3707 | RuntimeStoreRecordKind::Thread, |
| 3708 | thread_id, |
| 3709 | &path, |
| 3710 | ) |
| 3711 | }); |
| 3712 | } |
| 3713 | } |
| 3714 | } |
| 3715 | }; |
| 3716 | if record.schema_version > MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION { |
| 3717 | bail!( |
| 3718 | "Thread schema v{} is newer than supported v{}", |
| 3719 | record.schema_version, |
| 3720 | MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION |
| 3721 | ); |
| 3722 | } |
| 3723 | Ok(record) |
| 3724 | } |
| 3725 | |
| 3726 | pub fn load_turn(&self, turn_id: &str) -> Result<TurnRecord> { |
| 3727 | let path = self.turn_path(turn_id)?; |
| 3728 | let raw = read_store_file(&path).with_context(|| { |
| 3729 | RuntimeStoreRecordFailure::new( |
| 3730 | RuntimeStoreOperation::Read, |
| 3731 | RuntimeStoreRecordKind::Turn, |
| 3732 | turn_id, |
| 3733 | &path, |
| 3734 | ) |
| 3735 | })?; |
| 3736 | let record: TurnRecord = serde_json::from_str(&raw).with_context(|| { |
| 3737 | RuntimeStoreRecordFailure::new( |
| 3738 | RuntimeStoreOperation::Parse, |
| 3739 | RuntimeStoreRecordKind::Turn, |
| 3740 | turn_id, |
| 3741 | &path, |
| 3742 | ) |
| 3743 | })?; |
| 3744 | record.validate_output_token_limit()?; |
| 3745 | Ok(record) |
| 3746 | } |
| 3747 | |
| 3748 | pub fn load_item(&self, item_id: &str) -> Result<TurnItemRecord> { |
| 3749 | let path = self.item_path(item_id)?; |
| 3750 | let raw = read_store_file(&path).with_context(|| { |
| 3751 | RuntimeStoreRecordFailure::new( |
| 3752 | RuntimeStoreOperation::Read, |
| 3753 | RuntimeStoreRecordKind::Item, |
| 3754 | item_id, |
| 3755 | &path, |
| 3756 | ) |
| 3757 | })?; |
| 3758 | let record: TurnItemRecord = serde_json::from_str(&raw).with_context(|| { |
| 3759 | RuntimeStoreRecordFailure::new( |
| 3760 | RuntimeStoreOperation::Parse, |
| 3761 | RuntimeStoreRecordKind::Item, |
| 3762 | item_id, |
| 3763 | &path, |
| 3764 | ) |
| 3765 | })?; |
| 3766 | if record.schema_version > MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION { |
| 3767 | bail!( |
| 3768 | "Item schema v{} is newer than supported v{}", |
| 3769 | record.schema_version, |
| 3770 | MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION |
| 3771 | ); |
| 3772 | } |
| 3773 | if matches!( |
| 3774 | record.schema_version, |
| 3775 | IMAGE_RUNTIME_SCHEMA_VERSION | OUTPUT_LIMIT_RUNTIME_SCHEMA_VERSION |
| 3776 | ) && record.kind == TurnItemKind::UserMessage |
| 3777 | { |
| 3778 | record.user_content()?; |
| 3779 | } |
| 3780 | Ok(record) |
| 3781 | } |
| 3782 | |
| 3783 | pub fn list_threads(&self) -> Result<Vec<ThreadRecord>> { |
| 3784 | let (threads, skipped) = self.list_threads_lenient()?; |
| 3785 | for skipped in skipped { |
| 3786 | tracing::warn!(target: "runtime", "skipped an unreadable thread record: {skipped}"); |
| 3787 | } |
| 3788 | Ok(threads) |
| 3789 | } |
| 3790 | |
| 3791 | /// Every readable thread, plus a description of each record that could |
| 3792 | /// not be read. One corrupt record used to fail the whole thread rail |
| 3793 | /// (#6144 P7); it is now skipped and reported instead. A record from a |
| 3794 | /// newer schema is still refused outright — skipping it would hide work |
| 3795 | /// a newer build owns. |
| 3796 | pub fn list_threads_lenient(&self) -> Result<(Vec<ThreadRecord>, Vec<String>)> { |
| 3797 | self.read_threads(true) |
| 3798 | } |
| 3799 | |
| 3800 | fn read_threads(&self, repair: bool) -> Result<(Vec<ThreadRecord>, Vec<String>)> { |
| 3801 | let mut out = Vec::new(); |
| 3802 | let mut skipped = Vec::new(); |
| 3803 | let threads_dir = checked_existing_runtime_store_dir(&self.threads_dir)?; |
| 3804 | for entry in fs::read_dir(&threads_dir) |
| 3805 | .with_context(|| format!("Failed to read {}", threads_dir.display()))? |
| 3806 | { |
| 3807 | let entry = entry?; |
| 3808 | let path = entry.path(); |
| 3809 | if path.extension().is_none_or(|ext| ext != "json") { |
| 3810 | continue; |
| 3811 | } |
| 3812 | let raw = match read_store_file(&path) |
| 3813 | .with_context(|| format!("Failed to read {}", path.display())) |
| 3814 | { |
| 3815 | Ok(raw) => raw, |
| 3816 | Err(error) => { |
| 3817 | skipped.push(format!("{error:#}")); |
| 3818 | continue; |
| 3819 | } |
| 3820 | }; |
| 3821 | let thread: ThreadRecord = match serde_json::from_str(&raw) |
| 3822 | .with_context(|| format!("Failed to parse {}", path.display())) |
| 3823 | { |
| 3824 | Ok(thread) => thread, |
| 3825 | Err(error) => { |
| 3826 | Self::check_newer_thread_schema_version(&raw)?; |
| 3827 | let rebuilt = match path |
| 3828 | .file_stem() |
| 3829 | .and_then(|stem| stem.to_str()) |
| 3830 | .filter(|_| repair) |
| 3831 | { |
| 3832 | Some(thread_id) => match self.rebuild_thread_from_event_log(thread_id) { |
| 3833 | Ok(rebuilt) => rebuilt, |
| 3834 | Err(rebuild_err) |
| 3835 | if rebuild_err.to_string().contains("is newer than supported") => |
| 3836 | { |
| 3837 | return Err(rebuild_err); |
| 3838 | } |
| 3839 | Err(_) => None, |
| 3840 | }, |
| 3841 | None => None, |
| 3842 | }; |
| 3843 | if let Some(thread) = rebuilt { |
| 3844 | tracing::warn!( |
| 3845 | target: "runtime", |
| 3846 | thread_id = %thread.id, |
| 3847 | "rebuilt damaged thread record from event log during thread listing" |
| 3848 | ); |
| 3849 | let _ = self.save_thread(&thread); |
| 3850 | thread |
| 3851 | } else { |
| 3852 | skipped.push(format!("{error:#}")); |
| 3853 | continue; |
| 3854 | } |
| 3855 | } |
| 3856 | }; |
| 3857 | if thread.schema_version > MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION { |
| 3858 | bail!( |
| 3859 | "Thread schema v{} is newer than supported v{}", |
| 3860 | thread.schema_version, |
| 3861 | MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION |
| 3862 | ); |
| 3863 | } |
| 3864 | out.push(thread); |
| 3865 | } |
| 3866 | out.sort_by_key(|t| std::cmp::Reverse(t.updated_at)); |
| 3867 | Ok((out, skipped)) |
| 3868 | } |
| 3869 | |
| 3870 | pub fn list_turns_for_thread(&self, thread_id: &str) -> Result<Vec<TurnRecord>> { |
| 3871 | validated_record_id(thread_id, "thread id")?; |
| 3872 | let mut out = self.list_all_turns()?; |
| 3873 | out.retain(|turn| turn.thread_id == thread_id); |
| 3874 | Ok(out) |
| 3875 | } |
| 3876 | |
| 3877 | /// Every turn in the store, sorted by creation time. One directory scan; |
| 3878 | /// callers that need multiple threads' turns (boot recovery) use this |
| 3879 | /// instead of paying a full scan per thread (#3757). |
| 3880 | pub fn list_all_turns(&self) -> Result<Vec<TurnRecord>> { |
| 3881 | let mut out = Vec::new(); |
| 3882 | let turns_dir = checked_existing_runtime_store_dir(&self.turns_dir)?; |
| 3883 | for entry in fs::read_dir(&turns_dir) |
| 3884 | .with_context(|| format!("Failed to read {}", turns_dir.display()))? |
| 3885 | { |
| 3886 | let entry = entry?; |
| 3887 | let path = entry.path(); |
| 3888 | if path.extension().is_none_or(|ext| ext != "json") { |
| 3889 | continue; |
| 3890 | } |
| 3891 | let raw = read_store_file(&path) |
| 3892 | .with_context(|| format!("Failed to read {}", path.display()))?; |
| 3893 | #[cfg(any(test, feature = "test-support"))] |
| 3894 | self.turn_dir_files_read |
| 3895 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3896 | let turn: TurnRecord = serde_json::from_str(&raw) |
| 3897 | .with_context(|| format!("Failed to parse {}", path.display()))?; |
| 3898 | turn.validate_output_token_limit()?; |
| 3899 | out.push(turn); |
| 3900 | } |
| 3901 | out.sort_by(|left, right| { |
| 3902 | let left_parent = runtime_usage_partition_parent(left); |
| 3903 | let right_parent = runtime_usage_partition_parent(right); |
| 3904 | ( |
| 3905 | left.created_at, |
| 3906 | left_parent.unwrap_or(left.id.as_str()), |
| 3907 | left_parent.is_some(), |
| 3908 | left.id.as_str(), |
| 3909 | ) |
| 3910 | .cmp(&( |
| 3911 | right.created_at, |
| 3912 | right_parent.unwrap_or(right.id.as_str()), |
| 3913 | right_parent.is_some(), |
| 3914 | right.id.as_str(), |
| 3915 | )) |
| 3916 | }); |
| 3917 | Ok(out) |
| 3918 | } |
| 3919 | |
| 3920 | pub fn list_items_for_turn(&self, turn_id: &str) -> Result<Vec<TurnItemRecord>> { |
| 3921 | validated_record_id(turn_id, "turn id")?; |
| 3922 | let mut out = Vec::new(); |
| 3923 | let items_dir = checked_existing_runtime_store_dir(&self.items_dir)?; |
| 3924 | for entry in fs::read_dir(&items_dir) |
| 3925 | .with_context(|| format!("Failed to read {}", items_dir.display()))? |
| 3926 | { |
| 3927 | let entry = entry?; |
| 3928 | let path = entry.path(); |
| 3929 | if path.extension().is_none_or(|ext| ext != "json") { |
| 3930 | continue; |
| 3931 | } |
| 3932 | let item_id = path |
| 3933 | .file_stem() |
| 3934 | .map(|stem| stem.to_string_lossy().into_owned()) |
| 3935 | .unwrap_or_default(); |
| 3936 | let raw = read_store_file(&path).with_context(|| { |
| 3937 | RuntimeStoreRecordFailure::new( |
| 3938 | RuntimeStoreOperation::Read, |
| 3939 | RuntimeStoreRecordKind::Item, |
| 3940 | &item_id, |
| 3941 | &path, |
| 3942 | ) |
| 3943 | })?; |
| 3944 | #[cfg(any(test, feature = "test-support"))] |
| 3945 | self.item_dir_files_read |
| 3946 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3947 | let item: TurnItemRecord = serde_json::from_str(&raw).with_context(|| { |
| 3948 | RuntimeStoreRecordFailure::new( |
| 3949 | RuntimeStoreOperation::Parse, |
| 3950 | RuntimeStoreRecordKind::Item, |
| 3951 | &item_id, |
| 3952 | &path, |
| 3953 | ) |
| 3954 | })?; |
| 3955 | if item.schema_version > MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION { |
| 3956 | bail!( |
| 3957 | "Item schema v{} is newer than supported v{}", |
| 3958 | item.schema_version, |
| 3959 | MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION |
| 3960 | ); |
| 3961 | } |
| 3962 | if matches!( |
| 3963 | item.schema_version, |
| 3964 | IMAGE_RUNTIME_SCHEMA_VERSION | OUTPUT_LIMIT_RUNTIME_SCHEMA_VERSION |
| 3965 | ) && item.kind == TurnItemKind::UserMessage |
| 3966 | { |
| 3967 | item.user_content()?; |
| 3968 | } |
| 3969 | if item.turn_id == turn_id { |
| 3970 | out.push(item); |
| 3971 | } |
| 3972 | } |
| 3973 | sort_turn_items_by_start(&mut out); |
| 3974 | Ok(out) |
| 3975 | } |
| 3976 | |
| 3977 | fn thread_item( |
| 3978 | &self, |
| 3979 | thread_id: &str, |
| 3980 | item_id: &str, |
| 3981 | ) -> Result<Option<(TurnItemRecord, TurnRecord)>> { |
| 3982 | let item = match self.load_item(item_id) { |
| 3983 | Ok(item) => item, |
| 3984 | Err(error) if store_record_missing(&error) => return Ok(None), |
| 3985 | Err(error) => return Err(error), |
| 3986 | }; |
| 3987 | match self.load_turn(&item.turn_id) { |
| 3988 | Ok(turn) if turn.thread_id == thread_id => Ok(Some((item, turn))), |
| 3989 | Ok(_) => Ok(None), |
| 3990 | Err(error) if store_record_missing(&error) => Ok(None), |
| 3991 | Err(error) => Err(error), |
| 3992 | } |
| 3993 | } |
| 3994 | |
| 3995 | pub fn list_items_for_turns_map( |
| 3996 | &self, |
| 3997 | turn_ids: &[String], |
| 3998 | ) -> Result<HashMap<String, Vec<TurnItemRecord>>> { |
| 3999 | if turn_ids.is_empty() { |
| 4000 | return Ok(HashMap::new()); |
| 4001 | } |
| 4002 | |
| 4003 | for turn_id in turn_ids { |
| 4004 | validated_record_id(turn_id, "turn id")?; |
| 4005 | } |
| 4006 | |
| 4007 | let wanted: HashSet<&str> = turn_ids.iter().map(String::as_str).collect(); |
| 4008 | let mut out: HashMap<String, Vec<TurnItemRecord>> = HashMap::new(); |
| 4009 | for (turn_id, item_ids) in self.item_ids_for_turns(&wanted)? { |
| 4010 | for item_id in item_ids { |
| 4011 | // An index entry whose file is gone contributes nothing, which |
| 4012 | // is what the directory walk this replaced reported too. |
| 4013 | if !self.item_path(&item_id)?.exists() { |
| 4014 | continue; |
| 4015 | } |
| 4016 | let item = self.load_item(&item_id)?; |
| 4017 | out.entry(turn_id.clone()).or_default().push(item); |
| 4018 | } |
| 4019 | } |
| 4020 | |
| 4021 | for items in out.values_mut() { |
| 4022 | sort_turn_items_by_start(items); |
| 4023 | } |
| 4024 | Ok(out) |
| 4025 | } |
| 4026 | |
| 4027 | /// The item ids this store holds for each of `turn_ids`, from the one |
| 4028 | /// items-directory read [`Self::ensure_item_index`] performs. |
| 4029 | fn item_ids_for_turns(&self, turn_ids: &HashSet<&str>) -> Result<HashMap<String, Vec<String>>> { |
| 4030 | self.ensure_item_index()?; |
| 4031 | let index = self.item_index.read(); |
| 4032 | let by_turn = index |
| 4033 | .by_turn |
| 4034 | .as_ref() |
| 4035 | .context("item index must be published before it is read")?; |
| 4036 | Ok(turn_ids |
| 4037 | .iter() |
| 4038 | .filter_map(|turn_id| { |
| 4039 | by_turn |
| 4040 | .get(*turn_id) |
| 4041 | .map(|item_ids| ((*turn_id).to_string(), item_ids.clone())) |
| 4042 | }) |
| 4043 | .collect()) |
| 4044 | } |
| 4045 | |
| 4046 | /// Learn which items each turn owns: one listing, plus a record read for |
| 4047 | /// every item no earlier process has seen. |
| 4048 | /// |
| 4049 | /// An item's filename carries the item id and nothing else, so the only way |
| 4050 | /// to learn which items a turn has is to open the item records. Both callers |
| 4051 | /// used to do exactly that per request: [`Self::get_thread_detail`] |
| 4052 | /// (`GET /v1/threads/{id}`, one walk per thread opened) and the fork |
| 4053 | /// preparation whose items the transcript rebuild reads. On the store this |
| 4054 | /// was measured against — 61,441 items, 294MB, 140 threads — one walk costs |
| 4055 | /// ~1.4s warm and 6.7s cold, and it was the whole of a thread's open time; a |
| 4056 | /// median thread holds 272 items, so reading the ones it needs is ~7ms. |
| 4057 | /// |
| 4058 | /// The listing is cheap and decides membership; what an earlier process |
| 4059 | /// learned is read from [`Self::cache_item_index`]'s file, so a store that |
| 4060 | /// has been opened once costs the listing and nothing more. Measured on a |
| 4061 | /// 55,572-item store: 3.9s with no cache, 93ms with one. |
| 4062 | /// |
| 4063 | /// The walk is not parallelizable either, which is why this reads once |
| 4064 | /// instead of reading harder: sixteen concurrent `cat` streams of the same |
| 4065 | /// 61k files finished in 3.6s against 2.1s for one, and four in 1.5s. The |
| 4066 | /// cost is the per-file syscall, not the bytes. |
| 4067 | /// |
| 4068 | /// The read runs under the seed guard and outside the index guard, so a |
| 4069 | /// writer never waits for it. A write that lands while the read runs may or |
| 4070 | /// may not be in the directory snapshot it takes, so the writer records that |
| 4071 | /// write and the published map drains the records. A write with no read |
| 4072 | /// running records nothing: its file is already on disk, so the next read |
| 4073 | /// finds it in the directory itself. |
| 4074 | fn ensure_item_index(&self) -> Result<()> { |
| 4075 | if self.item_index.read().by_turn.is_some() { |
| 4076 | return Ok(()); |
| 4077 | } |
| 4078 | |
| 4079 | // One read at a time. A caller that finds the read already running |
| 4080 | // waits here and then takes the map it produced, rather than reading |
| 4081 | // the same directory a second time. |
| 4082 | let _seed = self.item_index_seed.lock(); |
| 4083 | if self.item_index.read().by_turn.is_some() { |
| 4084 | return Ok(()); |
| 4085 | } |
| 4086 | |
| 4087 | // The item ids the store holds now. This is a directory listing, not a |
| 4088 | // read of its records: on the store this was measured against it is |
| 4089 | // 27ms for 55,572 items against 4.8s to open every one of them. |
| 4090 | let items_dir = checked_existing_runtime_store_dir(&self.items_dir)?; |
| 4091 | let mut item_ids: Vec<String> = Vec::new(); |
| 4092 | for entry in fs::read_dir(&items_dir) |
| 4093 | .with_context(|| format!("Failed to read {}", items_dir.display()))? |
| 4094 | { |
| 4095 | let entry = entry?; |
| 4096 | let path = entry.path(); |
| 4097 | if path.extension().is_none_or(|ext| ext != "json") { |
| 4098 | continue; |
| 4099 | } |
| 4100 | item_ids.push( |
| 4101 | path.file_stem() |
| 4102 | .map(|stem| stem.to_string_lossy().into_owned()) |
| 4103 | .unwrap_or_default(), |
| 4104 | ); |
| 4105 | } |
| 4106 | |
| 4107 | // What an earlier process already learned about these ids. Only the ids |
| 4108 | // this listing does not account for are opened: a store that has been |
| 4109 | // read once costs the listing above and nothing more, however many |
| 4110 | // items it holds. |
| 4111 | let known = self.load_persisted_item_index(); |
| 4112 | |
| 4113 | let mut by_turn: HashMap<String, Vec<String>> = HashMap::new(); |
| 4114 | let mut by_item: HashMap<String, String> = HashMap::with_capacity(item_ids.len()); |
| 4115 | for item_id in item_ids { |
| 4116 | // An entry for an id that is no longer in the directory is simply |
| 4117 | // not consulted: the listing decides membership, so deleting an |
| 4118 | // item needs no invalidation here. |
| 4119 | let turn_id = match known.get(&item_id) { |
| 4120 | Some(turn_id) => turn_id.clone(), |
| 4121 | None => { |
| 4122 | #[cfg(any(test, feature = "test-support"))] |
| 4123 | self.item_dir_files_read |
| 4124 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 4125 | self.load_item_turn_id(&item_id)? |
| 4126 | } |
| 4127 | }; |
| 4128 | by_item.insert(item_id.clone(), turn_id.clone()); |
| 4129 | by_turn.entry(turn_id).or_default().push(item_id); |
| 4130 | } |
| 4131 | |
| 4132 | let differs_from_cache = by_item != known; |
| 4133 | { |
| 4134 | let mut index = self.item_index.write(); |
| 4135 | for (turn_id, item_id) in std::mem::take(&mut index.pending) { |
| 4136 | let item_ids = by_turn.entry(turn_id).or_default(); |
| 4137 | if !item_ids.contains(&item_id) { |
| 4138 | item_ids.push(item_id); |
| 4139 | } |
| 4140 | } |
| 4141 | index.by_turn = Some(by_turn); |
| 4142 | } |
| 4143 | drop(_seed); |
| 4144 | // Nothing is written here. Reading a thread must leave the store exactly |
| 4145 | // as it found it — a `GET` that rewrote a file would violate that for |
| 4146 | // every reader, and the tests that snapshot a store to prove a route is |
| 4147 | // read-only would be right to fail. Caching is [`Self::cache_item_index`], |
| 4148 | // called deliberately by the startup warm-up. |
| 4149 | if differs_from_cache { |
| 4150 | self.item_index_differs_from_cache |
| 4151 | .store(true, std::sync::atomic::Ordering::Relaxed); |
| 4152 | } |
| 4153 | Ok(()) |
| 4154 | } |
| 4155 | |
| 4156 | /// Build the item index and leave it on disk for the next process. |
| 4157 | /// |
| 4158 | /// The write belongs to a caller that has decided to pay for it — the |
| 4159 | /// server's startup warm-up — and not to the reads it saves. A cache cannot |
| 4160 | /// be wrong here, only absent: every id in the file is checked against the |
| 4161 | /// directory listing before it is used, so a stale entry costs a record read |
| 4162 | /// and nothing else. |
| 4163 | pub fn cache_item_index(&self) -> Result<()> { |
| 4164 | self.ensure_item_index()?; |
| 4165 | if !self.persist_caches { |
| 4166 | return Ok(()); |
| 4167 | } |
| 4168 | if !self |
| 4169 | .item_index_differs_from_cache |
| 4170 | .load(std::sync::atomic::Ordering::Relaxed) |
| 4171 | { |
| 4172 | // The file already says exactly what this process learned. |
| 4173 | return Ok(()); |
| 4174 | } |
| 4175 | let by_item = { |
| 4176 | let index = self.item_index.read(); |
| 4177 | index |
| 4178 | .by_turn |
| 4179 | .as_ref() |
| 4180 | .map(|by_turn| { |
| 4181 | by_turn |
| 4182 | .iter() |
| 4183 | .flat_map(|(turn_id, item_ids)| { |
| 4184 | item_ids |
| 4185 | .iter() |
| 4186 | .map(move |item_id| (item_id.clone(), turn_id.clone())) |
| 4187 | }) |
| 4188 | .collect::<HashMap<String, String>>() |
| 4189 | }) |
| 4190 | .unwrap_or_default() |
| 4191 | }; |
| 4192 | match self.write_persisted_item_index(&by_item) { |
| 4193 | // Cleared only once the file says it: a write that failed leaves |
| 4194 | // the flag set, so a later call in this process can still try. |
| 4195 | Ok(()) => self |
| 4196 | .item_index_differs_from_cache |
| 4197 | .store(false, std::sync::atomic::Ordering::Relaxed), |
| 4198 | // A cache that cannot be written costs the next process the read it |
| 4199 | // would have saved, which is the state every process was in before |
| 4200 | // this file existed. It is not a reason to fail startup. |
| 4201 | Err(error) => tracing::debug!(%error, "runtime item index could not be cached"), |
| 4202 | } |
| 4203 | Ok(()) |
| 4204 | } |
| 4205 | |
| 4206 | /// Where the item index is cached, beside the directories it describes. |
| 4207 | fn item_index_path(&self) -> Option<PathBuf> { |
| 4208 | self.threads_dir |
| 4209 | .parent() |
| 4210 | .map(|root| root.join(ITEM_INDEX_CACHE_FILE)) |
| 4211 | } |
| 4212 | |
| 4213 | /// The cached item->turn map, or an empty one to rebuild from. |
| 4214 | /// |
| 4215 | /// Every failure reads as "nothing known": a cache that cannot be trusted |
| 4216 | /// must cost the full read, never a wrong answer, so a file from another |
| 4217 | /// schema, a truncated file, or a file this process cannot read all take |
| 4218 | /// the same branch. |
| 4219 | fn load_persisted_item_index(&self) -> HashMap<String, String> { |
| 4220 | let Some(path) = self.item_index_path() else { |
| 4221 | return HashMap::new(); |
| 4222 | }; |
| 4223 | let raw = match read_store_file(&path) { |
| 4224 | Ok(raw) => raw, |
| 4225 | // Absent is the normal case for a store no process has warmed yet, |
| 4226 | // and a file this process may not read is no different from absent. |
| 4227 | Err(_) => return HashMap::new(), |
| 4228 | }; |
| 4229 | match serde_json::from_str::<PersistedItemIndex>(&raw) { |
| 4230 | Ok(cache) if cache.schema_version == ITEM_INDEX_SCHEMA_VERSION => cache.by_item, |
| 4231 | _ => HashMap::new(), |
| 4232 | } |
| 4233 | } |
| 4234 | |
| 4235 | /// Publish the cache for the next process. |
| 4236 | /// |
| 4237 | /// Deliberately not [`write_json_atomic`]: that one syncs the payload and |
| 4238 | /// then the parent directory, which is what a durable record owes and what a |
| 4239 | /// cache does not. Losing this file to a crash costs the next process one |
| 4240 | /// full read — the state every process was in before it existed — so the |
| 4241 | /// write is a plain rename over a temporary, atomic for readers and cheap |
| 4242 | /// for the caller. |
| 4243 | fn write_persisted_item_index(&self, by_item: &HashMap<String, String>) -> Result<()> { |
| 4244 | let Some(path) = self.item_index_path() else { |
| 4245 | return Ok(()); |
| 4246 | }; |
| 4247 | reject_symlinked_store_file(&path)?; |
| 4248 | let payload = serde_json::to_vec(&PersistedItemIndex { |
| 4249 | schema_version: ITEM_INDEX_SCHEMA_VERSION, |
| 4250 | by_item: by_item.clone(), |
| 4251 | })?; |
| 4252 | // Named for this process so two of them cannot overwrite each other's |
| 4253 | // temporary; the rename below is what publishes it either way. |
| 4254 | let temporary = path.with_file_name(format!( |
| 4255 | "{ITEM_INDEX_CACHE_FILE}.{}.tmp", |
| 4256 | std::process::id() |
| 4257 | )); |
| 4258 | fs::write(&temporary, payload) |
| 4259 | .with_context(|| format!("Failed to write {}", temporary.display()))?; |
| 4260 | fs::rename(&temporary, &path) |
| 4261 | .with_context(|| format!("Failed to publish {}", path.display()))?; |
| 4262 | Ok(()) |
| 4263 | } |
| 4264 | |
| 4265 | /// The turn an item belongs to, without materializing the record. |
| 4266 | /// |
| 4267 | /// Only used where the whole directory is read to learn that one field — |
| 4268 | /// see [`Self::ensure_item_index`]. An item's `detail` can hold a tool |
| 4269 | /// result of hundreds of kilobytes, and deserializing into |
| 4270 | /// [`TurnItemRecord`] allocates every one of them to answer a question |
| 4271 | /// about an id. |
| 4272 | fn load_item_turn_id(&self, item_id: &str) -> Result<String> { |
| 4273 | let path = self.item_path(item_id)?; |
| 4274 | let raw = read_store_file(&path).with_context(|| { |
| 4275 | RuntimeStoreRecordFailure::new( |
| 4276 | RuntimeStoreOperation::Read, |
| 4277 | RuntimeStoreRecordKind::Item, |
| 4278 | item_id, |
| 4279 | &path, |
| 4280 | ) |
| 4281 | })?; |
| 4282 | let reference: ItemTurnReference = serde_json::from_str(&raw).with_context(|| { |
| 4283 | RuntimeStoreRecordFailure::new( |
| 4284 | RuntimeStoreOperation::Parse, |
| 4285 | RuntimeStoreRecordKind::Item, |
| 4286 | item_id, |
| 4287 | &path, |
| 4288 | ) |
| 4289 | })?; |
| 4290 | Ok(reference.turn_id) |
| 4291 | } |
| 4292 | |
| 4293 | /// Drop what the cache says about item ownership if this write moves an |
| 4294 | /// item to another turn. |
| 4295 | /// |
| 4296 | /// An item's filename is its id, so a record written again under a second |
| 4297 | /// turn is indistinguishable from the outside: the listing sees the same |
| 4298 | /// name, and a cache built before the write keeps answering for the turn |
| 4299 | /// that lost it. Ownership is therefore checked at the one place it can |
| 4300 | /// change — the write — and the cache is dropped rather than patched. A |
| 4301 | /// missing cache costs the next process one full read, which is the safe |
| 4302 | /// side of this trade; a wrong owner is a turn that silently lists an item |
| 4303 | /// it no longer has and a turn that cannot find one it does. |
| 4304 | fn forget_cached_item_ownership(&self, item: &TurnItemRecord) { |
| 4305 | if !self.persist_caches { |
| 4306 | return; |
| 4307 | } |
| 4308 | let Some(cache) = self.item_index_path() else { |
| 4309 | return; |
| 4310 | }; |
| 4311 | // Nothing cached, nothing that can be stale — and no record read paid |
| 4312 | // by the common case of a store no process has warmed yet. |
| 4313 | if !cache.exists() { |
| 4314 | return; |
| 4315 | } |
| 4316 | let previous = match self.load_item_turn_id(&item.id) { |
| 4317 | Ok(turn_id) => turn_id, |
| 4318 | // A new id: no cached entry can name it. |
| 4319 | Err(error) if store_record_missing(&error) => return, |
| 4320 | // Unreadable, so its owner is unknown. Distrust the whole cache |
| 4321 | // rather than keep an entry that may be about to be wrong. |
| 4322 | Err(_) => { |
| 4323 | self.drop_persisted_item_index(); |
| 4324 | return; |
| 4325 | } |
| 4326 | }; |
| 4327 | if previous == item.turn_id { |
| 4328 | return; |
| 4329 | } |
| 4330 | // This process's index holds the same stale entry. |
| 4331 | { |
| 4332 | let mut index = self.item_index.write(); |
| 4333 | if let Some(by_turn) = index.by_turn.as_mut() |
| 4334 | && let Some(item_ids) = by_turn.get_mut(&previous) |
| 4335 | { |
| 4336 | item_ids.retain(|known| known != &item.id); |
| 4337 | } |
| 4338 | } |
| 4339 | self.drop_persisted_item_index(); |
| 4340 | } |
| 4341 | |
| 4342 | /// Forget the index kept on disk, so the next process rebuilds it. |
| 4343 | fn drop_persisted_item_index(&self) { |
| 4344 | if let Some(path) = self.item_index_path() |
| 4345 | && let Err(error) = remove_file_if_exists(&path) |
| 4346 | { |
| 4347 | tracing::debug!(%error, "runtime item index cache could not be dropped"); |
| 4348 | } |
| 4349 | } |
| 4350 | |
| 4351 | /// Keep the item index current across an item write. |
| 4352 | /// |
| 4353 | /// The two writers ([`Self::save_item`] and [`Self::save_items_batch`]) are |
| 4354 | /// the only paths that can put an item in this store, so this is what makes |
| 4355 | /// the index exact rather than a snapshot: a reader sees every item the |
| 4356 | /// directory would have shown it, including the late ones |
| 4357 | /// [`Self::attach_item_to_turn`] deliberately leaves out of a settled turn's |
| 4358 | /// `item_ids`. |
| 4359 | fn note_item_in_index(&self, turn_id: &str, item_id: &str) { |
| 4360 | // Probing the seed guard says whether a directory read is running, and |
| 4361 | // the guard is dropped immediately: this call must never wait behind |
| 4362 | // one. The item this follows is already on disk, so a read that starts |
| 4363 | // later finds it in the directory; only a read that is *already* |
| 4364 | // running may have passed the file, and only that case is recorded — |
| 4365 | // which is what keeps this queue finite in a process that writes items |
| 4366 | // without ever reading them. |
| 4367 | let read_in_flight = self.item_index_seed.try_lock().is_none(); |
| 4368 | let mut index = self.item_index.write(); |
| 4369 | if index.by_turn.is_none() { |
| 4370 | if read_in_flight { |
| 4371 | index |
| 4372 | .pending |
| 4373 | .push((turn_id.to_string(), item_id.to_string())); |
| 4374 | } |
| 4375 | return; |
| 4376 | } |
| 4377 | // The runtime saves one item id many times (in progress, then |
| 4378 | // completed or failed), and a write that raced the directory read may |
| 4379 | // already be in the map from that read. An id is listed once per turn. |
| 4380 | let item_ids = index |
| 4381 | .by_turn |
| 4382 | .as_mut() |
| 4383 | .expect("checked above") |
| 4384 | .entry(turn_id.to_string()) |
| 4385 | .or_default(); |
| 4386 | if !item_ids.iter().any(|known| known == item_id) { |
| 4387 | item_ids.push(item_id.to_string()); |
| 4388 | } |
| 4389 | } |
| 4390 | |
| 4391 | /// The newest message text for each row of the thread list, read from the |
| 4392 | /// thread's own newest turn. |
| 4393 | /// |
| 4394 | /// A row shows the newest message of the newest turn that has one. That |
| 4395 | /// used to be answered by [`Self::newest_message_text_by_turn`] over every |
| 4396 | /// turn of every listed thread, and that call walks the whole items |
| 4397 | /// directory — an item filename carries only the item id, never its turn. |
| 4398 | /// A page of 100 threads out of a 140-thread store therefore read all |
| 4399 | /// 58,048 item records to fill 100 previews: ~1.4s per summary, on every |
| 4400 | /// summary, measured 2026-09-26 against the 658MB store, which is the |
| 4401 | /// wait the rail's spinner was covering. |
| 4402 | /// |
| 4403 | /// A turn record carries its own `item_ids`, so one turn's newest message |
| 4404 | /// can be read directly, and the walk below stops at the first thread turn |
| 4405 | /// that yields one. The page measured above resolves all 100 previews from |
| 4406 | /// 165 item files — it reads the tail of each row's newest turn and |
| 4407 | /// nothing else. |
| 4408 | /// |
| 4409 | /// The choice of turn is the one the batch read made: newest first, an |
| 4410 | /// older turn only when the newer ones hold no message text at all. |
| 4411 | fn newest_message_text_by_thread( |
| 4412 | &self, |
| 4413 | turns_by_thread: &HashMap<String, Vec<TurnRecord>>, |
| 4414 | ) -> Result<HashMap<String, String>> { |
| 4415 | let mut previews: HashMap<String, String> = HashMap::new(); |
| 4416 | // A turn written before `item_ids` existed cannot be read by id: only a |
| 4417 | // scan of the items directory can find it. Those turns are collected |
| 4418 | // so the scan runs once for the page rather than once per turn, and the |
| 4419 | // thread's walk resumes from the turn it stopped on. |
| 4420 | let mut legacy_turn_ids: Vec<String> = Vec::new(); |
| 4421 | let mut legacy_stops: Vec<(&str, usize)> = Vec::new(); |
| 4422 | |
| 4423 | for (thread_id, turns) in turns_by_thread { |
| 4424 | let mut walked = turns.len(); |
| 4425 | while walked > 0 { |
| 4426 | walked -= 1; |
| 4427 | let turn = &turns[walked]; |
| 4428 | if turn.item_ids.is_empty() { |
| 4429 | // This turn and every turn older than it are legacy, and |
| 4430 | // both need the same directory scan: hand them all over at |
| 4431 | // once instead of scanning per turn. |
| 4432 | for turn in &turns[..=walked] { |
| 4433 | legacy_turn_ids.push(turn.id.clone()); |
| 4434 | } |
| 4435 | legacy_stops.push((thread_id.as_str(), walked)); |
| 4436 | break; |
| 4437 | } |
| 4438 | if let Some(text) = self.newest_message_text_in_turn(turn)? { |
| 4439 | previews.insert(thread_id.clone(), text); |
| 4440 | break; |
| 4441 | } |
| 4442 | } |
| 4443 | } |
| 4444 | |
| 4445 | if !legacy_turn_ids.is_empty() { |
| 4446 | let legacy = self.newest_message_text_by_turn(&legacy_turn_ids)?; |
| 4447 | for (thread_id, walked) in legacy_stops { |
| 4448 | let turns = &turns_by_thread[thread_id]; |
| 4449 | if let Some(text) = turns[..=walked] |
| 4450 | .iter() |
| 4451 | .rev() |
| 4452 | .find_map(|turn| legacy.get(&turn.id).cloned()) |
| 4453 | { |
| 4454 | previews.insert(thread_id.to_string(), text); |
| 4455 | } |
| 4456 | } |
| 4457 | } |
| 4458 | |
| 4459 | Ok(previews) |
| 4460 | } |
| 4461 | |
| 4462 | /// The newest message text `turn` appended, read from the turn's own item |
| 4463 | /// list instead of from a scan of the items directory. |
| 4464 | /// |
| 4465 | /// A turn appends its items in order, so the last message item it wrote is |
| 4466 | /// the newest message it has: what follows that message is a status, |
| 4467 | /// reasoning, file-change or tool record, never another message. Walking |
| 4468 | /// the ids from the tail therefore ends within the handful of files between |
| 4469 | /// the end of the turn and its last message, where reading the turn whole |
| 4470 | /// would read every item it ever wrote. |
| 4471 | /// |
| 4472 | /// Selection agrees with [`Self::newest_message_text_by_turn`] on every |
| 4473 | /// turn of the 658MB / 58k-item store this was measured against (538 turns, |
| 4474 | /// 3,537 message items, 2026-09-26): non-message items never win and an |
| 4475 | /// empty message is skipped rather than reported. The comparison that call |
| 4476 | /// makes is on `started_at`, and append order is timestamp order because |
| 4477 | /// the runtime writes each item as its turn produces it — for every source |
| 4478 | /// of `item_ids`, not only the live one: a fork rebuilds the cloned turn's |
| 4479 | /// list from items already ordered by [`sort_turn_items_by_start`], and an |
| 4480 | /// imported conversation pushes its seed items in the order the importer |
| 4481 | /// stamped them. Where the two orders could disagree is a hand-edited or |
| 4482 | /// externally written store; there this walk agrees with what |
| 4483 | /// `RuntimeThreadManager::reconstruct_messages_from_turns_with` would |
| 4484 | /// replay for the model — `item_ids` order — rather than with `started_at`, |
| 4485 | /// which is the agreement that matters for a preview. |
| 4486 | /// |
| 4487 | /// Reading only `turn.item_ids` is complete for messages, not just fast: |
| 4488 | /// every writer of an `AgentMessage`/`UserMessage` item registers the id on |
| 4489 | /// its turn at the same time. Streaming turns attach as they go (the turn |
| 4490 | /// is active, so [`Self::attach_item_to_turn`] appends); `start_turn` and |
| 4491 | /// `steer_turn` push the user item onto a turn they have just loaded or |
| 4492 | /// verified in progress; an imported conversation writes the whole list |
| 4493 | /// before its turn exists. [`Self::attach_item_to_turn`] does leave a |
| 4494 | /// settled turn's `item_ids` untouched, but the only items that reach a |
| 4495 | /// settled turn that way are status, tool and error records — kinds this |
| 4496 | /// walk skips — never messages, so a settled turn cannot hold a late |
| 4497 | /// message its preview missed. |
| 4498 | fn newest_message_text_in_turn(&self, turn: &TurnRecord) -> Result<Option<String>> { |
| 4499 | for item_id in turn.item_ids.iter().rev() { |
| 4500 | // A turn can name an item whose file was since removed; the |
| 4501 | // directory walk this replaced never saw such an id, so it must |
| 4502 | // not fail the whole summary page either. |
| 4503 | if !self.item_path(item_id)?.exists() { |
| 4504 | continue; |
| 4505 | } |
| 4506 | let item = self.load_item(item_id)?; |
| 4507 | if !matches!( |
| 4508 | item.kind, |
| 4509 | TurnItemKind::AgentMessage | TurnItemKind::UserMessage |
| 4510 | ) { |
| 4511 | continue; |
| 4512 | } |
| 4513 | let text = item.detail.unwrap_or(item.summary); |
| 4514 | if text.trim().is_empty() { |
| 4515 | continue; |
| 4516 | } |
| 4517 | return Ok(Some(text)); |
| 4518 | } |
| 4519 | Ok(None) |
| 4520 | } |
| 4521 | |
| 4522 | fn latest_prompt_at( |
| 4523 | &self, |
| 4524 | turns: &[TurnRecord], |
| 4525 | mut remaining_items: usize, |
| 4526 | ) -> Option<DateTime<Utc>> { |
| 4527 | const MAX_TURNS: usize = 32; |
| 4528 | for turn in turns.iter().rev().take(MAX_TURNS) { |
| 4529 | if turn.routing_settlement |
| 4530 | || runtime_usage_partition_parent(turn).is_some() |
| 4531 | || turn.mode.is_none() |
| 4532 | { |
| 4533 | continue; |
| 4534 | } |
| 4535 | let Some(first_item_id) = turn.item_ids.first() else { |
| 4536 | continue; |
| 4537 | }; |
| 4538 | let item_ids = if turn.steer_count == 0 { |
| 4539 | std::slice::from_ref(first_item_id) |
| 4540 | } else { |
| 4541 | turn.item_ids.as_slice() |
| 4542 | }; |
| 4543 | for item_id in item_ids.iter().rev() { |
| 4544 | remaining_items = remaining_items.checked_sub(1)?; |
| 4545 | if !self.item_path(item_id).ok()?.exists() { |
| 4546 | continue; |
| 4547 | } |
| 4548 | let item = self.load_item(item_id).ok()?; |
| 4549 | if item.turn_id == turn.id |
| 4550 | && item.kind == TurnItemKind::UserMessage |
| 4551 | && item.status == TurnItemLifecycleStatus::Completed |
| 4552 | && item.metadata.as_ref().is_none_or(|metadata| { |
| 4553 | metadata.is_object() && metadata.get("input_provenance").is_none() |
| 4554 | }) |
| 4555 | { |
| 4556 | return if item_id == first_item_id { |
| 4557 | item.started_at |
| 4558 | } else { |
| 4559 | item.ended_at |
| 4560 | }; |
| 4561 | } |
| 4562 | } |
| 4563 | } |
| 4564 | None |
| 4565 | } |
| 4566 | |
| 4567 | /// The newest agent/user message text in each requested turn, in one pass. |
| 4568 | /// |
| 4569 | /// This is the directory-scan fallback: the thread summary reads previews |
| 4570 | /// through [`Self::newest_message_text_by_thread`], and reaches this call |
| 4571 | /// only for turns whose record predates `item_ids`. |
| 4572 | /// |
| 4573 | /// [`Self::list_items_for_turns_map`] materializes every item of every |
| 4574 | /// requested turn. The thread summary needs only the last user/agent |
| 4575 | /// message per turn, and one page can span most of the store, so retaining |
| 4576 | /// that whole projection for a page held every item it covered in memory |
| 4577 | /// at once — a page's peak that grew with the page instead of with one |
| 4578 | /// thread. This holds at most two message texts per requested turn — the |
| 4579 | /// newest dated one and the last undated one read — and nothing else: |
| 4580 | /// tool calls, results and artifacts are read and dropped, and an older |
| 4581 | /// dated message is dropped the moment a newer one is read. |
| 4582 | /// |
| 4583 | /// The winner is the message [`sort_turn_items_by_start`] would place |
| 4584 | /// last: that comparator reads only `started_at`, substitutes one "now" |
| 4585 | /// for a missing timestamp once everything has been read, and is stable, |
| 4586 | /// so the later-read message wins a tie. The choice between the dated |
| 4587 | /// and the undated candidate is therefore made after the scan, against a |
| 4588 | /// "now" taken then: a message persisted mid-scan with a timestamp later |
| 4589 | /// than a "now" taken up front would otherwise outrank an undated one |
| 4590 | /// the sort would have placed last. |
| 4591 | /// |
| 4592 | /// Known limitation: peak memory is still up to two texts per turn of |
| 4593 | /// the page, untruncated, because the caller decides which turn's text |
| 4594 | /// becomes the row's preview and how much of it to show. |
| 4595 | pub fn newest_message_text_by_turn( |
| 4596 | &self, |
| 4597 | turn_ids: &[String], |
| 4598 | ) -> Result<HashMap<String, String>> { |
| 4599 | if turn_ids.is_empty() { |
| 4600 | return Ok(HashMap::new()); |
| 4601 | } |
| 4602 | |
| 4603 | for turn_id in turn_ids { |
| 4604 | validated_record_id(turn_id, "turn id")?; |
| 4605 | } |
| 4606 | |
| 4607 | let wanted: HashSet<&str> = turn_ids.iter().map(String::as_str).collect(); |
| 4608 | #[derive(Default)] |
| 4609 | struct Candidates { |
| 4610 | /// Newest `started_at` read so far; a later read wins a tie. |
| 4611 | dated: Option<(DateTime<Utc>, String)>, |
| 4612 | /// Last message read without a `started_at`. |
| 4613 | undated: Option<String>, |
| 4614 | } |
| 4615 | let mut per_turn: HashMap<String, Candidates> = HashMap::new(); |
| 4616 | let items_dir = checked_existing_runtime_store_dir(&self.items_dir)?; |
| 4617 | for entry in fs::read_dir(&items_dir) |
| 4618 | .with_context(|| format!("Failed to read {}", items_dir.display()))? |
| 4619 | { |
| 4620 | let entry = entry?; |
| 4621 | let path = entry.path(); |
| 4622 | if path.extension().is_none_or(|ext| ext != "json") { |
| 4623 | continue; |
| 4624 | } |
| 4625 | let item_id = path |
| 4626 | .file_stem() |
| 4627 | .map(|stem| stem.to_string_lossy().into_owned()) |
| 4628 | .unwrap_or_default(); |
| 4629 | let raw = read_store_file(&path).with_context(|| { |
| 4630 | RuntimeStoreRecordFailure::new( |
| 4631 | RuntimeStoreOperation::Read, |
| 4632 | RuntimeStoreRecordKind::Item, |
| 4633 | &item_id, |
| 4634 | &path, |
| 4635 | ) |
| 4636 | })?; |
| 4637 | #[cfg(any(test, feature = "test-support"))] |
| 4638 | self.item_dir_files_read |
| 4639 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 4640 | let item: TurnItemRecord = serde_json::from_str(&raw).with_context(|| { |
| 4641 | RuntimeStoreRecordFailure::new( |
| 4642 | RuntimeStoreOperation::Parse, |
| 4643 | RuntimeStoreRecordKind::Item, |
| 4644 | &item_id, |
| 4645 | &path, |
| 4646 | ) |
| 4647 | })?; |
| 4648 | if item.schema_version > MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION { |
| 4649 | bail!( |
| 4650 | "Item schema v{} is newer than supported v{}", |
| 4651 | item.schema_version, |
| 4652 | MAX_SUPPORTED_RUNTIME_SCHEMA_VERSION |
| 4653 | ); |
| 4654 | } |
| 4655 | if !wanted.contains(item.turn_id.as_str()) { |
| 4656 | continue; |
| 4657 | } |
| 4658 | if !matches!( |
| 4659 | item.kind, |
| 4660 | TurnItemKind::AgentMessage | TurnItemKind::UserMessage |
| 4661 | ) { |
| 4662 | continue; |
| 4663 | } |
| 4664 | if matches!( |
| 4665 | item.schema_version, |
| 4666 | IMAGE_RUNTIME_SCHEMA_VERSION | OUTPUT_LIMIT_RUNTIME_SCHEMA_VERSION |
| 4667 | ) && item.kind == TurnItemKind::UserMessage |
| 4668 | { |
| 4669 | item.user_content()?; |
| 4670 | } |
| 4671 | let text = item.detail.unwrap_or(item.summary); |
| 4672 | if text.trim().is_empty() { |
| 4673 | continue; |
| 4674 | } |
| 4675 | let slot = per_turn.entry(item.turn_id).or_default(); |
| 4676 | match item.started_at { |
| 4677 | Some(started_at) => { |
| 4678 | if slot |
| 4679 | .dated |
| 4680 | .as_ref() |
| 4681 | .is_none_or(|(held, _)| *held <= started_at) |
| 4682 | { |
| 4683 | slot.dated = Some((started_at, text)); |
| 4684 | } |
| 4685 | } |
| 4686 | None => slot.undated = Some(text), |
| 4687 | } |
| 4688 | } |
| 4689 | |
| 4690 | // The sort's stand-in for a missing timestamp, taken once the scan |
| 4691 | // is over exactly as `sort_turn_items_by_start` takes it after |
| 4692 | // collection: an undated message reads as newest unless a dated one |
| 4693 | // is timestamped later than this instant. |
| 4694 | let fallback = Utc::now(); |
| 4695 | Ok(per_turn |
| 4696 | .into_iter() |
| 4697 | .filter_map(|(turn_id, slot)| { |
| 4698 | let text = match (slot.dated, slot.undated) { |
| 4699 | (Some((started_at, dated)), Some(undated)) => { |
| 4700 | if started_at > fallback { |
| 4701 | dated |
| 4702 | } else { |
| 4703 | undated |
| 4704 | } |
| 4705 | } |
| 4706 | (Some((_, dated)), None) => dated, |
| 4707 | (None, Some(undated)) => undated, |
| 4708 | (None, None) => return None, |
| 4709 | }; |
| 4710 | Some((turn_id, text)) |
| 4711 | }) |
| 4712 | .collect()) |
| 4713 | } |
| 4714 | |
| 4715 | pub async fn append_event( |
| 4716 | &self, |
| 4717 | thread_id: &str, |
| 4718 | turn_id: Option<&str>, |
| 4719 | item_id: Option<&str>, |
| 4720 | event: impl Into<String>, |
| 4721 | payload: Value, |
| 4722 | ) -> Result<RuntimeEventRecord> { |
| 4723 | validated_record_id(thread_id, "thread id")?; |
| 4724 | if let Some(turn_id) = turn_id { |
| 4725 | validated_record_id(turn_id, "turn id")?; |
| 4726 | } |
| 4727 | if let Some(item_id) = item_id { |
| 4728 | validated_record_id(item_id, "item id")?; |
| 4729 | } |
| 4730 | let store = self.clone(); |
| 4731 | let thread_id = thread_id.to_string(); |
| 4732 | let turn_id = turn_id.map(ToString::to_string); |
| 4733 | let item_id = item_id.map(ToString::to_string); |
| 4734 | let event = event.into(); |
| 4735 | let record = tokio::task::spawn_blocking(move || { |
| 4736 | store.append_event_transaction( |
| 4737 | thread_id, |
| 4738 | turn_id, |
| 4739 | item_id, |
| 4740 | event, |
| 4741 | payload, |
| 4742 | EVENT_TRANSACTION_LOCK_TIMEOUT, |
| 4743 | ) |
| 4744 | }) |
| 4745 | .await |
| 4746 | .context("Runtime event transaction worker failed")??; |
| 4747 | let mut progress = self.thread_progress.lock(); |
| 4748 | let newest = progress |
| 4749 | .entry(record.thread_id.clone()) |
| 4750 | .or_insert(record.timestamp); |
| 4751 | *newest = (*newest).max(record.timestamp); |
| 4752 | drop(progress); |
| 4753 | Ok(record) |
| 4754 | } |
| 4755 | |
| 4756 | pub fn thread_last_progress_at(&self, thread_id: &str) -> Option<DateTime<Utc>> { |
| 4757 | self.thread_progress.lock().get(thread_id).copied() |
| 4758 | } |
| 4759 | |
| 4760 | pub fn forget_thread_progress(&self, keep: &std::collections::HashSet<String>) { |
| 4761 | self.thread_progress |
| 4762 | .lock() |
| 4763 | .retain(|thread, _| keep.contains(thread)); |
| 4764 | } |
| 4765 | |
| 4766 | fn append_event_transaction( |
| 4767 | &self, |
| 4768 | thread_id: String, |
| 4769 | turn_id: Option<String>, |
| 4770 | item_id: Option<String>, |
| 4771 | event: String, |
| 4772 | payload: Value, |
| 4773 | lock_timeout: Duration, |
| 4774 | ) -> Result<RuntimeEventRecord> { |
| 4775 | let path = self.events_path(&thread_id)?; |
| 4776 | self.with_event_transaction(lock_timeout, || { |
| 4777 | reject_symlinked_store_dir(&self.events_dir)?; |
| 4778 | repair_torn_event_log_tail(&path)?; |
| 4779 | let mut record = RuntimeEventRecord { |
| 4780 | schema_version: CURRENT_RUNTIME_SCHEMA_VERSION, |
| 4781 | seq: 0, |
| 4782 | timestamp: Utc::now(), |
| 4783 | thread_id, |
| 4784 | turn_id, |
| 4785 | item_id, |
| 4786 | event, |
| 4787 | payload, |
| 4788 | }; |
| 4789 | self.write_event_records_locked(&path, std::slice::from_mut(&mut record))?; |
| 4790 | Ok(record) |
| 4791 | }) |
| 4792 | } |
| 4793 | |
| 4794 | fn write_event_records_locked( |
| 4795 | &self, |
| 4796 | path: &Path, |
| 4797 | records: &mut [RuntimeEventRecord], |
| 4798 | ) -> Result<()> { |
| 4799 | if records.is_empty() { |
| 4800 | return Ok(()); |
| 4801 | } |
| 4802 | #[cfg(any(test, feature = "test-support"))] |
| 4803 | let thread_id = records[0].thread_id.clone(); |
| 4804 | let mut state = load_runtime_store_state(&self.state_path)?; |
| 4805 | let mut lines = Vec::new(); |
| 4806 | for record in records { |
| 4807 | record.seq = state.next_seq; |
| 4808 | state.next_seq = state |
| 4809 | .next_seq |
| 4810 | .checked_add(1) |
| 4811 | .context("Runtime event sequence exhausted")?; |
| 4812 | serde_json::to_writer(&mut lines, record)?; |
| 4813 | lines.push(b'\n'); |
| 4814 | } |
| 4815 | write_json_atomic(&self.state_path, &state)?; |
| 4816 | let mut file = open_runtime_store_file(path, "event append", |options| { |
| 4817 | options.create(true).append(true); |
| 4818 | })?; |
| 4819 | let rollback_file = open_runtime_store_file(path, "Runtime event rollback", |options| { |
| 4820 | options.write(true); |
| 4821 | })?; |
| 4822 | validate_same_runtime_store_file_handles(&file, &rollback_file, path)?; |
| 4823 | let original_len = file |
| 4824 | .metadata() |
| 4825 | .with_context(|| format!("Failed to inspect {}", path.display()))? |
| 4826 | .len(); |
| 4827 | let append_result = (|| -> std::io::Result<()> { |
| 4828 | file.write_all(&lines)?; |
| 4829 | file.flush()?; |
| 4830 | #[cfg(any(test, feature = "test-support"))] |
| 4831 | if take_test_event_append_fault(&thread_id, EventAppendTestFault::AfterFlush) { |
| 4832 | return Err(std::io::Error::other( |
| 4833 | "injected Runtime event failure after flush", |
| 4834 | )); |
| 4835 | } |
| 4836 | file.sync_all()?; |
| 4837 | #[cfg(any(test, feature = "test-support"))] |
| 4838 | if take_test_event_append_fault(&thread_id, EventAppendTestFault::AfterSync) { |
| 4839 | return Err(std::io::Error::other( |
| 4840 | "injected Runtime event failure after fsync", |
| 4841 | )); |
| 4842 | } |
| 4843 | Ok(()) |
| 4844 | })(); |
| 4845 | if let Err(append_error) = append_result { |
| 4846 | drop(file); |
| 4847 | let rollback_result = rollback_failed_event_append_handle(&rollback_file, original_len); |
| 4848 | let error = match rollback_result { |
| 4849 | Ok(()) => RuntimeEventAppendError { |
| 4850 | disposition: EventAppendFailureDisposition::RolledBack, |
| 4851 | append_error: append_error.to_string(), |
| 4852 | rollback_error: None, |
| 4853 | }, |
| 4854 | Err(rollback_error) => RuntimeEventAppendError { |
| 4855 | disposition: EventAppendFailureDisposition::Indeterminate, |
| 4856 | append_error: append_error.to_string(), |
| 4857 | rollback_error: Some(rollback_error.to_string()), |
| 4858 | }, |
| 4859 | }; |
| 4860 | return Err(anyhow!(error)); |
| 4861 | } |
| 4862 | Ok(()) |
| 4863 | } |
| 4864 | |
| 4865 | fn append_recovered_completions( |
| 4866 | &self, |
| 4867 | thread_id: &str, |
| 4868 | turns: &[TurnRecord], |
| 4869 | seen: &mut RecoveryCompletionIndex, |
| 4870 | ) -> Result<Vec<RuntimeEventRecord>> { |
| 4871 | let path = self.events_path(thread_id)?; |
| 4872 | self.with_event_transaction(EVENT_TRANSACTION_LOCK_TIMEOUT, || { |
| 4873 | reject_symlinked_store_dir(&self.events_dir)?; |
| 4874 | repair_torn_event_log_tail(&path)?; |
| 4875 | if path.try_exists()? { |
| 4876 | let mut file = |
| 4877 | open_runtime_store_file(&path, "Runtime recovery receipts", |options| { |
| 4878 | options.read(true); |
| 4879 | })?; |
| 4880 | if file.metadata()?.len() < seen.offset { |
| 4881 | *seen = Default::default(); |
| 4882 | } |
| 4883 | file.seek(SeekFrom::Start(seen.offset))?; |
| 4884 | let mut reader = BufReader::new(file); |
| 4885 | while let Some((event, bytes)) = read_complete_event_bytes(&mut reader, &path)? { |
| 4886 | seen.offset += bytes; |
| 4887 | if event.event == "turn.completed" |
| 4888 | && let Some(id) = event.turn_id |
| 4889 | { |
| 4890 | seen.completed.insert(id); |
| 4891 | } |
| 4892 | } |
| 4893 | } else { |
| 4894 | *seen = Default::default(); |
| 4895 | } |
| 4896 | let mut records = Vec::new(); |
| 4897 | for turn in turns { |
| 4898 | validated_record_id(&turn.id, "turn id")?; |
| 4899 | anyhow::ensure!( |
| 4900 | turn.thread_id == thread_id, |
| 4901 | "Recovery turn belongs to another thread" |
| 4902 | ); |
| 4903 | if seen.completed.contains(&turn.id) { |
| 4904 | continue; |
| 4905 | } |
| 4906 | records.push(RuntimeEventRecord { |
| 4907 | schema_version: CURRENT_RUNTIME_SCHEMA_VERSION, |
| 4908 | seq: 0, |
| 4909 | timestamp: Utc::now(), |
| 4910 | thread_id: thread_id.to_owned(), |
| 4911 | turn_id: Some(turn.id.clone()), |
| 4912 | item_id: None, |
| 4913 | event: "turn.completed".into(), |
| 4914 | payload: serde_json::json!({ "turn": turn, "recovered": true }), |
| 4915 | }); |
| 4916 | } |
| 4917 | self.write_event_records_locked(&path, &mut records)?; |
| 4918 | Ok(records) |
| 4919 | }) |
| 4920 | } |
| 4921 | |
| 4922 | fn extension_command_events( |
| 4923 | &self, |
| 4924 | thread_id: &str, |
| 4925 | fingerprint: &str, |
| 4926 | ) -> Result<(Option<Value>, Option<Value>, bool)> { |
| 4927 | let mut started = None; |
| 4928 | let mut finished = None; |
| 4929 | let mut cancelled = false; |
| 4930 | self.for_each_event(thread_id, |event| { |
| 4931 | if event |
| 4932 | .payload |
| 4933 | .get("operation_fingerprint") |
| 4934 | .and_then(Value::as_str) |
| 4935 | == Some(fingerprint) |
| 4936 | { |
| 4937 | match event.event.as_str() { |
| 4938 | "extension_command_started" => started = Some(event.payload), |
| 4939 | "extension_command_completed" => finished = Some(event.payload), |
| 4940 | "extension_command_cancelled" => cancelled = true, |
| 4941 | _ => {} |
| 4942 | } |
| 4943 | } |
| 4944 | Ok(()) |
| 4945 | })?; |
| 4946 | Ok((started, finished, cancelled)) |
| 4947 | } |
| 4948 | |
| 4949 | pub fn events_since( |
| 4950 | &self, |
| 4951 | thread_id: &str, |
| 4952 | since_seq: Option<u64>, |
| 4953 | ) -> Result<Vec<RuntimeEventRecord>> { |
| 4954 | let mut out = Vec::new(); |
| 4955 | self.for_each_event(thread_id, |event| { |
| 4956 | if since_seq.is_none_or(|since| event.seq > since) { |
| 4957 | out.push(event); |
| 4958 | } |
| 4959 | Ok(()) |
| 4960 | })?; |
| 4961 | Ok(out) |
| 4962 | } |
| 4963 | |
| 4964 | /// Visit every complete event of a thread in order without collecting |
| 4965 | /// the log, for callers that only need a summary of a long history. |
| 4966 | pub fn for_each_event( |
| 4967 | &self, |
| 4968 | thread_id: &str, |
| 4969 | mut visit: impl FnMut(RuntimeEventRecord) -> Result<()>, |
| 4970 | ) -> Result<()> { |
| 4971 | let path = self.events_path(thread_id)?; |
| 4972 | let Some(mut reader) = self.open_event_reader(thread_id)? else { |
| 4973 | return Ok(()); |
| 4974 | }; |
| 4975 | while let Some(event) = read_complete_event(&mut reader, &path)? { |
| 4976 | visit(event)?; |
| 4977 | } |
| 4978 | Ok(()) |
| 4979 | } |
| 4980 | |
| 4981 | /// Incremental JSONL replay from a byte cursor. The returned cursor only |
| 4982 | /// advances past complete newline-terminated records so a live tail can |
| 4983 | /// be retried without rereading earlier history. |
| 4984 | pub fn events_from_offset( |
| 4985 | &self, |
| 4986 | thread_id: &str, |
| 4987 | offset: u64, |
| 4988 | limit: Option<usize>, |
| 4989 | ) -> Result<(Vec<RuntimeEventRecord>, u64)> { |
| 4990 | let path = self.events_path(thread_id)?; |
| 4991 | self.with_event_transaction(EVENT_TRANSACTION_LOCK_TIMEOUT, || { |
| 4992 | reject_symlinked_store_dir(&self.events_dir)?; |
| 4993 | if !path.exists() { |
| 4994 | return Ok((Vec::new(), offset)); |
| 4995 | } |
| 4996 | let mut file = |
| 4997 | open_runtime_store_file(&path, "Runtime event cursor replay", |options| { |
| 4998 | options.read(true); |
| 4999 | })?; |
| 5000 | let committed_len = file |
| 5001 | .metadata() |
| 5002 | .with_context(|| format!("Failed to inspect {}", path.display()))? |
| 5003 | .len(); |
| 5004 | let start = offset.min(committed_len); |
| 5005 | file.seek(SeekFrom::Start(start))?; |
| 5006 | let mut reader = BufReader::new(file.take(committed_len.saturating_sub(start))); |
| 5007 | let mut out = Vec::new(); |
| 5008 | let mut cursor = start; |
| 5009 | while let Some((event, consumed)) = read_complete_event_bytes(&mut reader, &path)? { |
| 5010 | cursor += consumed; |
| 5011 | out.push(event); |
| 5012 | if limit.is_some_and(|limit| out.len() >= limit) { |
| 5013 | break; |
| 5014 | } |
| 5015 | } |
| 5016 | Ok((out, cursor)) |
| 5017 | }) |
| 5018 | } |
| 5019 | |
| 5020 | fn publish_event_replay( |
| 5021 | &self, |
| 5022 | thread_id: &str, |
| 5023 | since_seq: Option<u64>, |
| 5024 | tail_limit: Option<usize>, |
| 5025 | base_tx: oneshot::Sender<std::result::Result<u64, String>>, |
| 5026 | batch_tx: mpsc::Sender<std::result::Result<Vec<RuntimeEventRecord>, String>>, |
| 5027 | ) { |
| 5028 | let mut base_tx = Some(base_tx); |
| 5029 | // A panic here must not look like the end of history. Unwound, it |
| 5030 | // would drop `batch_tx` with no `Err`, the stream would read the |
| 5031 | // closed channel as "history complete", go live, and silently skip |
| 5032 | // the rest — with no `previous_seq` gap any client could detect. |
| 5033 | let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match tail_limit { |
| 5034 | Some(limit) => { |
| 5035 | self.publish_tail_event_replay(thread_id, since_seq, limit, &mut base_tx, &batch_tx) |
| 5036 | } |
| 5037 | None => self.publish_full_event_replay(thread_id, since_seq, &mut base_tx, &batch_tx), |
| 5038 | })); |
| 5039 | Self::route_replay_outcome(outcome, &mut base_tx, &batch_tx); |
| 5040 | } |
| 5041 | |
| 5042 | /// Deliver a replay worker's failure, including a panic, to whoever is |
| 5043 | /// waiting: the request before the base cursor was sent (HTTP 500), the |
| 5044 | /// open stream after it (`stream.end`). Success needs nothing: dropping |
| 5045 | /// `batch_tx` is how the stream learns history is complete. |
| 5046 | fn route_replay_outcome( |
| 5047 | outcome: std::thread::Result<Result<()>>, |
| 5048 | base_tx: &mut Option<oneshot::Sender<std::result::Result<u64, String>>>, |
| 5049 | batch_tx: &mpsc::Sender<std::result::Result<Vec<RuntimeEventRecord>, String>>, |
| 5050 | ) { |
| 5051 | let message = match outcome { |
| 5052 | Ok(Ok(())) => return, |
| 5053 | Ok(Err(error)) => format!("{error:#}"), |
| 5054 | Err(panic) => { |
| 5055 | let detail = panic |
| 5056 | .downcast_ref::<&str>() |
| 5057 | .map(|detail| (*detail).to_string()) |
| 5058 | .or_else(|| panic.downcast_ref::<String>().cloned()) |
| 5059 | .unwrap_or_else(|| "non-string panic payload".to_string()); |
| 5060 | format!("Runtime event replay worker panicked: {detail}") |
| 5061 | } |
| 5062 | }; |
| 5063 | if let Some(base_tx) = base_tx.take() { |
| 5064 | let _ = base_tx.send(Err(message)); |
| 5065 | } else { |
| 5066 | let _ = batch_tx.blocking_send(Err(message)); |
| 5067 | } |
| 5068 | } |
| 5069 | |
| 5070 | fn open_event_reader(&self, thread_id: &str) -> Result<Option<RuntimeEventReader>> { |
| 5071 | let path = self.events_path(thread_id)?; |
| 5072 | self.with_event_transaction(EVENT_TRANSACTION_LOCK_TIMEOUT, || { |
| 5073 | reject_symlinked_store_dir(&self.events_dir)?; |
| 5074 | if !path.exists() { |
| 5075 | return Ok(None); |
| 5076 | } |
| 5077 | let file = open_runtime_store_file(&path, "Runtime event replay", |options| { |
| 5078 | options.read(true); |
| 5079 | })?; |
| 5080 | let committed_len = file |
| 5081 | .metadata() |
| 5082 | .with_context(|| format!("Failed to inspect {}", path.display()))? |
| 5083 | .len(); |
| 5084 | Ok(Some(BufReader::new(file.take(committed_len)))) |
| 5085 | }) |
| 5086 | } |
| 5087 | |
| 5088 | fn contains_event(&self, thread_id: &str, expected: &RuntimeEventMatch) -> Result<bool> { |
| 5089 | let Some(mut reader) = self.open_event_reader(thread_id)? else { |
| 5090 | return Ok(false); |
| 5091 | }; |
| 5092 | let path = self.events_path(thread_id)?; |
| 5093 | while let Some(event) = read_complete_event(&mut reader, &path)? { |
| 5094 | let matches = match expected { |
| 5095 | RuntimeEventMatch::ThreadStarted => { |
| 5096 | event.event == "thread.started" |
| 5097 | && event |
| 5098 | .payload |
| 5099 | .get("thread") |
| 5100 | .and_then(|thread| thread.get("id")) |
| 5101 | .and_then(Value::as_str) |
| 5102 | == Some(thread_id) |
| 5103 | } |
| 5104 | RuntimeEventMatch::TurnCompleted { turn_id } => { |
| 5105 | event.event == "turn.completed" |
| 5106 | && event.turn_id.as_deref() == Some(turn_id.as_str()) |
| 5107 | } |
| 5108 | RuntimeEventMatch::WorkerLifecycle { |
| 5109 | turn_id, |
| 5110 | agent_id, |
| 5111 | event_name, |
| 5112 | } => { |
| 5113 | event.event == *event_name |
| 5114 | && event.turn_id.as_deref() == Some(turn_id.as_str()) |
| 5115 | && event.payload.get("agent_id").and_then(Value::as_str) |
| 5116 | == Some(agent_id.as_str()) |
| 5117 | } |
| 5118 | RuntimeEventMatch::DynamicTerminal { turn_id, call_id } => { |
| 5119 | matches!( |
| 5120 | event.event.as_str(), |
| 5121 | "tool_call.resolved" | "tool_call.canceled" | "tool_call.timeout" |
| 5122 | ) && event.turn_id.as_deref() == Some(turn_id.as_str()) |
| 5123 | && event.payload.get("call_id").and_then(Value::as_str) |
| 5124 | == Some(call_id.as_str()) |
| 5125 | } |
| 5126 | RuntimeEventMatch::AgentMail { |
| 5127 | event_name, |
| 5128 | message_id, |
| 5129 | attempt_count, |
| 5130 | } => { |
| 5131 | event.event == *event_name |
| 5132 | && event |
| 5133 | .payload |
| 5134 | .get("mail") |
| 5135 | .and_then(|mail| mail.get("message_id")) |
| 5136 | .and_then(Value::as_str) |
| 5137 | == Some(message_id.as_str()) |
| 5138 | && event |
| 5139 | .payload |
| 5140 | .get("mail") |
| 5141 | .and_then(|mail| mail.get("attempt_count")) |
| 5142 | .and_then(Value::as_u64) |
| 5143 | == Some(*attempt_count as u64) |
| 5144 | } |
| 5145 | }; |
| 5146 | if matches { |
| 5147 | return Ok(true); |
| 5148 | } |
| 5149 | } |
| 5150 | Ok(false) |
| 5151 | } |
| 5152 | |
| 5153 | fn publish_full_event_replay( |
| 5154 | &self, |
| 5155 | thread_id: &str, |
| 5156 | since_seq: Option<u64>, |
| 5157 | base_tx: &mut Option<oneshot::Sender<std::result::Result<u64, String>>>, |
| 5158 | batch_tx: &mpsc::Sender<std::result::Result<Vec<RuntimeEventRecord>, String>>, |
| 5159 | ) -> Result<()> { |
| 5160 | let Some(mut reader) = self.open_event_reader(thread_id)? else { |
| 5161 | if let Some(base_tx) = base_tx.take() { |
| 5162 | let _ = base_tx.send(Ok(since_seq.unwrap_or(0))); |
| 5163 | } |
| 5164 | return Ok(()); |
| 5165 | }; |
| 5166 | if base_tx |
| 5167 | .take() |
| 5168 | .is_some_and(|base_tx| base_tx.send(Ok(since_seq.unwrap_or(0))).is_err()) |
| 5169 | { |
| 5170 | return Ok(()); |
| 5171 | } |
| 5172 | |
| 5173 | let path = self.events_path(thread_id)?; |
| 5174 | let mut batch = Vec::with_capacity(RUNTIME_EVENT_REPLAY_BATCH_SIZE); |
| 5175 | while let Some(event) = read_complete_event(&mut reader, &path)? { |
| 5176 | if since_seq.is_some_and(|since| event.seq <= since) { |
| 5177 | continue; |
| 5178 | } |
| 5179 | batch.push(event); |
| 5180 | if batch.len() == RUNTIME_EVENT_REPLAY_BATCH_SIZE { |
| 5181 | if batch_tx.blocking_send(Ok(batch)).is_err() { |
| 5182 | return Ok(()); |
| 5183 | } |
| 5184 | batch = Vec::with_capacity(RUNTIME_EVENT_REPLAY_BATCH_SIZE); |
| 5185 | } |
| 5186 | } |
| 5187 | if !batch.is_empty() { |
| 5188 | let _ = batch_tx.blocking_send(Ok(batch)); |
| 5189 | } |
| 5190 | Ok(()) |
| 5191 | } |
| 5192 | |
| 5193 | fn publish_tail_event_replay( |
| 5194 | &self, |
| 5195 | thread_id: &str, |
| 5196 | since_seq: Option<u64>, |
| 5197 | tail_limit: usize, |
| 5198 | base_tx: &mut Option<oneshot::Sender<std::result::Result<u64, String>>>, |
| 5199 | batch_tx: &mpsc::Sender<std::result::Result<Vec<RuntimeEventRecord>, String>>, |
| 5200 | ) -> Result<()> { |
| 5201 | let Some(mut reader) = self.open_event_reader(thread_id)? else { |
| 5202 | if let Some(base_tx) = base_tx.take() { |
| 5203 | let _ = base_tx.send(Ok(since_seq.unwrap_or(0))); |
| 5204 | } |
| 5205 | return Ok(()); |
| 5206 | }; |
| 5207 | let path = self.events_path(thread_id)?; |
| 5208 | let mut base_seq = since_seq.unwrap_or(0); |
| 5209 | let mut tail = VecDeque::with_capacity(tail_limit.min(RUNTIME_EVENT_REPLAY_BATCH_SIZE)); |
| 5210 | while let Some(event) = read_complete_event(&mut reader, &path)? { |
| 5211 | if since_seq.is_some_and(|since| event.seq <= since) { |
| 5212 | continue; |
| 5213 | } |
| 5214 | if tail_limit == 0 { |
| 5215 | base_seq = event.seq; |
| 5216 | continue; |
| 5217 | } |
| 5218 | tail.push_back(event); |
| 5219 | if tail.len() > tail_limit |
| 5220 | && let Some(omitted) = tail.pop_front() |
| 5221 | { |
| 5222 | base_seq = omitted.seq; |
| 5223 | } |
| 5224 | } |
| 5225 | if base_tx |
| 5226 | .take() |
| 5227 | .is_some_and(|base_tx| base_tx.send(Ok(base_seq)).is_err()) |
| 5228 | { |
| 5229 | return Ok(()); |
| 5230 | } |
| 5231 | while !tail.is_empty() { |
| 5232 | let take = tail.len().min(RUNTIME_EVENT_REPLAY_BATCH_SIZE); |
| 5233 | let batch = tail.drain(..take).collect::<Vec<_>>(); |
| 5234 | if batch_tx.blocking_send(Ok(batch)).is_err() { |
| 5235 | return Ok(()); |
| 5236 | } |
| 5237 | } |
| 5238 | Ok(()) |
| 5239 | } |
| 5240 | |
| 5241 | pub async fn current_seq(&self) -> Result<u64> { |
| 5242 | let store = self.clone(); |
| 5243 | tokio::task::spawn_blocking(move || { |
| 5244 | store.with_event_transaction(EVENT_TRANSACTION_LOCK_TIMEOUT, || { |
| 5245 | Ok(load_runtime_store_state(&store.state_path)? |
| 5246 | .next_seq |
| 5247 | .saturating_sub(1)) |
| 5248 | }) |
| 5249 | }) |
| 5250 | .await |
| 5251 | .context("Runtime event cursor worker failed")? |
| 5252 | } |
| 5253 | } |
| 5254 | |
| 5255 | /// Why a session switch refused to adopt an existing Runtime store. |
| 5256 | /// |
| 5257 | /// Returned by [`RuntimeStoreBinding::adoption_refusal`]; the first guard |
| 5258 | /// that did not provably hold wins. Known limitation: it names one reason, |
| 5259 | /// not every one — a store both held and non-empty reports only the hold. |
| 5260 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 5261 | pub enum StoreAdoptionRefusal { |
| 5262 | /// The store is not at `<state>/sessions/<id>/runtime` (or a |
| 5263 | /// `runtime-recovered-*` sibling), or a symlink sits on the way down. |
| 5264 | Unconfined, |
| 5265 | /// The confined store path is not an existing directory. |
| 5266 | NotADirectory, |
| 5267 | /// Another live process holds the store's process-owner lock. |
| 5268 | HeldByLiveProcess, |
| 5269 | /// The named store directory holds work a switch would abandon. |
| 5270 | HasDurableWork { dir: &'static str }, |
| 5271 | /// An automation is pinned to this store's execution scope. |
| 5272 | ScopePinnedAutomation, |
| 5273 | } |
| 5274 | |
| 5275 | impl std::fmt::Display for StoreAdoptionRefusal { |
| 5276 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 5277 | match self { |
| 5278 | Self::Unconfined => f.write_str("the saved store is outside the session directory"), |
| 5279 | Self::NotADirectory => f.write_str("the saved store path is not an existing directory"), |
| 5280 | Self::HeldByLiveProcess => { |
| 5281 | f.write_str("another running Codewhale process holds the saved store") |
| 5282 | } |
| 5283 | Self::HasDurableWork { dir } => { |
| 5284 | write!(f, "the saved store still holds work in `{dir}`") |
| 5285 | } |
| 5286 | Self::ScopePinnedAutomation => { |
| 5287 | f.write_str("an automation is pinned to the saved store") |
| 5288 | } |
| 5289 | } |
| 5290 | } |
| 5291 | } |
| 5292 | |
| 5293 | /// Canonical spellings of configured sessions roots, keyed by the lexical |
| 5294 | /// root `resolve_state_dir("sessions")` returns (tests move the state dir per |
| 5295 | /// case, so one slot is not enough). The confinement predicate compares |
| 5296 | /// against this instead of resolving a path itself, so a `/resume`, `/load` |
| 5297 | /// or launch resume on the UI runtime never waits on filesystem resolution: |
| 5298 | /// those entry points warm the cache on a blocking thread first |
| 5299 | /// ([`prepare_canonical_sessions_root`]) (#6522). |
| 5300 | static CANONICAL_SESSIONS_ROOTS: std::sync::Mutex<Vec<(PathBuf, PathBuf)>> = |
| 5301 | std::sync::Mutex::new(Vec::new()); |
| 5302 | |
| 5303 | fn cached_canonical_sessions_root(sessions: &Path) -> Option<PathBuf> { |
| 5304 | CANONICAL_SESSIONS_ROOTS |
| 5305 | .lock() |
| 5306 | .ok()? |
| 5307 | .iter() |
| 5308 | .find(|(lexical, _)| lexical == sessions) |
| 5309 | .map(|(_, canonical)| canonical.clone()) |
| 5310 | } |
| 5311 | |
| 5312 | /// Resolve and remember the canonical form of `sessions`. Blocking: reach it |
| 5313 | /// through [`prepare_canonical_sessions_root`] from async code. A root that |
| 5314 | /// does not exist yet is not remembered, so a later call can still resolve it. |
| 5315 | fn resolve_canonical_sessions_root(sessions: &Path) -> Option<PathBuf> { |
| 5316 | let canonical = sessions.canonicalize().ok()?; |
| 5317 | if let Ok(mut cache) = CANONICAL_SESSIONS_ROOTS.lock() |
| 5318 | && !cache.iter().any(|(lexical, _)| lexical == sessions) |
| 5319 | { |
| 5320 | cache.push((sessions.to_path_buf(), canonical.clone())); |
| 5321 | } |
| 5322 | Some(canonical) |
| 5323 | } |
| 5324 | |
| 5325 | /// Resolve the configured sessions root's canonical spelling on a blocking |
| 5326 | /// thread so the store-confinement checks that follow on the UI runtime are |
| 5327 | /// pure comparisons. |
| 5328 | pub async fn prepare_canonical_sessions_root() { |
| 5329 | let Ok(sessions) = codewhale_config::resolve_state_dir("sessions") else { |
| 5330 | return; |
| 5331 | }; |
| 5332 | if cached_canonical_sessions_root(&sessions).is_some() { |
| 5333 | return; |
| 5334 | } |
| 5335 | let _ = tokio::task::spawn_blocking(move || resolve_canonical_sessions_root(&sessions)).await; |
| 5336 | } |
| 5337 | |
| 5338 | /// Durable host authority shared by conversations created in that host. |
| 5339 | /// A conversation id can change at launch; the locked Runtime store cannot. |
| 5340 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 5341 | pub struct RuntimeStoreBinding { |
| 5342 | pub data_dir: PathBuf, |
| 5343 | pub execution_scope: String, |
| 5344 | } |
| 5345 | |
| 5346 | impl RuntimeStoreBinding { |
| 5347 | /// The confinement shared by every store-recovery predicate: the bound |
| 5348 | /// store must sit at `<sessions>/<session-id>/runtime` (or a |
| 5349 | /// `runtime-recovered-*` sibling) with no symlink on the way down. Wrong |
| 5350 | /// owner, symlinks and external paths fail closed for all callers. |
| 5351 | fn is_confined_to_sessions_root(&self, sessions: &Path) -> Result<bool> { |
| 5352 | let Some(session_dir) = self.data_dir.parent() else { |
| 5353 | return Ok(false); |
| 5354 | }; |
| 5355 | let Some(store_name) = self.data_dir.file_name().and_then(|name| name.to_str()) else { |
| 5356 | return Ok(false); |
| 5357 | }; |
| 5358 | // A host records its binding from the store's canonical root |
| 5359 | // (`checked_runtime_store_root`), while the configured sessions root |
| 5360 | // is lexical. The two differ whenever an ancestor is spelled another |
| 5361 | // way — Windows `\\?\C:\` verbatim prefixes and 8.3 short names, or |
| 5362 | // a symlinked home/TMPDIR on Unix — and every real binding then read |
| 5363 | // as unconfined, so no switch could ever adopt it (#6418). Accept the |
| 5364 | // configured spelling or its canonical form only; nothing in the |
| 5365 | // binding's own path is resolved, so the symlink checks below still |
| 5366 | // fail closed. |
| 5367 | // |
| 5368 | // The canonical root comes from the cache the async entry points |
| 5369 | // (`TaskManager::start`, `/resume`, `/load`) warm off the UI runtime |
| 5370 | // via `prepare_canonical_sessions_root`; only a caller that never |
| 5371 | // warmed it (synchronous tests and tools) resolves it here. |
| 5372 | let parent = session_dir.parent(); |
| 5373 | let under_sessions = parent == Some(sessions) |
| 5374 | || cached_canonical_sessions_root(sessions) |
| 5375 | .or_else(|| resolve_canonical_sessions_root(sessions)) |
| 5376 | .is_some_and(|canonical| parent == Some(canonical.as_path())); |
| 5377 | if !under_sessions |
| 5378 | || !(store_name == "runtime" || store_name.starts_with("runtime-recovered-")) |
| 5379 | || !session_dir |
| 5380 | .file_name() |
| 5381 | .and_then(|name| name.to_str()) |
| 5382 | .is_some_and(codewhale_runtime::artifacts::is_valid_session_id) |
| 5383 | { |
| 5384 | return Ok(false); |
| 5385 | } |
| 5386 | for path in [sessions, session_dir, &self.data_dir] { |
| 5387 | reject_symlinked_store_dir(path)?; |
| 5388 | } |
| 5389 | Ok(true) |
| 5390 | } |
| 5391 | |
| 5392 | fn is_confined_session_store(&self) -> Result<bool> { |
| 5393 | let sessions = codewhale_config::resolve_state_dir("sessions")?; |
| 5394 | self.is_confined_to_sessions_root(&sessions) |
| 5395 | } |
| 5396 | |
| 5397 | fn is_confined_migration_store(&self, sessions_dir: &Path) -> Result<bool> { |
| 5398 | if self.is_confined_to_sessions_root(sessions_dir)? || self.is_confined_session_store()? { |
| 5399 | return Ok(true); |
| 5400 | } |
| 5401 | let mut tasks_roots = vec![crate::task_manager::default_tasks_dir()]; |
| 5402 | if sessions_dir.file_name().and_then(|n| n.to_str()) == Some("sessions") |
| 5403 | && let Some(state_root) = sessions_dir.parent() |
| 5404 | { |
| 5405 | tasks_roots.push(state_root.join("tasks")); |
| 5406 | } |
| 5407 | for tasks_dir in tasks_roots { |
| 5408 | let runtime_dir = tasks_dir.join("runtime"); |
| 5409 | let matches = self.data_dir == runtime_dir |
| 5410 | || cached_canonical_sessions_root(&tasks_dir) |
| 5411 | .or_else(|| resolve_canonical_sessions_root(&tasks_dir)) |
| 5412 | .is_some_and(|canonical_tasks| { |
| 5413 | self.data_dir == canonical_tasks.join("runtime") |
| 5414 | }); |
| 5415 | if matches { |
| 5416 | for path in [&tasks_dir, &runtime_dir, &self.data_dir] { |
| 5417 | reject_symlinked_store_dir(path)?; |
| 5418 | } |
| 5419 | return Ok(true); |
| 5420 | } |
| 5421 | } |
| 5422 | Ok(false) |
| 5423 | } |
| 5424 | |
| 5425 | /// Only a missing, confined session store can recover from its transcript. |
| 5426 | /// Existing stores with a wrong owner, symlinks and external paths fail closed. |
| 5427 | pub fn is_missing_session_store(&self) -> Result<bool> { |
| 5428 | if !self.is_confined_session_store()? { |
| 5429 | return Ok(false); |
| 5430 | } |
| 5431 | match fs::symlink_metadata(&self.data_dir) { |
| 5432 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(true), |
| 5433 | Err(err) => Err(err.into()), |
| 5434 | Ok(_) => Ok(false), |
| 5435 | } |
| 5436 | } |
| 5437 | |
| 5438 | /// The first store directory holding durable work, or `None` when the |
| 5439 | /// store holds nothing a session switch could abandon. |
| 5440 | /// |
| 5441 | /// The switch path can rebind a conversation but cannot carry a store's |
| 5442 | /// durable work across — queued tasks, pending approvals, agent mail — |
| 5443 | /// which is why only a *missing* store was ever allowed to recover. A |
| 5444 | /// store that exists and is empty is the case that policy never covered: |
| 5445 | /// there is nothing to abandon, so refusing protects nothing, and a |
| 5446 | /// force-quit leaves exactly this shape (#6207). |
| 5447 | /// |
| 5448 | /// Callers establish confinement and that `data_dir` is a directory |
| 5449 | /// first; this only reads. Scope-pinned automations live outside the |
| 5450 | /// store directories and are covered by |
| 5451 | /// [`Self::has_scope_pinned_automation`], not here. |
| 5452 | fn first_durable_work_dir(&self) -> Result<Option<&'static str>> { |
| 5453 | for name in RUNTIME_STORE_WORK_DIRS { |
| 5454 | match fs::read_dir(self.data_dir.join(name)) { |
| 5455 | Ok(mut entries) => { |
| 5456 | if entries.next().is_some() { |
| 5457 | return Ok(Some(name)); |
| 5458 | } |
| 5459 | } |
| 5460 | // A store opened by an older build may predate a directory; |
| 5461 | // absent is empty. |
| 5462 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} |
| 5463 | Err(err) => return Err(err.into()), |
| 5464 | } |
| 5465 | } |
| 5466 | // A sequence past its initial value means events were appended, even |
| 5467 | // if those files have since been pruned — reported as `events`. |
| 5468 | match fs::read_to_string(self.data_dir.join("state.json")) { |
| 5469 | Ok(raw) => { |
| 5470 | let state: RuntimeStoreState = serde_json::from_str(&raw)?; |
| 5471 | Ok((state.next_seq > 1).then_some("events")) |
| 5472 | } |
| 5473 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), |
| 5474 | Err(err) => Err(err.into()), |
| 5475 | } |
| 5476 | } |
| 5477 | |
| 5478 | /// True when another live process holds this store's process-owner lock. |
| 5479 | /// |
| 5480 | /// `open_inner` acquires the lock before the store is opened and holds it |
| 5481 | /// for the manager's lifetime, so a live holder's disk state is moving |
| 5482 | /// under us and an emptiness read against it is meaningless — that was |
| 5483 | /// the race that reverted the first #6207 fix. A missing lock file means |
| 5484 | /// no manager ever opened the store. The probe lock is released on drop; |
| 5485 | /// nothing is created or retained. |
| 5486 | /// |
| 5487 | /// Fails closed: an unconfined path reads as held, and an unexpected IO |
| 5488 | /// error refuses the adopt. |
| 5489 | pub fn has_live_holder(&self) -> Result<bool> { |
| 5490 | if !self.is_confined_session_store()? { |
| 5491 | return Ok(true); |
| 5492 | } |
| 5493 | let path = self.data_dir.join(RUNTIME_PROCESS_OWNER_LOCK_FILE); |
| 5494 | let file = match fs::OpenOptions::new().read(true).write(true).open(&path) { |
| 5495 | Ok(file) => file, |
| 5496 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(false), |
| 5497 | Err(err) => return Err(err.into()), |
| 5498 | }; |
| 5499 | match codewhale_util::lock::try_lock_exclusive(&file) { |
| 5500 | Ok(()) => Ok(false), |
| 5501 | Err(error) if codewhale_util::lock::is_contention(&error) => Ok(true), |
| 5502 | Err(error) => Err(error.into()), |
| 5503 | } |
| 5504 | } |
| 5505 | |
| 5506 | /// True when an automation's execution scope matches this binding. |
| 5507 | /// |
| 5508 | /// Scope-pinned automations are recorded outside the store directories, so |
| 5509 | /// [`Self::first_durable_work_dir`] cannot see them — adopting their store |
| 5510 | /// would orphan their scheduled work. A missing automations directory |
| 5511 | /// means no definitions exist. Read-only: the manager is only opened when |
| 5512 | /// the directory exists, and listing takes no locks. |
| 5513 | /// |
| 5514 | /// Fails closed: an unconfined path reads as pinned, and an unreadable |
| 5515 | /// automations directory refuses the adopt. |
| 5516 | pub fn has_scope_pinned_automation(&self) -> Result<bool> { |
| 5517 | if !self.is_confined_session_store()? { |
| 5518 | return Ok(true); |
| 5519 | } |
| 5520 | let root = crate::automation_manager::default_automations_dir(); |
| 5521 | if !root.join("automations").is_dir() { |
| 5522 | return Ok(false); |
| 5523 | } |
| 5524 | let manager = crate::automation_manager::AutomationManager::open(root)?; |
| 5525 | Ok(manager.list_automations()?.iter().any(|automation| { |
| 5526 | automation.execution_scope.as_deref() == Some(self.execution_scope.as_str()) |
| 5527 | })) |
| 5528 | } |
| 5529 | |
| 5530 | /// Why a session switch may not adopt the bound store, or `None` when it |
| 5531 | /// may: confined, a directory, unheld, empty, with no scope-pinned |
| 5532 | /// automation. Liveness is checked before emptiness — a live holder's |
| 5533 | /// disk state moves under the read — and the automation check runs last |
| 5534 | /// because it parses every definition. |
| 5535 | /// |
| 5536 | /// Fails closed: every refusal is the first condition that did not |
| 5537 | /// provably hold, and an unexpected IO or parse error is an `Err`, which |
| 5538 | /// callers treat as a refusal. The reason exists so a user can be told |
| 5539 | /// *which* guard refused (#6418); it never widens what is adoptable. |
| 5540 | pub fn adoption_refusal(&self) -> Result<Option<StoreAdoptionRefusal>> { |
| 5541 | if !self.is_confined_session_store()? { |
| 5542 | return Ok(Some(StoreAdoptionRefusal::Unconfined)); |
| 5543 | } |
| 5544 | if !self.data_dir.is_dir() { |
| 5545 | return Ok(Some(StoreAdoptionRefusal::NotADirectory)); |
| 5546 | } |
| 5547 | if self.has_live_holder()? { |
| 5548 | return Ok(Some(StoreAdoptionRefusal::HeldByLiveProcess)); |
| 5549 | } |
| 5550 | if let Some(dir) = self.first_durable_work_dir()? { |
| 5551 | return Ok(Some(StoreAdoptionRefusal::HasDurableWork { dir })); |
| 5552 | } |
| 5553 | if self.has_scope_pinned_automation()? { |
| 5554 | return Ok(Some(StoreAdoptionRefusal::ScopePinnedAutomation)); |
| 5555 | } |
| 5556 | Ok(None) |
| 5557 | } |
| 5558 | |
| 5559 | /// True when the bound store exists and a switch may adopt it; see |
| 5560 | /// [`Self::adoption_refusal`] for the reason when it may not. |
| 5561 | pub fn is_adoptable_empty_store(&self) -> Result<bool> { |
| 5562 | Ok(self.adoption_refusal()?.is_none()) |
| 5563 | } |
| 5564 | |
| 5565 | pub fn validate_existing_store(&self) -> Result<()> { |
| 5566 | anyhow::ensure!( |
| 5567 | self.data_dir.is_absolute(), |
| 5568 | "Saved Runtime store path must be absolute" |
| 5569 | ); |
| 5570 | let root = checked_existing_runtime_store_dir(&self.data_dir)?; |
| 5571 | let owner: RuntimeStoreOwner = |
| 5572 | serde_json::from_str(&read_store_file(&root.join(AGENT_MAIL_OWNER_FILE))?)?; |
| 5573 | validated_record_id(&owner.owner_id, "Runtime owner id")?; |
| 5574 | anyhow::ensure!( |
| 5575 | runtime_execution_scope(&owner.owner_id, &root.join(EVENT_TRANSACTION_LOCK_FILE)) |
| 5576 | == self.execution_scope, |
| 5577 | "Saved session Runtime store ownership does not match; refusing to recover another scope" |
| 5578 | ); |
| 5579 | Ok(()) |
| 5580 | } |
| 5581 | } |
| 5582 | |
| 5583 | fn runtime_execution_scope(owner_id: &str, event_lock_path: &Path) -> String { |
| 5584 | let mut digest = Sha256::new(); |
| 5585 | digest.update(owner_id.as_bytes()); |
| 5586 | digest.update([0]); |
| 5587 | digest.update(event_lock_path.as_os_str().as_encoded_bytes()); |
| 5588 | digest |
| 5589 | .finalize() |
| 5590 | .iter() |
| 5591 | .map(|byte| format!("{byte:02x}")) |
| 5592 | .collect() |
| 5593 | } |
| 5594 | |
| 5595 | fn runtime_dir_override() -> Option<PathBuf> { |
| 5596 | std::env::var("CODEWHALE_RUNTIME_DIR") |
| 5597 | .or_else(|_| std::env::var("DEEPSEEK_RUNTIME_DIR")) |
| 5598 | .ok() |
| 5599 | .filter(|override_dir| !override_dir.trim().is_empty()) |
| 5600 | .map(PathBuf::from) |
| 5601 | } |
| 5602 | |
| 5603 | /// The canonicalized runtime-dir override, when one is set. |
| 5604 | /// |
| 5605 | /// The control plane derives its endpoint from the same selection the store |
| 5606 | /// uses (`daemon_socket::store_selected_socket_path`), so a non-default store |
| 5607 | /// never shares the default owner's socket. Canonicalized through |
| 5608 | /// [`checked_runtime_store_root`] so an aliased, relative or `..`-bearing |
| 5609 | /// override cannot fork a second owner silently, and the same path the store |
| 5610 | /// is compared against later. An unresolvable override is an error, not a |
| 5611 | /// silent `None`: falling back would hand the caller the default endpoint for |
| 5612 | /// a store that is not the default one. |
| 5613 | #[cfg(unix)] |
| 5614 | pub fn canonical_runtime_dir_override() -> Result<Option<PathBuf>> { |
| 5615 | runtime_dir_override() |
| 5616 | .map(checked_runtime_store_root) |
| 5617 | .transpose() |
| 5618 | } |
| 5619 | |
| 5620 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 5621 | struct RuntimeTurnOperationBinding { |
| 5622 | schema_version: u32, |
| 5623 | thread_id: String, |
| 5624 | turn_id: String, |
| 5625 | operation_key_fingerprint: String, |
| 5626 | request_fingerprint: String, |
| 5627 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 5628 | watch_input_sha256: Option<String>, |
| 5629 | created_at: DateTime<Utc>, |
| 5630 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 5631 | preparation: Option<RuntimeTurnPreparation>, |
| 5632 | } |
| 5633 | |
| 5634 | #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] |
| 5635 | struct RuntimeTurnPreparation { |
| 5636 | id: String, |
| 5637 | source_fingerprint: String, |
| 5638 | admitted: bool, |
| 5639 | } |
| 5640 | |
| 5641 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 5642 | #[serde(deny_unknown_fields)] |
| 5643 | struct RuntimeThreadCreateBinding { |
| 5644 | schema_version: u32, |
| 5645 | operation_key_fingerprint: String, |
| 5646 | request_fingerprint: String, |
| 5647 | thread_id: String, |
| 5648 | created_at: DateTime<Utc>, |
| 5649 | committed: bool, |
| 5650 | } |
| 5651 | |
| 5652 | impl RuntimeThreadCreateBinding { |
| 5653 | fn validate(&self) -> Result<()> { |
| 5654 | anyhow::ensure!( |
| 5655 | self.schema_version == 1, |
| 5656 | "unsupported thread creation operation schema" |
| 5657 | ); |
| 5658 | validated_record_id(&self.thread_id, "thread creation operation id")?; |
| 5659 | validate_sha256_fingerprint( |
| 5660 | &self.operation_key_fingerprint, |
| 5661 | "thread creation operation fingerprint", |
| 5662 | )?; |
| 5663 | validate_sha256_fingerprint( |
| 5664 | &self.request_fingerprint, |
| 5665 | "thread creation request fingerprint", |
| 5666 | ) |
| 5667 | } |
| 5668 | } |
| 5669 | |
| 5670 | impl RuntimeTurnOperationBinding { |
| 5671 | fn validate(&self) -> Result<()> { |
| 5672 | if self.schema_version > TURN_OPERATION_BINDING_SCHEMA_VERSION { |
| 5673 | bail!( |
| 5674 | "Runtime turn operation binding schema v{} is newer than supported v{}", |
| 5675 | self.schema_version, |
| 5676 | TURN_OPERATION_BINDING_SCHEMA_VERSION |
| 5677 | ); |
| 5678 | } |
| 5679 | validated_record_id(&self.thread_id, "operation thread id")?; |
| 5680 | validated_record_id(&self.turn_id, "operation turn id")?; |
| 5681 | validate_sha256_fingerprint(&self.operation_key_fingerprint, "operation key fingerprint")?; |
| 5682 | validate_sha256_fingerprint(&self.request_fingerprint, "operation request fingerprint")?; |
| 5683 | if let Some(preparation) = &self.preparation { |
| 5684 | anyhow::ensure!( |
| 5685 | self.schema_version >= 2, |
| 5686 | "turn preparation requires its admission schema" |
| 5687 | ); |
| 5688 | validated_record_id(&preparation.id, "turn preparation id")?; |
| 5689 | validate_sha256_fingerprint( |
| 5690 | &preparation.source_fingerprint, |
| 5691 | "classifier source fingerprint", |
| 5692 | )?; |
| 5693 | } |
| 5694 | if let Some(digest) = &self.watch_input_sha256 { |
| 5695 | validate_sha256_fingerprint(digest, "watch input fingerprint")?; |
| 5696 | } |
| 5697 | Ok(()) |
| 5698 | } |
| 5699 | } |
| 5700 | |
| 5701 | fn validate_runtime_turn_operation_key(value: &str) -> Result<()> { |
| 5702 | if value.is_empty() { |
| 5703 | bail!("operation_key cannot be empty"); |
| 5704 | } |
| 5705 | if value.len() > MAX_RUNTIME_TURN_OPERATION_KEY_BYTES { |
| 5706 | bail!("operation_key cannot exceed {MAX_RUNTIME_TURN_OPERATION_KEY_BYTES} UTF-8 bytes"); |
| 5707 | } |
| 5708 | if value.trim() != value { |
| 5709 | bail!("operation_key cannot contain leading or trailing whitespace"); |
| 5710 | } |
| 5711 | if value.chars().any(char::is_control) { |
| 5712 | bail!("operation_key cannot contain control characters"); |
| 5713 | } |
| 5714 | Ok(()) |
| 5715 | } |
| 5716 | |
| 5717 | fn validate_sha256_fingerprint(value: &str, label: &str) -> Result<()> { |
| 5718 | if value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) { |
| 5719 | bail!("{label} must be a SHA-256 hex digest"); |
| 5720 | } |
| 5721 | Ok(()) |
| 5722 | } |
| 5723 | |
| 5724 | impl RuntimeStoreBinding { |
| 5725 | /// The binding a host that opened `data_dir` would have recorded: its |
| 5726 | /// canonical root and the scope derived from the store's owner. A store |
| 5727 | /// whose owner was never written has no scope an automation could pin. |
| 5728 | pub fn for_store_dir(data_dir: &Path) -> Result<Self> { |
| 5729 | let root = checked_runtime_store_root(data_dir.to_path_buf())?; |
| 5730 | let execution_scope = match read_store_file(&root.join(AGENT_MAIL_OWNER_FILE)) { |
| 5731 | Ok(raw) => { |
| 5732 | let owner: RuntimeStoreOwner = serde_json::from_str(&raw)?; |
| 5733 | runtime_execution_scope(&owner.owner_id, &root.join(EVENT_TRANSACTION_LOCK_FILE)) |
| 5734 | } |
| 5735 | Err(_) if !root.join(AGENT_MAIL_OWNER_FILE).exists() => String::new(), |
| 5736 | Err(error) => return Err(error), |
| 5737 | }; |
| 5738 | Ok(Self { |
| 5739 | data_dir: root, |
| 5740 | execution_scope, |
| 5741 | }) |
| 5742 | } |
| 5743 | |
| 5744 | /// Take this store's process-owner lock for maintenance, or `None` when |
| 5745 | /// a live process holds it (#6144). |
| 5746 | /// |
| 5747 | /// Holding the same lock a host takes in `open_inner` is what makes the |
| 5748 | /// maintenance exact: while it is held no process can open the store, so |
| 5749 | /// an emptiness read cannot race new work, and a move cannot pull the |
| 5750 | /// store out from under an opener — the opener fails its lock instead. |
| 5751 | /// Unconfined paths and non-directories are refused. |
| 5752 | pub fn try_hold(&self) -> Result<Option<HeldRuntimeStore>> { |
| 5753 | anyhow::ensure!( |
| 5754 | self.is_confined_session_store()?, |
| 5755 | "Runtime store {} is outside the sessions directory", |
| 5756 | self.data_dir.display() |
| 5757 | ); |
| 5758 | self.try_hold_verified_store(None) |
| 5759 | } |
| 5760 | |
| 5761 | pub fn try_hold_for_sessions_dir( |
| 5762 | &self, |
| 5763 | sessions_dir: &Path, |
| 5764 | ) -> Result<Option<HeldRuntimeStore>> { |
| 5765 | anyhow::ensure!( |
| 5766 | self.is_confined_migration_store(sessions_dir)?, |
| 5767 | "Runtime store {} is outside the sessions or tasks runtime directories", |
| 5768 | self.data_dir.display() |
| 5769 | ); |
| 5770 | self.try_hold_verified_store(Some(sessions_dir.to_path_buf())) |
| 5771 | } |
| 5772 | |
| 5773 | fn try_hold_verified_store( |
| 5774 | &self, |
| 5775 | migration_sessions_dir: Option<PathBuf>, |
| 5776 | ) -> Result<Option<HeldRuntimeStore>> { |
| 5777 | anyhow::ensure!( |
| 5778 | self.data_dir.is_dir(), |
| 5779 | "Runtime store {} is not a directory", |
| 5780 | self.data_dir.display() |
| 5781 | ); |
| 5782 | reject_symlinked_store_dir(&self.data_dir)?; |
| 5783 | let Some(lock) = RuntimeProcessOwnerLock::try_acquire_file( |
| 5784 | &self.data_dir.join(RUNTIME_PROCESS_OWNER_LOCK_FILE), |
| 5785 | true, |
| 5786 | )? |
| 5787 | else { |
| 5788 | return Ok(None); |
| 5789 | }; |
| 5790 | let held = HeldRuntimeStore { |
| 5791 | binding: self.clone(), |
| 5792 | migration_sessions_dir, |
| 5793 | _lock: lock, |
| 5794 | }; |
| 5795 | held.verify_confined()?; |
| 5796 | Ok(Some(held)) |
| 5797 | } |
| 5798 | |
| 5799 | pub fn preview_migrate_session_workspace( |
| 5800 | &self, |
| 5801 | sessions_dir: &Path, |
| 5802 | session_ids: Option<&HashSet<String>>, |
| 5803 | old_workspace: &Path, |
| 5804 | new_workspace: &Path, |
| 5805 | ) -> Result<Option<(Vec<String>, Vec<String>)>> { |
| 5806 | anyhow::ensure!( |
| 5807 | self.is_confined_migration_store(sessions_dir)?, |
| 5808 | "Runtime store {} is outside the sessions or tasks runtime directories", |
| 5809 | self.data_dir.display() |
| 5810 | ); |
| 5811 | reject_symlinked_store_dir(&self.data_dir)?; |
| 5812 | let lock_path = self.data_dir.join(RUNTIME_PROCESS_OWNER_LOCK_FILE); |
| 5813 | match open_runtime_store_file(&lock_path, "Execution owner lease", |options| { |
| 5814 | options.read(true); |
| 5815 | }) { |
| 5816 | Ok(file) => { |
| 5817 | let unlocked = codewhale_util::lock::try_lock_file_exclusive(&file) |
| 5818 | .context("Failed to probe execution owner lease")?; |
| 5819 | if unlocked { |
| 5820 | codewhale_util::lock::unlock(&file); |
| 5821 | } else { |
| 5822 | return Ok(None); |
| 5823 | } |
| 5824 | } |
| 5825 | Err(error) |
| 5826 | if error |
| 5827 | .downcast_ref::<std::io::Error>() |
| 5828 | .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::NotFound) => {} |
| 5829 | Err(error) => return Err(error), |
| 5830 | } |
| 5831 | if !self.data_dir.join("threads").is_dir() { |
| 5832 | return Ok(Some((Vec::new(), Vec::new()))); |
| 5833 | } |
| 5834 | let Some(store) = RuntimeThreadStore::open_read_only(self.data_dir.clone())? else { |
| 5835 | return Ok(Some((Vec::new(), Vec::new()))); |
| 5836 | }; |
| 5837 | let (migrated, skipped) = migrate_store_threads( |
| 5838 | &store, |
| 5839 | session_ids, |
| 5840 | old_workspace, |
| 5841 | new_workspace, |
| 5842 | true, |
| 5843 | None, |
| 5844 | )?; |
| 5845 | Ok(Some((migrated, skipped))) |
| 5846 | } |
| 5847 | } |
| 5848 | |
| 5849 | /// A Runtime store held under its process-owner lock by maintenance — |
| 5850 | /// session reconcile, or the switch/delete that just stopped binding it. |
| 5851 | pub struct HeldRuntimeStore { |
| 5852 | binding: RuntimeStoreBinding, |
| 5853 | migration_sessions_dir: Option<PathBuf>, |
| 5854 | _lock: RuntimeProcessOwnerLock, |
| 5855 | } |
| 5856 | |
| 5857 | /// One thread recovered from a store no document references. |
| 5858 | pub struct RecoverableThread { |
| 5859 | pub thread: ThreadRecord, |
| 5860 | pub messages: Vec<Message>, |
| 5861 | } |
| 5862 | |
| 5863 | impl HeldRuntimeStore { |
| 5864 | pub fn binding(&self) -> &RuntimeStoreBinding { |
| 5865 | &self.binding |
| 5866 | } |
| 5867 | |
| 5868 | /// Why this store must be kept, or `None` when it holds nothing: the same |
| 5869 | /// "nothing to lose" test a session switch applies before adopting it, |
| 5870 | /// read while no process can add work. |
| 5871 | pub fn keep_reason(&self) -> Result<Option<String>> { |
| 5872 | if let Some(dir) = self.binding.first_durable_work_dir()? { |
| 5873 | return Ok(Some(format!("holds work in `{dir}`"))); |
| 5874 | } |
| 5875 | if self.binding.has_scope_pinned_automation()? { |
| 5876 | return Ok(Some("an automation is pinned to it".to_string())); |
| 5877 | } |
| 5878 | Ok(None) |
| 5879 | } |
| 5880 | |
| 5881 | /// Move the store to `destination`, holding its lock for the whole move, |
| 5882 | /// so no opener can race it. Nothing is unlinked. |
| 5883 | /// |
| 5884 | /// The store directory itself is not renamed: it contains the open lock |
| 5885 | /// file, and Windows refuses to rename a directory while a handle inside |
| 5886 | /// it is open. Each entry is renamed into `destination` instead, the lock |
| 5887 | /// file last. Renaming the open, locked lock file is allowed on every |
| 5888 | /// platform: unix renames the inode the lock is on, and on Windows std |
| 5889 | /// opens files with `FILE_SHARE_DELETE`, which permits a rename while the |
| 5890 | /// handle is open (a `LockFile` byte-range lock does not block it). The |
| 5891 | /// lock is dropped only after the emptied source directory is removed. |
| 5892 | /// |
| 5893 | /// Unlinking the lock file after dropping it is what this must never do |
| 5894 | /// (#6144): on unix `remove_file` succeeds while another process holds a |
| 5895 | /// lock on the file, so an opener that locked in that gap would hold a |
| 5896 | /// lock on an unlinked inode, and the next opener would create and lock a |
| 5897 | /// fresh file: two owners of one store. An opener that opened the old |
| 5898 | /// path before the move and locks after it sees its file is no longer at |
| 5899 | /// the path and reopens (see [`RuntimeProcessOwnerLock`]). |
| 5900 | pub fn move_to(self, destination: &Path) -> Result<()> { |
| 5901 | anyhow::ensure!( |
| 5902 | !destination.exists(), |
| 5903 | "set-aside destination {} already exists", |
| 5904 | destination.display() |
| 5905 | ); |
| 5906 | let source = self.binding.data_dir.clone(); |
| 5907 | fs::create_dir_all(destination) |
| 5908 | .with_context(|| format!("Failed to create {}", destination.display()))?; |
| 5909 | let mut names: Vec<std::ffi::OsString> = Vec::new(); |
| 5910 | let listed = fs::read_dir(&source) |
| 5911 | .and_then(|entries| { |
| 5912 | for entry in entries { |
| 5913 | let name = entry?.file_name(); |
| 5914 | if name != RUNTIME_PROCESS_OWNER_LOCK_FILE { |
| 5915 | names.push(name); |
| 5916 | } |
| 5917 | } |
| 5918 | Ok(()) |
| 5919 | }) |
| 5920 | .with_context(|| format!("Failed to read Runtime store {}", source.display())); |
| 5921 | if let Err(error) = listed { |
| 5922 | let _ = fs::remove_dir(destination); |
| 5923 | return Err(error); |
| 5924 | } |
| 5925 | names.push(RUNTIME_PROCESS_OWNER_LOCK_FILE.into()); |
| 5926 | let mut moved: Vec<&std::ffi::OsString> = Vec::new(); |
| 5927 | for name in &names { |
| 5928 | if let Err(error) = fs::rename(source.join(name), destination.join(name)) { |
| 5929 | // Put back what already moved so the store is never left |
| 5930 | // split across two directories; the lock is still held. |
| 5931 | for name in moved.into_iter().rev() { |
| 5932 | let _ = fs::rename(destination.join(name), source.join(name)); |
| 5933 | } |
| 5934 | let _ = fs::remove_dir(destination); |
| 5935 | return Err(anyhow::Error::from(error).context(format!( |
| 5936 | "Failed to move Runtime store {} to {}", |
| 5937 | source.display(), |
| 5938 | destination.display() |
| 5939 | ))); |
| 5940 | } |
| 5941 | moved.push(name); |
| 5942 | } |
| 5943 | #[cfg(any(test, feature = "test-support"))] |
| 5944 | run_owner_lock_test_hook(OwnerLockTestPoint::LockFileMoved); |
| 5945 | // Still holding the lock. A directory that is no longer empty means |
| 5946 | // an opener created a fresh lock file in it after the move; that |
| 5947 | // store is its own, so it stays. |
| 5948 | let _ = fs::remove_dir(&source); |
| 5949 | drop(self); |
| 5950 | Ok(()) |
| 5951 | } |
| 5952 | |
| 5953 | fn open_store(&self) -> Result<RuntimeThreadStore> { |
| 5954 | self.verify_confined()?; |
| 5955 | RuntimeThreadStore::open(self.binding.data_dir.clone()) |
| 5956 | } |
| 5957 | |
| 5958 | fn verify_confined(&self) -> Result<()> { |
| 5959 | let confined = match self.migration_sessions_dir.as_deref() { |
| 5960 | Some(dir) => self.binding.is_confined_migration_store(dir)?, |
| 5961 | None => self.binding.is_confined_session_store()?, |
| 5962 | }; |
| 5963 | anyhow::ensure!( |
| 5964 | confined, |
| 5965 | "Runtime store {} is outside its confined root", |
| 5966 | self.binding.data_dir.display() |
| 5967 | ); |
| 5968 | reject_symlinked_store_dir(&self.binding.data_dir) |
| 5969 | } |
| 5970 | |
| 5971 | /// Threads in this store that name no session document, with their |
| 5972 | /// history rebuilt from their own turns. Threads with no turns carry no |
| 5973 | /// conversation to recover and are left out. |
| 5974 | /// |
| 5975 | /// Seed journals (#6555) are judged exactly as Runtime startup judges |
| 5976 | /// them, but read-only (this also serves dry runs): an uncommitted seed's |
| 5977 | /// turns are not history, and a thread whose journal cannot be settled is |
| 5978 | /// left out entirely. |
| 5979 | pub fn recoverable_threads(&self) -> Result<Vec<RecoverableThread>> { |
| 5980 | let store = self.open_store()?; |
| 5981 | let mut quarantined = HashSet::new(); |
| 5982 | let mut unpublished_turns = HashSet::new(); |
| 5983 | for path in store.seed_journal_paths()? { |
| 5984 | match store.judge_seed_journal(&path) { |
| 5985 | SeedJournalVerdict::Committed { .. } => {} |
| 5986 | SeedJournalVerdict::Uncommitted(journal) => { |
| 5987 | unpublished_turns.extend(journal.turn_ids); |
| 5988 | } |
| 5989 | SeedJournalVerdict::Quarantined { thread_ids, reason } => { |
| 5990 | tracing::warn!( |
| 5991 | target: "runtime", |
| 5992 | thread_ids = ?thread_ids, |
| 5993 | journal = %path.display(), |
| 5994 | "thread not recovered: seed journal cannot be settled ({reason})" |
| 5995 | ); |
| 5996 | quarantined.extend(thread_ids); |
| 5997 | } |
| 5998 | } |
| 5999 | } |
| 6000 | let (threads, _) = store.list_threads_lenient()?; |
| 6001 | let mut out = Vec::new(); |
| 6002 | for thread in threads { |
| 6003 | if thread.session_id.is_some() || quarantined.contains(&thread.id) { |
| 6004 | continue; |
| 6005 | } |
| 6006 | let mut turns = store.list_turns_for_thread(&thread.id)?; |
| 6007 | turns.retain(|turn| !unpublished_turns.contains(&turn.id)); |
| 6008 | if turns.is_empty() { |
| 6009 | continue; |
| 6010 | } |
| 6011 | let turn_ids: Vec<String> = turns.iter().map(|turn| turn.id.clone()).collect(); |
| 6012 | let items = store.list_items_for_turns_map(&turn_ids)?; |
| 6013 | let messages = store.history_from_records(&turns, &items)?; |
| 6014 | if messages.is_empty() { |
| 6015 | continue; |
| 6016 | } |
| 6017 | out.push(RecoverableThread { thread, messages }); |
| 6018 | } |
| 6019 | Ok(out) |
| 6020 | } |
| 6021 | |
| 6022 | /// Bind `thread_id` to the document just written for it, covering every |
| 6023 | /// turn the document was rebuilt from. |
| 6024 | pub fn bind_recovered_thread( |
| 6025 | &self, |
| 6026 | thread_id: &str, |
| 6027 | session: &crate::session_manager::SavedSession, |
| 6028 | ) -> Result<()> { |
| 6029 | let store = self.open_store()?; |
| 6030 | let _thread_mutation = store.thread_mutation.lock(); |
| 6031 | let mut thread = store.load_thread(thread_id)?; |
| 6032 | thread.session_id = Some(session.metadata.id.clone()); |
| 6033 | thread.saved_session_checkpoint = Some(SavedSessionCheckpoint { |
| 6034 | publication_observation: session |
| 6035 | .write_receipt |
| 6036 | .as_ref() |
| 6037 | .and_then(|receipt| receipt.observation().ok()), |
| 6038 | covered_turn_id: thread.latest_turn_id.clone(), |
| 6039 | messages_sha256: session_messages_sha256(&session.messages)?, |
| 6040 | messages_len: Some(session.messages.len()), |
| 6041 | retained_messages: None, |
| 6042 | }); |
| 6043 | thread.updated_at = Utc::now(); |
| 6044 | store.save_thread(&thread) |
| 6045 | } |
| 6046 | |
| 6047 | /// Unbind threads whose session document no longer exists (#6144 R4). |
| 6048 | /// `exists` answers for a session id; a thread whose document is present |
| 6049 | /// is untouched — its checkpoint is verified (and migrated) when it loads. |
| 6050 | pub fn unbind_threads_without_documents(&self, exists: impl Fn(&str) -> bool) -> Result<usize> { |
| 6051 | if !self.binding.data_dir.join("threads").is_dir() { |
| 6052 | return Ok(0); |
| 6053 | } |
| 6054 | let store = self.open_store()?; |
| 6055 | let (threads, _) = store.list_threads_lenient()?; |
| 6056 | let mut unbound = 0; |
| 6057 | for thread in threads { |
| 6058 | let Some(session_id) = thread.session_id.as_deref() else { |
| 6059 | continue; |
| 6060 | }; |
| 6061 | if exists(session_id) { |
| 6062 | continue; |
| 6063 | } |
| 6064 | unbound += unbind_session_threads_in_store( |
| 6065 | &store, |
| 6066 | &self.binding.data_dir, |
| 6067 | session_id, |
| 6068 | "its session document no longer exists", |
| 6069 | )?; |
| 6070 | } |
| 6071 | Ok(unbound) |
| 6072 | } |
| 6073 | |
| 6074 | pub fn migrate_session_workspace( |
| 6075 | &self, |
| 6076 | session_ids: Option<&HashSet<String>>, |
| 6077 | old_workspace: &Path, |
| 6078 | new_workspace: &Path, |
| 6079 | dry_run: bool, |
| 6080 | publication_update: Option<( |
| 6081 | &str, |
| 6082 | Option<&crate::session_manager::SessionObservation>, |
| 6083 | &crate::session_manager::SessionObservation, |
| 6084 | )>, |
| 6085 | ) -> Result<(Vec<String>, Vec<String>)> { |
| 6086 | if !self.binding.data_dir.join("threads").is_dir() { |
| 6087 | return Ok((Vec::new(), Vec::new())); |
| 6088 | } |
| 6089 | let store = if dry_run { |
| 6090 | self.verify_confined()?; |
| 6091 | let Some(store) = RuntimeThreadStore::open_read_only(self.binding.data_dir.clone())? |
| 6092 | else { |
| 6093 | return Ok((Vec::new(), Vec::new())); |
| 6094 | }; |
| 6095 | store |
| 6096 | } else { |
| 6097 | self.open_store()? |
| 6098 | }; |
| 6099 | migrate_store_threads( |
| 6100 | &store, |
| 6101 | session_ids, |
| 6102 | old_workspace, |
| 6103 | new_workspace, |
| 6104 | dry_run, |
| 6105 | publication_update, |
| 6106 | ) |
| 6107 | } |
| 6108 | } |
| 6109 | |
| 6110 | fn migrate_store_threads( |
| 6111 | store: &RuntimeThreadStore, |
| 6112 | session_ids: Option<&HashSet<String>>, |
| 6113 | old_workspace: &Path, |
| 6114 | new_workspace: &Path, |
| 6115 | dry_run: bool, |
| 6116 | publication_update: Option<( |
| 6117 | &str, |
| 6118 | Option<&crate::session_manager::SessionObservation>, |
| 6119 | &crate::session_manager::SessionObservation, |
| 6120 | )>, |
| 6121 | ) -> Result<(Vec<String>, Vec<String>)> { |
| 6122 | let _thread_mutation = store.thread_mutation.lock(); |
| 6123 | let (threads, mut skipped) = store.list_threads_lenient()?; |
| 6124 | let mut migrated = Vec::new(); |
| 6125 | for mut thread in threads { |
| 6126 | if let Some(allowed) = session_ids { |
| 6127 | let Some(session_id) = thread.session_id.as_deref() else { |
| 6128 | continue; |
| 6129 | }; |
| 6130 | if !allowed.contains(session_id) { |
| 6131 | continue; |
| 6132 | } |
| 6133 | } |
| 6134 | let next_workspace = crate::session_manager::remap_workspace_path( |
| 6135 | &thread.workspace, |
| 6136 | old_workspace, |
| 6137 | new_workspace, |
| 6138 | ); |
| 6139 | let mut observation_updated = false; |
| 6140 | if let Some((expected_id, before_obs, after_obs)) = publication_update |
| 6141 | && thread.session_id.as_deref() == Some(expected_id) |
| 6142 | && let Some(checkpoint) = thread.saved_session_checkpoint.as_mut() |
| 6143 | && let Some(obs) = checkpoint.publication_observation.as_ref() |
| 6144 | && obs.same_session_target(after_obs) |
| 6145 | && obs != after_obs |
| 6146 | { |
| 6147 | if before_obs.is_some_and(|pre| obs == pre) { |
| 6148 | checkpoint.publication_observation = Some(after_obs.clone()); |
| 6149 | observation_updated = true; |
| 6150 | } else { |
| 6151 | skipped.push(format!( |
| 6152 | "thread {}: its saved-session observation predates this migration or a change made outside it; reopen session {expected_id} before saving from this thread", |
| 6153 | thread.id |
| 6154 | )); |
| 6155 | } |
| 6156 | } |
| 6157 | let workspace_remapped = next_workspace.is_some(); |
| 6158 | if let Some(next) = next_workspace { |
| 6159 | thread.workspace = next; |
| 6160 | migrated.push(thread.id.clone()); |
| 6161 | } |
| 6162 | if !dry_run && (workspace_remapped || observation_updated) { |
| 6163 | store.save_thread(&thread)?; |
| 6164 | } |
| 6165 | } |
| 6166 | Ok((migrated, skipped)) |
| 6167 | } |
| 6168 | |
| 6169 | /// Clear `session_id` (and its checkpoint) on every thread in `store` that |
| 6170 | /// names it, recording each old binding in the reconcile receipts. |
| 6171 | fn unbind_session_threads_in_store( |
| 6172 | store: &RuntimeThreadStore, |
| 6173 | store_dir: &Path, |
| 6174 | session_id: &str, |
| 6175 | reason: &str, |
| 6176 | ) -> Result<usize> { |
| 6177 | let _thread_mutation = store.thread_mutation.lock(); |
| 6178 | let (threads, _) = store.list_threads_lenient()?; |
| 6179 | let mut unbound = 0; |
| 6180 | for mut thread in threads { |
| 6181 | if thread.session_id.as_deref() != Some(session_id) { |
| 6182 | continue; |
| 6183 | } |
| 6184 | crate::session_reconcile::record_thread_unbound(store_dir, &thread, reason); |
| 6185 | thread.session_id = None; |
| 6186 | thread.saved_session_checkpoint = None; |
| 6187 | thread.updated_at = Utc::now(); |
| 6188 | store.save_thread(&thread)?; |
| 6189 | unbound += 1; |
| 6190 | } |
| 6191 | Ok(unbound) |
| 6192 | } |
| 6193 | |
| 6194 | /// How many times an owner-lock acquire reopens the path after finding the |
| 6195 | /// file it locked was moved out of the store. Each retry needs another |
| 6196 | /// maintenance move to land in the same window, so a few is plenty. |
| 6197 | const OWNER_LOCK_MOVED_RETRIES: usize = 4; |
| 6198 | |
| 6199 | /// True when `file` is still the file at `path`. [`HeldRuntimeStore::move_to`] |
| 6200 | /// renames a held lock file out of its store, so a process that opened the |
| 6201 | /// path before that move and locked after it holds a lock on the moved store, |
| 6202 | /// not on the one at `path` (#6144). A held file that is no longer one |
| 6203 | /// regular file (unlinked, or linked twice) is not at the path either. |
| 6204 | fn owner_lock_is_at_path(file: &File, path: &Path) -> Result<bool> { |
| 6205 | let Ok(held) = runtime_store_file_identity(file) else { |
| 6206 | return Ok(false); |
| 6207 | }; |
| 6208 | let current = match open_runtime_store_file(path, "Runtime process owner lock", |options| { |
| 6209 | options.read(true); |
| 6210 | }) { |
| 6211 | Ok(current) => current, |
| 6212 | Err(error) |
| 6213 | if error |
| 6214 | .root_cause() |
| 6215 | .downcast_ref::<std::io::Error>() |
| 6216 | .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) => |
| 6217 | { |
| 6218 | return Ok(false); |
| 6219 | } |
| 6220 | Err(error) => return Err(error), |
| 6221 | }; |
| 6222 | Ok(runtime_store_file_identity(¤t)? == held) |
| 6223 | } |
| 6224 | |
| 6225 | #[cfg(any(test, feature = "test-support"))] |
| 6226 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 6227 | pub enum OwnerLockTestPoint { |
| 6228 | /// In `RuntimeProcessOwnerLock::acquire`, after the lock file is opened |
| 6229 | /// and before it is locked. |
| 6230 | LockFileOpened, |
| 6231 | /// In `HeldRuntimeStore::move_to`, after the held lock file is renamed |
| 6232 | /// into the destination and before the lock is dropped. |
| 6233 | LockFileMoved, |
| 6234 | } |
| 6235 | |
| 6236 | #[cfg(any(test, feature = "test-support"))] |
| 6237 | type OwnerLockTestHooks = Vec<(OwnerLockTestPoint, Box<dyn FnOnce()>)>; |
| 6238 | |
| 6239 | #[cfg(any(test, feature = "test-support"))] |
| 6240 | thread_local! { |
| 6241 | static OWNER_LOCK_TEST_HOOKS: std::cell::RefCell<OwnerLockTestHooks> = |
| 6242 | const { std::cell::RefCell::new(Vec::new()) }; |
| 6243 | } |
| 6244 | |
| 6245 | /// Run `hook` once, on this thread, the next time `point` is reached. |
| 6246 | #[cfg(any(test, feature = "test-support"))] |
| 6247 | pub fn set_owner_lock_test_hook(point: OwnerLockTestPoint, hook: impl FnOnce() + 'static) { |
| 6248 | OWNER_LOCK_TEST_HOOKS.with(|hooks| hooks.borrow_mut().push((point, Box::new(hook)))); |
| 6249 | } |
| 6250 | |
| 6251 | #[cfg(any(test, feature = "test-support"))] |
| 6252 | fn run_owner_lock_test_hook(point: OwnerLockTestPoint) { |
| 6253 | let hook = OWNER_LOCK_TEST_HOOKS.with(|hooks| { |
| 6254 | let mut hooks = hooks.borrow_mut(); |
| 6255 | let index = hooks.iter().position(|(at, _)| *at == point)?; |
| 6256 | Some(hooks.remove(index).1) |
| 6257 | }); |
| 6258 | if let Some(hook) = hook { |
| 6259 | hook(); |
| 6260 | } |
| 6261 | } |
| 6262 | |
| 6263 | #[derive(Debug)] |
| 6264 | pub struct RuntimeProcessOwnerLock { |
| 6265 | _file: File, |
| 6266 | #[cfg(any(unix, windows))] |
| 6267 | generation: String, |
| 6268 | /// Set once [`Self::record_holder`] wrote a holder record, so `Drop` clears |
| 6269 | /// it before the lock is released instead of leaving a stale pid behind. |
| 6270 | holder_recorded: bool, |
| 6271 | } |
| 6272 | |
| 6273 | impl RuntimeProcessOwnerLock { |
| 6274 | /// Reuse the Runtime's protected OS lease for task-store ownership. A |
| 6275 | /// missing existing lease is uncertainty, never proof that an owner died. |
| 6276 | pub fn try_acquire_file(path: &Path, create: bool) -> Result<Option<Self>> { |
| 6277 | let root = checked_runtime_store_root( |
| 6278 | path.parent() |
| 6279 | .context("Owner lease has no parent")? |
| 6280 | .to_path_buf(), |
| 6281 | )?; |
| 6282 | for _ in 0..OWNER_LOCK_MOVED_RETRIES { |
| 6283 | ensure_runtime_store_dir(&root)?; |
| 6284 | let file = open_runtime_store_file(path, "Execution owner lease", |options| { |
| 6285 | options |
| 6286 | .create(create) |
| 6287 | .truncate(false) |
| 6288 | .read(true) |
| 6289 | .write(true); |
| 6290 | })?; |
| 6291 | match codewhale_util::lock::try_lock_exclusive(&file) { |
| 6292 | Ok(()) => {} |
| 6293 | Err(error) if codewhale_util::lock::is_contention(&error) => return Ok(None), |
| 6294 | Err(error) => { |
| 6295 | return Err(error).context("Failed to acquire execution owner lease"); |
| 6296 | } |
| 6297 | } |
| 6298 | if owner_lock_is_at_path(&file, path)? { |
| 6299 | return Ok(Some(Self { |
| 6300 | _file: file, |
| 6301 | #[cfg(any(unix, windows))] |
| 6302 | generation: uuid::Uuid::new_v4().to_string(), |
| 6303 | holder_recorded: false, |
| 6304 | })); |
| 6305 | } |
| 6306 | // Moved out of this store between open and lock: reopen. |
| 6307 | } |
| 6308 | Ok(None) |
| 6309 | } |
| 6310 | |
| 6311 | /// Host admission reuses this exact store lease, never a PID-file lock. |
| 6312 | #[cfg(any(unix, windows))] |
| 6313 | pub fn try_acquire_for_host(root: &Path, create: bool) -> Result<Option<Self>> { |
| 6314 | if !create { |
| 6315 | checked_existing_runtime_store_dir(root)?; |
| 6316 | } |
| 6317 | Self::try_acquire_file(&root.join(RUNTIME_PROCESS_OWNER_LOCK_FILE), create) |
| 6318 | } |
| 6319 | |
| 6320 | pub fn validate_at_root(&self, root: &Path) -> Result<()> { |
| 6321 | let root = checked_runtime_store_root(root.to_path_buf())?; |
| 6322 | anyhow::ensure!( |
| 6323 | owner_lock_is_at_path(&self._file, &root.join(RUNTIME_PROCESS_OWNER_LOCK_FILE))?, |
| 6324 | "held Runtime owner lease changed before host recovery" |
| 6325 | ); |
| 6326 | Ok(()) |
| 6327 | } |
| 6328 | |
| 6329 | pub fn acquire(root: &Path) -> Result<Self> { |
| 6330 | let root = checked_runtime_store_root(root.to_path_buf())?; |
| 6331 | let path = root.join(RUNTIME_PROCESS_OWNER_LOCK_FILE); |
| 6332 | // Same-process drop-then-reopen can observe WouldBlock for a brief |
| 6333 | // window while the previous fd is still closing — the same close- |
| 6334 | // release race #5735 hit on the Runtime Chat scope lock. Retry only |
| 6335 | // that contention; a lock that stays held still belongs to its owner. |
| 6336 | let deadline = Instant::now() + Duration::from_millis(25); |
| 6337 | for _ in 0..OWNER_LOCK_MOVED_RETRIES { |
| 6338 | ensure_runtime_store_dir(&root)?; |
| 6339 | let file = open_runtime_store_file(&path, "Runtime process owner lock", |options| { |
| 6340 | options.create(true).truncate(false).read(true).write(true); |
| 6341 | })?; |
| 6342 | #[cfg(unix)] |
| 6343 | { |
| 6344 | use std::os::unix::fs::PermissionsExt as _; |
| 6345 | file.set_permissions(fs::Permissions::from_mode(0o600)) |
| 6346 | .context("Failed to protect Runtime process owner lock")?; |
| 6347 | } |
| 6348 | #[cfg(any(test, feature = "test-support"))] |
| 6349 | run_owner_lock_test_hook(OwnerLockTestPoint::LockFileOpened); |
| 6350 | loop { |
| 6351 | match codewhale_util::lock::try_lock_exclusive(&file) { |
| 6352 | Ok(()) => break, |
| 6353 | Err(error) if codewhale_util::lock::is_contention(&error) => { |
| 6354 | if Instant::now() >= deadline { |
| 6355 | return Err(Self::held_error()); |
| 6356 | } |
| 6357 | std::thread::yield_now(); |
| 6358 | std::thread::sleep(Duration::from_millis(1)); |
| 6359 | } |
| 6360 | Err(error) => { |
| 6361 | return Err(error).context("Failed to acquire Runtime process owner lock"); |
| 6362 | } |
| 6363 | } |
| 6364 | } |
| 6365 | if owner_lock_is_at_path(&file, &path)? { |
| 6366 | return Ok(Self { |
| 6367 | _file: file, |
| 6368 | #[cfg(any(unix, windows))] |
| 6369 | generation: uuid::Uuid::new_v4().to_string(), |
| 6370 | holder_recorded: false, |
| 6371 | }); |
| 6372 | } |
| 6373 | // A maintenance move renamed the file out of this store between |
| 6374 | // our open and our lock; the lock we hold is on the moved store. |
| 6375 | } |
| 6376 | Err(Self::held_error()) |
| 6377 | } |
| 6378 | |
| 6379 | /// Write this process's pid and the acquisition time into the lock file so |
| 6380 | /// a contender that finds the lock busy can say who holds it (#6573). |
| 6381 | /// Best effort: diagnostics must never fail the lock holder. |
| 6382 | pub fn record_holder(&mut self) { |
| 6383 | let since_ms = std::time::SystemTime::now() |
| 6384 | .duration_since(std::time::UNIX_EPOCH) |
| 6385 | .map_or(0, |elapsed| elapsed.as_millis()); |
| 6386 | let record = format!("pid={} since_ms={since_ms}\n", std::process::id()); |
| 6387 | let mut file = &self._file; |
| 6388 | let written = file |
| 6389 | .set_len(0) |
| 6390 | .and_then(|()| file.seek(SeekFrom::Start(0)).map(|_| ())) |
| 6391 | .and_then(|()| file.write_all(record.as_bytes())); |
| 6392 | match written { |
| 6393 | Ok(()) => self.holder_recorded = true, |
| 6394 | Err(error) => tracing::debug!(%error, "Could not record lock holder"), |
| 6395 | } |
| 6396 | } |
| 6397 | |
| 6398 | /// Read the holder recorded by [`Self::record_holder`]: its pid and how |
| 6399 | /// long it has held the lock. Never blocks (the lock does not cover the |
| 6400 | /// record: `flock` is advisory, and the Windows range starts after it) and |
| 6401 | /// never fails: anything unreadable or malformed is `None`. |
| 6402 | pub fn read_holder(path: &Path) -> Option<(u32, Duration)> { |
| 6403 | let file = open_runtime_store_file(path, "Owner lock holder record", |options| { |
| 6404 | options.read(true); |
| 6405 | }) |
| 6406 | .ok()?; |
| 6407 | let mut text = String::new(); |
| 6408 | file.take(codewhale_util::lock::OWNER_LOCK_HOLDER_MAX_BYTES) |
| 6409 | .read_to_string(&mut text) |
| 6410 | .ok()?; |
| 6411 | let mut pid = None; |
| 6412 | let mut since_ms = None; |
| 6413 | for field in text.split_whitespace() { |
| 6414 | match field.split_once('=') { |
| 6415 | Some(("pid", value)) => pid = value.parse::<u32>().ok(), |
| 6416 | Some(("since_ms", value)) => since_ms = value.parse::<u64>().ok(), |
| 6417 | _ => {} |
| 6418 | } |
| 6419 | } |
| 6420 | let since = std::time::UNIX_EPOCH + Duration::from_millis(since_ms?); |
| 6421 | let held_for = std::time::SystemTime::now() |
| 6422 | .duration_since(since) |
| 6423 | .unwrap_or_default(); |
| 6424 | Some((pid?, held_for)) |
| 6425 | } |
| 6426 | |
| 6427 | /// A held lock is typed `WouldBlock` so callers (the credential scrub, |
| 6428 | /// #6601) can tell a busy owner from a real lock failure. |
| 6429 | fn held_error() -> anyhow::Error { |
| 6430 | std::io::Error::new( |
| 6431 | std::io::ErrorKind::WouldBlock, |
| 6432 | RUNTIME_PROCESS_OWNER_LOCK_HELD, |
| 6433 | ) |
| 6434 | .into() |
| 6435 | } |
| 6436 | } |
| 6437 | |
| 6438 | impl Drop for RuntimeProcessOwnerLock { |
| 6439 | fn drop(&mut self) { |
| 6440 | if self.holder_recorded { |
| 6441 | // Best effort: a stale pid must not outlive the lock it described. |
| 6442 | let _ = self._file.set_len(0); |
| 6443 | } |
| 6444 | // close() also releases, but unlocking first lets a same-process |
| 6445 | // reopen proceed without racing the previous fd's teardown (#5735). |
| 6446 | codewhale_util::lock::unlock(&self._file); |
| 6447 | } |
| 6448 | } |
| 6449 | |
| 6450 | #[cfg(any(test, feature = "test-support"))] |
| 6451 | pub struct SnapshotTestPoint { |
| 6452 | pub thread_id: String, |
| 6453 | pub latest_seq: u64, |
| 6454 | pub resume: oneshot::Sender<()>, |
| 6455 | } |
| 6456 | |
| 6457 | #[cfg(any(test, feature = "test-support"))] |
| 6458 | pub struct ReplayTestPoint { |
| 6459 | pub thread_id: String, |
| 6460 | pub resume: oneshot::Sender<()>, |
| 6461 | } |
| 6462 | |
| 6463 | /// Canonical history intent lives in the existing Runtime operation directory. |
| 6464 | /// A reserved identity remains recoverable after an interrupted request. |
| 6465 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 6466 | #[serde(deny_unknown_fields)] |
| 6467 | pub struct RuntimeHistoryOperation { |
| 6468 | version: u32, |
| 6469 | key_fingerprint: String, |
| 6470 | pub committed: bool, |
| 6471 | pub created_at: chrono::DateTime<Utc>, |
| 6472 | pub receipt: codewhale_protocol::CanonicalThreadReceipt, |
| 6473 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 6474 | pub journal_witness: Option<RuntimeHistoryWitness>, |
| 6475 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 6476 | pub association: Option<codewhale_protocol::CanonicalThreadOperationAssociation>, |
| 6477 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 6478 | pub target_document_digest: Option<String>, |
| 6479 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 6480 | publication_base: Option<crate::session_manager::SessionObservation>, |
| 6481 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 6482 | goal_source_digest: Option<String>, |
| 6483 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 6484 | goal_target_digest: Option<String>, |
| 6485 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 6486 | pub session_goal_source_digest: Option<String>, |
| 6487 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 6488 | pub session_goal_target_digest: Option<String>, |
| 6489 | } |
| 6490 | |
| 6491 | /// Only reconstruction facts accompany the existing full-journal digest. The |
| 6492 | /// full graph remains in the protected SavedSession, not another history store. |
| 6493 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 6494 | #[serde(deny_unknown_fields)] |
| 6495 | pub struct RuntimeHistoryWitness { |
| 6496 | pub entries_len: usize, |
| 6497 | pub leaf_id: Option<String>, |
| 6498 | pub schema_version: u32, |
| 6499 | pub spawn_depth: u32, |
| 6500 | pub seed_from_message_index: usize, |
| 6501 | pub workspace: PathBuf, |
| 6502 | } |
| 6503 | impl RuntimeHistoryOperation { |
| 6504 | pub fn session_publication_id(&self) -> Result<String> { |
| 6505 | self.validate()?; |
| 6506 | Ok(codewhale_runtime::hashing::sha256_hex( |
| 6507 | codewhale_runtime::hashing::canonical_json(&serde_json::json!({ |
| 6508 | "session_publication": 1, |
| 6509 | "key_fingerprint": self.key_fingerprint, |
| 6510 | "receipt": self.receipt, |
| 6511 | })) |
| 6512 | .as_bytes(), |
| 6513 | )) |
| 6514 | } |
| 6515 | |
| 6516 | fn validate(&self) -> Result<()> { |
| 6517 | anyhow::ensure!( |
| 6518 | self.version == 1 && self.receipt.version == 1, |
| 6519 | "unsupported history operation schema" |
| 6520 | ); |
| 6521 | validate_sha256_fingerprint(&self.key_fingerprint, "history operation fingerprint")?; |
| 6522 | validate_sha256_fingerprint(&self.receipt.request_digest, "history request digest")?; |
| 6523 | validate_sha256_fingerprint(&self.receipt.history_digest, "history digest")?; |
| 6524 | validated_record_id(&self.receipt.runtime_thread_id, "history thread id")?; |
| 6525 | validated_record_id(&self.receipt.session_id, "history session id")?; |
| 6526 | validate_runtime_turn_operation_key(&self.receipt.operation_key)?; |
| 6527 | anyhow::ensure!( |
| 6528 | self.key_fingerprint |
| 6529 | == codewhale_runtime::hashing::sha256_hex( |
| 6530 | format!( |
| 6531 | "codewhale:history-operation:v1\0{}", |
| 6532 | self.receipt.operation_key |
| 6533 | ) |
| 6534 | .as_bytes() |
| 6535 | ), |
| 6536 | "history operation key does not match its binding" |
| 6537 | ); |
| 6538 | anyhow::ensure!( |
| 6539 | self.receipt.data_dir.is_absolute() |
| 6540 | && !self.receipt.execution_scope.is_empty() |
| 6541 | && self.receipt.execution_scope.len() <= 128, |
| 6542 | "invalid history operation store binding" |
| 6543 | ); |
| 6544 | if let Some(witness) = self.journal_witness.as_ref() { |
| 6545 | anyhow::ensure!( |
| 6546 | witness.entries_len <= codewhale_protocol::MAX_CANONICAL_HISTORY_ENTRIES |
| 6547 | && witness.seed_from_message_index <= witness.entries_len |
| 6548 | && witness.workspace.is_absolute() |
| 6549 | && witness.schema_version == 1 |
| 6550 | && witness |
| 6551 | .leaf_id |
| 6552 | .as_ref() |
| 6553 | .is_none_or(|id| id.len() <= 256 && !id.is_empty()), |
| 6554 | "invalid canonical operation journal witness" |
| 6555 | ); |
| 6556 | } |
| 6557 | for digest in [ |
| 6558 | self.session_goal_source_digest.as_ref(), |
| 6559 | self.session_goal_target_digest.as_ref(), |
| 6560 | ] |
| 6561 | .into_iter() |
| 6562 | .flatten() |
| 6563 | { |
| 6564 | validate_sha256_fingerprint(digest, "history session goal digest")?; |
| 6565 | } |
| 6566 | anyhow::ensure!( |
| 6567 | self.session_goal_source_digest.is_some() == self.session_goal_target_digest.is_some(), |
| 6568 | "history session goal witness is incomplete" |
| 6569 | ); |
| 6570 | if let Some(digest) = self.target_document_digest.as_ref() { |
| 6571 | validate_sha256_fingerprint(digest, "history target document digest")?; |
| 6572 | } |
| 6573 | anyhow::ensure!( |
| 6574 | self.goal_source_digest.is_some() == self.goal_target_digest.is_some(), |
| 6575 | "incomplete imported goal witness" |
| 6576 | ); |
| 6577 | for digest in [ |
| 6578 | self.goal_source_digest.as_ref(), |
| 6579 | self.goal_target_digest.as_ref(), |
| 6580 | ] |
| 6581 | .into_iter() |
| 6582 | .flatten() |
| 6583 | { |
| 6584 | validate_sha256_fingerprint(digest, "imported goal witness")?; |
| 6585 | } |
| 6586 | if let Some(association) = self.association.as_ref() { |
| 6587 | use codewhale_protocol::CanonicalThreadOperationKind; |
| 6588 | anyhow::ensure!( |
| 6589 | match association.kind { |
| 6590 | CanonicalThreadOperationKind::Create => |
| 6591 | association.source_runtime_thread_id.is_none() |
| 6592 | && association.source_session_id.is_none(), |
| 6593 | CanonicalThreadOperationKind::Resume | CanonicalThreadOperationKind::Fork => |
| 6594 | association.source_session_id.is_some(), |
| 6595 | }, |
| 6596 | "invalid canonical operation source association" |
| 6597 | ); |
| 6598 | if let Some(id) = association.source_runtime_thread_id.as_ref() { |
| 6599 | validated_record_id(id, "history source thread id")?; |
| 6600 | } |
| 6601 | if let Some(id) = association.source_session_id.as_ref() { |
| 6602 | validated_record_id(id, "history source session id")?; |
| 6603 | } |
| 6604 | anyhow::ensure!( |
| 6605 | self.journal_witness.is_some(), |
| 6606 | "operation association has no captured scope witness" |
| 6607 | ); |
| 6608 | } |
| 6609 | Ok(()) |
| 6610 | } |
| 6611 | } |
| 6612 | |
| 6613 | /// Durable intent of one `seed_thread_from_messages` transaction (#6555). |
| 6614 | /// The seed committed when the thread's `latest_turn_id` moved from |
| 6615 | /// `previous_latest_turn_id` to the final journaled turn; see |
| 6616 | /// [`RuntimeThreadStore::settle_seed_journals`]. |
| 6617 | #[derive(Debug, Serialize, Deserialize)] |
| 6618 | struct SeedJournal { |
| 6619 | thread_id: String, |
| 6620 | previous_latest_turn_id: Option<String>, |
| 6621 | turn_ids: Vec<String>, |
| 6622 | item_ids: Vec<String>, |
| 6623 | } |
| 6624 | |
| 6625 | /// What a seed journal proves; see |
| 6626 | /// [`RuntimeThreadStore::judge_seed_journal`]. |
| 6627 | enum SeedJournalVerdict { |
| 6628 | /// The seed committed; its records are history and the journal is stale. |
| 6629 | Committed { thread_id: String }, |
| 6630 | /// The seed never published; its records are withheld and discarded. |
| 6631 | Uncommitted(SeedJournal), |
| 6632 | /// Intent or ownership is uncertain. Nothing is deleted; these threads |
| 6633 | /// are held out of recovery until the journal is repaired. |
| 6634 | Quarantined { |
| 6635 | thread_ids: Vec<String>, |
| 6636 | reason: String, |
| 6637 | }, |
| 6638 | } |
| 6639 | |
| 6640 | /// True when a store read failed only because the record file is absent. |
| 6641 | fn store_record_missing(error: &anyhow::Error) -> bool { |
| 6642 | error |
| 6643 | .downcast_ref::<io::Error>() |
| 6644 | .is_some_and(|error| error.kind() == io::ErrorKind::NotFound) |
| 6645 | } |
| 6646 | |
| 6647 | fn duration_ms(start: DateTime<Utc>, end: DateTime<Utc>) -> u64 { |
| 6648 | let millis = (end - start).num_milliseconds(); |
| 6649 | if millis.is_negative() { |
| 6650 | 0 |
| 6651 | } else { |
| 6652 | u64::try_from(millis).unwrap_or(u64::MAX) |
| 6653 | } |
| 6654 | } |
| 6655 | |
| 6656 | pub fn checked_runtime_store_root(root: PathBuf) -> Result<PathBuf> { |
| 6657 | if root.as_os_str().is_empty() { |
| 6658 | bail!("Runtime store root cannot be empty"); |
| 6659 | } |
| 6660 | if root |
| 6661 | .components() |
| 6662 | .any(|component| matches!(component, Component::ParentDir)) |
| 6663 | { |
| 6664 | bail!("Runtime store root cannot contain '..' components"); |
| 6665 | } |
| 6666 | let absolute = if root.is_absolute() { |
| 6667 | root |
| 6668 | } else { |
| 6669 | std::env::current_dir() |
| 6670 | .context("failed to resolve current directory for runtime store")? |
| 6671 | .join(root) |
| 6672 | }; |
| 6673 | match absolute.canonicalize() { |
| 6674 | Ok(path) => Ok(path), |
| 6675 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => { |
| 6676 | Ok(normalize_path_components(&absolute)) |
| 6677 | } |
| 6678 | Err(err) => Err(err).with_context(|| { |
| 6679 | format!( |
| 6680 | "Failed to resolve runtime store root {}", |
| 6681 | absolute.display() |
| 6682 | ) |
| 6683 | }), |
| 6684 | } |
| 6685 | } |
| 6686 | |
| 6687 | fn checked_existing_runtime_store_dir(path: &Path) -> Result<PathBuf> { |
| 6688 | reject_symlinked_store_dir(path)?; |
| 6689 | path.canonicalize() |
| 6690 | .with_context(|| format!("Failed to resolve {}", path.display())) |
| 6691 | } |
| 6692 | |
| 6693 | fn normalize_path_components(path: &Path) -> PathBuf { |
| 6694 | let mut normalized = PathBuf::new(); |
| 6695 | for component in path.components() { |
| 6696 | match component { |
| 6697 | Component::Prefix(_) | Component::RootDir => normalized.push(component.as_os_str()), |
| 6698 | Component::CurDir => {} |
| 6699 | Component::ParentDir => { |
| 6700 | normalized.pop(); |
| 6701 | } |
| 6702 | Component::Normal(part) => normalized.push(part), |
| 6703 | } |
| 6704 | } |
| 6705 | if normalized.as_os_str().is_empty() { |
| 6706 | PathBuf::from(".") |
| 6707 | } else { |
| 6708 | normalized |
| 6709 | } |
| 6710 | } |
| 6711 | |
| 6712 | fn reject_symlinked_store_file(path: &Path) -> Result<()> { |
| 6713 | let Ok(metadata) = fs::symlink_metadata(path) else { |
| 6714 | return Ok(()); |
| 6715 | }; |
| 6716 | if metadata.file_type().is_symlink() { |
| 6717 | bail!( |
| 6718 | "Runtime store file must not be a symlink: {}", |
| 6719 | path.display() |
| 6720 | ); |
| 6721 | } |
| 6722 | Ok(()) |
| 6723 | } |
| 6724 | |
| 6725 | fn open_runtime_store_file( |
| 6726 | path: &Path, |
| 6727 | purpose: &str, |
| 6728 | configure: impl FnOnce(&mut OpenOptions), |
| 6729 | ) -> Result<File> { |
| 6730 | reject_symlinked_store_file(path)?; |
| 6731 | let mut options = OpenOptions::new(); |
| 6732 | configure(&mut options); |
| 6733 | #[cfg(unix)] |
| 6734 | { |
| 6735 | use std::os::unix::fs::OpenOptionsExt as _; |
| 6736 | options |
| 6737 | .mode(0o600) |
| 6738 | .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC); |
| 6739 | } |
| 6740 | #[cfg(windows)] |
| 6741 | { |
| 6742 | use std::os::windows::fs::OpenOptionsExt as _; |
| 6743 | use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT; |
| 6744 | options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT); |
| 6745 | } |
| 6746 | let file = options |
| 6747 | .open(path) |
| 6748 | .with_context(|| format!("Failed to open {purpose} {}", path.display()))?; |
| 6749 | runtime_store_file_identity(&file) |
| 6750 | .with_context(|| format!("Invalid {purpose} {}", path.display()))?; |
| 6751 | Ok(file) |
| 6752 | } |
| 6753 | |
| 6754 | fn read_runtime_store_owner(path: &Path) -> Result<Option<String>> { |
| 6755 | let file = match open_runtime_store_file(path, "Runtime store owner", |options| { |
| 6756 | options.read(true); |
| 6757 | }) { |
| 6758 | Ok(file) => file, |
| 6759 | Err(error) |
| 6760 | if error |
| 6761 | .downcast_ref::<std::io::Error>() |
| 6762 | .is_some_and(|cause| cause.kind() == std::io::ErrorKind::NotFound) => |
| 6763 | { |
| 6764 | return Ok(None); |
| 6765 | } |
| 6766 | Err(error) => return Err(error), |
| 6767 | }; |
| 6768 | let owner: RuntimeStoreOwner = serde_json::from_reader(file) |
| 6769 | .with_context(|| format!("Failed to parse {}", path.display()))?; |
| 6770 | validated_record_id(&owner.owner_id, "Runtime owner id")?; |
| 6771 | Ok(Some(owner.owner_id)) |
| 6772 | } |
| 6773 | |
| 6774 | fn load_or_create_runtime_store_owner(owner_path: &Path, event_lock_path: &Path) -> Result<String> { |
| 6775 | let lock_file = |
| 6776 | open_runtime_store_file(event_lock_path, "Runtime store ownership lock", |options| { |
| 6777 | options.create(true).truncate(false).read(true).write(true); |
| 6778 | })?; |
| 6779 | #[cfg(unix)] |
| 6780 | { |
| 6781 | use std::os::unix::fs::PermissionsExt as _; |
| 6782 | lock_file |
| 6783 | .set_permissions(fs::Permissions::from_mode(0o600)) |
| 6784 | .context("Failed to secure Runtime store ownership lock")?; |
| 6785 | } |
| 6786 | let mut lock = fd_lock::RwLock::new(lock_file); |
| 6787 | let started = Instant::now(); |
| 6788 | loop { |
| 6789 | match lock.try_write() { |
| 6790 | Ok(_guard) => { |
| 6791 | if let Some(owner_id) = read_runtime_store_owner(owner_path)? { |
| 6792 | return Ok(owner_id); |
| 6793 | } |
| 6794 | let owner_id = format!("owner_{}", Uuid::new_v4().simple()); |
| 6795 | write_json_atomic( |
| 6796 | owner_path, |
| 6797 | &RuntimeStoreOwner { |
| 6798 | owner_id: owner_id.clone(), |
| 6799 | }, |
| 6800 | )?; |
| 6801 | return Ok(owner_id); |
| 6802 | } |
| 6803 | Err(error) |
| 6804 | if matches!( |
| 6805 | error.kind(), |
| 6806 | std::io::ErrorKind::WouldBlock | std::io::ErrorKind::Interrupted |
| 6807 | ) => |
| 6808 | { |
| 6809 | wait_for_event_lock(started, EVENT_TRANSACTION_LOCK_TIMEOUT)?; |
| 6810 | } |
| 6811 | Err(error) => { |
| 6812 | return Err(error).context("Failed to lock Runtime store ownership"); |
| 6813 | } |
| 6814 | } |
| 6815 | } |
| 6816 | } |
| 6817 | |
| 6818 | #[cfg(unix)] |
| 6819 | fn runtime_store_file_identity(file: &File) -> Result<(u64, u64)> { |
| 6820 | use std::os::unix::fs::MetadataExt as _; |
| 6821 | |
| 6822 | let metadata = file.metadata()?; |
| 6823 | anyhow::ensure!( |
| 6824 | metadata.is_file() && metadata.nlink() == 1, |
| 6825 | "not one regular file" |
| 6826 | ); |
| 6827 | Ok((metadata.dev(), metadata.ino())) |
| 6828 | } |
| 6829 | |
| 6830 | #[cfg(windows)] |
| 6831 | fn runtime_store_file_identity(file: &File) -> Result<(u64, u64)> { |
| 6832 | use std::os::windows::fs::MetadataExt as _; |
| 6833 | use std::os::windows::io::AsRawHandle as _; |
| 6834 | use windows_sys::Win32::Storage::FileSystem::{ |
| 6835 | BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT, GetFileInformationByHandle, |
| 6836 | }; |
| 6837 | |
| 6838 | let metadata = file.metadata()?; |
| 6839 | let safe = metadata.is_file() && metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0; |
| 6840 | anyhow::ensure!(safe, "not a regular non-reparse file"); |
| 6841 | let mut info = BY_HANDLE_FILE_INFORMATION::default(); |
| 6842 | // SAFETY: the handle and writable output remain valid for the call. |
| 6843 | if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 { |
| 6844 | return Err(std::io::Error::last_os_error()).context("Inspect Runtime store file identity"); |
| 6845 | } |
| 6846 | anyhow::ensure!(info.nNumberOfLinks == 1, "has multiple filesystem links"); |
| 6847 | Ok(( |
| 6848 | u64::from(info.dwVolumeSerialNumber), |
| 6849 | (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow), |
| 6850 | )) |
| 6851 | } |
| 6852 | |
| 6853 | #[cfg(all(not(unix), not(windows)))] |
| 6854 | fn runtime_store_file_identity(file: &File) -> Result<(u64, u64)> { |
| 6855 | anyhow::ensure!(file.metadata()?.is_file(), "must be a regular file"); |
| 6856 | Ok((0, 0)) |
| 6857 | } |
| 6858 | |
| 6859 | fn validate_same_runtime_store_file_handles( |
| 6860 | first: &File, |
| 6861 | second: &File, |
| 6862 | path: &Path, |
| 6863 | ) -> Result<()> { |
| 6864 | let first = runtime_store_file_identity(first)?; |
| 6865 | let second = runtime_store_file_identity(second)?; |
| 6866 | anyhow::ensure!( |
| 6867 | first == second, |
| 6868 | "Runtime event file changed: {}", |
| 6869 | path.display() |
| 6870 | ); |
| 6871 | Ok(()) |
| 6872 | } |
| 6873 | |
| 6874 | fn wait_for_event_lock(started: Instant, timeout: Duration) -> Result<()> { |
| 6875 | let elapsed = started.elapsed(); |
| 6876 | if elapsed >= timeout { |
| 6877 | return Err(anyhow!(RuntimeEventLockTimeout(timeout))); |
| 6878 | } |
| 6879 | std::thread::sleep(EVENT_TRANSACTION_LOCK_POLL.min(timeout - elapsed)); |
| 6880 | Ok(()) |
| 6881 | } |
| 6882 | |
| 6883 | fn rollback_failed_event_append_handle(rollback_file: &File, original_len: u64) -> Result<()> { |
| 6884 | rollback_file |
| 6885 | .set_len(original_len) |
| 6886 | .context("Failed to roll back Runtime event")?; |
| 6887 | rollback_file |
| 6888 | .sync_all() |
| 6889 | .context("Failed to sync Runtime event rollback") |
| 6890 | } |
| 6891 | |
| 6892 | fn reject_symlinked_store_dir(path: &Path) -> Result<()> { |
| 6893 | let Ok(metadata) = fs::symlink_metadata(path) else { |
| 6894 | return Ok(()); |
| 6895 | }; |
| 6896 | if metadata.file_type().is_symlink() { |
| 6897 | bail!( |
| 6898 | "Runtime store directory must not be a symlink: {}", |
| 6899 | path.display() |
| 6900 | ); |
| 6901 | } |
| 6902 | if !metadata.is_dir() { |
| 6903 | bail!("Runtime store path must be a directory: {}", path.display()); |
| 6904 | } |
| 6905 | Ok(()) |
| 6906 | } |
| 6907 | |
| 6908 | fn ensure_runtime_store_dir(path: &Path) -> Result<()> { |
| 6909 | fs::create_dir_all(path).with_context(|| format!("Failed to create {}", path.display()))?; |
| 6910 | reject_symlinked_store_dir(path) |
| 6911 | } |
| 6912 | |
| 6913 | fn read_complete_event( |
| 6914 | reader: &mut impl BufRead, |
| 6915 | path: &Path, |
| 6916 | ) -> Result<Option<RuntimeEventRecord>> { |
| 6917 | Ok(read_complete_event_bytes(reader, path)?.map(|(event, _)| event)) |
| 6918 | } |
| 6919 | |
| 6920 | fn read_complete_event_bytes( |
| 6921 | reader: &mut impl BufRead, |
| 6922 | path: &Path, |
| 6923 | ) -> Result<Option<(RuntimeEventRecord, u64)>> { |
| 6924 | let mut skipped = 0u64; |
| 6925 | loop { |
| 6926 | let mut line = String::new(); |
| 6927 | if reader.read_line(&mut line)? == 0 { |
| 6928 | return Ok(None); |
| 6929 | } |
| 6930 | // A concurrent append can be visible before write_all finishes. The |
| 6931 | // subscribed broadcast path will deliver that event after its durable |
| 6932 | // append completes, so stop at an unterminated live tail instead of |
| 6933 | // misclassifying it as durable corruption. Store startup separately |
| 6934 | // truncates an unterminated tail left by a dead process. |
| 6935 | if !line.ends_with('\n') { |
| 6936 | return Ok(None); |
| 6937 | } |
| 6938 | skipped += u64::try_from(line.len()).unwrap_or(u64::MAX); |
| 6939 | if line.trim().is_empty() { |
| 6940 | continue; |
| 6941 | } |
| 6942 | let event = serde_json::from_str(&line) |
| 6943 | .with_context(|| format!("Failed to parse event line in {}", path.display()))?; |
| 6944 | return Ok(Some((event, skipped))); |
| 6945 | } |
| 6946 | } |
| 6947 | |
| 6948 | /// Remove only an unterminated final JSONL fragment left by a process or |
| 6949 | /// machine stopping before the append's newline commit marker. This includes |
| 6950 | /// an otherwise valid JSON object whose delimiter never reached disk: without |
| 6951 | /// the newline, the append did not commit. A newline-terminated bad record is |
| 6952 | /// not crash debris we can identify safely, so normal replay keeps rejecting |
| 6953 | /// it instead of silently discarding durable data. |
| 6954 | fn repair_torn_event_log_tails(events_dir: &Path) -> Result<()> { |
| 6955 | let events_dir = checked_existing_runtime_store_dir(events_dir)?; |
| 6956 | for entry in fs::read_dir(&events_dir) |
| 6957 | .with_context(|| format!("Failed to read {}", events_dir.display()))? |
| 6958 | { |
| 6959 | let entry = entry?; |
| 6960 | let path = entry.path(); |
| 6961 | if path |
| 6962 | .extension() |
| 6963 | .is_none_or(|extension| extension != "jsonl") |
| 6964 | { |
| 6965 | continue; |
| 6966 | } |
| 6967 | if !entry |
| 6968 | .file_type() |
| 6969 | .with_context(|| format!("Failed to inspect {}", path.display()))? |
| 6970 | .is_file() |
| 6971 | { |
| 6972 | continue; |
| 6973 | } |
| 6974 | repair_torn_event_log_tail(&path)?; |
| 6975 | } |
| 6976 | Ok(()) |
| 6977 | } |
| 6978 | |
| 6979 | fn repair_torn_event_log_tail(path: &Path) -> Result<()> { |
| 6980 | if !path.exists() { |
| 6981 | return Ok(()); |
| 6982 | } |
| 6983 | let mut file = open_runtime_store_file(path, "Runtime event tail recovery", |options| { |
| 6984 | options.read(true).write(true); |
| 6985 | })?; |
| 6986 | let len = file |
| 6987 | .metadata() |
| 6988 | .with_context(|| format!("Failed to inspect {}", path.display()))? |
| 6989 | .len(); |
| 6990 | if len == 0 { |
| 6991 | return Ok(()); |
| 6992 | } |
| 6993 | |
| 6994 | file.seek(SeekFrom::End(-1))?; |
| 6995 | let mut last = [0_u8; 1]; |
| 6996 | file.read_exact(&mut last)?; |
| 6997 | if last[0] == b'\n' { |
| 6998 | return Ok(()); |
| 6999 | } |
| 7000 | |
| 7001 | let mut search_end = len; |
| 7002 | let mut truncate_at = 0_u64; |
| 7003 | let mut buffer = [0_u8; 8 * 1024]; |
| 7004 | let buffer_len = u64::try_from(buffer.len()).expect("event recovery buffer fits u64"); |
| 7005 | while search_end > 0 { |
| 7006 | let chunk_len = usize::try_from(search_end.min(buffer_len)) |
| 7007 | .expect("event recovery chunk length fits usize"); |
| 7008 | let chunk_len_u64 = u64::try_from(chunk_len).expect("event recovery chunk length fits u64"); |
| 7009 | let chunk_start = search_end - chunk_len_u64; |
| 7010 | file.seek(SeekFrom::Start(chunk_start))?; |
| 7011 | file.read_exact(&mut buffer[..chunk_len])?; |
| 7012 | if let Some(index) = buffer[..chunk_len].iter().rposition(|byte| *byte == b'\n') { |
| 7013 | truncate_at = chunk_start |
| 7014 | + u64::try_from(index).expect("event recovery newline index fits u64") |
| 7015 | + 1; |
| 7016 | break; |
| 7017 | } |
| 7018 | search_end = chunk_start; |
| 7019 | } |
| 7020 | |
| 7021 | file.set_len(truncate_at) |
| 7022 | .with_context(|| format!("Failed to truncate torn tail in {}", path.display()))?; |
| 7023 | file.sync_all() |
| 7024 | .with_context(|| format!("Failed to sync repaired {}", path.display()))?; |
| 7025 | tracing::warn!( |
| 7026 | path = %path.display(), |
| 7027 | removed_bytes = len.saturating_sub(truncate_at), |
| 7028 | "Recovered an unterminated Runtime event-log tail" |
| 7029 | ); |
| 7030 | Ok(()) |
| 7031 | } |
| 7032 | |
| 7033 | fn read_store_file(path: &Path) -> Result<String> { |
| 7034 | reject_symlinked_store_file(path)?; |
| 7035 | fs::read_to_string(path).with_context(|| format!("Failed to read {}", path.display())) |
| 7036 | } |
| 7037 | |
| 7038 | fn load_runtime_store_state(path: &Path) -> Result<RuntimeStoreState> { |
| 7039 | let file = open_runtime_store_file(path, "Runtime store state", |options| { |
| 7040 | options.read(true); |
| 7041 | })?; |
| 7042 | serde_json::from_reader(file).with_context(|| format!("Failed to parse {}", path.display())) |
| 7043 | } |
| 7044 | |
| 7045 | fn write_json_atomic<T: Serialize>(path: &Path, value: &T) -> Result<()> { |
| 7046 | if let Some(parent) = path.parent() { |
| 7047 | fs::create_dir_all(parent) |
| 7048 | .with_context(|| format!("Failed to create directory {}", parent.display()))?; |
| 7049 | } |
| 7050 | reject_symlinked_store_file(path)?; |
| 7051 | let payload = serde_json::to_string_pretty(value)?; |
| 7052 | let parent = path |
| 7053 | .parent() |
| 7054 | .ok_or_else(|| anyhow!("Runtime record has no parent"))?; |
| 7055 | let name = path |
| 7056 | .file_name() |
| 7057 | .ok_or_else(|| anyhow!("Runtime record has no basename"))?; |
| 7058 | codewhale_util::files::WorkspaceFile::open_resolved_root(parent, Path::new(name), false) |
| 7059 | .and_then(|file| file.replace(payload.as_bytes())) |
| 7060 | .with_context(|| format!("Failed to write {}", path.display()))?; |
| 7061 | #[cfg(unix)] |
| 7062 | if let (Some(ancestor), Some(name)) = (parent.parent(), parent.file_name()) { |
| 7063 | codewhale_util::files::WorkspaceFile::open_resolved_root(ancestor, Path::new(name), false)? |
| 7064 | .sync_parent()?; |
| 7065 | } |
| 7066 | Ok(()) |
| 7067 | } |
| 7068 | |
| 7069 | fn remove_file_if_exists(path: &Path) -> Result<()> { |
| 7070 | reject_symlinked_store_file(path)?; |
| 7071 | match fs::remove_file(path) { |
| 7072 | Ok(()) => Ok(()), |
| 7073 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), |
| 7074 | Err(err) => Err(err).with_context(|| format!("Failed to remove {}", path.display())), |
| 7075 | } |
| 7076 | } |
| 7077 | |
| 7078 | mod agent_mail_store; |
| 7079 | pub mod job_operations; |
| 7080 | pub mod manager; |
| 7081 | pub mod thread_graph; |
| 7082 | mod turn_artifacts; |
| 7083 | pub use turn_artifacts::{ |
| 7084 | FileChangeKind, TurnArtifactKind, TurnArtifactRef, TurnWorkspaceArtifacts, TurnWorkspaceReason, |
| 7085 | TurnWorkspaceState, |
| 7086 | }; |
| 7087 | |
| 7088 | #[cfg(test)] |
| 7089 | mod tests; |
| 7090 | |
| 7091 | pub fn reconstruct_messages_from_turns_with( |
| 7092 | turns: &[TurnRecord], |
| 7093 | items_by_turn: &HashMap<String, Vec<TurnItemRecord>>, |
| 7094 | ) -> Result<Vec<Message>> { |
| 7095 | let mut messages = Vec::new(); |
| 7096 | let mut execution_providers = HashMap::new(); |
| 7097 | for turn in turns { |
| 7098 | let items = ordered_turn_items(turn, items_by_turn)?; |
| 7099 | |
| 7100 | for item in items.iter().filter(|item| projects_tool_history(item)) { |
| 7101 | for side in ["tool_use_id", "tool_result_for"] { |
| 7102 | if let Some(identity) = RuntimeToolIdentity::read(item.metadata.as_ref(), side)? { |
| 7103 | check_execution_provider( |
| 7104 | &mut execution_providers, |
| 7105 | identity.execution_id, |
| 7106 | identity.provider_id, |
| 7107 | )?; |
| 7108 | } |
| 7109 | } |
| 7110 | } |
| 7111 | |
| 7112 | // Only results this same projection will emit can settle a call. |
| 7113 | // New execution and legacy provider key domains remain disjoint; |
| 7114 | // provider identity must also agree with an explicit execution. |
| 7115 | let recorded_results: HashSet<_> = items |
| 7116 | .iter() |
| 7117 | .filter(|item| projects_tool_history(item)) |
| 7118 | .map(|item| RuntimeToolIdentity::read(item.metadata.as_ref(), "tool_result_for")) |
| 7119 | .collect::<Result<Vec<_>>>()? |
| 7120 | .into_iter() |
| 7121 | .flatten() |
| 7122 | .map(RuntimeToolIdentity::key) |
| 7123 | .collect(); |
| 7124 | |
| 7125 | let mut assistant_blocks: Vec<ContentBlock> = Vec::new(); |
| 7126 | let mut user_blocks: Vec<ContentBlock> = Vec::new(); |
| 7127 | let flush_assistant = |blocks: &mut Vec<ContentBlock>, msgs: &mut Vec<Message>| { |
| 7128 | if !blocks.is_empty() { |
| 7129 | msgs.push(Message { |
| 7130 | role: Role::Assistant, |
| 7131 | content: std::mem::take(blocks), |
| 7132 | }); |
| 7133 | } |
| 7134 | }; |
| 7135 | let flush_user = |blocks: &mut Vec<ContentBlock>, msgs: &mut Vec<Message>| { |
| 7136 | if !blocks.is_empty() { |
| 7137 | msgs.push(Message { |
| 7138 | role: Role::User, |
| 7139 | content: std::mem::take(blocks), |
| 7140 | }); |
| 7141 | } |
| 7142 | }; |
| 7143 | for item in &items { |
| 7144 | match item.kind { |
| 7145 | TurnItemKind::UserMessage => { |
| 7146 | // A steer the engine never committed is recorded |
| 7147 | // `queued` or `canceled` precisely because the model |
| 7148 | // never saw it. Replaying it here would put words into |
| 7149 | // the context that the record says were not delivered |
| 7150 | // — the record is right, so it stays out (#6276). |
| 7151 | if matches!( |
| 7152 | item.status, |
| 7153 | TurnItemLifecycleStatus::Queued | TurnItemLifecycleStatus::Canceled |
| 7154 | ) { |
| 7155 | continue; |
| 7156 | } |
| 7157 | flush_assistant(&mut assistant_blocks, &mut messages); |
| 7158 | user_blocks.extend(item.user_content()?); |
| 7159 | } |
| 7160 | TurnItemKind::AgentMessage => { |
| 7161 | flush_user(&mut user_blocks, &mut messages); |
| 7162 | let text = item.detail.clone().unwrap_or_else(|| item.summary.clone()); |
| 7163 | if !text.trim().is_empty() { |
| 7164 | assistant_blocks.push(ContentBlock::Text { |
| 7165 | text, |
| 7166 | cache_control: None, |
| 7167 | }); |
| 7168 | } |
| 7169 | } |
| 7170 | TurnItemKind::AgentReasoning => { |
| 7171 | flush_user(&mut user_blocks, &mut messages); |
| 7172 | let thinking = item.detail.clone().unwrap_or_else(|| item.summary.clone()); |
| 7173 | if !thinking.trim().is_empty() { |
| 7174 | assistant_blocks.push(ContentBlock::Thinking { |
| 7175 | thinking, |
| 7176 | signature: None, |
| 7177 | state: None, |
| 7178 | redacted_data: None, |
| 7179 | }); |
| 7180 | } |
| 7181 | } |
| 7182 | _ if projects_tool_history(item) => { |
| 7183 | let meta = item.metadata.as_ref(); |
| 7184 | let meta_str = |key: &str| { |
| 7185 | meta.and_then(|m| m.get(key)) |
| 7186 | .and_then(Value::as_str) |
| 7187 | .unwrap_or_default() |
| 7188 | .to_string() |
| 7189 | }; |
| 7190 | let call = RuntimeToolIdentity::read(meta, "tool_use_id")?; |
| 7191 | let result = RuntimeToolIdentity::read(meta, "tool_result_for")?; |
| 7192 | let tool_name = meta_str("tool_name"); |
| 7193 | // A call whose own outcome the store never recorded is |
| 7194 | // answered with the outcome it does hold, decided while |
| 7195 | // the id is still borrowed — see |
| 7196 | // `unanswered_call_result`. |
| 7197 | let unanswered = call.and_then(|identity| { |
| 7198 | unanswered_call_result(item, identity, &tool_name, &recorded_results) |
| 7199 | .map(|content| (identity, content)) |
| 7200 | }); |
| 7201 | // Completed live turns persist the call and its result |
| 7202 | // on one item; seeded history persists them as two. |
| 7203 | // Both shapes must rebuild the paired tool_call / |
| 7204 | // tool_result. Snapshots persisted before tool identity |
| 7205 | // was durable carry neither side: skip them rather than |
| 7206 | // replay an empty tool_call shell that strict |
| 7207 | // OpenAI-compatible endpoints reject (#5823). |
| 7208 | if let Some(identity) = call.filter(|_| !tool_name.is_empty()) { |
| 7209 | flush_user(&mut user_blocks, &mut messages); |
| 7210 | let input_str = meta |
| 7211 | .and_then(|m| m.get("tool_input")) |
| 7212 | .and_then(Value::as_str) |
| 7213 | .map(str::to_string) |
| 7214 | .or_else(|| item.detail.clone()) |
| 7215 | .unwrap_or_default(); |
| 7216 | let input: serde_json::Value = |
| 7217 | serde_json::from_str(&input_str).unwrap_or(serde_json::Value::Null); |
| 7218 | assistant_blocks.push(ContentBlock::ToolUse { |
| 7219 | execution_id: identity.execution_id.map(str::to_string), |
| 7220 | id: identity.provider_id.to_string(), |
| 7221 | name: tool_name, |
| 7222 | input, |
| 7223 | caller: meta |
| 7224 | .and_then(|m| m.get("tool_caller")) |
| 7225 | .map(|value| serde_json::from_value(value.clone())) |
| 7226 | .transpose() |
| 7227 | .context("Invalid stored tool caller")?, |
| 7228 | thought_signature: meta |
| 7229 | .and_then(|m| m.get("tool_thought_signature")) |
| 7230 | .map(|value| { |
| 7231 | value |
| 7232 | .as_str() |
| 7233 | .map(str::to_string) |
| 7234 | .context("Invalid stored tool thought signature") |
| 7235 | }) |
| 7236 | .transpose()?, |
| 7237 | }); |
| 7238 | } |
| 7239 | if let Some(identity) = result { |
| 7240 | flush_assistant(&mut assistant_blocks, &mut messages); |
| 7241 | let content = item.detail.clone().unwrap_or_default(); |
| 7242 | let is_error = item.recorded_tool_error(); |
| 7243 | let content_blocks = meta |
| 7244 | .and_then(|m| m.get("content_blocks")) |
| 7245 | .and_then(Value::as_array) |
| 7246 | .cloned(); |
| 7247 | user_blocks.push(ContentBlock::ToolResult { |
| 7248 | execution_id: identity.execution_id.map(str::to_string), |
| 7249 | tool_use_id: identity.provider_id.to_string(), |
| 7250 | content, |
| 7251 | is_error, |
| 7252 | content_blocks, |
| 7253 | }); |
| 7254 | } else if let Some((identity, content)) = unanswered { |
| 7255 | // The call above had no recorded outcome: pair it |
| 7256 | // here, in the position the live transcript held |
| 7257 | // its result, so the rebuilt turn is complete. |
| 7258 | flush_assistant(&mut assistant_blocks, &mut messages); |
| 7259 | user_blocks.push(ContentBlock::ToolResult { |
| 7260 | execution_id: identity.execution_id.map(str::to_string), |
| 7261 | tool_use_id: identity.provider_id.to_string(), |
| 7262 | content, |
| 7263 | is_error: Some(true), |
| 7264 | content_blocks: None, |
| 7265 | }); |
| 7266 | } |
| 7267 | } |
| 7268 | _ => {} |
| 7269 | } |
| 7270 | } |
| 7271 | flush_assistant(&mut assistant_blocks, &mut messages); |
| 7272 | flush_user(&mut user_blocks, &mut messages); |
| 7273 | } |
| 7274 | Ok(messages) |
| 7275 | } |
| 7276 |