Batch persistent history reads during reverse search (#33905)

## Why

Reverse search fetched persistent history one entry at a time, making a deep or unsuccessful search require a lookup for every older entry.

## What changed

- Keep the newest-entry probe lightweight, then scan older persistent history in bounded batches.
- Cache batch results by absolute offset and preserve continuation cursors across repeated searches.
- Ignore stale responses, retry failed batch reads a bounded number of times, and restore the draft without reporting a false “no match” state when history is unavailable.

## Testing

- Cover batch continuation, caching after query changes or cancellation, stale metadata, retry exhaustion, and thread routing.
- Verify that scanning 1,024 entries uses one single-entry lookup and eight batch lookups.

GitOrigin-RevId: efc791fcbd5290050af703dd31c5c21b33240e23
This commit is contained in:
Charlie Marsh authored and copyberry committed 2026-07-17 21:16:07 +00:00
1 parent 025db22058
commit 7ed19a9758
13 files changed
+965 -107

No files matched your search

+8
View File
@@ -462,6 +462,14 @@ impl App {
self.lookup_message_history_entry(thread_id, offset, log_id)
.await?;
}
AppEvent::LookupMessageHistoryBatch {
thread_id,
cursor,
log_id,
} => {
self.lookup_message_history_batch(thread_id, cursor, log_id)
.await?;
}
AppEvent::ApproveRecentAutoReviewDenial { thread_id, id } => {
self.chat_widget
.approve_recent_auto_review_denial(thread_id, id);
+70 -3
View File
@@ -13,6 +13,7 @@ use super::*;
use crate::app_backtrack::BacktrackSelection;
use crate::app_backtrack::BacktrackState;
use crate::app_backtrack::user_count;
use crate::app_event::HistoryBatchEntryResponse;
use crate::chatwidget::ChatWidgetInit;
use crate::chatwidget::create_initial_user_message;
@@ -468,9 +469,34 @@ async fn history_lookup_response_is_routed_to_requesting_thread() -> Result<()>
panic!("expected thread-routed history response");
};
assert_eq!(routed_thread_id, thread_id);
assert_eq!(event.offset, 0);
assert_eq!(event.log_id, 1);
assert!(event.entry.is_none());
assert_eq!(
event,
HistoryLookupResponse::Entry {
offset: 0,
log_id: 1,
entry: None,
}
);
let cursor = codex_message_history::HistoryBatchCursor::new(/*end_offset*/ 10);
app.lookup_message_history_batch(thread_id, cursor, /*log_id*/ 1)
.await?;
let app_event = tokio::time::timeout(Duration::from_secs(1), app_event_rx.recv())
.await
.expect("history batch lookup should emit an app event")
.expect("app event channel should stay open");
let AppEvent::ThreadHistoryEntryResponse {
thread_id: routed_thread_id,
event,
} = app_event
else {
panic!("expected thread-routed history batch response");
};
assert_eq!(routed_thread_id, thread_id);
assert_eq!(
event,
HistoryLookupResponse::BatchError { cursor, log_id: 1 }
);
Ok(())
}
@@ -514,6 +540,47 @@ async fn enqueue_thread_event_does_not_block_when_channel_full() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn active_history_batch_is_delivered_without_replay_buffering() -> Result<()> {
let mut app = make_test_app().await;
let thread_id = ThreadId::new();
app.thread_event_channels
.insert(thread_id, ThreadEventChannel::new(/*capacity*/ 4));
app.set_thread_active(thread_id, /*active*/ true).await;
let cursor = codex_message_history::HistoryBatchCursor::new(/*end_offset*/ 1);
let event = HistoryLookupResponse::Batch {
cursor,
log_id: 1,
entries: vec![HistoryBatchEntryResponse {
offset: 1,
entry: Some("history entry".to_string()),
}],
next_older_cursor: Some(codex_message_history::HistoryBatchCursor::new(
/*end_offset*/ 0,
)),
};
app.enqueue_thread_history_entry_response(thread_id, event.clone())
.await?;
let channel = app
.thread_event_channels
.get_mut(&thread_id)
.expect("missing thread channel");
assert!(channel.store.lock().await.buffer.is_empty());
let mut receiver = channel.receiver.take().expect("missing receiver");
let delivered = time::timeout(Duration::from_millis(50), receiver.recv())
.await
.expect("timed out waiting for history batch")
.expect("missing history batch");
let ThreadBufferedEvent::HistoryEntryResponse(delivered) = delivered else {
panic!("expected history batch response");
};
assert_eq!(delivered, event);
Ok(())
}
#[tokio::test]
async fn replay_thread_snapshot_restores_draft_and_queued_input() {
let mut app = make_test_app().await;
+66 -11
View File
@@ -500,7 +500,7 @@ impl App {
app_event_tx.send(AppEvent::ThreadHistoryEntryResponse {
thread_id,
event: HistoryLookupResponse {
event: HistoryLookupResponse::Entry {
offset,
log_id,
entry: entry_opt.map(|entry| entry.text),
@@ -510,6 +510,55 @@ impl App {
Ok(())
}
/// Fetch one bounded local cross-session history batch for the requesting thread.
pub(super) async fn lookup_message_history_batch(
&mut self,
thread_id: ThreadId,
cursor: codex_message_history::HistoryBatchCursor,
log_id: u64,
) -> Result<()> {
let history_config = codex_message_history::HistoryConfig::new(
self.chat_widget.config_ref().codex_home.clone(),
&self.chat_widget.config_ref().history,
);
let app_event_tx = self.app_event_tx.clone();
tokio::spawn(async move {
let event = match tokio::task::spawn_blocking(move || {
codex_message_history::lookup_batch(log_id, cursor, &history_config)
})
.await
{
Ok(Ok(batch)) => {
let entries = batch
.entries
.into_iter()
.map(|entry| crate::app_event::HistoryBatchEntryResponse {
offset: entry.offset,
entry: entry.entry.map(|entry| entry.text),
})
.collect();
HistoryLookupResponse::Batch {
cursor,
log_id,
entries,
next_older_cursor: batch.next_older_cursor,
}
}
Ok(Err(err)) => {
tracing::warn!(error = %err, "history batch lookup failed");
HistoryLookupResponse::BatchError { cursor, log_id }
}
Err(err) => {
tracing::warn!(error = %err, "history batch lookup task failed");
HistoryLookupResponse::BatchError { cursor, log_id }
}
};
app_event_tx.send(AppEvent::ThreadHistoryEntryResponse { thread_id, event });
});
Ok(())
}
pub(super) async fn try_submit_active_thread_op_via_app_server(
&mut self,
app_server: &mut AppServerSession,
@@ -1058,18 +1107,24 @@ impl App {
let should_send = {
let mut guard = store.lock().await;
guard
.buffer
.push_back(ThreadBufferedEvent::HistoryEntryResponse(event.clone()));
if guard.buffer.len() > guard.capacity
&& let Some(removed) = guard.buffer.pop_front()
&& let ThreadBufferedEvent::Request(request) = &removed
{
let should_send = guard.active;
// Active batch responses remain queued in the receiver across a concurrent detach, so
// retaining another deep copy for thread replay only accumulates already-delivered
// history data. Inactive responses still need the buffer because they are not sent.
if !should_send || !matches!(&event, HistoryLookupResponse::Batch { .. }) {
guard
.pending_interactive_replay
.note_evicted_server_request(request);
.buffer
.push_back(ThreadBufferedEvent::HistoryEntryResponse(event.clone()));
if guard.buffer.len() > guard.capacity
&& let Some(removed) = guard.buffer.pop_front()
&& let ThreadBufferedEvent::Request(request) = &removed
{
guard
.pending_interactive_replay
.note_evicted_server_request(request);
}
}
guard.active
should_send
};
if should_send {