Advance thread updatedAt only at turn start

This commit is contained in:
Jeremy Rose
2026-06-11 15:19:40 -07:00
parent 387adc6c4b
commit aaef719ae9
13 changed files with 173 additions and 132 deletions
+2
View File
@@ -356,6 +356,8 @@ Like `thread/resume`, experimental clients can pass `excludeTurns: true` to `thr
- `cursor` — opaque string from a prior response; omit for the first page.
- `limit` — server defaults to a reasonable page size if unset.
- `sortKey` — `created_at` (default) or `updated_at`.
- `updatedAt` is initialized when the thread is created and advances when a turn starts. Persisted
output and turn completion do not advance it.
- `sortDirection` — `desc` (default) or `asc`.
- `modelProviders` — restrict results to specific providers; unset, null, or an empty array will include all providers.
- `sourceKinds` — restrict results to specific sources; omit or pass `[]` for interactive sessions only (`cli`, `vscode`).
@@ -2199,9 +2199,25 @@ async fn thread_resume_defers_updated_at_until_turn_start() -> Result<()> {
.await??;
let ThreadResumeResponse { thread, .. } = to_response::<ThreadResumeResponse>(resume_resp)?;
assert_eq!(thread.updated_at, before_resume.updated_at);
assert_eq!(thread.status, ThreadStatus::Idle);
let read_id = mcp
.send_thread_read_request(ThreadReadParams {
thread_id: thread_id.clone(),
include_turns: false,
})
.await?;
let read_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(read_id)),
)
.await??;
let ThreadReadResponse {
thread: after_resume,
..
} = to_response::<ThreadReadResponse>(read_resp)?;
assert_eq!(after_resume.updated_at, before_resume.updated_at);
let after_modified = std::fs::metadata(&rollout.rollout_file_path)?.modified()?;
assert_eq!(after_modified, rollout.before_modified);
+1 -3
View File
@@ -497,7 +497,6 @@ pub async fn reconcile_rollout(
items,
"reconcile_rollout",
new_thread_memory_mode,
/*updated_at_override*/ None,
)
.await;
return;
@@ -623,7 +622,6 @@ pub async fn apply_rollout_items(
items: &[RolloutItem],
stage: &str,
new_thread_memory_mode: Option<&str>,
updated_at_override: Option<DateTime<Utc>>,
) {
let Some(ctx) = context else {
return;
@@ -648,7 +646,7 @@ pub async fn apply_rollout_items(
builder.rollout_path = rollout_path.to_path_buf();
builder.cwd = normalize_cwd_for_state_db(&builder.cwd);
if let Err(err) = ctx
.apply_rollout_items(&builder, items, new_thread_memory_mode, updated_at_override)
.apply_rollout_items(&builder, items, new_thread_memory_mode)
.await
{
warn!(
-1
View File
@@ -9,7 +9,6 @@ mod extract;
pub mod log_db;
mod migrations;
mod model;
mod paths;
mod runtime;
mod telemetry;
-9
View File
@@ -1,9 +0,0 @@
use chrono::DateTime;
use chrono::Utc;
use std::path::Path;
pub(crate) async fn file_modified_time_utc(path: &Path) -> Option<DateTime<Utc>> {
let modified = tokio::fs::metadata(path).await.ok()?.modified().ok()?;
let updated_at: DateTime<Utc> = modified.into();
Some(updated_at)
}
-1
View File
@@ -27,7 +27,6 @@ use crate::model::anchor_from_item;
use crate::model::datetime_to_epoch_millis;
use crate::model::datetime_to_epoch_seconds;
use crate::model::epoch_millis_to_datetime;
use crate::paths::file_modified_time_utc;
use crate::telemetry::DbKind;
use crate::telemetry::DbTelemetry;
use chrono::DateTime;
+17 -39
View File
@@ -680,7 +680,7 @@ WHERE id = ?
metadata: &crate::ThreadMetadata,
creation_memory_mode: Option<&str>,
) -> anyhow::Result<()> {
let updated_at = self.allocate_thread_updated_at(metadata.updated_at)?;
let insert_updated_at = self.allocate_thread_updated_at(metadata.updated_at)?;
let preview = metadata_preview(metadata);
// Backfill/reconcile callers merge existing git info before upserting, but that
// read/modify/write is not atomic. Preserve non-null SQLite git fields here so
@@ -720,9 +720,9 @@ INSERT INTO threads (
ON CONFLICT(id) DO UPDATE SET
rollout_path = excluded.rollout_path,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
updated_at = threads.updated_at,
created_at_ms = excluded.created_at_ms,
updated_at_ms = excluded.updated_at_ms,
updated_at_ms = threads.updated_at_ms,
source = excluded.source,
thread_source = excluded.thread_source,
agent_nickname = excluded.agent_nickname,
@@ -749,9 +749,9 @@ ON CONFLICT(id) DO UPDATE SET
.bind(metadata.id.to_string())
.bind(metadata.rollout_path.display().to_string())
.bind(datetime_to_epoch_seconds(metadata.created_at))
.bind(datetime_to_epoch_seconds(updated_at))
.bind(datetime_to_epoch_seconds(insert_updated_at))
.bind(datetime_to_epoch_millis(metadata.created_at))
.bind(datetime_to_epoch_millis(updated_at))
.bind(datetime_to_epoch_millis(insert_updated_at))
.bind(metadata.source.as_str())
.bind(
metadata
@@ -797,7 +797,6 @@ ON CONFLICT(id) DO UPDATE SET
builder: &ThreadMetadataBuilder,
items: &[RolloutItem],
new_thread_memory_mode: Option<&str>,
updated_at_override: Option<DateTime<Utc>>,
) -> anyhow::Result<()> {
if items.is_empty() {
return Ok(());
@@ -813,13 +812,6 @@ ON CONFLICT(id) DO UPDATE SET
if let Some(existing_metadata) = existing_metadata.as_ref() {
metadata.prefer_existing_git_info(existing_metadata);
}
let updated_at = match updated_at_override {
Some(updated_at) => Some(updated_at),
None => file_modified_time_utc(builder.rollout_path.as_path()).await,
};
if let Some(updated_at) = updated_at {
metadata.updated_at = updated_at;
}
let upsert_result = if existing_metadata.is_none() {
self.upsert_thread_with_creation_memory_mode(&metadata, new_thread_memory_mode)
.await
@@ -849,9 +841,6 @@ ON CONFLICT(id) DO UPDATE SET
};
metadata.archived_at = Some(archived_at);
metadata.rollout_path = rollout_path.to_path_buf();
if let Some(updated_at) = file_modified_time_utc(rollout_path).await {
metadata.updated_at = updated_at;
}
if metadata.id != thread_id {
warn!(
"thread id mismatch during archive: expected {thread_id}, got {}",
@@ -872,9 +861,6 @@ ON CONFLICT(id) DO UPDATE SET
};
metadata.archived_at = None;
metadata.rollout_path = rollout_path.to_path_buf();
if let Some(updated_at) = file_modified_time_utc(rollout_path).await {
metadata.updated_at = updated_at;
}
if metadata.id != thread_id {
warn!(
"thread id mismatch during unarchive: expected {thread_id}, got {}",
@@ -1773,10 +1759,7 @@ mod tests {
})];
runtime
.apply_rollout_items(
&builder, &items, /*new_thread_memory_mode*/ None,
/*updated_at_override*/ None,
)
.apply_rollout_items(&builder, &items, /*new_thread_memory_mode*/ None)
.await
.expect("apply_rollout_items should succeed");
@@ -1838,10 +1821,7 @@ mod tests {
})];
runtime
.apply_rollout_items(
&builder, &items, /*new_thread_memory_mode*/ None,
/*updated_at_override*/ None,
)
.apply_rollout_items(&builder, &items, /*new_thread_memory_mode*/ None)
.await
.expect("apply_rollout_items should succeed");
@@ -2142,13 +2122,19 @@ mod tests {
.expect("touch should succeed");
assert!(touched);
metadata.title = "title from stale snapshot".to_string();
runtime
.upsert_thread(&metadata)
.await
.expect("stale metadata upsert should succeed");
let persisted = runtime
.get_thread(thread_id)
.await
.expect("thread should load")
.expect("thread should exist");
assert_eq!(persisted.updated_at, touched_at);
assert_eq!(persisted.title, "original title");
assert_eq!(persisted.title, "title from stale snapshot");
assert_eq!(
persisted.first_user_message.as_deref(),
Some("first-user-message")
@@ -2255,7 +2241,7 @@ mod tests {
}
#[tokio::test]
async fn apply_rollout_items_uses_override_updated_at_when_provided() {
async fn apply_rollout_items_does_not_advance_updated_at() {
let codex_home = unique_temp_dir();
let runtime = StateRuntime::init(codex_home.clone(), "test-provider".to_string())
.await
@@ -2291,16 +2277,8 @@ mod tests {
rate_limits: None,
},
))];
let override_updated_at =
DateTime::<Utc>::from_timestamp(1_700_001_234, 0).expect("timestamp");
runtime
.apply_rollout_items(
&builder,
&items,
/*new_thread_memory_mode*/ None,
Some(override_updated_at),
)
.apply_rollout_items(&builder, &items, /*new_thread_memory_mode*/ None)
.await
.expect("apply_rollout_items should succeed");
@@ -2310,7 +2288,7 @@ mod tests {
.expect("thread should load")
.expect("thread should exist");
assert_eq!(persisted.tokens_used, 321);
assert_eq!(persisted.updated_at, override_updated_at);
assert_eq!(persisted.updated_at, metadata.updated_at);
}
#[tokio::test]
@@ -173,5 +173,6 @@ mod tests {
.expect("thread metadata should exist");
assert_eq!(updated.rollout_path, archived_path);
assert!(updated.archived_at.is_some());
assert_eq!(updated.updated_at, metadata.updated_at);
}
}
+78
View File
@@ -302,10 +302,16 @@ mod tests {
use codex_protocol::ThreadId;
use codex_protocol::models::BaseInstructions;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::MessagePhase;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::AgentMessageEvent;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::ThreadMemoryMode;
use codex_protocol::protocol::TurnCompleteEvent;
use codex_protocol::protocol::TurnStartedEvent;
use codex_protocol::protocol::UserMessageEvent;
use tempfile::TempDir;
@@ -437,6 +443,78 @@ mod tests {
assert_eq!(metadata.title, "observed append");
}
#[tokio::test]
async fn live_thread_output_does_not_advance_updated_at() {
let home = TempDir::new().expect("temp dir");
let config = test_config(home.path());
let runtime = codex_state::StateRuntime::init(
config.sqlite_home.clone(),
config.default_model_provider_id.clone(),
)
.await
.expect("state db should initialize");
let store = Arc::new(LocalThreadStore::new(config, Some(runtime.clone())));
let thread_id = ThreadId::default();
let live_thread = LiveThread::create(store, create_thread_params(thread_id))
.await
.expect("create live thread");
live_thread
.append_items(&[RolloutItem::EventMsg(EventMsg::TurnStarted(
TurnStartedEvent {
turn_id: "turn-1".to_string(),
trace_id: None,
started_at: None,
model_context_window: None,
collaboration_mode_kind: Default::default(),
},
))])
.await
.expect("append turn start");
live_thread.flush().await.expect("flush thread");
let after_turn_start = runtime
.get_thread(thread_id)
.await
.expect("sqlite metadata read")
.expect("sqlite metadata")
.updated_at;
live_thread
.append_items(&[
RolloutItem::EventMsg(EventMsg::AgentMessage(AgentMessageEvent {
message: "commentary".to_string(),
phase: Some(MessagePhase::Commentary),
memory_citation: None,
})),
RolloutItem::ResponseItem(ResponseItem::FunctionCallOutput {
call_id: "call-1".to_string(),
output: FunctionCallOutputPayload::from_text("tool output".to_string()),
}),
RolloutItem::EventMsg(EventMsg::TokenCount(
codex_protocol::protocol::TokenCountEvent {
info: None,
rate_limits: None,
},
)),
RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent {
turn_id: "turn-1".to_string(),
last_agent_message: None,
completed_at: None,
duration_ms: None,
time_to_first_token_ms: None,
})),
])
.await
.expect("append post-start items");
live_thread.flush().await.expect("flush thread");
let completed = runtime
.get_thread(thread_id)
.await
.expect("sqlite metadata read")
.expect("sqlite metadata");
assert_eq!(completed.updated_at, after_turn_start);
}
#[tokio::test]
async fn live_thread_shutdown_does_not_materialize_empty_thread_metadata() {
let home = TempDir::new().expect("temp dir");
@@ -55,6 +55,7 @@ pub(super) async fn read_thread(
&& (params.include_archived || rollout_thread.archived_at.is_none())
&& !rollout_thread.preview.is_empty()
{
rollout_thread.updated_at = thread.updated_at;
if thread.name.is_some() {
rollout_thread.name = thread.name;
}
@@ -196,5 +196,6 @@ mod tests {
.expect("thread metadata should exist");
assert_eq!(updated.rollout_path, restored_path);
assert_eq!(updated.archived_at, None);
assert_eq!(updated.updated_at, metadata.updated_at);
}
}
@@ -204,6 +204,7 @@ async fn apply_metadata_update(
.map_err(|err| ThreadStoreError::Internal {
message: format!("failed to read thread metadata for {thread_id}: {err}"),
})?;
let advance_updated_at = patch.updated_at.filter(|_| existing.is_some());
if existing.is_none() && rollout_path.is_none() {
let resolved = resolve_rollout_path(store, thread_id, include_archived).await?;
rollout_path_archived = resolved.archived;
@@ -257,7 +258,9 @@ async fn apply_metadata_update(
if let Some(created_at) = patch.created_at {
metadata.created_at = created_at;
}
if let Some(updated_at) = patch.updated_at {
if existing.is_none()
&& let Some(updated_at) = patch.updated_at
{
metadata.updated_at = updated_at;
}
if let Some(source) = patch.source {
@@ -310,6 +313,16 @@ async fn apply_metadata_update(
.map_err(|err| ThreadStoreError::Internal {
message: format!("failed to update thread metadata for {thread_id}: {err}"),
})?;
if let Some(updated_at) = advance_updated_at {
state_db
.touch_thread_updated_at(thread_id, updated_at)
.await
.map_err(|err| ThreadStoreError::Internal {
message: format!(
"failed to advance thread updated_at for {thread_id}: {err}"
),
})?;
}
if let Some(memory_mode) = patch.memory_mode {
state_db
.set_thread_memory_mode(thread_id, memory_mode_as_str(memory_mode))
@@ -1,6 +1,3 @@
use std::time::Duration;
use std::time::Instant;
use chrono::DateTime;
use chrono::NaiveDateTime;
use chrono::Utc;
@@ -20,11 +17,6 @@ use crate::ResumeThreadParams;
use crate::ThreadMetadataPatch;
const IMAGE_ONLY_USER_MESSAGE_PLACEHOLDER: &str = "[Image]";
#[cfg(not(test))]
const THREAD_UPDATED_AT_TOUCH_INTERVAL: Duration = Duration::from_secs(5);
#[cfg(test)]
const THREAD_UPDATED_AT_TOUCH_INTERVAL: Duration = Duration::from_millis(50);
/// Live-thread helper that derives metadata updates from canonical rollout items.
///
/// Stores receive raw history plus explicit metadata patches. This helper keeps append-derived
@@ -38,7 +30,6 @@ pub(crate) struct ThreadMetadataSync {
title_seen: bool,
pending_update: Option<ThreadMetadataPatch>,
pending_update_generation: u64,
last_touch_persisted_at: Option<Instant>,
defer_create_update_until_history_exists: bool,
defer_resume_update_until_append: bool,
}
@@ -84,7 +75,6 @@ impl ThreadMetadataSync {
title_seen: false,
pending_update: Some(update),
pending_update_generation: 1,
last_touch_persisted_at: None,
defer_create_update_until_history_exists: true,
defer_resume_update_until_append: false,
}
@@ -103,7 +93,6 @@ impl ThreadMetadataSync {
title_seen: false,
pending_update: None,
pending_update_generation: 0,
last_touch_persisted_at: None,
defer_create_update_until_history_exists: false,
defer_resume_update_until_append: false,
};
@@ -140,9 +129,6 @@ impl ThreadMetadataSync {
if self.pending_update_generation == update.generation {
self.pending_update = None;
}
if update.patch.updated_at.is_some() {
self.last_touch_persisted_at = Some(Instant::now());
}
}
pub(crate) fn observe_appended_items(
@@ -154,31 +140,32 @@ impl ThreadMetadataSync {
let affects_metadata = items
.iter()
.any(codex_state::rollout_item_affects_thread_metadata);
let advances_updated_at = items
.iter()
.any(|item| matches!(item, RolloutItem::EventMsg(EventMsg::TurnStarted(_))));
let update = if affects_metadata {
self.observe_items(items)?
} else {
thread_updated_at_touch()
};
self.merge_pending_update(Some(update));
if !affects_metadata
&& !self
.pending_update
.as_ref()
.is_some_and(update_has_metadata_facts)
&& self.last_touch_persisted_at.is_some_and(|last_touch| {
Instant::now().duration_since(last_touch) < THREAD_UPDATED_AT_TOUCH_INTERVAL
self.observe_items(items, advances_updated_at)
} else if advances_updated_at {
Some(ThreadMetadataPatch {
updated_at: Some(Utc::now()),
..Default::default()
})
{
return None;
}
} else {
None
};
self.merge_pending_update(update);
self.take_pending_update()
}
fn observe_items(&mut self, items: &[RolloutItem]) -> Option<ThreadMetadataPatch> {
fn observe_items(
&mut self,
items: &[RolloutItem],
advances_updated_at: bool,
) -> Option<ThreadMetadataPatch> {
self.observe_items_with_update(
items,
ThreadMetadataPatch {
updated_at: Some(Utc::now()),
updated_at: advances_updated_at.then(Utc::now),
..Default::default()
},
)
@@ -331,36 +318,6 @@ fn user_message_preview(user: &UserMessageEvent) -> Option<String> {
None
}
fn thread_updated_at_touch() -> ThreadMetadataPatch {
ThreadMetadataPatch {
updated_at: Some(Utc::now()),
..Default::default()
}
}
fn update_has_metadata_facts(update: &ThreadMetadataPatch) -> bool {
update.rollout_path.is_some()
|| update.preview.is_some()
|| update.title.is_some()
|| update.model_provider.is_some()
|| update.model.is_some()
|| update.reasoning_effort.is_some()
|| update.created_at.is_some()
|| update.source.is_some()
|| update.thread_source.is_some()
|| update.agent_nickname.is_some()
|| update.agent_role.is_some()
|| update.agent_path.is_some()
|| update.cwd.is_some()
|| update.cli_version.is_some()
|| update.approval_mode.is_some()
|| update.permission_profile.is_some()
|| update.token_usage.is_some()
|| update.first_user_message.is_some()
|| update.git_info.is_some()
|| update.memory_mode.is_some()
}
fn git_info_patch_from_observation(git_info: GitInfo) -> GitInfoPatch {
GitInfoPatch {
sha: git_info.commit_hash.map(|sha| Some(sha.0)),
@@ -378,6 +335,7 @@ mod tests {
use codex_protocol::protocol::ThreadGoal;
use codex_protocol::protocol::ThreadGoalStatus;
use codex_protocol::protocol::ThreadGoalUpdatedEvent;
use codex_protocol::protocol::TurnStartedEvent;
use codex_protocol::protocol::UserMessageEvent;
use pretty_assertions::assert_eq;
@@ -464,11 +422,11 @@ mod tests {
assert_eq!(update.patch.preview, None);
assert_eq!(update.patch.title, None);
assert_eq!(update.patch.first_user_message, None);
assert!(update.patch.updated_at.is_some());
assert_eq!(update.patch.updated_at, None);
}
#[test]
fn metadata_irrelevant_items_coalesce_updated_at_touches() {
fn metadata_irrelevant_items_do_not_advance_updated_at() {
let thread_id = ThreadId::new();
let mut sync = ThreadMetadataSync::for_resume(&resume_params(thread_id, Vec::new()));
let item = RolloutItem::Compacted(CompactedItem {
@@ -477,21 +435,27 @@ mod tests {
window_id: None,
});
let first = sync
.observe_appended_items(std::slice::from_ref(&item))
.expect("first touch should apply immediately");
assert!(first.patch.updated_at.is_some());
sync.mark_pending_update_applied(&first);
assert!(sync.observe_appended_items(&[item]).is_none());
}
assert!(
sync.observe_appended_items(std::slice::from_ref(&item))
.is_none(),
"second touch inside the coalescing window should wait for a barrier"
);
assert!(
sync.take_pending_update().is_some(),
"coalesced touches still flush at the next barrier"
);
#[test]
fn turn_start_advances_updated_at() {
let thread_id = ThreadId::new();
let mut sync = ThreadMetadataSync::for_resume(&resume_params(thread_id, Vec::new()));
let update = sync
.observe_appended_items(&[RolloutItem::EventMsg(EventMsg::TurnStarted(
TurnStartedEvent {
turn_id: "turn-1".to_string(),
trace_id: None,
started_at: None,
model_context_window: None,
collaboration_mode_kind: Default::default(),
},
))])
.expect("turn start should produce a metadata update");
assert!(update.patch.updated_at.is_some());
}
#[test]