Attach inherited rollout history to diagnostic reports (#47653)

## Why

Selected rollouts can reference history stored in ancestor rollouts through `history_base`. Attaching only the selected files leaves that inherited history out of diagnostic reports.

## What changed

When `include_logs` is enabled, follow nested `history_base` references and attach ancestor prefixes up to the recorded byte offsets. Deduplicate ancestors, retain the largest requested prefix, and skip rollouts already selected for upload.

Bound discovery to 64 ancestors and five seconds, and enforce attachment size limits. Missing, unreadable, or incomplete ancestor prefixes are best effort and do not prevent the report upload.

## Testing

Add a unit test verifying that nested parent and grandparent history bases are attached with the expected filenames and contents.

GitOrigin-RevId: d9bba3e50573d25843d2eaedeae775946223ed0e
This commit is contained in:
Dmitriy Kovalenko
2026-09-23 20:15:48 +00:00
committed by copyberry
parent e6da6fd7c7
commit 5bfb04b247
4 changed files with 214 additions and 0 deletions
@@ -545,6 +545,7 @@ mod diagnostics;
mod environment_processor;
mod feedback_doctor_report;
mod feedback_processor;
mod feedback_rollout_history;
mod feedback_thread_index;
mod fs_processor;
mod git_processor;
@@ -279,6 +279,13 @@ impl FeedbackRequestProcessor {
upload_tags.entry(key).or_insert(value);
}
}
extra_attachments.extend(
super::feedback_rollout_history::history_base_attachments(
&self.config.codex_home,
&attachment_paths,
)
.await,
);
}
let session_source = self.thread_manager.session_source();
@@ -0,0 +1,136 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use codex_feedback::FeedbackAttachment;
use codex_feedback::FeedbackAttachmentPath;
use codex_feedback::MAX_ATTACHMENT_BYTES;
use codex_feedback::MAX_ATTACHMENTS_BYTES;
use codex_rollout::find_rollout_path_by_rollout_id;
use codex_rollout::read_session_meta_line;
use codex_rollout::rollout_id_from_path;
const MAX_HISTORY_ROLLOUTS: usize = 64;
const HISTORY_LOOKUP_TIMEOUT: Duration = Duration::from_secs(5);
pub(super) async fn history_base_attachments(
codex_home: &Path,
attachments: &[FeedbackAttachmentPath],
) -> Vec<FeedbackAttachment> {
let selected = attachments
.iter()
.filter_map(|attachment| rollout_id_from_path(&attachment.path))
.collect::<HashSet<_>>();
let mut pending = attachments
.iter()
.filter(|attachment| rollout_id_from_path(&attachment.path).is_some())
.map(|attachment| attachment.path.clone())
.collect::<Vec<_>>();
let mut positions = HashMap::new();
let mut ancestors: Vec<(PathBuf, usize)> = Vec::new();
// Preserve discovered prefixes if the bounded filesystem walk times out.
let discovery = async {
let mut next = 0;
while next < pending.len() {
let path = &pending[next];
next += 1;
let meta = match read_session_meta_line(path).await {
Ok(meta) => meta,
Err(err) => {
tracing::error!(
?err,
"failed to read feedback history metadata at {}",
path.display()
);
continue;
}
};
let Some(base) = meta.meta.history_base else {
continue;
};
if selected.contains(&base.thread_id) {
continue;
}
let Ok(end_byte_offset) = usize::try_from(base.end_byte_offset) else {
continue;
};
if end_byte_offset > MAX_ATTACHMENT_BYTES {
continue;
}
if let Some(&index) = positions.get(&base.thread_id) {
let (_, previous_end_byte_offset): &mut (PathBuf, usize) = &mut ancestors[index];
*previous_end_byte_offset = (*previous_end_byte_offset).max(end_byte_offset);
continue;
}
if positions.len() == MAX_HISTORY_ROLLOUTS {
tracing::error!("feedback history rollout limit reached");
break;
}
// The wire field names an immutable rollout, not the owner's current thread.
let path = match find_rollout_path_by_rollout_id(codex_home, base.thread_id).await {
Ok(Some(path)) => path,
Ok(None) => continue,
Err(err) => {
tracing::error!(
?err,
"failed to locate feedback history rollout {}",
base.thread_id
);
continue;
}
};
positions.insert(base.thread_id, ancestors.len());
pending.push(path.clone());
ancestors.push((path, end_byte_offset));
}
};
if tokio::time::timeout(HISTORY_LOOKUP_TIMEOUT, discovery)
.await
.is_err()
{
tracing::error!("feedback history lookup timed out");
}
// Freeze exactly the inherited bytes before upload. Unreadable or oversized
// ancestors are best effort and cannot turn an accepted report into an error.
tokio::task::spawn_blocking(move || {
let mut remaining = MAX_ATTACHMENTS_BYTES;
let mut result = Vec::new();
for (path, end_byte_offset) in ancestors {
if end_byte_offset > remaining {
continue;
}
let plain_path = codex_rollout::plain_rollout_path(&path);
let Some(filename) = plain_path.file_name() else {
continue;
};
match codex_rollout::read_rollout_prefix(&path, end_byte_offset) {
Ok(Some(buffer)) if buffer.len() == end_byte_offset => {
remaining -= buffer.len();
result.push(FeedbackAttachment {
buffer,
filename: filename.to_string_lossy().into_owned(),
content_type: Some("application/jsonl".to_string()),
});
}
Ok(_) => tracing::error!(
"couldn't attach history: incomplete feedback history prefix at {}",
path.display()
),
Err(err) => tracing::error!(
?err,
"couldn't read feedback history prefix at {}",
path.display()
),
}
}
result
})
.await
.unwrap_or_default() // Keep uploading the selected rollouts if this task fails.
}
#[cfg(test)]
#[path = "feedback_rollout_history_tests.rs"]
mod tests;
@@ -0,0 +1,70 @@
use super::*;
use codex_protocol::ThreadId;
use codex_protocol::protocol::HistoryPosition;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
#[tokio::test]
async fn includes_nested_history_bases() -> anyhow::Result<()> {
let home = TempDir::new()?;
let directory = home.path().join("sessions");
std::fs::create_dir_all(&directory)?;
let (grandparent, grandparent_end) = write_rollout(&directory, /*base*/ None)?;
let (parent, parent_end) = write_rollout(&directory, Some(grandparent_end))?;
let (rollout, _) = write_rollout(&directory, Some(parent_end))?;
let attachments = history_base_attachments(
home.path(),
&[FeedbackAttachmentPath {
path: rollout,
attachment_filename_override: None,
}],
)
.await;
let expected = [parent, grandparent]
.into_iter()
.map(|path| {
Ok((
path.file_name().unwrap().to_string_lossy().into_owned(),
std::fs::read(path)?,
))
})
.collect::<anyhow::Result<Vec<_>>>()?;
assert_eq!(
attachments
.into_iter()
.map(|attachment| (attachment.filename, attachment.buffer))
.collect::<Vec<_>>(),
expected
);
Ok(())
}
fn write_rollout(
directory: &Path,
base: Option<HistoryPosition>,
) -> anyhow::Result<(PathBuf, HistoryPosition)> {
let id = ThreadId::new();
let ordinal = base.map_or(0, |base| base.end_ordinal_exclusive);
let path = directory.join(format!("rollout-2026-09-22T12-00-00-{id}.jsonl"));
let meta = json!({
"ordinal": ordinal,
"timestamp": "2026-09-22T12:00:00Z", "type": "session_meta",
"payload": {
"id": id, "timestamp": "2026-09-22T12:00:00Z", "cwd": directory,
"originator": "test", "cli_version": "test", "history_mode": "paginated", "history_base": base,
},
});
let contents = format!("{meta}\n");
std::fs::write(&path, &contents)?;
Ok((
path,
HistoryPosition {
thread_id: id,
end_ordinal_exclusive: ordinal + 1,
end_byte_offset: contents.len() as u64,
},
))
}