Add experimental attached thread forks (#56351)

## What changed

- Add `attachToSource` to `thread/fork` to persist a fork attached to its source without emitting `thread/started`. Attached forks require local storage and cannot use `ephemeral` or `deferGoalContinuation`.
- Hide attached threads from ordinary listings and add `attachedToThreadId` to `thread/list` for explicit discovery, including empty threads. Keep this relationship separate from spawned-agent parent and ancestor filters.
- Persist attachment metadata in rollouts and SQLite so it survives restarts and database recovery. Reject source deletion until its attached threads are deleted.

## Testing

Add coverage for legacy and paginated history, restart and missing or corrupt database recovery, filtered listings and pagination, resume, conflicting options, and deletion safeguards across store instances.

GitOrigin-RevId: 589f3174fc36f6054e75d65818360695645a5913
This commit is contained in:
Brent Traut
2026-10-23 04:52:47 +00:00
committed by copyberry
parent 4610b573e5
commit 30587d7885
70 changed files with 1078 additions and 68 deletions
@@ -41,6 +41,7 @@ pub(super) async fn create_thread(
)
.with_creator(params.creator_user_id, params.creator_account_id)
.with_session_id(params.session_id)
.with_attached_thread(params.attached_thread)
.with_selected_capability_roots(params.selected_capability_roots)
.with_runtime_workspace_roots(params.runtime_workspace_roots.map(|roots| {
roots
@@ -12,6 +12,7 @@ use std::io::ErrorKind;
use std::path::Path;
use std::path::PathBuf;
use codex_protocol::ThreadId;
use codex_rollout::ARCHIVED_SESSIONS_SUBDIR;
use codex_rollout::RolloutReferenceIndex;
use codex_rollout::SESSIONS_SUBDIR;
@@ -33,6 +34,32 @@ struct ThreadRollouts {
paths: Vec<PathBuf>,
}
impl LocalThreadStore {
/// Reject deletion while any candidate has attached threads. Call before stopping live work;
/// deletion repeats this check under existing writer ownership to cover concurrent creation.
pub async fn ensure_no_attached_threads(
&self,
thread_ids: &[ThreadId],
) -> ThreadStoreResult<()> {
let reference_index = scan_reference_index(self).await?;
check_attached_children(&reference_index, thread_ids)
}
}
fn check_attached_children(
reference_index: &RolloutReferenceIndex,
thread_ids: &[ThreadId],
) -> ThreadStoreResult<()> {
let Some(child) = reference_index.attached_child(thread_ids) else {
return Ok(());
};
Err(ThreadStoreError::InvalidRequest {
message: format!(
"cannot delete thread while attached thread {child} exists; delete the attached thread first"
),
})
}
impl ThreadRollouts {
fn from_index(
reference_index: &RolloutReferenceIndex,
@@ -70,10 +97,11 @@ pub(super) async fn delete_thread(
let thread_id = params.thread_id;
let _lifecycle_guard = store.live_writer_locks.lock_lifecycle(thread_id).await;
let _live_writer_guard = store.live_writer_locks.lock(thread_id).await;
let mut writer_guards = store.acquire_writer_locks(&[thread_id]).await?;
let reference_index = scan_reference_index(store).await?;
let thread_rollouts = ThreadRollouts::from_index(&reference_index, thread_id);
check_attached_children(&reference_index, &[thread_id])?;
ensure_no_external_references(&reference_index, std::slice::from_ref(&thread_rollouts))?;
let mut writer_guards = store.acquire_writer_locks(&[thread_id]).await?;
if let Some(cleanup) = &store.thread_data_cleanup {
cleanup(vec![thread_id]).await?;
}
@@ -113,14 +141,14 @@ pub(super) async fn delete_threads(
_live_writer_guards.push(store.live_writer_locks.lock(thread_id).await);
}
let mut writer_guards = store.acquire_writer_locks(&lock_thread_ids).await?;
let reference_index = scan_reference_index(store).await?;
let thread_rollouts = thread_ids
.iter()
.map(|thread_id| ThreadRollouts::from_index(&reference_index, *thread_id))
.collect::<Vec<_>>();
check_attached_children(&reference_index, &lock_thread_ids)?;
ensure_no_external_references(&reference_index, thread_rollouts.as_slice())?;
let mut writer_guards = store.acquire_writer_locks(&lock_thread_ids).await?;
if let Some(cleanup) = &store.thread_data_cleanup {
cleanup(thread_ids.clone()).await?;
}
@@ -136,7 +164,7 @@ pub(super) async fn delete_threads(
Ok(())
}
async fn delete_state_rows(
pub(super) async fn delete_state_rows(
store: &LocalThreadStore,
thread_ids: &[codex_protocol::ThreadId],
) -> ThreadStoreResult<u64> {
@@ -272,7 +300,10 @@ async fn delete_thread_after_reference_check(
Ok(())
}
fn delete_rollout_file(store: &LocalThreadStore, rollout_path: &Path) -> ThreadStoreResult<bool> {
pub(super) fn delete_rollout_file(
store: &LocalThreadStore,
rollout_path: &Path,
) -> ThreadStoreResult<bool> {
let plain_path = codex_rollout::plain_rollout_path(rollout_path);
let compressed_path = plain_path.with_extension("jsonl.zst");
let deleted_plain = delete_rollout_path(store, plain_path.as_path())?;
+18 -27
View File
@@ -198,23 +198,10 @@ async fn list_section_threads(
},
search_term: params.search_term.as_deref(),
};
let page = match params.relation_filter {
Some(ThreadRelationFilter::DirectChildrenOf(thread_id)) => {
let page = match params.relation_filter.map(state_relation_filter) {
Some(relation_filter) => {
state_db
.list_threads_by_relation(
params.page_size,
codex_state::ThreadRelationFilter::DirectChildrenOf(thread_id),
filters,
)
.await
}
Some(ThreadRelationFilter::DescendantsOf(thread_id)) => {
state_db
.list_threads_by_relation(
params.page_size,
codex_state::ThreadRelationFilter::DescendantsOf(thread_id),
filters,
)
.list_threads_by_relation(params.page_size, relation_filter, filters)
.await
}
None => state_db.list_threads(params.page_size, filters).await,
@@ -255,16 +242,6 @@ pub(super) async fn list_rollout_threads(
sort_direction: codex_rollout::SortDirection,
) -> ThreadStoreResult<codex_rollout::ThreadsPage> {
if params.relation_filter.is_some() || params.section.is_some() || params.project_id.is_some() {
let relation_filter = params
.relation_filter
.map(|relation_filter| match relation_filter {
ThreadRelationFilter::DirectChildrenOf(parent_thread_id) => {
codex_state::ThreadRelationFilter::DirectChildrenOf(parent_thread_id)
}
ThreadRelationFilter::DescendantsOf(ancestor_thread_id) => {
codex_state::ThreadRelationFilter::DescendantsOf(ancestor_thread_id)
}
});
let page = codex_rollout::state_db::list_threads_db(
state_db.as_deref(),
&config.sqlite,
@@ -275,7 +252,7 @@ pub(super) async fn list_rollout_threads(
params.allowed_sources.as_slice(),
params.model_providers.as_deref(),
params.cwd_filters.as_deref(),
relation_filter,
params.relation_filter.map(state_relation_filter),
params.archived,
params.section.as_ref().map(Option::as_deref),
params.project_id.as_ref().map(Option::as_deref),
@@ -354,6 +331,20 @@ pub(super) async fn list_rollout_threads(
})
}
fn state_relation_filter(filter: ThreadRelationFilter) -> codex_state::ThreadRelationFilter {
match filter {
ThreadRelationFilter::DirectChildrenOf(id) => {
codex_state::ThreadRelationFilter::DirectChildrenOf(id)
}
ThreadRelationFilter::DescendantsOf(id) => {
codex_state::ThreadRelationFilter::DescendantsOf(id)
}
ThreadRelationFilter::AttachedThreadsOf(id) => {
codex_state::ThreadRelationFilter::AttachedThreadsOf(id)
}
}
}
#[cfg(test)]
mod tests {
use chrono::Utc;
@@ -28,11 +28,45 @@ pub(super) async fn create_thread(
params: CreateThreadParams,
) -> ThreadStoreResult<()> {
let thread_id = params.thread_id;
let attachment = if params.attached_thread {
let parent = params
.forked_from_id
.filter(|parent| *parent != thread_id)
.ok_or_else(|| ThreadStoreError::InvalidRequest {
message: "attached threads require a distinct fork source".to_string(),
})?;
let state = store
.state_db
.as_ref()
.ok_or(ThreadStoreError::Unsupported {
operation: "attached_threads",
})?;
// Keep parent deletion out until the child's canonical metadata is durable.
let source_ownership = (
store.live_writer_locks.lock(parent).await,
store.acquire_writer_locks(&[parent]).await?,
);
super::thread_rollout_resolver::resolve_current_including_archived(store, parent)
.await?
.ok_or(ThreadStoreError::ThreadNotFound { thread_id: parent })?;
Some((state, source_ownership))
} else {
None
};
let _live_writer_guard = store.live_writer_locks.lock(thread_id).await;
let history_mode = params.history_mode;
store.ensure_live_recorder_absent(thread_id).await?;
let writer_lock = store.acquire_writer_lock(thread_id)?;
let recorder = create_thread::create_thread(store, params, writer_lock.clone()).await?;
if let Some((state, _source_ownership)) = attachment {
recorder.persist().await.map_err(thread_store_io_error)?;
if let Err(error) = index_attached_thread(store, state, recorder.rollout_path()).await {
recorder.discard().await.map_err(thread_store_io_error)?;
super::delete_thread::delete_rollout_file(store, recorder.rollout_path())?;
super::delete_thread::delete_state_rows(store, &[thread_id]).await?;
return Err(error);
}
}
store
.insert_live_recorder(thread_id, recorder, thread_id, history_mode, writer_lock)
.await
@@ -235,6 +269,40 @@ pub(super) async fn discard_thread(
.map_err(thread_store_io_error)
}
async fn index_attached_thread(
store: &LocalThreadStore,
state: &codex_state::StateRuntime,
path: &std::path::Path,
) -> ThreadStoreResult<()> {
let meta = codex_rollout::read_session_meta_line(path)
.await
.map_err(thread_store_io_error)?;
let memory_mode = meta.meta.memory_mode.clone();
let items = [RolloutItem::SessionMeta(Box::new(meta))];
let mut builder = codex_rollout::builder_from_items(&items, path).ok_or_else(|| {
ThreadStoreError::Internal {
message: format!("invalid attached thread metadata at {}", path.display()),
}
})?;
if super::helpers::rollout_path_is_archived(&store.config.codex_home, path) {
builder.archived_at = Some(builder.updated_at.unwrap_or(builder.created_at));
}
state
.apply_rollout_items(
&builder,
&items,
memory_mode.as_deref(),
/*updated_at_override*/ None,
)
.await
.map_err(|err| ThreadStoreError::Internal {
message: format!(
"failed to index attached thread at {}: {err}",
path.display()
),
})
}
pub(super) async fn rollout_path(
store: &LocalThreadStore,
thread_id: ThreadId,
+115
View File
@@ -1602,6 +1602,120 @@ mod tests {
}
}
#[tokio::test]
async fn attached_creation_and_deletion_coordinate_across_stores() {
let home = TempDir::new().expect("temp dir");
let config = test_config(home.path());
let runtime = codex_state::StateRuntime::init(
config.sqlite.clone(),
config.default_model_provider_id.clone(),
)
.await
.expect("initialize state db");
let first = LocalThreadStore::new(config.clone(), Some(runtime.clone()));
let second = LocalThreadStore::new(config, Some(runtime.clone()));
let parent_uuid = uuid::Uuid::new_v4();
let parent = ThreadId::from_u128(parent_uuid.as_u128());
let parent_path = write_session_file(home.path(), "2025-01-03T00-00-00", parent_uuid)
.expect("write parent");
let child = ThreadId::new();
let mut params = create_thread_params(child);
params.attached_thread = true;
assert!(matches!(
second.create_thread(params.clone()).await,
Err(ThreadStoreError::InvalidRequest { .. })
));
params.forked_from_id = Some(parent);
let parent_guard = first.acquire_writer_lock(parent).expect("lock parent");
assert!(matches!(
second.create_thread(params.clone()).await,
Err(ThreadStoreError::Conflict { .. })
));
drop(parent_guard);
let pool = runtime
.sqlite()
.open_read_write_pool(&runtime.sqlite().state_db_path())
.await
.expect("open state db");
sqlx::query(
"CREATE TRIGGER fail_attached_index BEFORE UPDATE OF memory_mode ON threads WHEN NEW.attached_thread_parent_id IS NOT NULL BEGIN SELECT RAISE(ABORT, 'index failed'); END",
)
.execute(&pool)
.await
.expect("inject index failure");
let mut failing_params = params.clone();
failing_params.metadata.memory_mode = ThreadMemoryMode::Disabled;
second
.create_thread(failing_params)
.await
.expect_err("indexing must fail");
first
.ensure_no_attached_threads(&[parent])
.await
.expect("failed creation must not leave an attached rollout");
assert!(
runtime
.get_thread(child)
.await
.expect("read index")
.is_none()
);
sqlx::query("DROP TRIGGER fail_attached_index")
.execute(&pool)
.await
.expect("remove index failure");
second
.create_thread(params.clone())
.await
.expect("create child");
assert_eq!(
runtime
.delete_thread(child)
.await
.expect("remove index row"),
1
);
assert!(matches!(
first
.delete_threads(DeleteThreadsParams {
thread_ids: vec![parent]
})
.await,
Err(ThreadStoreError::InvalidRequest { .. })
));
assert!(
parent_path.exists(),
"refused deletion must preserve parent"
);
second
.discard_thread(child)
.await
.expect("release child writer");
assert!(matches!(
first
.delete_threads(DeleteThreadsParams {
thread_ids: vec![parent]
})
.await,
Err(ThreadStoreError::InvalidRequest { .. })
));
first
.delete_thread(DeleteThreadParams { thread_id: child })
.await
.expect("delete child");
first
.delete_threads(DeleteThreadsParams {
thread_ids: vec![parent],
})
.await
.expect("parent can be deleted after its child");
assert!(!parent_path.exists());
assert!(matches!(
second.create_thread(params).await,
Err(ThreadStoreError::ThreadNotFound { thread_id }) if thread_id == parent
));
}
#[tokio::test]
async fn resume_thread_reopens_live_writer_and_appends_with_stale_sqlite_path() {
let home = TempDir::new().expect("temp dir");
@@ -2246,6 +2360,7 @@ mod tests {
fn create_thread_params(thread_id: ThreadId) -> CreateThreadParams {
CreateThreadParams {
attached_thread: false,
creator_user_id: None,
creator_account_id: None,
session_id: thread_id.into(),
@@ -457,6 +457,7 @@ fn staged_model_patch() -> ThreadMetadataPatch {
fn create_thread_params(thread_id: ThreadId) -> CreateThreadParams {
CreateThreadParams {
attached_thread: false,
creator_user_id: None,
creator_account_id: None,
session_id: thread_id.into(),
@@ -181,6 +181,7 @@ async fn create_replacement_recorder(
)
.with_creator(source_meta.creator_user_id, source_meta.creator_account_id)
.with_session_id(source_meta.session_id)
.with_attached_thread(source_meta.attached_thread)
.with_rollout_id(rollout_id)
.with_selected_capability_roots(source_meta.selected_capability_roots)
.with_runtime_workspace_roots(source_meta.runtime_workspace_roots)
@@ -272,6 +272,7 @@ async fn rollout_paths_for_thread(
async fn create_paginated_thread(store: &LocalThreadStore, thread_id: ThreadId) {
store
.create_thread(CreateThreadParams {
attached_thread: false,
creator_user_id: Some("creator-user".to_string()),
creator_account_id: Some("creator-account".to_string()),
session_id: thread_id.into(),
@@ -754,6 +754,7 @@ async fn paginated_realtime_items_materialize_separately_in_rollout_order() {
let legacy_thread_id = ThreadId::new();
store
.create_thread(CreateThreadParams {
attached_thread: false,
creator_user_id: None,
creator_account_id: None,
session_id: legacy_thread_id.into(),
@@ -3068,6 +3069,7 @@ async fn create_paginated_subagent_thread(
) {
store
.create_thread(CreateThreadParams {
attached_thread: false,
creator_user_id: None,
creator_account_id: None,
session_id: thread_id.into(),
@@ -676,7 +676,9 @@ async fn metadata_for_missing_sqlite_row(
patch.source.clone().unwrap_or(SessionSource::Unknown),
);
builder.model_provider = patch.model_provider.clone();
builder.history_mode = canonical_history_mode(store, thread_id, rollout_path).await?;
let (history_mode, attached_thread_parent_id) =
canonical_history_mode_and_attachment(store, thread_id, rollout_path).await?;
builder.history_mode = history_mode;
builder.thread_source = patch.thread_source.clone().flatten();
builder.agent_nickname = patch.agent_nickname.clone().flatten();
builder.agent_role = patch.agent_role.clone().flatten();
@@ -684,21 +686,25 @@ async fn metadata_for_missing_sqlite_row(
builder.cwd = patch.cwd.clone().map(normalize_cwd).unwrap_or_default();
builder.cli_version = patch.cli_version.clone();
let mut metadata = builder.build(store.config.default_model_provider_id.as_str());
metadata.attached_thread_parent_id = attached_thread_parent_id;
if rollout_path_archived {
metadata.archived_at = Some(metadata.updated_at);
}
Ok(metadata)
}
async fn canonical_history_mode(
async fn canonical_history_mode_and_attachment(
store: &LocalThreadStore,
thread_id: ThreadId,
rollout_path: &Path,
) -> ThreadStoreResult<ThreadHistoryMode> {
) -> ThreadStoreResult<(ThreadHistoryMode, Option<ThreadId>)> {
if let Some((path, meta)) = live_writer::unpersisted_session_meta(store, thread_id).await
&& path == rollout_path
{
return Ok(meta.history_mode);
return Ok((
meta.history_mode,
meta.forked_from_id.filter(|_| meta.attached_thread),
));
}
let session_meta = match read_session_meta_line(rollout_path).await {
Ok(session_meta) => session_meta,
@@ -715,7 +721,7 @@ async fn canonical_history_mode(
{
// The live writer retains the canonical mode selected before its deferred
// SessionMeta reaches JSONL.
return Ok(history_mode);
return Ok((history_mode, None));
}
return Err(ThreadStoreError::Internal {
message: format!(
@@ -732,7 +738,13 @@ async fn canonical_history_mode(
),
});
}
Ok(session_meta.meta.history_mode)
Ok((
session_meta.meta.history_mode,
session_meta
.meta
.forked_from_id
.filter(|_| session_meta.meta.attached_thread),
))
}
fn requires_rollout_compatibility_update(patch: &ThreadMetadataPatch) -> bool {