返回 CodeWhale
tests.rs
1 use super::*;
2 use crate::runtime_threads::{
3 RuntimeProcessOwnerLock, RuntimeThreadStore, manager::CreateThreadRequest,
4 manager::RuntimeThreadManager, manager::RuntimeThreadManagerConfig,
5 };
6 use crate::session_manager::create_saved_session_with_id_and_mode;
7 use crate::test_support::{EnvVarGuard, lock_test_env};
8 use codewhale_models::{ContentBlock, Message, Role};
9 use codewhale_runtime::config::Config;
10
11 fn text(role: Role, text: &str) -> Message {
12 Message {
13 role,
14 content: vec![ContentBlock::Text {
15 text: text.to_string(),
16 cache_control: None,
17 }],
18 }
19 }
20
21 fn fixture_config() -> Config {
22 let mut config = Config::default().with_legacy_root(
23 Some("local-reconcile-fixture".into()),
24 Some("http://127.0.0.1:1/v1".into()),
25 );
26 config.set_feature("mcp", false).unwrap();
27 config.set_feature("subagents", false).unwrap();
28 config
29 }
30
31 /// An isolated Codewhale home whose sessions directory is the configured
32 /// one, so store confinement holds for fixtures created under it.
33 struct Fixture {
34 sessions: SessionManager,
35 home: tempfile::TempDir,
36 _runtime: EnvVarGuard,
37 _legacy_runtime: EnvVarGuard,
38 _tasks: EnvVarGuard,
39 _home: EnvVarGuard,
40 }
41
42 impl Fixture {
43 fn new() -> Self {
44 let home = tempfile::tempdir().expect("home");
45 let guard = EnvVarGuard::set("CODEWHALE_HOME", home.path());
46 let runtime = EnvVarGuard::remove("CODEWHALE_RUNTIME_DIR");
47 let legacy_runtime = EnvVarGuard::remove("DEEPSEEK_RUNTIME_DIR");
48 let tasks = EnvVarGuard::remove("CODEWHALE_TASKS_DIR");
49 let sessions = SessionManager::default_location().expect("sessions");
50 Self {
51 sessions,
52 home,
53 _runtime: runtime,
54 _legacy_runtime: legacy_runtime,
55 _tasks: tasks,
56 _home: guard,
57 }
58 }
59
60 fn dir(&self) -> PathBuf {
61 self.sessions.sessions_dir().to_path_buf()
62 }
63
64 /// An opened, empty store at `sessions/<owner>/runtime`.
65 fn empty_store(&self, owner: &str) -> PathBuf {
66 let path = self.dir().join(owner).join("runtime");
67 RuntimeThreadStore::open(path.clone()).expect("open store");
68 path
69 }
70
71 fn document(&self, id: &str, store: Option<&Path>) -> SavedSession {
72 let mut session = create_saved_session_with_id_and_mode(
73 id.to_string(),
74 &[text(Role::User, "hello"), text(Role::Assistant, "hi")],
75 "deepseek-v4-pro",
76 self.home.path(),
77 0,
78 None,
79 None,
80 );
81 session.metadata.runtime_store =
82 store.map(|store| RuntimeStoreBinding::for_store_dir(store).expect("binding"));
83 self.sessions.save_session(&session).expect("save");
84 session
85 }
86
87 /// A store holding one task-bound thread with a two-message turn, and no
88 /// document bound to it. Returns the store and the thread id.
89 async fn store_with_thread(&self, owner: &str) -> (PathBuf, String) {
90 let path = self.dir().join(owner).join("runtime");
91 let manager = RuntimeThreadManager::open(
92 fixture_config(),
93 self.home.path().to_path_buf(),
94 RuntimeThreadManagerConfig {
95 mcp_auth_context: Default::default(),
96 data_dir: path.clone(),
97 task_data_dir: self.home.path().join("tasks"),
98 sessions_dir: None,
99 max_active_threads: 2,
100 },
101 )
102 .expect("manager");
103 let thread = manager
104 .create_thread(CreateThreadRequest {
105 task_id: Some("task_orphaned".into()),
106 workspace: Some(self.home.path().to_path_buf()),
107 ..CreateThreadRequest::default()
108 })
109 .await
110 .expect("thread");
111 manager
112 .seed_thread_from_messages(
113 &thread.id,
114 &[
115 text(Role::User, "rebuild the parser"),
116 text(Role::Assistant, "parser rebuilt"),
117 ],
118 )
119 .await
120 .expect("seed");
121 drop(manager);
122 (path, thread.id)
123 }
124
125 fn run(&self) -> ReconcileSummary {
126 self.run_with(ReconcileOptions {
127 artifact_idle: Duration::ZERO,
128 ..ReconcileOptions::default()
129 })
130 }
131
132 fn run_with(&self, options: ReconcileOptions) -> ReconcileSummary {
133 reconcile(&self.sessions, &options).expect("reconcile")
134 }
135
136 fn set_aside_root(&self) -> PathBuf {
137 self.dir().join(SET_ASIDE_DIR)
138 }
139
140 fn receipts(&self) -> String {
141 fs::read_to_string(self.dir().join(RECONCILE_DIR).join(RECEIPTS_FILE)).unwrap_or_default()
142 }
143 }
144
145 fn manifests(root: &Path) -> String {
146 let mut out = String::new();
147 if let Ok(runs) = fs::read_dir(root) {
148 for run in runs.flatten() {
149 out.push_str(&fs::read_to_string(run.path().join(MANIFEST_FILE)).unwrap_or_default());
150 }
151 }
152 out
153 }
154
155 /// The measured shape (#6144): documents are bound to a store under
156 /// *another* id's directory, and that directory has no document of its own.
157 /// Only the store nothing binds may move.
158 /// The reconcile lock sidecar is owner-only, even when an older release left
159 /// it world-readable.
160 #[cfg(unix)]
161 #[test]
162 fn reconcile_lock_file_is_owner_only() {
163 use std::os::unix::fs::PermissionsExt as _;
164 let _lock = lock_test_env();
165 let fixture = Fixture::new();
166 let lock = fixture.dir().join(RECONCILE_LOCK_FILE);
167 let mode = || fs::metadata(&lock).unwrap().permissions().mode() & 0o777;
168
169 fixture.run();
170 assert_eq!(mode(), 0o600);
171
172 fs::set_permissions(&lock, fs::Permissions::from_mode(0o644)).unwrap();
173 fixture.run();
174 assert_eq!(mode(), 0o600);
175 }
176
177 #[test]
178 fn reconcile_sets_aside_only_stores_no_document_binds() {
179 let _env = lock_test_env();
180 let fx = Fixture::new();
181 let host_store = fx.empty_store("host-anchor");
182 fx.document("conversation-a", Some(&host_store));
183 fx.document("conversation-b", Some(&host_store));
184 let orphan = fx.empty_store("crashed-anchor");
185 let task_runtime = fx.home.path().join("tasks").join("runtime");
186 fs::create_dir_all(&task_runtime).unwrap();
187 fs::write(task_runtime.join("state.json"), b"{}").unwrap();
188 fs::write(task_runtime.join("events.lock"), b"").unwrap();
189
190 let summary = fx.run();
191
192 assert!(summary.errors.is_empty(), "{:?}", summary.errors);
193 assert_eq!(summary.stores_set_aside, 1, "{summary:?}");
194 assert!(host_store.is_dir(), "a bound store must never move");
195 assert!(!orphan.exists());
196 assert!(
197 !fx.dir().join("crashed-anchor").exists(),
198 "the emptied directory goes"
199 );
200 let manifest = manifests(&fx.set_aside_root());
201 assert!(manifest.contains("crashed-anchor"), "{manifest}");
202 assert!(fx.receipts().contains("store_set_aside"));
203 assert_eq!(summary.notice().is_some(), summary.changed());
204 assert_eq!(last_run(&fx.dir()), Some(summary));
205
206 // Idempotent: nothing left to do.
207 let again = fx.run();
208 assert!(!again.changed(), "{again:?}");
209 }
210
211 /// A store whose owner lock is held is in use by a live process: skipped and
212 /// reported, never moved. Holding that lock through the move is also what
213 /// makes a concurrent opener fail its lock instead of racing the move.
214 #[test]
215 fn reconcile_skips_a_store_a_live_process_holds() {
216 let _env = lock_test_env();
217 let fx = Fixture::new();
218 let held = fx.empty_store("live-host");
219 let lock = RuntimeProcessOwnerLock::acquire(&held).expect("hold");
220
221 let summary = fx.run();
222 assert_eq!(summary.stores_set_aside, 0);
223 assert_eq!(summary.stores_in_use, 1);
224 assert!(held.is_dir());
225
226 drop(lock);
227 assert_eq!(fx.run().stores_set_aside, 1);
228 }
229
230 /// R3: a store no document binds but that holds a conversation is
231 /// re-indexed, not set aside, and a second run is a no-op.
232 #[tokio::test]
233 async fn reconcile_reindexes_threads_in_an_unbound_store() {
234 let _env = lock_test_env();
235 let fx = Fixture::new();
236 let (store, thread_id) = fx.store_with_thread("worker-anchor").await;
237
238 let summary = fx.run();
239 assert_eq!(summary.sessions_recovered, 1, "{summary:?}");
240 assert_eq!(summary.stores_set_aside, 0);
241 assert!(store.is_dir());
242
243 let id = crate::runtime_threads::thread_session_id(&thread_id);
244 let recovered = fx.sessions.load_session(&id).expect("recovered document");
245 assert!(recovered.metadata.title.starts_with("Recovered: "));
246 assert_eq!(
247 recovered.messages,
248 vec![
249 text(Role::User, "rebuild the parser"),
250 text(Role::Assistant, "parser rebuilt")
251 ]
252 );
253 let binding = recovered
254 .metadata
255 .runtime_store
256 .expect("bound to its store");
257 assert_eq!(binding.data_dir, store.canonicalize().unwrap());
258 let thread = RuntimeThreadStore::open(store.clone())
259 .unwrap()
260 .load_thread(&thread_id)
261 .unwrap();
262 assert_eq!(thread.session_id.as_deref(), Some(id.as_str()));
263 assert_eq!(
264 thread
265 .saved_session_checkpoint
266 .as_ref()
267 .and_then(|checkpoint| checkpoint.messages_len),
268 Some(2)
269 );
270
271 let again = fx.run();
272 assert_eq!(again.sessions_recovered, 0, "{again:?}");
273 assert_eq!(again.stores_set_aside, 0);
274 }
275
276 /// R4: a thread in a bound store whose document is gone is unbound, with
277 /// the old binding in the receipts.
278 #[tokio::test]
279 async fn reconcile_unbinds_threads_whose_document_is_gone() {
280 let _env = lock_test_env();
281 let fx = Fixture::new();
282 let (store, thread_id) = fx.store_with_thread("host").await;
283 fx.document("keeper", Some(&store));
284 {
285 let opened = RuntimeThreadStore::open(store.clone()).unwrap();
286 let mut thread = opened.load_thread(&thread_id).unwrap();
287 thread.session_id = Some("deleted-document".into());
288 opened.save_thread(&thread).unwrap();
289 }
290
291 let summary = fx.run();
292 assert_eq!(summary.threads_unbound, 1, "{summary:?}");
293 let thread = RuntimeThreadStore::open(store.clone())
294 .unwrap()
295 .load_thread(&thread_id)
296 .unwrap();
297 assert_eq!(thread.session_id, None);
298 let receipts = fs::read_to_string(store.join(THREAD_UNBIND_RECEIPTS_FILE)).unwrap();
299 assert!(receipts.contains("thread_unbound") && receipts.contains("deleted-document"));
300 }
301
302 /// R4 then R3 in a store no document binds: deleting a document from the
303 /// session picker leaves the threads naming it bound. They are unbound (with
304 /// a receipt) and then recovered, instead of keeping the store forever.
305 #[tokio::test]
306 async fn reconcile_recovers_threads_in_an_unbound_store_bound_to_a_missing_document() {
307 let _env = lock_test_env();
308 let fx = Fixture::new();
309 let (store, thread_id) = fx.store_with_thread("picker-deleted").await;
310 {
311 let opened = RuntimeThreadStore::open(store.clone()).unwrap();
312 let mut thread = opened.load_thread(&thread_id).unwrap();
313 thread.session_id = Some("deleted-from-picker".into());
314 opened.save_thread(&thread).unwrap();
315 }
316
317 let summary = fx.run();
318 assert_eq!(summary.threads_unbound, 1, "{summary:?}");
319 assert_eq!(summary.sessions_recovered, 1, "{summary:?}");
320 assert_eq!(summary.stores_kept_with_work, 0, "{summary:?}");
321
322 let id = crate::runtime_threads::thread_session_id(&thread_id);
323 let recovered = fx.sessions.load_session(&id).expect("recovered document");
324 assert!(recovered.metadata.title.starts_with("Recovered: "));
325 assert_eq!(
326 recovered
327 .metadata
328 .runtime_store
329 .expect("bound to its store")
330 .data_dir,
331 store.canonicalize().unwrap()
332 );
333 let thread = RuntimeThreadStore::open(store.clone())
334 .unwrap()
335 .load_thread(&thread_id)
336 .unwrap();
337 assert_eq!(thread.session_id.as_deref(), Some(id.as_str()));
338 let receipts = fs::read_to_string(store.join(THREAD_UNBIND_RECEIPTS_FILE)).unwrap();
339 assert!(receipts.contains("deleted-from-picker"), "{receipts}");
340
341 let again = fx.run();
342 assert!(!again.changed(), "{again:?}");
343 }
344
345 /// #6555: reconcile judges seed journals exactly as Runtime startup does,
346 /// but never settles them. An unpublished seed's turns are not history, and
347 /// a thread whose journal cannot be settled is not recovered.
348 #[tokio::test]
349 async fn reconcile_does_not_recover_an_unpublished_or_unsettled_seed() {
350 let _env = lock_test_env();
351 for journal_state in ["uncommitted", "unreadable"] {
352 let fx = Fixture::new();
353 let (store, thread_id) = fx.store_with_thread("seeding-anchor").await;
354 let journal_path = store.join("threads").join(format!("{thread_id}.seed"));
355 {
356 let opened = RuntimeThreadStore::open(store.clone()).unwrap();
357 let turns = opened.list_turns_for_thread(&thread_id).unwrap();
358 let items = opened.list_items_for_turn(&turns[0].id).unwrap();
359 // The process stopped between the seed's records and its commit.
360 let mut thread = opened.load_thread(&thread_id).unwrap();
361 thread.latest_turn_id = None;
362 opened.save_thread(&thread).unwrap();
363 let journal = serde_json::json!({
364 "thread_id": thread_id,
365 "previous_latest_turn_id": null,
366 "turn_ids": turns.iter().map(|turn| turn.id.clone()).collect::<Vec<_>>(),
367 "item_ids": items.iter().map(|item| item.id.clone()).collect::<Vec<_>>(),
368 });
369 let bytes = match journal_state {
370 "uncommitted" => serde_json::to_vec(&journal).unwrap(),
371 _ => b"{truncated seed intent".to_vec(),
372 };
373 fs::write(&journal_path, bytes).unwrap();
374 }
375
376 let summary = fx.run();
377 assert_eq!(
378 summary.sessions_recovered, 0,
379 "{journal_state}: {summary:?}"
380 );
381 assert_eq!(
382 summary.stores_kept_with_work, 1,
383 "{journal_state}: {summary:?}"
384 );
385 assert!(
386 journal_path.is_file(),
387 "{journal_state}: reconcile leaves the journal for Runtime startup"
388 );
389 let thread = RuntimeThreadStore::open(store.clone())
390 .unwrap()
391 .load_thread(&thread_id)
392 .unwrap();
393 assert_eq!(thread.session_id, None, "{journal_state}");
394 }
395 }
396
397 /// R1: an unreadable document is set aside with its hash; a document from a
398 /// newer build is left alone.
399 #[test]
400 fn reconcile_sets_aside_unreadable_documents_and_keeps_newer_ones() {
401 let _env = lock_test_env();
402 let fx = Fixture::new();
403 fs::write(fx.dir().join("torn.json"), b"{\"metadata\": {\"id\": ").unwrap();
404 fs::write(
405 fx.dir().join("future.json"),
406 br#"{"schema_version": 999, "shape": "unknown"}"#,
407 )
408 .unwrap();
409
410 let summary = fx.run();
411 assert_eq!(summary.documents_set_aside, 1, "{summary:?}");
412 assert_eq!(summary.documents_newer_schema, 1);
413 assert!(!fx.dir().join("torn.json").exists());
414 assert!(fx.dir().join("future.json").exists());
415 let manifest = manifests(&fx.set_aside_root());
416 assert!(
417 manifest.contains("torn.json") && manifest.contains("sha256"),
418 "{manifest}"
419 );
420 }
421
422 /// R6: a document-less artifact directory nothing names is set aside; one a
423 /// document mentions, or one still being written, is kept.
424 #[test]
425 fn reconcile_sets_aside_unreferenced_artifact_directories() {
426 let _env = lock_test_env();
427 let fx = Fixture::new();
428 let lost = "0f0f0f0f-1111-4222-8333-444444444444";
429 let named = "0a0a0a0a-1111-4222-8333-555555555555";
430 for id in [lost, named] {
431 let artifacts = fx.dir().join(id).join("artifacts");
432 fs::create_dir_all(&artifacts).unwrap();
433 fs::write(artifacts.join("context-transfer-x.json"), b"[]").unwrap();
434 }
435 let mut mentions = create_saved_session_with_id_and_mode(
436 "mentions".into(),
437 &[text(Role::User, &format!("see sessions/{named}/artifacts"))],
438 "deepseek-v4-pro",
439 fx.home.path(),
440 0,
441 None,
442 None,
443 );
444 mentions.metadata.title = "Mentions".into();
445 fx.sessions.save_session(&mentions).unwrap();
446
447 // Recent directories are kept until they have been idle long enough.
448 let recent = fx.run_with(ReconcileOptions::default());
449 assert_eq!(recent.artifact_dirs_set_aside, 0);
450
451 let summary = fx.run();
452 assert_eq!(summary.artifact_dirs_set_aside, 1, "{summary:?}");
453 assert_eq!(summary.artifact_dirs_kept, 1);
454 assert!(!fx.dir().join(lost).exists());
455 assert!(fx.dir().join(named).exists());
456 }
457
458 /// The per-run limit stops a run and the next continues; a second process
459 /// arriving while one runs does nothing.
460 #[test]
461 fn reconcile_is_bounded_and_single_flight() {
462 let _env = lock_test_env();
463 let fx = Fixture::new();
464 fx.empty_store("orphan-one");
465 fx.empty_store("orphan-two");
466
467 let first = fx.run_with(ReconcileOptions {
468 limit: 1,
469 ..ReconcileOptions::default()
470 });
471 assert_eq!(first.stores_set_aside, 1);
472 assert!(first.limit_reached);
473 let second = fx.run();
474 assert_eq!(second.stores_set_aside, 1);
475 assert!(!second.limit_reached);
476
477 let lock = fs::OpenOptions::new()
478 .create(true)
479 .truncate(false)
480 .write(true)
481 .open(fx.dir().join(RECONCILE_LOCK_FILE))
482 .unwrap();
483 assert!(codewhale_util::lock::try_lock_file_exclusive(&lock).unwrap());
484 let skipped = fx.run();
485 assert!(skipped.skipped_concurrent);
486 }
487
488 /// P2: deleting a document retires the store its *binding* names — not
489 /// `sessions/<id>/runtime` — unless another document binds it or it holds
490 /// work. A `runtime-recovered-*` store under the deleted id is never removed.
491 #[tokio::test]
492 async fn deleting_a_document_retires_the_store_it_released() {
493 let _env = lock_test_env();
494 let fx = Fixture::new();
495 let shared = fx.empty_store("host-one");
496 let sole = fx.empty_store("host-two");
497 fx.document("keeps-shared", Some(&shared));
498 fx.document("uses-shared", Some(&shared));
499 fx.document("uses-sole", Some(&sole));
500 let (busy, _) = fx.store_with_thread("host-three").await;
501 fx.document("uses-busy", Some(&busy));
502 let recovered = fx.dir().join("uses-sole").join("runtime-recovered-session");
503 RuntimeThreadStore::open(recovered.clone()).unwrap();
504 fx.document("bound-to-recovered", Some(&recovered));
505
506 fx.sessions.delete_session("uses-shared").unwrap();
507 fx.sessions.delete_session("uses-sole").unwrap();
508 fx.sessions.delete_session("uses-busy").unwrap();
509
510 assert!(shared.is_dir(), "another document still binds it");
511 assert!(!sole.exists(), "released and empty: set aside");
512 assert!(busy.is_dir(), "holds work: kept");
513 assert!(recovered.is_dir(), "bound elsewhere: never deleted");
514 assert!(manifests(&fx.set_aside_root()).contains("host-two"));
515 }
516
517 /// P8: concurrent boot-owner stamps from separate handles lose no entry.
518 #[test]
519 fn concurrent_boot_owner_stamps_keep_every_entry() {
520 let _env = lock_test_env();
521 let fx = Fixture::new();
522 let ids: Vec<String> = (0..8).map(|index| format!("stamped-{index}")).collect();
523 for id in &ids {
524 fx.document(id, None);
525 }
526 let dir = fx.dir();
527 std::thread::scope(|scope| {
528 for id in &ids {
529 let dir = dir.clone();
530 scope.spawn(move || {
531 let manager = SessionManager::new(dir).unwrap();
532 manager.record_session_boot_owner(id, "boot_test").unwrap();
533 });
534 }
535 });
536 for id in &ids {
537 assert_eq!(
538 fx.sessions.session_boot_owner(id).as_deref(),
539 Some("boot_test")
540 );
541 }
542 }
543
544 #[test]
545 fn summary_notice_and_doctor_line_name_what_changed() {
546 let quiet = ReconcileSummary::default();
547 assert_eq!(quiet.notice(), None);
548 assert!(quiet.doctor_detail().contains("never"));
549
550 let incomplete = ReconcileSummary {
551 errors: vec!["session reference exceeds the inspection limit".into()],
552 ..ReconcileSummary::default()
553 };
554 let notice = incomplete.notice().unwrap();
555 assert_eq!(notice, "Session check incomplete · codewhale doctor --full");
556 assert!(incomplete.doctor_detail().contains(&incomplete.errors[0]));
557
558 let changed = ReconcileSummary {
559 ran_at: Some(Utc::now()),
560 sessions_recovered: 2,
561 threads_unbound: 5,
562 stores_set_aside: 140,
563 stores_in_use: 1,
564 set_aside_path: Some(PathBuf::from("/tmp/set-aside")),
565 errors: vec!["big.json: too large".into(), "other: unreadable".into()],
566 ..ReconcileSummary::default()
567 };
568 let notice = changed.notice().unwrap();
569 assert!(notice.contains("2 recovered"), "{notice}");
570 assert!(notice.contains("5 stale links cleared"), "{notice}");
571 assert!(notice.contains("140 unused items set aside"), "{notice}");
572 assert!(notice.ends_with("codewhale doctor --full"), "{notice}");
573 let detail = changed.doctor_detail();
574 assert!(detail.contains("/tmp/set-aside"), "{detail}");
575 assert!(detail.contains("140 stores"), "{detail}");
576 assert!(detail.contains("1 unbound stores in use"), "{detail}");
577 assert!(
578 detail.contains("2 item(s) could not be inspected and were left unchanged, first: big.json: too large (+1 more)"),
579 "{detail}"
580 );
581 assert!(detail.contains("--repair-sessions --dry-run"), "{detail}");
582
583 let dry = ReconcileSummary {
584 dry_run: true,
585 errors: Vec::new(),
586 ..changed
587 };
588 assert_eq!(dry.notice(), None, "a dry run changed nothing");
589 }
590
590 lines RUST