Preserve thread-local model ID state across replay and compaction (#60942)

## What changed

- Initialize item and context-window ID generators per thread, reuse the stored window on resume, and give history reconstruction a separate item generator.
- Recover item ordinals from checkpoint replacement history, guardian history, and retained context without lowering the cursor established by earlier records.
- Stamp compaction resume metadata with the next item ordinal in append order, tracking the cursor in local and in-memory thread stores.

## Testing

Extend the history ordinal test to verify that a checkpoint records the cursor at its position in a batch, excluding later allocations.

GitOrigin-RevId: 7121b747a039dc5477235078702137d1ff74e789
This commit is contained in:
Ruslan Nigmatullin
2026-11-12 00:27:01 +00:00
committed by copyberry
parent c93732887e
commit 77cbcdb4a6
19 changed files with 227 additions and 112 deletions
+12 -6
View File
@@ -665,16 +665,22 @@ impl InMemoryThreadStore {
}
let mut state = self.state.lock().await;
let history_mode = history_mode_from_state(&state, params.thread_id);
let persisted_items = into_persisted_rollout_items(params.items, history_mode);
let mut persisted_items = into_persisted_rollout_items(params.items, history_mode);
if persisted_items.is_empty() {
return Ok(());
}
state.calls.append_items += 1;
state
.histories
.entry(params.thread_id)
.or_default()
.extend(persisted_items);
let history = state.histories.entry(params.thread_id).or_default();
if persisted_items
.iter()
.any(|item| matches!(item, RolloutItem::Compacted(_)))
{
codex_rollout::stamp_item_ordinals(
codex_rollout::next_model_id_ordinals(history).0,
&mut persisted_items,
);
}
history.extend(persisted_items);
Ok(())
}
+31 -30
View File
@@ -28,6 +28,15 @@ pub(super) async fn create_thread(
params: CreateThreadParams,
) -> ThreadStoreResult<()> {
let thread_id = params.thread_id;
let inherited_cursor = if params.initial_window_id.allocation().is_some()
&& let (Some(parent), Some(base)) = (params.forked_from_id, params.history_base)
{
let lineage = store.resolve_rollout_lineage_for_reference(parent).await?;
let prefix = super::model_context::load_for_fork(lineage, Some(base)).await?;
codex_rollout::next_model_id_ordinals(&prefix).0
} else {
0
};
let attachment = if params.attached_thread {
let parent = params
.forked_from_id
@@ -53,7 +62,7 @@ pub(super) async fn create_thread(
} else {
None
};
let _live_writer_guard = store.live_writer_locks.lock(thread_id).await;
let mut cursor = 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)?;
@@ -69,14 +78,16 @@ pub(super) async fn create_thread(
}
store
.insert_live_recorder(thread_id, recorder, thread_id, history_mode, writer_lock)
.await
.await?;
*cursor = inherited_cursor;
Ok(())
}
pub(super) async fn resume_thread(
store: &LocalThreadStore,
params: ResumeThreadParams,
) -> ThreadStoreResult<Arc<Vec<RolloutItem>>> {
let _live_writer_guard = store.live_writer_locks.lock(params.thread_id).await;
let mut cursor = store.live_writer_locks.lock(params.thread_id).await;
store.ensure_live_recorder_absent(params.thread_id).await?;
let writer_lock = store.acquire_writer_lock(params.thread_id)?;
let rollout_path = match params.rollout_path {
@@ -167,6 +178,7 @@ pub(super) async fn resume_thread(
writer_lock,
)
.await?;
*cursor = codex_rollout::next_model_id_ordinals(&history).0;
Ok(history)
}
@@ -420,27 +432,30 @@ async fn write_and_project(
// Every live write should have a recorder: create/resume installs one, while
// shutdown/discard/delete removes it. Keep the lookup defensive so late writes fail after
// teardown.
let _live_writer_guard = store.live_writer_locks.lock(thread_id).await;
let mut cursor = store.live_writer_locks.lock(thread_id).await;
let (recorder, rollout_id, history_mode) = live_writer_parts(store, thread_id).await?;
let sync_rollout_path = matches!(&write_op, RolloutWriteOp::Persist | RolloutWriteOp::Flush);
let write_op = match write_op {
match write_op {
RolloutWriteOp::AppendItems(items) => {
let items = into_persisted_rollout_items(items, history_mode);
let mut items = into_persisted_rollout_items(items, history_mode);
if items.is_empty() {
return Ok(());
}
RolloutWriteOp::AppendItems(items)
let next = codex_rollout::stamp_item_ordinals(*cursor, &mut items);
recorder
.record_canonical_items(&items)
.await
.map_err(thread_store_io_error)?;
// Once queued, the recorder owns the batch even if flush is cancelled or retried.
*cursor = next;
recorder.flush().await.map_err(thread_store_io_error)?;
}
RolloutWriteOp::Persist => RolloutWriteOp::Persist,
RolloutWriteOp::Flush => RolloutWriteOp::Flush,
};
if matches!(history_mode, ThreadHistoryMode::Legacy) {
durable_write(&recorder, write_op).await?;
} else {
RolloutWriteOp::Persist => recorder.persist().await.map_err(thread_store_io_error)?,
RolloutWriteOp::Flush => recorder.flush().await.map_err(thread_store_io_error)?,
}
if matches!(history_mode, ThreadHistoryMode::Paginated) {
// SQLite is a rebuildable view and must never get ahead of canonical history.
let rollout_path = recorder.rollout_path();
// SQLite is a rebuildable view. The flush barrier must win before projection starts so it
// can lag JSONL after failure, but can never get ahead of canonical history.
durable_write(&recorder, write_op).await?;
if let Err(err) = super::thread_history_materialization::materialize_to_sqlite(
store,
rollout_id,
@@ -456,17 +471,3 @@ async fn write_and_project(
}
Ok(())
}
async fn durable_write(recorder: &RolloutRecorder, write: RolloutWriteOp) -> ThreadStoreResult<()> {
match write {
RolloutWriteOp::AppendItems(items) => {
recorder
.record_canonical_items(items.as_slice())
.await
.map_err(thread_store_io_error)?;
recorder.flush().await.map_err(thread_store_io_error)
}
RolloutWriteOp::Persist => recorder.persist().await.map_err(thread_store_io_error),
RolloutWriteOp::Flush => recorder.flush().await.map_err(thread_store_io_error),
}
}
+3 -3
View File
@@ -187,8 +187,8 @@ struct LiveWriterLocks {
#[derive(Default)]
struct ThreadCoordination {
// Serialize writes and capture consistent fork snapshots.
writer: Arc<Mutex<()>>,
// Serializes writes and holds the next item ordinal observed in this writer’s rollout.
writer: Arc<Mutex<u64>>,
// Forks hold a shared lease until their child reference is durable; deletion, archive, and
// unarchive require exclusive access. Keeping this separate from `writer` lets the source
// accept writes during child initialization, including MCP startup that can take 30 seconds.
@@ -206,7 +206,7 @@ impl LiveWriterLocks {
.clone()
}
async fn lock(&self, thread_id: ThreadId) -> OwnedMutexGuard<()> {
async fn lock(&self, thread_id: ThreadId) -> OwnedMutexGuard<u64> {
self.coordination(thread_id)
.await
.writer
@@ -85,7 +85,7 @@ struct MigrationLocks {
_maintenance: Option<Arc<RolloutMaintenanceGuard>>,
_writer: WriterLockGuard,
// Let local writers proceed only after releasing the cross-process locks.
_live_writer: OwnedMutexGuard<()>,
_live_writer: OwnedMutexGuard<u64>,
}
enum CanonicalizationAttempt {