Add metadata-only reads to the thread store (#64651)

## Why

Callers that only need canonical session metadata should be able to read it
without loading the full rollout history.

## What changed

Add `ThreadStore::read_session_meta`. The default implementation looks for
the session header in the latest model context and falls back to history if
the header is absent or model context reads are unsupported.

The local store reads only the selected rollout's header and skips SQLite
read repair, which can parse the full rollout. If archiving or unarchiving
moves the file before SQLite updates its path, the lookup can follow the
rollout to its new location while respecting `include_archived`.

## Testing

Cover paginated metadata reads, the history fallback for a saved child
thread, and metadata reads with missing or stale SQLite entries. Verify that
a valid header can still be read when the rest of the rollout contains invalid
bytes.

GitOrigin-RevId: 08790b2db80d35e67f5a101dc38d760987b2d710
This commit is contained in:
ioanbudea-OAI
2026-11-30 00:51:08 +00:00
committed by copyberry
parent ba431841b4
commit fd7f1f0346
8 changed files with 334 additions and 45 deletions
@@ -90,8 +90,6 @@ impl ThreadStore for GatedChildMetadataStore {
fn flush_thread(thread_id: ThreadId) -> ();
fn shutdown_thread(thread_id: ThreadId) -> ();
fn discard_thread(thread_id: ThreadId) -> ();
fn load_history(params: LoadThreadHistoryParams) -> StoredThreadHistory;
fn load_latest_model_context(params: LoadThreadHistoryParams) -> StoredModelContext;
fn read_thread_by_rollout_path(params: ReadThreadByRolloutPathParams) -> StoredThread;
fn list_threads(params: ListThreadsParams) -> ThreadPage;
fn update_thread_metadata(params: UpdateThreadMetadataParams) -> Option<StoredThread>;
@@ -100,6 +98,40 @@ impl ThreadStore for GatedChildMetadataStore {
fn delete_thread(params: DeleteThreadParams) -> ();
}
fn load_history(
&self,
params: LoadThreadHistoryParams,
) -> ThreadStoreFuture<'_, StoredThreadHistory> {
Box::pin(async move {
if params.thread_id != self.failed_child {
return self.inner.load_history(params).await;
}
// Emulate a store that exposes this saved child's header through load_history.
let context = self.inner.load_latest_model_context(params).await?;
Ok(StoredThreadHistory {
thread_id: context.thread_id,
items: context.items,
revision: context.revision,
})
})
}
fn load_latest_model_context(
&self,
params: LoadThreadHistoryParams,
) -> ThreadStoreFuture<'_, StoredModelContext> {
Box::pin(async move {
let omit_header = params.thread_id == self.failed_child;
let mut context = self.inner.load_latest_model_context(params).await?;
if omit_header {
context
.items
.retain(|item| !matches!(item, RolloutItem::SessionMeta(_)));
}
Ok(context)
})
}
fn resume_thread(
&self,
params: ResumeThreadParams,
@@ -262,6 +294,12 @@ async fn cold_root_resume_overlaps_child_reads_and_applies_identities_in_graph_o
started: started_tx,
completed: completed_tx,
});
let params = LoadThreadHistoryParams {
thread_id: failed,
include_archived: false,
};
let meta = store.read_session_meta(params).await?;
assert_eq!((meta.id, meta.session_id), (failed, root.into()));
let resume_url = format!("{}/v1", server.uri());
let mut resume_builder = test_codex()
.with_thread_store(store)
+12
View File
@@ -365,6 +365,18 @@ mod tests {
assert_eq!(thread.history_mode, ThreadHistoryMode::Paginated);
assert!(thread.history.is_none());
let meta = store
.read_session_meta(LoadThreadHistoryParams {
thread_id,
include_archived: false,
})
.await
.expect("canonical metadata without a legacy history read");
assert_eq!(
(meta.id, meta.history_mode),
(thread_id, ThreadHistoryMode::Paginated)
);
let thread = store
.read_thread_by_rollout_path(ReadThreadByRolloutPathParams {
rollout_path,
@@ -368,5 +368,57 @@ mod tests {
assert_eq!(updated.rollout_path, archived_path);
assert!(updated.archived_at.is_some());
assert_eq!(updated.recency_at, metadata.recency_at);
let contents = std::fs::read_to_string(&archived_path).expect("archived rollout");
let (header, history) = contents.split_once('\n').expect("header and history");
let mut header: serde_json::Value = serde_json::from_str(header).expect("header");
let mut metadata = metadata;
for mode in [ThreadHistoryMode::Legacy, ThreadHistoryMode::Paginated] {
metadata.history_mode = mode;
header["payload"]["history_mode"] = serde_json::to_value(mode).expect("history mode");
std::fs::write(&archived_path, format!("{header}\n{history}")).expect("update header");
// The file moved, but SQLite still points to its old location.
runtime
.upsert_thread(&metadata)
.await
.expect("stale SQLite path");
let meta = store
.read_session_meta(crate::LoadThreadHistoryParams {
thread_id,
include_archived: true,
})
.await
.expect("metadata before SQLite update");
let expected = codex_rollout::read_session_meta_line(&archived_path)
.await
.expect("archived header")
.meta;
assert_eq!(
serde_json::to_value(meta).expect("metadata"),
serde_json::to_value(&expected).expect("header")
);
let params = crate::LoadThreadHistoryParams {
thread_id,
include_archived: false,
};
assert!(matches!(
store.read_session_meta(params.clone()).await,
Err(ThreadStoreError::ThreadNotFound { .. })
));
runtime
.mark_archived(thread_id, &archived_path, Utc::now())
.await
.expect("archived SQLite path");
std::fs::rename(&archived_path, &active_path)
.expect("move before unarchive SQLite update");
let meta = store
.read_session_meta(params)
.await
.expect("visible unarchived metadata");
assert_eq!(
serde_json::to_value(meta).expect("metadata"),
serde_json::to_value(expected).expect("header")
);
std::fs::rename(&active_path, &archived_path).expect("restore archived rollout");
}
}
}
+8
View File
@@ -47,6 +47,7 @@ mod test_support;
mod timestamp_metadata_tests;
use codex_protocol::ThreadId;
use codex_protocol::protocol::SessionMeta;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_protocol::realtime::RealtimeItem;
use codex_rollout::ResponseItemEnvelope;
@@ -675,6 +676,13 @@ impl ThreadStore for LocalThreadStore {
Box::pin(LocalThreadStore::load_history(self, params))
}
fn read_session_meta(
&self,
params: LoadThreadHistoryParams,
) -> ThreadStoreFuture<'_, SessionMeta> {
Box::pin(read_thread::read_session_meta(self, params))
}
fn load_latest_model_context(
&self,
params: LoadThreadHistoryParams,
@@ -22,6 +22,7 @@ use super::helpers::set_thread_name;
use super::helpers::sqlite_thread_name;
use super::helpers::stored_thread_from_rollout_item;
use super::thread_rollout_resolver;
use crate::LoadThreadHistoryParams;
use crate::ReadThreadParams;
use crate::StoredThread;
use crate::StoredThreadHistory;
@@ -29,6 +30,76 @@ use crate::ThreadStoreError;
use crate::ThreadStoreResult;
use crate::error::reject_paginated_history_mode;
pub(super) async fn read_session_meta(
store: &LocalThreadStore,
params: LoadThreadHistoryParams,
) -> ThreadStoreResult<SessionMeta> {
match session_meta_path(store, &params).await? {
(_, Some(meta)) => Ok(meta),
(path, None) => read_session_meta_from_path(store, params, &path).await,
}
}
async fn session_meta_path(
store: &LocalThreadStore,
params: &LoadThreadHistoryParams,
) -> ThreadStoreResult<(std::path::PathBuf, Option<SessionMeta>)> {
if let Some(resolved) = thread_rollout_resolver::resolve_for_session_meta(store, params).await?
{
return Ok((resolved.path, resolved.session_meta));
}
let metadata = read_sqlite_metadata(store, params.thread_id).await.ok_or(
ThreadStoreError::ThreadNotFound {
thread_id: params.thread_id,
},
)?;
Ok((metadata.rollout_path, None))
}
pub(super) async fn read_session_meta_from_path(
store: &LocalThreadStore,
params: LoadThreadHistoryParams,
path: &std::path::Path,
) -> ThreadStoreResult<SessionMeta> {
let mut path = path.to_path_buf();
let meta = match read_session_meta_line(&path).await {
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
// Archive moves precede SQLite updates; follow the selected immutable rollout.
path = match codex_rollout::rollout_id_from_path(&path) {
Some(rollout_id) => codex_rollout::find_rollout_path_by_rollout_id(
store.config.codex_home.as_path(),
rollout_id,
)
.await
.map_err(|err| ThreadStoreError::Internal {
message: err.to_string(),
})?
.ok_or(ThreadStoreError::ThreadNotFound {
thread_id: params.thread_id,
})?,
None => match session_meta_path(store, &params).await? {
(_, Some(meta)) => return Ok(meta),
(path, None) => path,
},
};
read_required_session_meta_line(&path).await?
}
result => result.map_err(|err| ThreadStoreError::Internal {
message: err.to_string(),
})?,
}
.meta;
if meta.id != params.thread_id
|| (!params.include_archived
&& rollout_path_is_archived(store.config.codex_home.as_path(), &path))
{
return Err(ThreadStoreError::ThreadNotFound {
thread_id: params.thread_id,
});
}
Ok(meta)
}
pub(super) async fn read_thread(
store: &LocalThreadStore,
params: ReadThreadParams,
@@ -1,7 +1,8 @@
//! Regression coverage for metadata reads without SQLite.
//! Regression coverage for rollout metadata reads and SQLite fallback.
use std::fs;
use std::fs::FileTimes;
use std::sync::Arc;
use chrono::DateTime;
use chrono::Utc;
@@ -12,10 +13,13 @@ use codex_protocol::protocol::ThreadSource;
use codex_rollout::RolloutItem;
use codex_rollout::RolloutLine;
use pretty_assertions::assert_eq;
use serde_json::to_value;
use tempfile::TempDir;
use super::LocalThreadStore;
use super::test_support::test_config;
use crate::ArchiveThreadParams;
use crate::LoadThreadHistoryParams;
use crate::ReadThreadParams;
use crate::ThreadStore;
@@ -58,6 +62,7 @@ async fn empty_archived_reads_without_sqlite_preserve_source_and_file_time()
include_history: false,
})
.await?;
let stale_path = path.clone();
let by_path = store
.read_thread_by_rollout_path(
path, /*include_archived*/ true, /*include_history*/ false,
@@ -85,5 +90,31 @@ async fn empty_archived_reads_without_sqlite_preserve_source_and_file_time()
),
);
}
let other = LocalThreadStore::new(test_config(home.path()), /*state_db*/ None);
let moved = other
.unarchive_thread(ArchiveThreadParams { thread_id })
.await?;
let config = test_config(home.path());
let state_db = codex_state::StateRuntime::init(
config.sqlite.clone(),
config.default_model_provider_id.clone(),
)
.await?;
let indexed_store = LocalThreadStore::new(config, Some(Arc::clone(&state_db)));
let params = LoadThreadHistoryParams {
thread_id,
include_archived: true,
};
assert!(state_db.get_thread(thread_id).await?.is_none());
let meta = indexed_store.read_session_meta(params.clone()).await?;
let expected = to_value(&line.item)?;
assert_eq!(to_value(meta)?, expected["payload"]);
assert!(state_db.get_thread(thread_id).await?.is_none());
fs::write(
moved.rollout_path.expect("unarchived rollout"),
[serde_json::to_vec(&line)?.as_slice(), b"\n\xff"].concat(),
)?;
let meta = super::read_thread::read_session_meta_from_path(&store, params, &stale_path).await?;
assert_eq!(to_value(meta)?, expected["payload"]);
Ok(())
}
@@ -3,10 +3,12 @@
//! Most threads have one rollout file. `thread/revert` keeps the thread ID stable while switching
//! the thread to a new rollout file, so callers cannot infer the selected path from the thread ID
//! alone. This module centralizes live-writer, SQLite, and filesystem fallback resolution.
//! Session metadata reads skip read repair to avoid parsing the rest of the rollout.
use std::path::PathBuf;
use codex_protocol::ThreadId;
use codex_protocol::protocol::SessionMeta;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_rollout::find_archived_thread_path_by_id_str;
use codex_rollout::find_thread_path_by_id_str;
@@ -14,6 +16,7 @@ use codex_rollout::find_thread_path_by_id_str;
use super::LocalThreadStore;
use super::helpers::rollout_path_is_archived;
use super::live_writer;
use crate::LoadThreadHistoryParams;
use crate::ThreadStoreError;
use crate::ThreadStoreResult;
@@ -21,12 +24,14 @@ use crate::ThreadStoreResult;
///
/// For ordinary threads, `thread_id` and `rollout_id` are the same. After `thread/revert`,
/// `thread_id` stays stable while `rollout_id` identifies the new immutable rollout file.
#[derive(Clone, Debug, PartialEq, Eq)]
#[derive(Debug)]
pub(super) struct ResolvedThreadRollout {
pub(super) thread_id: ThreadId,
pub(super) rollout_id: ThreadId,
pub(super) path: PathBuf,
pub(super) location: RolloutLocation,
/// Header already read to verify the SQLite path belongs to this thread.
pub(super) session_meta: Option<SessionMeta>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -39,14 +44,38 @@ pub(super) async fn resolve_current(
store: &LocalThreadStore,
thread_id: ThreadId,
) -> ThreadStoreResult<Option<ResolvedThreadRollout>> {
resolve(store, thread_id, LookupScope::ExcludeArchived).await
resolve(
store,
thread_id,
LookupScope::ExcludeArchived,
ReadRepair::Enabled,
)
.await
}
pub(super) async fn resolve_current_including_archived(
store: &LocalThreadStore,
thread_id: ThreadId,
) -> ThreadStoreResult<Option<ResolvedThreadRollout>> {
resolve(store, thread_id, LookupScope::IncludeArchived).await
resolve(
store,
thread_id,
LookupScope::IncludeArchived,
ReadRepair::Enabled,
)
.await
}
pub(super) async fn resolve_for_session_meta(
store: &LocalThreadStore,
params: &LoadThreadHistoryParams,
) -> ThreadStoreResult<Option<ResolvedThreadRollout>> {
let scope = if params.include_archived {
LookupScope::IncludeArchived
} else {
LookupScope::ExcludeArchived
};
resolve(store, params.thread_id, scope, ReadRepair::Disabled).await
}
#[derive(Clone, Copy)]
@@ -64,6 +93,11 @@ impl LookupScope {
}
}
enum ReadRepair {
Enabled,
Disabled,
}
/// Resolves a thread's selected rollout in this order:
///
/// 1. The live writer, when one exists.
@@ -74,12 +108,14 @@ async fn resolve(
store: &LocalThreadStore,
thread_id: ThreadId,
scope: LookupScope,
read_repair: ReadRepair,
) -> ThreadStoreResult<Option<ResolvedThreadRollout>> {
if let Ok(path) = live_writer::rollout_path(store, thread_id).await
&& codex_rollout::existing_rollout_path(path.as_path())
.await
.is_some()
&& let Some(resolved) = resolve_path_in_scope(store, thread_id, path, scope).await?
&& let Some(resolved) =
resolve_path_in_scope(store, thread_id, path, scope, /*session_meta*/ None).await?
{
return Ok(Some(resolved));
}
@@ -95,13 +131,16 @@ async fn resolve(
if let Some(path) =
codex_rollout::existing_rollout_path(metadata.rollout_path.as_path()).await
{
let belongs_to_thread =
match codex_rollout::read_session_meta_line(path.as_path()).await {
Ok(session_meta) => session_meta.meta.id == thread_id,
Err(_) => true,
};
if belongs_to_thread {
return resolve_path_in_scope(store, thread_id, path, scope).await;
let session_meta = codex_rollout::read_session_meta_line(&path)
.await
.ok()
.map(|line| line.meta);
if session_meta
.as_ref()
.is_none_or(|meta| meta.id == thread_id)
{
return resolve_path_in_scope(store, thread_id, path, scope, session_meta)
.await;
}
}
if metadata.history_mode == ThreadHistoryMode::Paginated {
@@ -116,15 +155,21 @@ async fn resolve(
}
}
}
// The fallback can deserialize the full rollout while reseeding a missing SQLite row.
let fallback_state_db = match read_repair {
ReadRepair::Enabled => state_db_ctx.as_deref(),
ReadRepair::Disabled => None,
};
if let Some(path) = find_thread_path_by_id_str(
store.config.codex_home.as_path(),
&thread_id.to_string(),
state_db_ctx.as_deref(),
fallback_state_db,
)
.await
.map_err(|err| ThreadStoreError::InvalidRequest {
message: format!("failed to locate thread id {thread_id}: {err}"),
})? && let Some(resolved) = resolve_path_in_scope(store, thread_id, path, scope).await?
})? && let Some(resolved) =
resolve_path_in_scope(store, thread_id, path, scope, /*session_meta*/ None).await?
{
return Ok(Some(resolved));
}
@@ -134,14 +179,16 @@ async fn resolve(
let path = find_archived_thread_path_by_id_str(
store.config.codex_home.as_path(),
&thread_id.to_string(),
state_db_ctx.as_deref(),
fallback_state_db,
)
.await
.map_err(|err| ThreadStoreError::InvalidRequest {
message: format!("failed to locate archived thread id {thread_id}: {err}"),
})?;
match path {
Some(path) => resolve_path_in_scope(store, thread_id, path, scope).await,
Some(path) => {
resolve_path_in_scope(store, thread_id, path, scope, /*session_meta*/ None).await
}
None => Ok(None),
}
}
@@ -151,12 +198,40 @@ async fn resolve_path_in_scope(
thread_id: ThreadId,
path: PathBuf,
scope: LookupScope,
session_meta: Option<SessionMeta>,
) -> ThreadStoreResult<Option<ResolvedThreadRollout>> {
let location = location_for_path(store, path.as_path());
if !scope.accepts(location) {
return Ok(None);
}
resolve_path(thread_id, path, location).await.map(Some)
let rollout_id = match codex_rollout::rollout_id_from_path(path.as_path()) {
Some(rollout_id) => rollout_id,
None => {
let history_mode = match &session_meta {
Some(meta) => meta.history_mode,
None => {
codex_rollout::read_session_meta_line(&path)
.await
.map_err(|err| ThreadStoreError::Internal {
message: format!(
"failed to read session metadata {}: {err}",
path.display()
),
})?
.meta
.history_mode
}
};
rollout_id_from_path_or_legacy_thread_id(path.as_path(), thread_id, history_mode)?
}
};
Ok(Some(ResolvedThreadRollout {
thread_id,
rollout_id,
path,
location,
session_meta,
}))
}
fn location_for_path(store: &LocalThreadStore, path: &std::path::Path) -> RolloutLocation {
@@ -167,32 +242,6 @@ fn location_for_path(store: &LocalThreadStore, path: &std::path::Path) -> Rollou
}
}
async fn resolve_path(
thread_id: ThreadId,
path: PathBuf,
location: RolloutLocation,
) -> ThreadStoreResult<ResolvedThreadRollout> {
let rollout_id = match codex_rollout::rollout_id_from_path(path.as_path()) {
Some(rollout_id) => rollout_id,
None => {
let history_mode = codex_rollout::read_session_meta_line(path.as_path())
.await
.map_err(|err| ThreadStoreError::Internal {
message: format!("failed to read session metadata {}: {err}", path.display()),
})?
.meta
.history_mode;
rollout_id_from_path_or_legacy_thread_id(path.as_path(), thread_id, history_mode)?
}
};
Ok(ResolvedThreadRollout {
thread_id,
rollout_id,
path,
location,
})
}
/// Returns the immutable rollout ID for a path while preserving legacy noncanonical filenames.
pub(super) fn rollout_id_from_path_or_legacy_thread_id(
path: &std::path::Path,
+28
View File
@@ -1,4 +1,5 @@
use codex_protocol::ThreadId;
use codex_protocol::protocol::SessionMeta;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_protocol::realtime::RealtimeItem;
use codex_rollout::ResponseItemEnvelope;
@@ -287,6 +288,33 @@ pub trait ThreadStore: Any + Send + Sync {
params: LoadThreadHistoryParams,
) -> ThreadStoreFuture<'_, StoredThreadHistory>;
/// Returns canonical session metadata; filesystem stores read only the rollout header.
fn read_session_meta(
&self,
params: LoadThreadHistoryParams,
) -> ThreadStoreFuture<'_, SessionMeta> {
Box::pin(async move {
let thread_id = params.thread_id;
let find_meta = |items: Vec<RolloutItem>| {
items.into_iter().find_map(|item| match item {
RolloutItem::SessionMeta(meta) if meta.meta.id == thread_id => Some(meta.meta),
_ => None,
})
};
match self.load_latest_model_context(params.clone()).await {
Ok(context) => {
if let Some(meta) = find_meta(context.items) {
return Ok(meta);
}
}
Err(ThreadStoreError::Unsupported { .. }) => {}
Err(err) => return Err(err),
}
find_meta(self.load_history(params).await?.items)
.ok_or(ThreadStoreError::ThreadNotFound { thread_id })
})
}
/// Loads one logical call from authoritative persisted history. Separated-frame stores
/// must override this method to include their frame table; a lagging projection must fail
/// rather than report that the session is absent.