1use crate::GOALS_DB_FILENAME;
2use crate::LOGS_DB_FILENAME;
3use crate::LogEntry;
4use crate::LogQuery;
5use crate::LogRow;
6use crate::MEMORIES_DB_FILENAME;
7use crate::STATE_DB_FILENAME;
8use crate::SortKey;
9use crate::SqliteConfig;
10use crate::THREAD_HISTORY_DB_FILENAME;
11use crate::ThreadMetadata;
12use crate::ThreadMetadataBuilder;
13use crate::ThreadsPage;
14use crate::apply_rollout_item;
15use crate::migrations::repair_legacy_recency_migration_version;
16use crate::migrations::runtime_goals_migrator;
17use crate::migrations::runtime_logs_migrator;
18use crate::migrations::runtime_memories_migrator;
19use crate::migrations::runtime_state_migrator;
20use crate::migrations::runtime_thread_history_migrator;
21use crate::model::ThreadRow;
22use crate::model::anchor_from_item;
23use crate::model::datetime_to_epoch_millis;
24use crate::model::datetime_to_epoch_seconds;
25use crate::model::epoch_millis_to_datetime;
26use crate::paths::file_modified_time_utc;
27use crate::telemetry::DbKind;
28use crate::telemetry::DbTelemetry;
29use chrono::DateTime;
30use chrono::Utc;
31use codex_protocol::ThreadId;
32use codex_protocol::protocol::RolloutItem;
33use codex_utils_absolute_path::AbsolutePathBuf;
34use serde_json::Value;
35use sqlx::QueryBuilder;
36use sqlx::Row;
37use sqlx::Sqlite;
38use sqlx::SqliteConnection;
39use sqlx::SqlitePool;
40use sqlx::migrate::Migrator;
41use std::collections::BTreeSet;
42use std::path::Path;
43use std::path::PathBuf;
44use std::sync::Arc;
45use std::sync::atomic::AtomicI64;
46use std::time::Instant;
47use tracing::warn;
48
49mod backfill;
50mod external_agent_config_imports;
51mod goals;
52mod logs;
53mod memories;
54mod recovery;
55mod remote_control;
56#[cfg(test)]
57pub(crate) mod test_support;
58mod threads;
59
60pub use external_agent_config_imports::ExternalAgentConfigImportDetailsRecord;
61pub use external_agent_config_imports::ExternalAgentConfigImportFailureRecord;
62pub use external_agent_config_imports::ExternalAgentConfigImportHistoryRecord;
63pub use external_agent_config_imports::ExternalAgentConfigImportSuccessRecord;
64pub use goals::GoalAccountingMode;
65pub use goals::GoalAccountingOutcome;
66pub use goals::GoalStore;
67pub use goals::GoalUpdate;
68pub use memories::MemoryStore;
69pub use recovery::RuntimeDbBackup;
70pub use recovery::backup_runtime_db_for_fresh_start;
71pub use recovery::is_sqlite_corruption_error;
72pub use recovery::runtime_db_path_for_corruption_error;
73pub use recovery::sqlite_error_detail_is_corruption;
74pub use recovery::sqlite_error_detail_is_lock;
75pub use remote_control::RemoteControlEnrollmentRecord;
76pub use threads::ThreadFilterOptions;
77
78const LOG_PARTITION_SIZE_LIMIT_BYTES: i64 = 10 * 1024 * 1024;
85const LOG_PARTITION_ROW_LIMIT: i64 = 1_000;
86
87#[derive(Clone, Copy)]
88struct RuntimeDbSpec {
89 label: &'static str,
90 filename: &'static str,
91 kind: DbKind,
92 open_phase: &'static str,
93 migrate_phase: &'static str,
94}
95
96impl RuntimeDbSpec {
97 fn path(self, codex_home: &Path) -> PathBuf {
98 codex_home.join(self.filename)
99 }
100}
101
102const STATE_DB: RuntimeDbSpec = RuntimeDbSpec {
103 label: "state DB",
104 filename: STATE_DB_FILENAME,
105 kind: DbKind::State,
106 open_phase: "open_state",
107 migrate_phase: "migrate_state",
108};
109
110const LOGS_DB: RuntimeDbSpec = RuntimeDbSpec {
111 label: "log DB",
112 filename: LOGS_DB_FILENAME,
113 kind: DbKind::Logs,
114 open_phase: "open_logs",
115 migrate_phase: "migrate_logs",
116};
117
118const GOALS_DB: RuntimeDbSpec = RuntimeDbSpec {
119 label: "goals DB",
120 filename: GOALS_DB_FILENAME,
121 kind: DbKind::Goals,
122 open_phase: "open_goals",
123 migrate_phase: "migrate_goals",
124};
125
126const MEMORIES_DB: RuntimeDbSpec = RuntimeDbSpec {
127 label: "memories DB",
128 filename: MEMORIES_DB_FILENAME,
129 kind: DbKind::Memories,
130 open_phase: "open_memories",
131 migrate_phase: "migrate_memories",
132};
133
134const THREAD_HISTORY_DB: RuntimeDbSpec = RuntimeDbSpec {
135 label: "thread history DB",
136 filename: THREAD_HISTORY_DB_FILENAME,
137 kind: DbKind::ThreadHistory,
138 open_phase: "open_thread_history",
139 migrate_phase: "migrate_thread_history",
140};
141
142const RUNTIME_DBS: [RuntimeDbSpec; 5] =
143 [STATE_DB, LOGS_DB, GOALS_DB, MEMORIES_DB, THREAD_HISTORY_DB];
144
145#[derive(Clone, Debug, Eq, PartialEq)]
146pub struct RuntimeDbPath {
147 pub label: &'static str,
148 pub path: PathBuf,
149}
150
151#[derive(Clone)]
152pub struct StateRuntime {
153 codex_home: PathBuf,
154 default_provider: String,
155 pool: Arc<sqlx::SqlitePool>,
156 logs_pool: Arc<sqlx::SqlitePool>,
157 thread_goals: GoalStore,
158 memories: MemoryStore,
159 thread_updated_at_millis: Arc<AtomicI64>,
160 thread_recency_at_millis: Arc<AtomicI64>,
161}
162
163impl StateRuntime {
164 pub async fn init(codex_home: PathBuf, default_provider: String) -> anyhow::Result<Arc<Self>> {
170 Self::init_inner(
171 codex_home,
172 default_provider,
173 None,
174 )
175 .await
176 }
177
178 #[cfg(test)]
179 pub(crate) async fn init_with_telemetry_for_tests(
180 codex_home: PathBuf,
181 default_provider: String,
182 telemetry_override: &dyn DbTelemetry,
183 ) -> anyhow::Result<Arc<Self>> {
184 Self::init_inner(codex_home, default_provider, Some(telemetry_override)).await
185 }
186
187 async fn init_inner(
188 codex_home: PathBuf,
189 default_provider: String,
190 telemetry_override: Option<&dyn DbTelemetry>,
191 ) -> anyhow::Result<Arc<Self>> {
192 let sqlite = SqliteConfig::from_sqlite_home(AbsolutePathBuf::try_from(codex_home.clone())?);
193 tokio::fs::create_dir_all(&codex_home).await?;
194 let state_migrator = runtime_state_migrator();
195 let logs_migrator = runtime_logs_migrator();
196 let goals_migrator = runtime_goals_migrator();
197 let memories_migrator = runtime_memories_migrator();
198 let state_path = STATE_DB.path(codex_home.as_path());
199 let logs_path = LOGS_DB.path(codex_home.as_path());
200 let goals_path = GOALS_DB.path(codex_home.as_path());
201 let memories_path = MEMORIES_DB.path(codex_home.as_path());
202 let pool = match open_state_sqlite(
203 &sqlite,
204 &state_path,
205 &state_migrator,
206 telemetry_override,
207 )
208 .await
209 {
210 Ok(db) => Arc::new(db),
211 Err(err) => {
212 warn!("failed to open state db at {}: {err}", state_path.display());
213 return Err(err);
214 }
215 };
216 let logs_pool =
217 match open_logs_sqlite(&sqlite, &logs_path, &logs_migrator, telemetry_override).await {
218 Ok(db) => Arc::new(db),
219 Err(err) => {
220 warn!("failed to open logs db at {}: {err}", logs_path.display());
221 close_sqlite_pools(&[pool.as_ref()]).await;
222 return Err(err);
223 }
224 };
225 let goals_pool = match open_goals_sqlite(
226 &sqlite,
227 &goals_path,
228 &goals_migrator,
229 telemetry_override,
230 )
231 .await
232 {
233 Ok(db) => Arc::new(db),
234 Err(err) => {
235 warn!("failed to open goals db at {}: {err}", goals_path.display());
236 close_sqlite_pools(&[pool.as_ref(), logs_pool.as_ref()]).await;
237 return Err(err);
238 }
239 };
240 let memories_pool = match open_memories_sqlite(
241 &sqlite,
242 &memories_path,
243 &memories_migrator,
244 telemetry_override,
245 )
246 .await
247 {
248 Ok(db) => Arc::new(db),
249 Err(err) => {
250 warn!(
251 "failed to open memories db at {}: {err}",
252 memories_path.display()
253 );
254 close_sqlite_pools(&[pool.as_ref(), logs_pool.as_ref(), goals_pool.as_ref()]).await;
255 return Err(err);
256 }
257 };
258 let started = Instant::now();
259 let backfill_state_result = ensure_backfill_state_row_in_pool(pool.as_ref()).await;
260 crate::telemetry::record_init_result(
261 telemetry_override,
262 DbKind::State,
263 "ensure_backfill_state",
264 started.elapsed(),
265 &backfill_state_result,
266 );
267 if let Err(err) = backfill_state_result {
268 close_sqlite_pools(&[
269 pool.as_ref(),
270 logs_pool.as_ref(),
271 goals_pool.as_ref(),
272 memories_pool.as_ref(),
273 ])
274 .await;
275 return Err(err);
276 }
277 let started = Instant::now();
278 let thread_timestamp_millis_result: anyhow::Result<(Option<i64>, Option<i64>)> =
279 sqlx::query_as(
280 "SELECT MAX(threads.updated_at_ms), MAX(threads.recency_at_ms) FROM threads",
281 )
282 .fetch_one(pool.as_ref())
283 .await
284 .map_err(anyhow::Error::from);
285 crate::telemetry::record_init_result(
286 telemetry_override,
287 DbKind::State,
288 "post_init_query",
289 started.elapsed(),
290 &thread_timestamp_millis_result,
291 );
292 let (thread_updated_at_millis, thread_recency_at_millis) =
293 match thread_timestamp_millis_result {
294 Ok(value) => value,
295 Err(err) => {
296 close_sqlite_pools(&[
297 pool.as_ref(),
298 logs_pool.as_ref(),
299 goals_pool.as_ref(),
300 memories_pool.as_ref(),
301 ])
302 .await;
303 return Err(err);
304 }
305 };
306 let thread_updated_at_millis = thread_updated_at_millis.unwrap_or(0);
307 let thread_recency_at_millis = thread_recency_at_millis.unwrap_or(0);
308 let runtime = Arc::new(Self {
309 thread_goals: GoalStore::new(Arc::clone(&goals_pool)),
310 memories: MemoryStore::new(Arc::clone(&memories_pool), Arc::clone(&pool)),
311 pool,
312 logs_pool,
313 codex_home,
314 default_provider,
315 thread_updated_at_millis: Arc::new(AtomicI64::new(thread_updated_at_millis)),
316 thread_recency_at_millis: Arc::new(AtomicI64::new(thread_recency_at_millis)),
317 });
318 if let Err(err) = runtime.run_logs_startup_maintenance().await {
319 warn!(
320 "failed to run startup maintenance for logs db at {}: {err}",
321 logs_path.display(),
322 );
323 }
324 Ok(runtime)
325 }
326
327 pub fn codex_home(&self) -> &Path {
329 self.codex_home.as_path()
330 }
331
332 pub fn thread_goals(&self) -> &GoalStore {
333 &self.thread_goals
334 }
335
336 pub fn memories(&self) -> &MemoryStore {
337 &self.memories
338 }
339
340 pub async fn close(&self) {
342 self.memories.close().await;
343 self.thread_goals.close().await;
344 self.logs_pool.close().await;
345 self.pool.close().await;
346 }
347
348 pub async fn clear_memory_data_in_sqlite_home(sqlite_home: &Path) -> anyhow::Result<bool> {
349 let sqlite = SqliteConfig::from_sqlite_home(AbsolutePathBuf::try_from(sqlite_home)?);
350 let memories_path = MEMORIES_DB.path(sqlite_home);
351 if !tokio::fs::try_exists(&memories_path).await? {
352 return Ok(false);
353 }
354
355 let memories_migrator = runtime_memories_migrator();
356 let pool = open_memories_sqlite(
357 &sqlite,
358 &memories_path,
359 &memories_migrator,
360 None,
361 )
362 .await?;
363 memories::clear_memory_data_in_pool(&pool).await?;
364 pool.close().await;
365 Ok(true)
366 }
367}
368
369async fn close_sqlite_pools(pools: &[&SqlitePool]) {
370 for pool in pools {
371 pool.close().await;
372 }
373}
374
375async fn open_state_sqlite(
376 sqlite: &SqliteConfig,
377 path: &Path,
378 migrator: &Migrator,
379 telemetry_override: Option<&dyn DbTelemetry>,
380) -> anyhow::Result<SqlitePool> {
381 open_sqlite(sqlite, path, migrator, STATE_DB, telemetry_override).await
385}
386
387async fn open_logs_sqlite(
388 sqlite: &SqliteConfig,
389 path: &Path,
390 migrator: &Migrator,
391 telemetry_override: Option<&dyn DbTelemetry>,
392) -> anyhow::Result<SqlitePool> {
393 open_sqlite(sqlite, path, migrator, LOGS_DB, telemetry_override).await
394}
395
396async fn open_goals_sqlite(
397 sqlite: &SqliteConfig,
398 path: &Path,
399 migrator: &Migrator,
400 telemetry_override: Option<&dyn DbTelemetry>,
401) -> anyhow::Result<SqlitePool> {
402 open_sqlite(sqlite, path, migrator, GOALS_DB, telemetry_override).await
403}
404
405async fn open_memories_sqlite(
406 sqlite: &SqliteConfig,
407 path: &Path,
408 migrator: &Migrator,
409 telemetry_override: Option<&dyn DbTelemetry>,
410) -> anyhow::Result<SqlitePool> {
411 open_sqlite(sqlite, path, migrator, MEMORIES_DB, telemetry_override).await
412}
413
414pub async fn open_thread_history_db(sqlite_home: &Path) -> anyhow::Result<SqlitePool> {
416 let sqlite = SqliteConfig::from_sqlite_home(AbsolutePathBuf::try_from(sqlite_home)?);
417 let migrator = runtime_thread_history_migrator();
418 open_sqlite(
419 &sqlite,
420 thread_history_db_path(sqlite_home).as_path(),
421 &migrator,
422 THREAD_HISTORY_DB,
423 None,
424 )
425 .await
426}
427
428async fn open_sqlite(
429 sqlite: &SqliteConfig,
430 path: &Path,
431 migrator: &Migrator,
432 spec: RuntimeDbSpec,
433 telemetry_override: Option<&dyn DbTelemetry>,
434) -> anyhow::Result<SqlitePool> {
435 let started = Instant::now();
436 let pool_result = sqlite
437 .open_read_write_pool(path)
438 .await
439 .map_err(anyhow::Error::from);
440 crate::telemetry::record_init_result(
441 telemetry_override,
442 spec.kind,
443 spec.open_phase,
444 started.elapsed(),
445 &pool_result,
446 );
447 let pool = pool_result
448 .map_err(|source| recovery::RuntimeDbInitError::new(spec.label, "open", path, source))?;
449 let started = Instant::now();
450 let migrate_result = async {
451 if matches!(spec.kind, DbKind::State) {
452 repair_legacy_recency_migration_version(&pool, migrator).await?;
453 }
454 migrator.run(&pool).await.map_err(anyhow::Error::from)
455 }
456 .await;
457 crate::telemetry::record_init_result(
458 telemetry_override,
459 spec.kind,
460 spec.migrate_phase,
461 started.elapsed(),
462 &migrate_result,
463 );
464 if let Err(source) = migrate_result {
465 pool.close().await;
466 return Err(recovery::RuntimeDbInitError::new(spec.label, "migrate", path, source).into());
467 }
468 Ok(pool)
469}
470
471pub(super) async fn ensure_backfill_state_row_in_pool(
472 pool: &sqlx::SqlitePool,
473) -> anyhow::Result<()> {
474 if sqlx::query_scalar::<_, i64>("SELECT 1 FROM backfill_state WHERE id = 1")
477 .fetch_optional(pool)
478 .await?
479 .is_some()
480 {
481 return Ok(());
482 }
483
484 sqlx::query(
485 r#"
486INSERT INTO backfill_state (id, status, last_watermark, last_success_at, updated_at)
487VALUES (?, ?, NULL, NULL, ?)
488ON CONFLICT(id) DO NOTHING
489 "#,
490 )
491 .bind(1_i64)
492 .bind(crate::BackfillStatus::Pending.as_str())
493 .bind(Utc::now().timestamp())
494 .execute(pool)
495 .await?;
496 Ok(())
497}
498
499pub fn state_db_filename() -> String {
500 STATE_DB.filename.to_string()
501}
502
503pub fn state_db_path(codex_home: &Path) -> PathBuf {
504 STATE_DB.path(codex_home)
505}
506
507pub fn logs_db_filename() -> String {
508 LOGS_DB.filename.to_string()
509}
510
511pub fn logs_db_path(codex_home: &Path) -> PathBuf {
512 LOGS_DB.path(codex_home)
513}
514
515pub fn goals_db_filename() -> String {
516 GOALS_DB.filename.to_string()
517}
518
519pub fn goals_db_path(codex_home: &Path) -> PathBuf {
520 GOALS_DB.path(codex_home)
521}
522
523pub fn memories_db_filename() -> String {
524 MEMORIES_DB.filename.to_string()
525}
526
527pub fn memories_db_path(codex_home: &Path) -> PathBuf {
528 MEMORIES_DB.path(codex_home)
529}
530
531pub fn thread_history_db_filename() -> String {
532 THREAD_HISTORY_DB.filename.to_string()
533}
534
535pub fn thread_history_db_path(codex_home: &Path) -> PathBuf {
536 THREAD_HISTORY_DB.path(codex_home)
537}
538
539pub fn runtime_db_paths(codex_home: &Path) -> Vec<RuntimeDbPath> {
540 RUNTIME_DBS
541 .iter()
542 .map(|spec| RuntimeDbPath {
543 label: spec.label,
544 path: spec.path(codex_home),
545 })
546 .collect()
547}
548
549pub async fn sqlite_integrity_check(path: &Path) -> anyhow::Result<Vec<String>> {
551 let sqlite =
552 SqliteConfig::from_sqlite_home(AbsolutePathBuf::try_from(path.parent().unwrap_or(path))?);
553 let pool = sqlite.open_read_only_pool(path).await?;
554 let rows = sqlx::query_scalar::<_, String>("PRAGMA integrity_check")
555 .fetch_all(&pool)
556 .await?;
557 pool.close().await;
558 Ok(rows)
559}
560
561#[cfg(test)]
562mod tests {
563 use super::StateRuntime;
564 use super::open_state_sqlite;
565 use super::runtime_state_migrator;
566 use super::sqlite_integrity_check;
567 use super::state_db_path;
568 use super::test_support::unique_temp_dir;
569 use crate::DB_INIT_METRIC;
570 use crate::DbTelemetry;
571 use crate::migrations::STATE_MIGRATOR;
572 use codex_utils_absolute_path::test_support::PathExt;
573 use pretty_assertions::assert_eq;
574 use sqlx::SqlitePool;
575 use sqlx::migrate::MigrateError;
576 use std::collections::BTreeMap;
577 use std::collections::BTreeSet;
578 use std::path::Path;
579 use std::sync::Mutex;
580
581 #[derive(Default)]
582 struct TestTelemetry {
583 counters: Mutex<Vec<MetricEvent>>,
584 }
585
586 #[derive(Debug, Eq, PartialEq)]
587 struct MetricEvent {
588 name: String,
589 tags: BTreeMap<String, String>,
590 }
591
592 impl TestTelemetry {
593 fn counters(&self) -> Vec<MetricEvent> {
594 self.counters
595 .lock()
596 .expect("telemetry lock")
597 .iter()
598 .map(|event| MetricEvent {
599 name: event.name.clone(),
600 tags: event.tags.clone(),
601 })
602 .collect()
603 }
604 }
605
606 impl DbTelemetry for TestTelemetry {
607 fn counter(&self, name: &str, _inc: i64, tags: &[(&str, &str)]) {
608 self.counters
609 .lock()
610 .expect("telemetry lock")
611 .push(MetricEvent {
612 name: name.to_string(),
613 tags: tags_to_map(tags),
614 });
615 }
616
617 fn record_duration(
618 &self,
619 _name: &str,
620 _duration: std::time::Duration,
621 _tags: &[(&str, &str)],
622 ) {
623 }
624 }
625
626 fn tags_to_map(tags: &[(&str, &str)]) -> BTreeMap<String, String> {
627 tags.iter()
628 .map(|(key, value)| ((*key).to_string(), (*value).to_string()))
629 .collect()
630 }
631
632 async fn open_db_pool(path: &Path) -> SqlitePool {
633 crate::SqliteConfig::new_for_testing(path.parent().unwrap_or(path).abs())
634 .open_read_write_pool(path)
635 .await
636 .expect("open sqlite pool")
637 }
638
639 #[tokio::test]
640 async fn sqlite_integrity_check_reports_ok_for_valid_db() {
641 let codex_home = unique_temp_dir();
642 tokio::fs::create_dir_all(&codex_home)
643 .await
644 .expect("create codex home");
645 let path = state_db_path(codex_home.as_path());
646 let pool = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs())
647 .open_read_write_pool(&path)
648 .await
649 .expect("open sqlite db");
650 sqlx::query("CREATE TABLE sample (id INTEGER PRIMARY KEY)")
651 .execute(&pool)
652 .await
653 .expect("create sample table");
654 pool.close().await;
655
656 let result = sqlite_integrity_check(&path)
657 .await
658 .expect("integrity check should run");
659
660 assert_eq!(result, vec!["ok".to_string()]);
661 let _ = tokio::fs::remove_dir_all(codex_home).await;
662 }
663
664 #[tokio::test]
665 async fn open_state_sqlite_tolerates_newer_applied_migrations() {
666 let codex_home = unique_temp_dir();
667 tokio::fs::create_dir_all(&codex_home)
668 .await
669 .expect("create codex home");
670 let state_path = state_db_path(codex_home.as_path());
671 let pool = crate::SqliteConfig::new_for_testing(codex_home.as_path().abs())
672 .open_read_write_pool(&state_path)
673 .await
674 .expect("open state db");
675 STATE_MIGRATOR
676 .run(&pool)
677 .await
678 .expect("apply current state schema");
679 sqlx::query(
680 "INSERT INTO _sqlx_migrations (version, description, success, checksum, execution_time) VALUES (?, ?, ?, ?, ?)",
681 )
682 .bind(9_999_i64)
683 .bind("future migration")
684 .bind(true)
685 .bind(vec![1_u8, 2, 3, 4])
686 .bind(1_i64)
687 .execute(&pool)
688 .await
689 .expect("insert future migration record");
690 pool.close().await;
691
692 let strict_pool = open_db_pool(state_path.as_path()).await;
693 let strict_err = STATE_MIGRATOR
694 .run(&strict_pool)
695 .await
696 .expect_err("strict migrator should reject newer applied migrations");
697 assert!(matches!(strict_err, MigrateError::VersionMissing(9_999)));
698 strict_pool.close().await;
699
700 let tolerant_migrator = runtime_state_migrator();
701 let tolerant_pool = open_state_sqlite(
702 &crate::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
703 state_path.as_path(),
704 &tolerant_migrator,
705 None,
706 )
707 .await
708 .expect("runtime migrator should tolerate newer applied migrations");
709 tolerant_pool.close().await;
710
711 let _ = tokio::fs::remove_dir_all(codex_home).await;
712 }
713
714 #[tokio::test]
715 async fn init_records_successful_sqlite_init_phases_to_explicit_telemetry() {
716 let codex_home = unique_temp_dir();
717 let telemetry = TestTelemetry::default();
718
719 let runtime = StateRuntime::init_with_telemetry_for_tests(
720 codex_home.clone(),
721 "test-provider".to_string(),
722 &telemetry,
723 )
724 .await
725 .expect("state runtime should initialize");
726
727 let phases = telemetry
728 .counters()
729 .into_iter()
730 .filter(|event| event.name == DB_INIT_METRIC)
731 .filter(|event| event.tags.get("status").map(String::as_str) == Some("success"))
732 .filter_map(|event| event.tags.get("phase").cloned())
733 .collect::<BTreeSet<_>>();
734 let expected = [
735 "open_state",
736 "migrate_state",
737 "open_logs",
738 "migrate_logs",
739 "open_goals",
740 "migrate_goals",
741 "open_memories",
742 "migrate_memories",
743 "ensure_backfill_state",
744 "post_init_query",
745 ]
746 .into_iter()
747 .map(str::to_string)
748 .collect::<BTreeSet<_>>();
749 assert_eq!(phases, expected);
750
751 runtime.close().await;
752 let _ = tokio::fs::remove_dir_all(codex_home).await;
753 }
754}