Stop rollout reads when the calling task is cancelled (#53947)

## Why

Blocking rollout reads can continue decompressing and scanning history after the calling async task is dropped.

## What changed

Propagate caller cancellation through rollout readers, prefix validation, model-context scans, history materialization, and working-directory lookup. Check cancellation during compressed input and output, bounded reads, seeks, and between history records. Return an error on cancellation so partial history cannot be mistaken for a complete read.

## Testing

Add regression coverage for dropping a caller during decompression, cancelling compressed input and output (including skippable frames), cancelling reads and seeks on plain and decoded snapshots, and cancelling history materialization between records.

GitOrigin-RevId: e3dac952789b53402f2a5f17c2a2232506feb9d6
This commit is contained in:
jif
2026-10-14 10:46:14 +00:00
committed by copyberry
parent 5670b1c18e
commit 78dc250384
10 changed files with 236 additions and 38 deletions
@@ -115,10 +115,13 @@ pub(super) async fn load_for_fork(
// Recover only the runtime version before applying the fork cutoff. Stop at the
// newest version-bearing context instead of retaining the source's full replay.
let source_lineage = lineage.clone();
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
session_meta.meta.multi_agent_version = tokio::task::spawn_blocking(move || {
for segment in source_lineage.segments().iter().rev() {
let file =
codex_rollout::open_rollout_seekable_reader(segment.rollout_path.as_path())?;
let file = codex_rollout::open_rollout_seekable_reader(
segment.rollout_path.as_path(),
|| stop.is_closed(),
)?;
let mut scanner = match segment.end.map(|end| end.end_byte_offset) {
Some(end_byte_offset) => ReverseJsonlScanner::new_at(file, end_byte_offset)?,
None => ReverseJsonlScanner::new(file)?,
@@ -145,6 +148,7 @@ pub(super) async fn load_for_fork(
.map_err(|err| ThreadStoreError::Internal {
message: format!("failed to read fork runtime version: {err}"),
})?;
drop(keep_running);
}
match history_base {
Some(history_base) => {
@@ -159,13 +163,15 @@ async fn scan_model_context_from_lineage(
lineage: RolloutLineage,
session_meta: SessionMetaLine,
) -> ThreadStoreResult<Vec<RolloutItem>> {
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
let scan = tokio::task::spawn_blocking(move || {
scan_model_context_from_lineage_blocking(&lineage, session_meta)
scan_model_context_from_lineage_blocking(&lineage, session_meta, || stop.is_closed())
})
.await
.map_err(|err| ThreadStoreError::Internal {
message: format!("failed to join model context scan: {err}"),
})?;
drop(keep_running);
match scan {
Ok(items) => Ok(items),
Err(err) => Err(ThreadStoreError::Internal {
@@ -177,10 +183,14 @@ async fn scan_model_context_from_lineage(
fn scan_model_context_from_lineage_blocking(
lineage: &RolloutLineage,
session_meta: SessionMetaLine,
is_cancelled: impl Fn() -> bool,
) -> io::Result<Vec<RolloutItem>> {
let mut scan = ModelContextScan::default();
'segments: for segment in lineage.segments().iter().rev() {
let file = codex_rollout::open_rollout_seekable_reader(segment.rollout_path.as_path())?;
let file = codex_rollout::open_rollout_seekable_reader(
segment.rollout_path.as_path(),
&is_cancelled,
)?;
let mut scanner = match segment.end.map(|end| end.end_byte_offset) {
Some(end_byte_offset) => ReverseJsonlScanner::new_at(file, end_byte_offset)?,
None => ReverseJsonlScanner::new(file)?,
@@ -284,8 +284,9 @@ async fn validate_cutoff_bounds(
}
let path = rollout_path.to_path_buf();
let end_byte_offset = end.end_byte_offset;
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
let contains_prefix = tokio::task::spawn_blocking(move || {
codex_rollout::rollout_contains_prefix(&path, end_byte_offset)
codex_rollout::rollout_contains_prefix(&path, end_byte_offset, || stop.is_closed())
})
.await
.map_err(|err| ThreadStoreError::Internal {
@@ -297,6 +298,7 @@ async fn validate_cutoff_bounds(
rollout_path.display()
),
})?;
drop(keep_running);
if !contains_prefix {
return Err(malformed_lineage(
requested_thread_id,
@@ -91,7 +91,8 @@ async fn read_projection_steps(
) -> ThreadStoreResult<(Vec<RolloutProjectionStep>, u64)> {
let path = rollout_path.to_path_buf();
let span = tracing::Span::current();
tokio::task::spawn_blocking(move || {
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
let result = tokio::task::spawn_blocking(move || {
let _entered = span.enter();
read_projection_steps_sync(
&path,
@@ -99,12 +100,15 @@ async fn read_projection_steps(
expected_ordinal,
thread_id,
subagent_history_start_ordinal,
|| stop.is_closed(),
)
})
.await
.map_err(|err| ThreadStoreError::Internal {
message: format!("failed to join rollout projection read: {err}"),
})?
})?;
drop(keep_running);
result
}
/// Read and project the complete durable prefix in one blocking task.
@@ -114,15 +118,16 @@ fn read_projection_steps_sync(
expected_ordinal: u64,
thread_id: ThreadId,
subagent_history_start_ordinal: Option<u64>,
is_cancelled: impl Fn() -> bool,
) -> ThreadStoreResult<(Vec<RolloutProjectionStep>, u64)> {
let mut file = match codex_rollout::open_rollout_seekable_reader(rollout_path) {
let mut file = match codex_rollout::open_rollout_seekable_reader(rollout_path, &is_cancelled) {
Ok(file) => file,
Err(err) if err.kind() == std::io::ErrorKind::NotFound && start_offset == 0 => {
return Ok((Vec::new(), 0));
}
Err(err) => return Err(thread_store_io_error(err)),
};
let file_end_offset = file.metadata().map_err(thread_store_io_error)?.len();
let file_end_offset = file.seek(SeekFrom::End(0)).map_err(thread_store_io_error)?;
let byte_count =
file_end_offset
.checked_sub(start_offset)
@@ -139,15 +144,19 @@ fn read_projection_steps_sync(
.map_err(thread_store_io_error)?;
// Only project the newline-terminated prefix; leave a trailing partial record for the next
// pass.
let complete_byte_count = bytes
.iter()
.rposition(|byte| *byte == b'\n')
.map_or(0, |index| index + 1);
let mut projections = Vec::new();
let mut next_ordinal = expected_ordinal;
let mut next_offset = start_offset;
let mut line_start_offset = start_offset;
for line_bytes in bytes[..complete_byte_count].split_inclusive(|byte| *byte == b'\n') {
for line_bytes in bytes.split_inclusive(|byte| *byte == b'\n') {
if is_cancelled() {
return Err(thread_store_io_error(std::io::Error::other(
"rollout read cancelled",
)));
}
if !line_bytes.ends_with(b"\n") {
break;
}
let line_end_offset = line_start_offset
.checked_add(u64::try_from(line_bytes.len()).map_err(|_| {
ThreadStoreError::Internal {
@@ -1,3 +1,4 @@
use std::cell::Cell;
use std::fs;
use std::io::Write;
use std::path::Path;
@@ -2470,6 +2471,20 @@ async fn blank_and_rejected_rollout_lines_advance_projection() {
.expect("queue valid retry");
recorder.flush().await.expect("flush valid retry");
// Replay this small file, cancelling between records after its single read completes.
let checks = Cell::new(0);
assert!(
super::read_projection_steps_sync(
rollout_path.as_path(),
/*start_offset*/ 0,
/*expected_ordinal*/ 0,
thread_id,
/*subagent_history_start_ordinal*/ None,
|| checks.replace(checks.get() + 1) >= 6,
)
.is_err()
);
super::materialize_to_sqlite(&store, thread_id, rollout_path.as_path())
.await
.expect("project valid retry after rejected line");