| 1 | //! Repair of the saved-session store (#6144). |
| 2 | //! |
| 3 | //! The session document is the one authority for a conversation. Two links |
| 4 | //! hang off it, each with exactly one home: document → Runtime store in |
| 5 | //! `metadata.runtime_store`, and Runtime thread → document in |
| 6 | //! `ThreadRecord.session_id` plus its checkpoint. A directory's *name* is not |
| 7 | //! ownership: a host store sits under whichever id the process booted with, |
| 8 | //! and every conversation that process saved binds it. |
| 9 | //! |
| 10 | //! The write paths now keep those links consistent (stores are retired where |
| 11 | //! they are abandoned, export is idempotent, deleting a document unbinds its |
| 12 | //! threads, checkpoints cover a prefix). What they cannot prevent — a crash |
| 13 | //! or kill between two writes, and everything earlier builds left behind — is |
| 14 | //! repaired here, on load: |
| 15 | //! |
| 16 | //! - **R1** an unreadable document is set aside (a newer-schema one is left in |
| 17 | //! place and reported); |
| 18 | //! - **R2/R5** a store no document binds, holding no work, is set aside while |
| 19 | //! its process-owner lock is held, so no process can open it mid-move; a |
| 20 | //! store another process holds is skipped and counted as in use; |
| 21 | //! - **R3** a store no document binds that holds threads is re-indexed: one |
| 22 | //! "Recovered:" document per thread, bound to the store, with the thread |
| 23 | //! bound back to it; |
| 24 | //! - **R4** a thread bound to a document that no longer exists is unbound |
| 25 | //! (the old binding goes in the receipts) and loads from its own turns; |
| 26 | //! - **R6** a directory with no document, no store and only artifacts or |
| 27 | //! approval receipts is set aside when no document, thread or derived |
| 28 | //! thread id names it and it has been untouched for a day. |
| 29 | //! |
| 30 | //! Repair only ever *moves* things, into `sessions/.set-aside/<run>/`, with a |
| 31 | //! `MANIFEST.jsonl` naming each original path; it never unlinks. Every action |
| 32 | //! appends a line to `sessions/.reconcile/receipts.jsonl` (a dropped thread |
| 33 | //! binding is recorded in its store's `session-unbind-receipts.jsonl`), and |
| 34 | //! the run's summary is kept in `sessions/.reconcile/last.json` for |
| 35 | //! `codewhale doctor`. |
| 36 | |
| 37 | use std::collections::HashSet; |
| 38 | use std::fs; |
| 39 | use std::io::{self, Write as _}; |
| 40 | use std::path::{Path, PathBuf}; |
| 41 | use std::time::{Duration, SystemTime}; |
| 42 | |
| 43 | use chrono::{DateTime, Utc}; |
| 44 | use serde::{Deserialize, Serialize}; |
| 45 | use serde_json::{Value, json}; |
| 46 | use sha2::{Digest, Sha256}; |
| 47 | |
| 48 | use crate::runtime_threads::{RuntimeStoreBinding, ThreadRecord}; |
| 49 | use crate::session_manager::{ |
| 50 | SavedSession, SessionManager, is_offline_queue_file, is_runtime_store_dir_name, |
| 51 | read_session_reference_bytes, |
| 52 | }; |
| 53 | |
| 54 | pub const SET_ASIDE_DIR: &str = ".set-aside"; |
| 55 | const RECONCILE_DIR: &str = ".reconcile"; |
| 56 | const RECONCILE_LOCK_FILE: &str = ".reconcile.lock"; |
| 57 | const RECEIPTS_FILE: &str = "receipts.jsonl"; |
| 58 | const LAST_RUN_FILE: &str = "last.json"; |
| 59 | const MANIFEST_FILE: &str = "MANIFEST.jsonl"; |
| 60 | const LATE_USAGE_DIR: &str = ".late-usage"; |
| 61 | const CHECKPOINTS_DIR: &str = "checkpoints"; |
| 62 | const SESSION_BOOT_OWNERS_FILE: &str = "session_boot_owners.json"; |
| 63 | /// Upper bound on actions per run; the rest waits for the next launch. |
| 64 | pub const DEFAULT_ACTION_LIMIT: usize = 500; |
| 65 | /// A document-less artifact directory has no lock to prove nobody is still |
| 66 | /// writing it (an older build's engine, say), so it must also be idle. |
| 67 | const ARTIFACT_DIR_IDLE: Duration = Duration::from_secs(24 * 60 * 60); |
| 68 | |
| 69 | /// What one reconcile run did (or, dry, would do). |
| 70 | #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] |
| 71 | pub struct ReconcileSummary { |
| 72 | pub ran_at: Option<DateTime<Utc>>, |
| 73 | #[serde(default)] |
| 74 | pub dry_run: bool, |
| 75 | /// Another process was already reconciling; nothing was examined. |
| 76 | #[serde(default)] |
| 77 | pub skipped_concurrent: bool, |
| 78 | /// R1: unreadable documents set aside. |
| 79 | #[serde(default)] |
| 80 | pub documents_set_aside: usize, |
| 81 | /// Documents written by a newer build, left in place. |
| 82 | #[serde(default)] |
| 83 | pub documents_newer_schema: usize, |
| 84 | /// R2/R5: unbound, empty Runtime stores set aside. |
| 85 | #[serde(default)] |
| 86 | pub stores_set_aside: usize, |
| 87 | /// Unbound stores that hold work with no thread to re-index; kept. |
| 88 | #[serde(default)] |
| 89 | pub stores_kept_with_work: usize, |
| 90 | /// Unbound stores a live process holds; left for a later run. |
| 91 | #[serde(default)] |
| 92 | pub stores_in_use: usize, |
| 93 | /// R3: "Recovered:" documents written for threads in unbound stores. |
| 94 | #[serde(default)] |
| 95 | pub sessions_recovered: usize, |
| 96 | /// R4: threads whose document no longer exists, unbound. |
| 97 | #[serde(default)] |
| 98 | pub threads_unbound: usize, |
| 99 | /// R6: document-less artifact directories set aside. |
| 100 | #[serde(default)] |
| 101 | pub artifact_dirs_set_aside: usize, |
| 102 | /// Document-less directories kept because something names them, they |
| 103 | /// are recent, or they hold something this repair does not recognise. |
| 104 | #[serde(default)] |
| 105 | pub artifact_dirs_kept: usize, |
| 106 | /// The per-run action limit stopped this run; the next one continues. |
| 107 | #[serde(default)] |
| 108 | pub limit_reached: bool, |
| 109 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 110 | pub set_aside_path: Option<PathBuf>, |
| 111 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 112 | pub errors: Vec<String>, |
| 113 | } |
| 114 | |
| 115 | impl ReconcileSummary { |
| 116 | fn actions(&self) -> usize { |
| 117 | self.documents_set_aside |
| 118 | + self.stores_set_aside |
| 119 | + self.sessions_recovered |
| 120 | + self.threads_unbound |
| 121 | + self.artifact_dirs_set_aside |
| 122 | } |
| 123 | |
| 124 | /// Whether this run changed anything on disk. |
| 125 | #[must_use] |
| 126 | pub fn changed(&self) -> bool { |
| 127 | !self.dry_run && self.actions() > 0 |
| 128 | } |
| 129 | |
| 130 | /// One line for the first frame when something changed or inspection failed. |
| 131 | #[must_use] |
| 132 | pub fn notice(&self) -> Option<String> { |
| 133 | if !self.changed() { |
| 134 | return (!self.errors.is_empty()) |
| 135 | .then(|| "Session check incomplete · codewhale doctor --full".to_owned()); |
| 136 | } |
| 137 | let mut parts = Vec::new(); |
| 138 | if self.sessions_recovered > 0 { |
| 139 | parts.push(format!("{} recovered", self.sessions_recovered)); |
| 140 | } |
| 141 | if self.threads_unbound > 0 { |
| 142 | parts.push(format!("{} stale links cleared", self.threads_unbound)); |
| 143 | } |
| 144 | let set_aside = |
| 145 | self.stores_set_aside + self.artifact_dirs_set_aside + self.documents_set_aside; |
| 146 | if set_aside > 0 { |
| 147 | parts.push(format!("{set_aside} unused items set aside")); |
| 148 | } |
| 149 | let mut line = format!("Sessions repaired: {}", parts.join(", ")); |
| 150 | if self.set_aside_path.is_some() || !self.errors.is_empty() { |
| 151 | line.push_str(" · codewhale doctor --full"); |
| 152 | } |
| 153 | Some(line) |
| 154 | } |
| 155 | |
| 156 | /// The `codewhale doctor` detail for this run. |
| 157 | #[must_use] |
| 158 | pub fn doctor_detail(&self) -> String { |
| 159 | let when = self |
| 160 | .ran_at |
| 161 | .map_or_else(|| "never".to_string(), |at| at.to_rfc3339()); |
| 162 | let mut line = format!( |
| 163 | "last repair {when}: {} recovered, {} threads unbound, {} stores + {} artifact dirs + {} unreadable documents set aside, {} newer-schema documents left in place, {} unbound stores in use by another process, {} kept with work", |
| 164 | self.sessions_recovered, |
| 165 | self.threads_unbound, |
| 166 | self.stores_set_aside, |
| 167 | self.artifact_dirs_set_aside, |
| 168 | self.documents_set_aside, |
| 169 | self.documents_newer_schema, |
| 170 | self.stores_in_use, |
| 171 | self.stores_kept_with_work, |
| 172 | ); |
| 173 | if self.limit_reached { |
| 174 | line.push_str("; more remains for the next run"); |
| 175 | } |
| 176 | if let Some(path) = &self.set_aside_path { |
| 177 | line.push_str(&format!("; set aside under {}", path.display())); |
| 178 | } |
| 179 | if let Some(first) = self.errors.first() { |
| 180 | line.push_str(&format!( |
| 181 | "; {} item(s) could not be inspected and were left unchanged, first: {first}", |
| 182 | self.errors.len() |
| 183 | )); |
| 184 | if self.errors.len() > 1 { |
| 185 | line.push_str(&format!(" (+{} more)", self.errors.len() - 1)); |
| 186 | } |
| 187 | line.push_str( |
| 188 | ". Nothing was lost; `codewhale doctor --repair-sessions --dry-run` lists every item", |
| 189 | ); |
| 190 | } |
| 191 | line |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | #[derive(Debug, Clone)] |
| 196 | pub struct ReconcileOptions { |
| 197 | /// Examine and count, but move and write nothing. |
| 198 | pub dry_run: bool, |
| 199 | pub limit: usize, |
| 200 | /// A document being resumed right now; never touched. |
| 201 | pub skip_session: Option<String>, |
| 202 | /// How long a document-less artifact directory must sit untouched. |
| 203 | pub artifact_idle: Duration, |
| 204 | } |
| 205 | |
| 206 | impl Default for ReconcileOptions { |
| 207 | fn default() -> Self { |
| 208 | Self { |
| 209 | dry_run: false, |
| 210 | limit: DEFAULT_ACTION_LIMIT, |
| 211 | skip_session: None, |
| 212 | artifact_idle: ARTIFACT_DIR_IDLE, |
| 213 | } |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | /// The summary of the last completed (non-dry) run, if any. |
| 218 | #[must_use] |
| 219 | pub fn last_run(sessions_dir: &Path) -> Option<ReconcileSummary> { |
| 220 | let raw = fs::read(sessions_dir.join(RECONCILE_DIR).join(LAST_RUN_FILE)).ok()?; |
| 221 | serde_json::from_slice(&raw).ok() |
| 222 | } |
| 223 | |
| 224 | static PENDING_NOTICE: std::sync::Mutex<Option<String>> = std::sync::Mutex::new(None); |
| 225 | |
| 226 | /// The first-frame notice a background run left, taken once. |
| 227 | pub fn take_pending_notice() -> Option<String> { |
| 228 | PENDING_NOTICE.lock().ok()?.take() |
| 229 | } |
| 230 | |
| 231 | /// Reconcile the default sessions store on a blocking worker. Called once a |
| 232 | /// host holds its own Runtime store, so that store and any store the launch |
| 233 | /// just opened read as in use rather than as candidates. |
| 234 | pub fn spawn_background_reconcile(skip_session: Option<String>) { |
| 235 | tokio::task::spawn_blocking(move || { |
| 236 | let Ok(manager) = SessionManager::default_location() else { |
| 237 | return; |
| 238 | }; |
| 239 | let options = ReconcileOptions { |
| 240 | skip_session, |
| 241 | ..ReconcileOptions::default() |
| 242 | }; |
| 243 | match reconcile(&manager, &options) { |
| 244 | Ok(summary) => { |
| 245 | if let Some(notice) = summary.notice() |
| 246 | && let Ok(mut pending) = PENDING_NOTICE.lock() |
| 247 | { |
| 248 | *pending = Some(notice); |
| 249 | } |
| 250 | } |
| 251 | Err(error) => tracing::warn!(%error, "session store repair did not run"), |
| 252 | } |
| 253 | }); |
| 254 | } |
| 255 | |
| 256 | /// Run one bounded reconcile pass over `sessions`' store. |
| 257 | pub fn reconcile( |
| 258 | sessions: &SessionManager, |
| 259 | options: &ReconcileOptions, |
| 260 | ) -> io::Result<ReconcileSummary> { |
| 261 | let sessions_dir = sessions.sessions_dir().to_path_buf(); |
| 262 | let mut summary = ReconcileSummary { |
| 263 | ran_at: Some(Utc::now()), |
| 264 | dry_run: options.dry_run, |
| 265 | ..ReconcileSummary::default() |
| 266 | }; |
| 267 | let lock_file = |
| 268 | crate::session_manager::open_private_lock_file(&sessions_dir.join(RECONCILE_LOCK_FILE))?; |
| 269 | if !codewhale_util::lock::try_lock_file_exclusive(&lock_file)? { |
| 270 | summary.skipped_concurrent = true; |
| 271 | return Ok(summary); |
| 272 | } |
| 273 | let mut run = Run { |
| 274 | sessions, |
| 275 | canonical_root: sessions_dir |
| 276 | .canonicalize() |
| 277 | .unwrap_or_else(|_| sessions_dir.clone()), |
| 278 | sessions_dir, |
| 279 | options, |
| 280 | set_aside: SetAside::default(), |
| 281 | summary, |
| 282 | }; |
| 283 | run.execute(); |
| 284 | let summary = run.summary; |
| 285 | if !options.dry_run { |
| 286 | let dir = sessions.sessions_dir().join(RECONCILE_DIR); |
| 287 | fs::create_dir_all(&dir)?; |
| 288 | let bytes = serde_json::to_vec_pretty(&summary).map_err(io::Error::other)?; |
| 289 | codewhale_util::utils::write_atomic(&dir.join(LAST_RUN_FILE), &bytes)?; |
| 290 | } |
| 291 | drop(lock_file); |
| 292 | Ok(summary) |
| 293 | } |
| 294 | |
| 295 | /// Receipts of thread bindings dropped in a store, kept in that store's root |
| 296 | /// (outside its work directories, so they never make it look busy). |
| 297 | pub const THREAD_UNBIND_RECEIPTS_FILE: &str = "session-unbind-receipts.jsonl"; |
| 298 | |
| 299 | /// Record the binding a thread is losing, next to the thread itself: the |
| 300 | /// store is the one place every writer that unbinds (the thread's own host, |
| 301 | /// the Runtime API, reconcile) already knows. |
| 302 | pub fn record_thread_unbound(store_dir: &Path, thread: &ThreadRecord, reason: &str) { |
| 303 | let receipt = json!({ |
| 304 | "action": "thread_unbound", |
| 305 | "thread_id": thread.id, |
| 306 | "session_id": thread.session_id, |
| 307 | "saved_session_checkpoint": thread.saved_session_checkpoint, |
| 308 | "reason": reason, |
| 309 | "at": Utc::now(), |
| 310 | }); |
| 311 | let result = fs::OpenOptions::new() |
| 312 | .create(true) |
| 313 | .append(true) |
| 314 | .open(store_dir.join(THREAD_UNBIND_RECEIPTS_FILE)) |
| 315 | .and_then(|mut file| { |
| 316 | let mut line = serde_json::to_vec(&receipt).map_err(io::Error::other)?; |
| 317 | line.push(b'\n'); |
| 318 | file.write_all(&line) |
| 319 | }); |
| 320 | if let Err(error) = result { |
| 321 | tracing::warn!(%error, thread_id = %thread.id, "thread unbind receipt was not written"); |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | /// Set aside `store` when no document or checkpoint binds it, no process |
| 326 | /// holds it, and it holds no work. Returns where it went. Used where a store |
| 327 | /// is abandoned — a switch that rebinds its conversation elsewhere, a delete |
| 328 | /// — so the abandonment does not wait for the next reconcile. |
| 329 | pub fn retire_unbound_store( |
| 330 | sessions: &SessionManager, |
| 331 | store: &Path, |
| 332 | reason: &str, |
| 333 | ) -> Option<PathBuf> { |
| 334 | if !store.is_dir() { |
| 335 | return None; |
| 336 | } |
| 337 | let references = collect_document_references(sessions.sessions_dir(), false); |
| 338 | if !references.incomplete.is_empty() { |
| 339 | tracing::warn!(store = %store.display(), error = %references.incomplete[0], "released store kept because reference inspection is incomplete"); |
| 340 | return None; |
| 341 | } |
| 342 | if references.binds(store) { |
| 343 | return None; |
| 344 | } |
| 345 | let binding = RuntimeStoreBinding::for_store_dir(store).ok()?; |
| 346 | let held = binding.try_hold().ok().flatten()?; |
| 347 | if !matches!(held.keep_reason(), Ok(None)) { |
| 348 | return None; |
| 349 | } |
| 350 | let canonical_root = sessions |
| 351 | .sessions_dir() |
| 352 | .canonicalize() |
| 353 | .unwrap_or_else(|_| sessions.sessions_dir().to_path_buf()); |
| 354 | let mut set_aside = SetAside::default(); |
| 355 | let original = held.binding().data_dir.clone(); |
| 356 | let target = set_aside |
| 357 | .target_for(sessions.sessions_dir(), &canonical_root, &original) |
| 358 | .ok()?; |
| 359 | if let Err(error) = held.move_to(&target) { |
| 360 | tracing::debug!(store = %original.display(), %error, "released store was not set aside"); |
| 361 | return None; |
| 362 | } |
| 363 | set_aside.manifest(&original, &target, reason, json!({"kind": "runtime_store"})); |
| 364 | append_receipt( |
| 365 | sessions.sessions_dir(), |
| 366 | json!({"action": "store_set_aside", "path": original, "moved_to": target, "reason": reason}), |
| 367 | ); |
| 368 | remove_if_empty(original.parent()); |
| 369 | Some(target) |
| 370 | } |
| 371 | |
| 372 | /// [`retire_unbound_store`] off the calling thread when a Tokio runtime is |
| 373 | /// running (a session switch runs on the UI runtime and must not wait on a |
| 374 | /// scan of every document), inline otherwise. |
| 375 | pub fn retire_unbound_store_in_background( |
| 376 | sessions: SessionManager, |
| 377 | store: PathBuf, |
| 378 | reason: &'static str, |
| 379 | ) { |
| 380 | match tokio::runtime::Handle::try_current() { |
| 381 | Ok(runtime) => { |
| 382 | runtime.spawn_blocking(move || retire_unbound_store(&sessions, &store, reason)); |
| 383 | } |
| 384 | Err(_) => { |
| 385 | retire_unbound_store(&sessions, &store, reason); |
| 386 | } |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | fn append_receipt(sessions_dir: &Path, mut receipt: Value) { |
| 391 | if let Value::Object(map) = &mut receipt { |
| 392 | map.insert("at".into(), json!(Utc::now())); |
| 393 | } |
| 394 | let dir = sessions_dir.join(RECONCILE_DIR); |
| 395 | let result = fs::create_dir_all(&dir).and_then(|()| { |
| 396 | let mut file = fs::OpenOptions::new() |
| 397 | .create(true) |
| 398 | .append(true) |
| 399 | .open(dir.join(RECEIPTS_FILE))?; |
| 400 | let mut line = serde_json::to_vec(&receipt).map_err(io::Error::other)?; |
| 401 | line.push(b'\n'); |
| 402 | file.write_all(&line) |
| 403 | }); |
| 404 | if let Err(error) = result { |
| 405 | tracing::warn!(%error, "session repair receipt was not written"); |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | fn remove_if_empty(dir: Option<&Path>) { |
| 410 | if let Some(dir) = dir |
| 411 | && fs::read_dir(dir).is_ok_and(|mut entries| entries.next().is_none()) |
| 412 | { |
| 413 | let _ = fs::remove_dir(dir); |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | /// One `.set-aside/<run>/` directory, created on first use. |
| 418 | #[derive(Default)] |
| 419 | struct SetAside { |
| 420 | run_dir: Option<PathBuf>, |
| 421 | } |
| 422 | |
| 423 | impl SetAside { |
| 424 | fn target_for( |
| 425 | &mut self, |
| 426 | sessions_dir: &Path, |
| 427 | canonical_root: &Path, |
| 428 | original: &Path, |
| 429 | ) -> io::Result<PathBuf> { |
| 430 | let run_dir = match &self.run_dir { |
| 431 | Some(dir) => dir.clone(), |
| 432 | None => { |
| 433 | let stamp = Utc::now().format("%Y%m%dT%H%M%SZ"); |
| 434 | let suffix = &uuid::Uuid::new_v4().simple().to_string()[..6]; |
| 435 | let dir = sessions_dir |
| 436 | .join(SET_ASIDE_DIR) |
| 437 | .join(format!("{stamp}-{suffix}")); |
| 438 | fs::create_dir_all(&dir)?; |
| 439 | self.run_dir = Some(dir.clone()); |
| 440 | dir |
| 441 | } |
| 442 | }; |
| 443 | let relative = original |
| 444 | .strip_prefix(canonical_root) |
| 445 | .or_else(|_| original.strip_prefix(sessions_dir)) |
| 446 | .map(Path::to_path_buf) |
| 447 | .unwrap_or_else(|_| { |
| 448 | original |
| 449 | .file_name() |
| 450 | .map(PathBuf::from) |
| 451 | .unwrap_or_else(|| PathBuf::from("unnamed")) |
| 452 | }); |
| 453 | Ok(run_dir.join(relative)) |
| 454 | } |
| 455 | |
| 456 | fn manifest(&self, original: &Path, moved_to: &Path, reason: &str, detail: Value) { |
| 457 | let Some(run_dir) = &self.run_dir else { |
| 458 | return; |
| 459 | }; |
| 460 | let line = json!({ |
| 461 | "original": original, |
| 462 | "moved_to": moved_to, |
| 463 | "reason": reason, |
| 464 | "detail": detail, |
| 465 | "at": Utc::now(), |
| 466 | }); |
| 467 | let result = fs::OpenOptions::new() |
| 468 | .create(true) |
| 469 | .append(true) |
| 470 | .open(run_dir.join(MANIFEST_FILE)) |
| 471 | .and_then(|mut file| { |
| 472 | let mut bytes = serde_json::to_vec(&line).map_err(io::Error::other)?; |
| 473 | bytes.push(b'\n'); |
| 474 | file.write_all(&bytes) |
| 475 | }); |
| 476 | if let Err(error) = result { |
| 477 | tracing::warn!(%error, "set-aside manifest entry was not written"); |
| 478 | } |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | /// Everything that names a session id or a store. |
| 483 | #[derive(Default)] |
| 484 | struct References { |
| 485 | /// Ids with a readable document or a crash-recovery checkpoint. |
| 486 | documents: HashSet<String>, |
| 487 | /// Stores some document or checkpoint binds (canonical where possible). |
| 488 | bound_stores: HashSet<PathBuf>, |
| 489 | /// Ids named by a Runtime thread, or derived from one. |
| 490 | thread_named: HashSet<String>, |
| 491 | /// Every uuid-shaped token found in any document's text. |
| 492 | document_tokens: HashSet<String>, |
| 493 | /// Document texts, kept only to answer non-uuid ids (rare). |
| 494 | document_texts: Vec<String>, |
| 495 | incomplete: Vec<String>, |
| 496 | } |
| 497 | |
| 498 | impl References { |
| 499 | fn failed(&mut self, path: &Path, error: impl std::fmt::Display) { |
| 500 | self.incomplete.push(format!("{}: {error}", path.display())); |
| 501 | } |
| 502 | |
| 503 | fn binds(&self, store: &Path) -> bool { |
| 504 | self.bound_stores.contains(&canonical(store)) || self.bound_stores.contains(store) |
| 505 | } |
| 506 | |
| 507 | fn names(&self, id: &str) -> bool { |
| 508 | self.documents.contains(id) |
| 509 | || self.thread_named.contains(id) |
| 510 | || self.document_tokens.contains(id) |
| 511 | || (!looks_like_uuid(id) && self.document_texts.iter().any(|text| text.contains(id))) |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | fn canonical(path: &Path) -> PathBuf { |
| 516 | path.canonicalize().unwrap_or_else(|_| path.to_path_buf()) |
| 517 | } |
| 518 | |
| 519 | fn looks_like_uuid(id: &str) -> bool { |
| 520 | id.len() == 36 && uuid::Uuid::parse_str(id).is_ok() |
| 521 | } |
| 522 | |
| 523 | fn uuid_tokens(bytes: &[u8]) -> impl Iterator<Item = String> + '_ { |
| 524 | static UUID: std::sync::LazyLock<regex::bytes::Regex> = std::sync::LazyLock::new(|| { |
| 525 | regex::bytes::Regex::new( |
| 526 | "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}", |
| 527 | ) |
| 528 | .expect("uuid pattern") |
| 529 | }); |
| 530 | UUID.find_iter(bytes) |
| 531 | .map(|found| String::from_utf8_lossy(found.as_bytes()).to_ascii_lowercase()) |
| 532 | } |
| 533 | |
| 534 | fn document_id(path: &Path) -> Option<String> { |
| 535 | if path.extension().is_none_or(|ext| ext != "json") |
| 536 | || path |
| 537 | .file_name() |
| 538 | .is_some_and(|name| name == SESSION_BOOT_OWNERS_FILE) |
| 539 | { |
| 540 | return None; |
| 541 | } |
| 542 | let id = path.file_stem()?.to_str()?; |
| 543 | codewhale_runtime::artifacts::is_valid_session_id(id).then(|| id.to_string()) |
| 544 | } |
| 545 | |
| 546 | /// Store bindings and ids of every readable document and checkpoint. With |
| 547 | /// `keep_text`, also collect what R6 needs to know which ids documents mention. |
| 548 | fn collect_document_references(sessions_dir: &Path, keep_text: bool) -> References { |
| 549 | let mut references = References::default(); |
| 550 | let checkpoints_dir = sessions_dir.join(CHECKPOINTS_DIR); |
| 551 | let scan = |dir: &Path, references: &mut References, keep_text: bool| { |
| 552 | let entries = match fs::read_dir(dir) { |
| 553 | Ok(entries) => entries, |
| 554 | Err(error) if error.kind() == io::ErrorKind::NotFound => return, |
| 555 | Err(error) => { |
| 556 | references.failed(dir, error); |
| 557 | return; |
| 558 | } |
| 559 | }; |
| 560 | for entry in entries { |
| 561 | let entry = match entry { |
| 562 | Ok(entry) => entry, |
| 563 | Err(error) => { |
| 564 | references.failed(dir, error); |
| 565 | continue; |
| 566 | } |
| 567 | }; |
| 568 | let path = entry.path(); |
| 569 | if dir == checkpoints_dir |
| 570 | && path |
| 571 | .file_name() |
| 572 | .and_then(|name| name.to_str()) |
| 573 | .is_some_and(is_offline_queue_file) |
| 574 | { |
| 575 | continue; |
| 576 | } |
| 577 | let Some(id) = document_id(&path) else { |
| 578 | continue; |
| 579 | }; |
| 580 | references.documents.insert(id); |
| 581 | let metadata = match SessionManager::load_session_metadata(&path) { |
| 582 | Ok(metadata) => metadata, |
| 583 | Err(error) => { |
| 584 | references.failed(&path, error); |
| 585 | continue; |
| 586 | } |
| 587 | }; |
| 588 | references.documents.insert(metadata.id); |
| 589 | if let Some(binding) = metadata.runtime_store { |
| 590 | references.bound_stores.insert(canonical(&binding.data_dir)); |
| 591 | references.bound_stores.insert(binding.data_dir); |
| 592 | } |
| 593 | if keep_text { |
| 594 | match read_session_reference_bytes(&path) { |
| 595 | Ok(bytes) => { |
| 596 | references.document_tokens.extend(uuid_tokens(&bytes)); |
| 597 | references |
| 598 | .document_texts |
| 599 | .push(String::from_utf8_lossy(&bytes).into_owned()); |
| 600 | } |
| 601 | Err(error) => references.failed(&path, error), |
| 602 | } |
| 603 | } |
| 604 | } |
| 605 | }; |
| 606 | scan(sessions_dir, &mut references, keep_text); |
| 607 | scan( |
| 608 | &sessions_dir.join(CHECKPOINTS_DIR), |
| 609 | &mut references, |
| 610 | keep_text, |
| 611 | ); |
| 612 | references |
| 613 | } |
| 614 | |
| 615 | /// One store directory under a session directory. |
| 616 | struct StoreDir { |
| 617 | owner_id: String, |
| 618 | path: PathBuf, |
| 619 | } |
| 620 | |
| 621 | struct Run<'a> { |
| 622 | sessions: &'a SessionManager, |
| 623 | sessions_dir: PathBuf, |
| 624 | canonical_root: PathBuf, |
| 625 | options: &'a ReconcileOptions, |
| 626 | set_aside: SetAside, |
| 627 | summary: ReconcileSummary, |
| 628 | } |
| 629 | |
| 630 | impl Run<'_> { |
| 631 | fn budget_left(&mut self) -> bool { |
| 632 | if self.summary.actions() >= self.options.limit { |
| 633 | self.summary.limit_reached = true; |
| 634 | return false; |
| 635 | } |
| 636 | true |
| 637 | } |
| 638 | |
| 639 | fn error(&mut self, context: &str, error: impl std::fmt::Display) { |
| 640 | self.summary.errors.push(format!("{context}: {error}")); |
| 641 | } |
| 642 | |
| 643 | fn receipt(&self, receipt: Value) { |
| 644 | if !self.options.dry_run { |
| 645 | append_receipt(&self.sessions_dir, receipt); |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | fn execute(&mut self) { |
| 650 | self.repair_documents(); |
| 651 | let mut references = collect_document_references(&self.sessions_dir, true); |
| 652 | let stores = self.store_dirs(&mut references); |
| 653 | self.collect_thread_references(&stores, &mut references); |
| 654 | self.summary |
| 655 | .errors |
| 656 | .extend(references.incomplete.iter().cloned()); |
| 657 | for store in &stores { |
| 658 | if !self.budget_left() { |
| 659 | return; |
| 660 | } |
| 661 | self.repair_store(store, &references); |
| 662 | } |
| 663 | self.repair_artifact_dirs(&references); |
| 664 | if let Some(dir) = &self.set_aside.run_dir { |
| 665 | self.summary.set_aside_path = Some(dir.clone()); |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | /// R1: set aside documents that cannot be read at all. |
| 670 | fn repair_documents(&mut self) { |
| 671 | let entries = match fs::read_dir(&self.sessions_dir) { |
| 672 | Ok(entries) => entries, |
| 673 | Err(error) => { |
| 674 | self.error("session documents", error); |
| 675 | return; |
| 676 | } |
| 677 | }; |
| 678 | let mut paths = Vec::new(); |
| 679 | for entry in entries { |
| 680 | match entry { |
| 681 | Ok(entry) => paths.push(entry.path()), |
| 682 | Err(error) => self.error("session documents", error), |
| 683 | } |
| 684 | } |
| 685 | paths.sort(); |
| 686 | for path in paths { |
| 687 | let Some(id) = document_id(&path) else { |
| 688 | continue; |
| 689 | }; |
| 690 | if self.options.skip_session.as_deref() == Some(id.as_str()) { |
| 691 | continue; |
| 692 | } |
| 693 | match SessionManager::load_session_metadata(&path) { |
| 694 | Ok(_) => continue, |
| 695 | Err(error) if error.kind() == io::ErrorKind::InvalidData => {} |
| 696 | Err(error) => { |
| 697 | self.error(&path.display().to_string(), error); |
| 698 | continue; |
| 699 | } |
| 700 | } |
| 701 | let sessions = self.sessions; |
| 702 | let result = sessions.with_session_file_lock(&id, || { |
| 703 | match SessionManager::load_session_metadata(&path) { |
| 704 | Ok(_) => return Ok(()), |
| 705 | Err(error) if error.kind() == io::ErrorKind::InvalidData => {} |
| 706 | Err(error) => return Err(error), |
| 707 | } |
| 708 | match classify_unlisted_document(&path) { |
| 709 | DocumentState::Readable => {} |
| 710 | DocumentState::NewerSchema => self.summary.documents_newer_schema += 1, |
| 711 | DocumentState::Unavailable(reason) => { |
| 712 | self.error(&path.display().to_string(), reason) |
| 713 | } |
| 714 | DocumentState::Unreadable(reason) => { |
| 715 | if self.budget_left() { |
| 716 | let errors = self.summary.errors.len(); |
| 717 | self.set_aside_path( |
| 718 | &path, |
| 719 | &format!("unreadable document: {reason}"), |
| 720 | true, |
| 721 | ); |
| 722 | if self.summary.errors.len() == errors { |
| 723 | self.summary.documents_set_aside += 1; |
| 724 | } |
| 725 | } |
| 726 | } |
| 727 | } |
| 728 | Ok(()) |
| 729 | }); |
| 730 | if let Err(error) = result { |
| 731 | self.error(&path.display().to_string(), error); |
| 732 | } |
| 733 | if self.summary.limit_reached { |
| 734 | return; |
| 735 | } |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | fn store_dirs(&self, references: &mut References) -> Vec<StoreDir> { |
| 740 | let mut out = Vec::new(); |
| 741 | let entries = match fs::read_dir(&self.sessions_dir) { |
| 742 | Ok(entries) => entries, |
| 743 | Err(error) => { |
| 744 | references.failed(&self.sessions_dir, error); |
| 745 | return out; |
| 746 | } |
| 747 | }; |
| 748 | for entry in entries { |
| 749 | let entry = match entry { |
| 750 | Ok(entry) => entry, |
| 751 | Err(error) => { |
| 752 | references.failed(&self.sessions_dir, error); |
| 753 | continue; |
| 754 | } |
| 755 | }; |
| 756 | let owner = entry.file_name(); |
| 757 | let Some(owner_id) = owner.to_str() else { |
| 758 | continue; |
| 759 | }; |
| 760 | if !codewhale_runtime::artifacts::is_valid_session_id(owner_id) |
| 761 | || !entry.path().is_dir() |
| 762 | { |
| 763 | continue; |
| 764 | } |
| 765 | let children = match fs::read_dir(entry.path()) { |
| 766 | Ok(children) => children, |
| 767 | Err(error) => { |
| 768 | references.failed(&entry.path(), error); |
| 769 | continue; |
| 770 | } |
| 771 | }; |
| 772 | for child in children { |
| 773 | let child = match child { |
| 774 | Ok(child) => child, |
| 775 | Err(error) => { |
| 776 | references.failed(&entry.path(), error); |
| 777 | continue; |
| 778 | } |
| 779 | }; |
| 780 | if is_runtime_store_dir_name(&child.file_name()) && child.path().is_dir() { |
| 781 | out.push(StoreDir { |
| 782 | owner_id: owner_id.to_string(), |
| 783 | path: child.path(), |
| 784 | }); |
| 785 | } |
| 786 | } |
| 787 | } |
| 788 | out.sort_by(|left, right| left.path.cmp(&right.path)); |
| 789 | out |
| 790 | } |
| 791 | |
| 792 | /// Every thread in every store (read-only; no locks) names its bound |
| 793 | /// document and the id its engine writes under. Plus the host stores |
| 794 | /// outside the sessions directory (`codewhale serve`, task runtimes). |
| 795 | fn collect_thread_references(&self, stores: &[StoreDir], references: &mut References) { |
| 796 | let mut roots: Vec<PathBuf> = stores.iter().map(|store| store.path.clone()).collect(); |
| 797 | let tasks = crate::task_manager::default_tasks_dir().join("runtime"); |
| 798 | roots.push(tasks.clone()); |
| 799 | match fs::read_dir(&tasks) { |
| 800 | Ok(entries) => { |
| 801 | for entry in entries { |
| 802 | match entry { |
| 803 | Ok(entry) if entry.file_type().is_ok_and(|kind| kind.is_file()) => {} |
| 804 | Ok(entry) => roots.push(entry.path()), |
| 805 | Err(error) => references.failed(&tasks, error), |
| 806 | } |
| 807 | } |
| 808 | } |
| 809 | Err(error) if error.kind() == io::ErrorKind::NotFound => {} |
| 810 | Err(error) => references.failed(&tasks, error), |
| 811 | } |
| 812 | for root in roots { |
| 813 | let threads = root.join("threads"); |
| 814 | let entries = match fs::read_dir(&threads) { |
| 815 | Ok(entries) => entries, |
| 816 | Err(error) if error.kind() == io::ErrorKind::NotFound => continue, |
| 817 | Err(error) => { |
| 818 | references.failed(&threads, error); |
| 819 | continue; |
| 820 | } |
| 821 | }; |
| 822 | for entry in entries { |
| 823 | let entry = match entry { |
| 824 | Ok(entry) => entry, |
| 825 | Err(error) => { |
| 826 | references.failed(&threads, error); |
| 827 | continue; |
| 828 | } |
| 829 | }; |
| 830 | let path = entry.path(); |
| 831 | if path.extension().is_none_or(|ext| ext != "json") { |
| 832 | continue; |
| 833 | } |
| 834 | if let Some(thread_id) = path.file_stem().and_then(|stem| stem.to_str()) { |
| 835 | references |
| 836 | .thread_named |
| 837 | .insert(crate::runtime_threads::thread_session_id(thread_id)); |
| 838 | } |
| 839 | match read_session_reference_bytes(&path).and_then(|raw| { |
| 840 | serde_json::from_slice::<Value>(&raw) |
| 841 | .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error)) |
| 842 | }) { |
| 843 | Ok(value) => { |
| 844 | if let Some(session_id) = value.get("session_id").and_then(Value::as_str) { |
| 845 | references.thread_named.insert(session_id.to_string()); |
| 846 | } |
| 847 | } |
| 848 | Err(error) => references.failed(&path, error), |
| 849 | } |
| 850 | } |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | fn repair_store(&mut self, store: &StoreDir, references: &References) { |
| 855 | if !references.incomplete.is_empty() { |
| 856 | return; |
| 857 | } |
| 858 | let binding = match RuntimeStoreBinding::for_store_dir(&store.path) { |
| 859 | Ok(binding) => binding, |
| 860 | Err(error) => return self.error(&format!("store {}", store.path.display()), error), |
| 861 | }; |
| 862 | let held = match binding.try_hold() { |
| 863 | Ok(Some(held)) => held, |
| 864 | Ok(None) => { |
| 865 | if !references.binds(&store.path) { |
| 866 | self.summary.stores_in_use += 1; |
| 867 | } |
| 868 | return; |
| 869 | } |
| 870 | Err(error) => return self.error(&format!("store {}", store.path.display()), error), |
| 871 | }; |
| 872 | if self |
| 873 | .options |
| 874 | .skip_session |
| 875 | .as_deref() |
| 876 | .is_some_and(|skip| skip == store.owner_id) |
| 877 | { |
| 878 | return; |
| 879 | } |
| 880 | let exists = |id: &str| references.documents.contains(id); |
| 881 | if references.binds(&store.path) { |
| 882 | // R4 for a bound store nobody holds. |
| 883 | if self.options.dry_run { |
| 884 | return; |
| 885 | } |
| 886 | match held.unbind_threads_without_documents(exists) { |
| 887 | Ok(count) => self.summary.threads_unbound += count, |
| 888 | Err(error) => self.error(&format!("threads in {}", store.path.display()), error), |
| 889 | } |
| 890 | return; |
| 891 | } |
| 892 | match held.keep_reason() { |
| 893 | Ok(None) => { |
| 894 | let tombstoned = self |
| 895 | .sessions_dir |
| 896 | .join(LATE_USAGE_DIR) |
| 897 | .join(format!("{}.deleted", store.owner_id)) |
| 898 | .exists(); |
| 899 | let reason = if tombstoned { |
| 900 | "empty Runtime store of a deleted session" |
| 901 | } else { |
| 902 | "empty Runtime store no document binds" |
| 903 | }; |
| 904 | self.summary.stores_set_aside += 1; |
| 905 | if self.options.dry_run { |
| 906 | return; |
| 907 | } |
| 908 | let target = match self.set_aside.target_for( |
| 909 | &self.sessions_dir, |
| 910 | &self.canonical_root, |
| 911 | &held.binding().data_dir.clone(), |
| 912 | ) { |
| 913 | Ok(target) => target, |
| 914 | Err(error) => { |
| 915 | self.summary.stores_set_aside -= 1; |
| 916 | return self.error("set-aside directory", error); |
| 917 | } |
| 918 | }; |
| 919 | let original = held.binding().data_dir.clone(); |
| 920 | if let Err(error) = held.move_to(&target) { |
| 921 | self.summary.stores_set_aside -= 1; |
| 922 | return self.error(&format!("store {}", original.display()), error); |
| 923 | } |
| 924 | self.set_aside.manifest( |
| 925 | &original, |
| 926 | &target, |
| 927 | reason, |
| 928 | json!({"kind": "runtime_store"}), |
| 929 | ); |
| 930 | self.receipt(json!({"action": "store_set_aside", "path": original, "moved_to": target, "reason": reason})); |
| 931 | remove_if_empty(store.path.parent()); |
| 932 | } |
| 933 | Ok(Some(_)) => self.recover_store(held, &store.path, exists), |
| 934 | Err(error) => self.error(&format!("store {}", store.path.display()), error), |
| 935 | } |
| 936 | } |
| 937 | |
| 938 | /// R3: give each conversation in an unbound store a document of its own. |
| 939 | fn recover_store( |
| 940 | &mut self, |
| 941 | held: crate::runtime_threads::HeldRuntimeStore, |
| 942 | path: &Path, |
| 943 | exists: impl Fn(&str) -> bool, |
| 944 | ) { |
| 945 | // R4 applies here too. Deleting a document from the session picker |
| 946 | // does not unbind the threads naming it, so an unbound store can hold |
| 947 | // threads bound to a document that is gone. Left bound, they are |
| 948 | // neither loadable through that document nor recoverable below, and |
| 949 | // the store is kept forever. Unbinding them (with a receipt) makes |
| 950 | // them recoverable in this same pass. |
| 951 | if !self.options.dry_run { |
| 952 | match held.unbind_threads_without_documents(&exists) { |
| 953 | Ok(count) => self.summary.threads_unbound += count, |
| 954 | Err(error) => return self.error(&format!("threads in {}", path.display()), error), |
| 955 | } |
| 956 | } |
| 957 | let threads = match held.recoverable_threads() { |
| 958 | Ok(threads) => threads, |
| 959 | Err(error) => return self.error(&format!("threads in {}", path.display()), error), |
| 960 | }; |
| 961 | if threads.is_empty() { |
| 962 | self.summary.stores_kept_with_work += 1; |
| 963 | return; |
| 964 | } |
| 965 | for recovered in threads { |
| 966 | if !self.budget_left() { |
| 967 | return; |
| 968 | } |
| 969 | self.summary.sessions_recovered += 1; |
| 970 | if self.options.dry_run { |
| 971 | continue; |
| 972 | } |
| 973 | let session = match self.recovered_document(&held, &recovered, &exists) { |
| 974 | Ok(session) => session, |
| 975 | Err(error) => { |
| 976 | self.summary.sessions_recovered -= 1; |
| 977 | self.error(&format!("recover thread {}", recovered.thread.id), error); |
| 978 | continue; |
| 979 | } |
| 980 | }; |
| 981 | if let Err(error) = held.bind_recovered_thread(&recovered.thread.id, &session) { |
| 982 | self.error(&format!("bind thread {}", recovered.thread.id), error); |
| 983 | continue; |
| 984 | } |
| 985 | self.receipt(json!({ |
| 986 | "action": "session_recovered", |
| 987 | "store": path, |
| 988 | "thread_id": recovered.thread.id, |
| 989 | "session_id": session.metadata.id, |
| 990 | "title": session.metadata.title, |
| 991 | })); |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | fn recovered_document( |
| 996 | &self, |
| 997 | held: &crate::runtime_threads::HeldRuntimeStore, |
| 998 | recovered: &crate::runtime_threads::RecoverableThread, |
| 999 | exists: &impl Fn(&str) -> bool, |
| 1000 | ) -> anyhow::Result<SavedSession> { |
| 1001 | let thread = &recovered.thread; |
| 1002 | let id = crate::runtime_threads::thread_session_id(&thread.id); |
| 1003 | // A run that stopped between saving the document and binding the |
| 1004 | // thread left the document behind at this same id; reuse it. |
| 1005 | if exists(&id) || self.sessions.session_document_exists(&id) { |
| 1006 | return Ok(self.sessions.resume_session(&id)?.session); |
| 1007 | } |
| 1008 | let source = self |
| 1009 | .sessions |
| 1010 | .expect_absent_session(&id)? |
| 1011 | .capture(crate::session_manager::SessionWriteOwner::control())?; |
| 1012 | let mut session = crate::session_manager::create_saved_session_with_id_and_mode( |
| 1013 | id, |
| 1014 | &recovered.messages, |
| 1015 | &thread.model, |
| 1016 | &thread.workspace, |
| 1017 | 0, |
| 1018 | thread |
| 1019 | .system_prompt |
| 1020 | .clone() |
| 1021 | .map(codewhale_models::SystemPrompt::Text) |
| 1022 | .as_ref(), |
| 1023 | Some(thread.mode.as_str()), |
| 1024 | ); |
| 1025 | if let Some(provider) = thread.model_provider.as_deref() { |
| 1026 | session |
| 1027 | .metadata |
| 1028 | .set_model_provider_route(provider, thread.model_provider_id.as_deref()); |
| 1029 | } |
| 1030 | let label = thread |
| 1031 | .title |
| 1032 | .clone() |
| 1033 | .filter(|title| !title.trim().is_empty()) |
| 1034 | .unwrap_or_else(|| session.metadata.title.clone()); |
| 1035 | session.metadata.title = recovered_title(&label); |
| 1036 | session.metadata.runtime_store = Some(held.binding().clone()); |
| 1037 | session.write_receipt = Some(source); |
| 1038 | let publication = self.sessions.publish_session(&session)?; |
| 1039 | session.adopt_publication(&publication); |
| 1040 | Ok(session) |
| 1041 | } |
| 1042 | |
| 1043 | /// R6: directories with no document and no store that hold only |
| 1044 | /// artifacts or approval receipts nothing names. |
| 1045 | fn repair_artifact_dirs(&mut self, references: &References) { |
| 1046 | if !references.incomplete.is_empty() { |
| 1047 | return; |
| 1048 | } |
| 1049 | let Ok(entries) = fs::read_dir(&self.sessions_dir) else { |
| 1050 | return; |
| 1051 | }; |
| 1052 | let mut dirs: Vec<(String, PathBuf)> = entries |
| 1053 | .flatten() |
| 1054 | .filter_map(|entry| { |
| 1055 | let name = entry.file_name().to_str()?.to_string(); |
| 1056 | (codewhale_runtime::artifacts::is_valid_session_id(&name) && entry.path().is_dir()) |
| 1057 | .then(|| (name, entry.path())) |
| 1058 | }) |
| 1059 | .collect(); |
| 1060 | dirs.sort(); |
| 1061 | let idle_before = SystemTime::now() |
| 1062 | .checked_sub(self.options.artifact_idle) |
| 1063 | .unwrap_or(SystemTime::UNIX_EPOCH); |
| 1064 | for (id, path) in dirs { |
| 1065 | if references.documents.contains(&id) |
| 1066 | || self.options.skip_session.as_deref() == Some(id.as_str()) |
| 1067 | || !holds_only_artifacts(&path) |
| 1068 | { |
| 1069 | continue; |
| 1070 | } |
| 1071 | if references.names(&id.to_ascii_lowercase()) |
| 1072 | || references.names(&id) |
| 1073 | || newest_mtime(&path).is_none_or(|mtime| mtime > idle_before) |
| 1074 | { |
| 1075 | self.summary.artifact_dirs_kept += 1; |
| 1076 | continue; |
| 1077 | } |
| 1078 | if !self.budget_left() { |
| 1079 | return; |
| 1080 | } |
| 1081 | self.set_aside_path( |
| 1082 | &path, |
| 1083 | "artifacts of a conversation no document or thread names", |
| 1084 | false, |
| 1085 | ); |
| 1086 | self.summary.artifact_dirs_set_aside += 1; |
| 1087 | } |
| 1088 | } |
| 1089 | |
| 1090 | fn set_aside_path(&mut self, path: &Path, reason: &str, hash: bool) { |
| 1091 | if self.options.dry_run { |
| 1092 | return; |
| 1093 | } |
| 1094 | let detail = if hash { |
| 1095 | match read_session_reference_bytes(path) { |
| 1096 | Ok(bytes) => json!({"sha256": file_sha256(&bytes), "bytes": bytes.len()}), |
| 1097 | Err(error) => return self.error(&format!("set aside {}", path.display()), error), |
| 1098 | } |
| 1099 | } else { |
| 1100 | json!({"kind": "directory"}) |
| 1101 | }; |
| 1102 | let target = match self |
| 1103 | .set_aside |
| 1104 | .target_for(&self.sessions_dir, &self.canonical_root, path) |
| 1105 | { |
| 1106 | Ok(target) => target, |
| 1107 | Err(error) => return self.error("set-aside directory", error), |
| 1108 | }; |
| 1109 | if let Some(parent) = target.parent() |
| 1110 | && let Err(error) = fs::create_dir_all(parent) |
| 1111 | { |
| 1112 | return self.error("set-aside directory", error); |
| 1113 | } |
| 1114 | if let Err(error) = fs::rename(path, &target) { |
| 1115 | return self.error(&format!("set aside {}", path.display()), error); |
| 1116 | } |
| 1117 | self.set_aside.manifest(path, &target, reason, detail); |
| 1118 | self.receipt( |
| 1119 | json!({"action": "set_aside", "path": path, "moved_to": target, "reason": reason}), |
| 1120 | ); |
| 1121 | } |
| 1122 | } |
| 1123 | |
| 1124 | enum DocumentState { |
| 1125 | Readable, |
| 1126 | NewerSchema, |
| 1127 | Unreadable(String), |
| 1128 | Unavailable(String), |
| 1129 | } |
| 1130 | |
| 1131 | /// A document `list_sessions` could not list: newer, readable after all, or |
| 1132 | /// genuinely unreadable. |
| 1133 | fn classify_unlisted_document(path: &Path) -> DocumentState { |
| 1134 | let bytes = match read_session_reference_bytes(path) { |
| 1135 | Ok(bytes) => bytes, |
| 1136 | Err(error) => return DocumentState::Unavailable(error.to_string()), |
| 1137 | }; |
| 1138 | if let Ok(value) = serde_json::from_slice::<Value>(&bytes) |
| 1139 | && value |
| 1140 | .get("schema_version") |
| 1141 | .and_then(Value::as_u64) |
| 1142 | .is_some_and(|version| { |
| 1143 | version > u64::from(crate::session_manager::CURRENT_SESSION_SCHEMA_VERSION) |
| 1144 | }) |
| 1145 | { |
| 1146 | return DocumentState::NewerSchema; |
| 1147 | } |
| 1148 | match serde_json::from_slice::<SavedSession>(&bytes) { |
| 1149 | Ok(_) => DocumentState::Readable, |
| 1150 | Err(error) => DocumentState::Unreadable(error.to_string()), |
| 1151 | } |
| 1152 | } |
| 1153 | |
| 1154 | fn holds_only_artifacts(dir: &Path) -> bool { |
| 1155 | let Ok(entries) = fs::read_dir(dir) else { |
| 1156 | return false; |
| 1157 | }; |
| 1158 | let mut any = false; |
| 1159 | for entry in entries.flatten() { |
| 1160 | any = true; |
| 1161 | let name = entry.file_name(); |
| 1162 | let Some(name) = name.to_str() else { |
| 1163 | return false; |
| 1164 | }; |
| 1165 | if !matches!( |
| 1166 | name, |
| 1167 | "artifacts" | "approval_receipts.jsonl" | "approval_receipts.lock" |
| 1168 | ) { |
| 1169 | return false; |
| 1170 | } |
| 1171 | } |
| 1172 | any |
| 1173 | } |
| 1174 | |
| 1175 | fn newest_mtime(path: &Path) -> Option<SystemTime> { |
| 1176 | let metadata = fs::symlink_metadata(path).ok()?; |
| 1177 | let mut newest = metadata.modified().ok()?; |
| 1178 | if metadata.is_dir() { |
| 1179 | for entry in fs::read_dir(path).ok()?.flatten() { |
| 1180 | if let Some(child) = newest_mtime(&entry.path()) { |
| 1181 | newest = newest.max(child); |
| 1182 | } |
| 1183 | } |
| 1184 | } |
| 1185 | Some(newest) |
| 1186 | } |
| 1187 | |
| 1188 | fn recovered_title(label: &str) -> String { |
| 1189 | let title = |
| 1190 | crate::session_manager::sanitize_session_title(&format!("Recovered: {}", label.trim())); |
| 1191 | title |
| 1192 | .chars() |
| 1193 | .take(crate::session_manager::MAX_SESSION_TITLE_CHARS) |
| 1194 | .collect() |
| 1195 | } |
| 1196 | |
| 1197 | /// SHA-256 of a file's bytes, for the manifest. |
| 1198 | fn file_sha256(bytes: &[u8]) -> String { |
| 1199 | Sha256::digest(bytes) |
| 1200 | .iter() |
| 1201 | .map(|byte| format!("{byte:02x}")) |
| 1202 | .collect() |
| 1203 | } |
| 1204 | |
| 1205 | #[cfg(test)] |
| 1206 | #[path = "session_reconcile/tests.rs"] |
| 1207 | mod tests; |
| 1208 |