Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,119 @@
//! Preserves access to replacement rollout files before they are published.
//! Metadata failures leave the source intact; never silently replace ownership
//! or discard a macOS ACL when switching between plain and compressed files.
//! Apply ACLs last because they can prohibit subsequent metadata updates.
//! Reject delete-deny ACLs before installation so failed replacements remain removable.
use std::fs::File;
use std::fs::FileTimes;
use std::io;
#[cfg(target_os = "macos")]
use std::os::fd::AsRawFd;
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
// libc does not expose the macOS ACL APIs.
#[cfg(target_os = "macos")]
unsafe extern "C" {
fn acl_get_fd(fd: libc::c_int) -> *mut libc::c_void;
fn acl_get_entry(
acl: *mut libc::c_void,
entry_id: libc::c_int,
entry: *mut *mut libc::c_void,
) -> libc::c_int;
fn acl_get_tag_type(entry: *mut libc::c_void, tag: *mut libc::c_uint) -> libc::c_int;
fn acl_get_permset_mask_np(entry: *mut libc::c_void, permissions: *mut u64) -> libc::c_int;
fn acl_init(count: libc::c_int) -> *mut libc::c_void;
fn acl_set_fd(fd: libc::c_int, acl: *mut libc::c_void) -> libc::c_int;
fn acl_free(acl: *mut libc::c_void) -> libc::c_int;
}
pub(super) fn copy(source: &File, destination: &File) -> io::Result<()> {
let metadata = source.metadata()?;
#[cfg(unix)]
{
let destination_metadata = destination.metadata()?;
if (destination_metadata.uid(), destination_metadata.gid())
!= (metadata.uid(), metadata.gid())
{
// Chown can clear mode bits, so restore permissions afterwards.
// Failure must abort publication rather than change who owns the file.
std::os::unix::fs::fchown(destination, Some(metadata.uid()), Some(metadata.gid()))?;
}
}
destination.set_permissions(metadata.permissions())?;
destination.set_times(FileTimes::new().set_modified(metadata.modified()?))?;
#[cfg(target_os = "macos")]
{
// COPYFILE_ACL merges inherited destination entries and drops inherited
// source entries. Replace the entire ACL to preserve its order and denies.
// SAFETY: source stays open and the returned ACL is freed below.
let mut acl = unsafe { acl_get_fd(source.as_raw_fd()) };
let source_has_no_acl = acl.is_null();
if source_has_no_acl {
let error = io::Error::last_os_error();
if error.raw_os_error() != Some(libc::ENOENT) {
return Err(error);
}
// No source ACL: also clear any ACL inherited by the new file.
// SAFETY: zero is a valid entry count; allocation failure returns null.
acl = unsafe {
acl_init(/*count*/ 0)
};
if acl.is_null() {
return Err(io::Error::last_os_error());
}
}
let result = (|| {
// These values come from macOS <sys/acl.h>.
const ACL_EXTENDED_DENY: libc::c_uint = 2;
const ACL_DELETE: u64 = 1 << 4;
let mut entry_id = 0;
loop {
let mut entry = std::ptr::null_mut();
// SAFETY: acl is valid and entry points to writable pointer storage.
if unsafe { acl_get_entry(acl, entry_id, &mut entry) } != 0 {
let error = io::Error::last_os_error();
// macOS returns EINVAL when the entry index reaches the end.
if error.raw_os_error() == Some(libc::EINVAL) {
break;
}
return Err(error);
}
let mut tag = 0;
let mut permissions = 0;
// SAFETY: entry belongs to the live acl; both outputs are writable.
if unsafe { acl_get_tag_type(entry, &mut tag) } != 0
|| unsafe { acl_get_permset_mask_np(entry, &mut permissions) } != 0
{
return Err(io::Error::last_os_error());
}
// Conservatively reject any delete deny, regardless of principal or
// ordering. Installing it can prevent both publication and cleanup,
// and the ACL may also deny restoring permissions after a failure.
if tag == ACL_EXTENDED_DENY && permissions & ACL_DELETE != 0 {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"cannot replace a rollout with a delete-deny ACL",
));
}
entry_id += 1;
}
// SAFETY: destination stays open and acl is a valid owned allocation.
if unsafe { acl_set_fd(destination.as_raw_fd(), acl) } == 0 {
return Ok(());
}
let error = io::Error::last_os_error();
// Filesystems without ACL support reject even an empty ACL. There
// is nothing to preserve only when the source had no ACL.
if source_has_no_acl && error.raw_os_error() == Some(libc::ENOTSUP) {
return Ok(());
}
Err(error)
})();
// SAFETY: acl came from acl_get_fd or acl_init and is no longer used.
unsafe { acl_free(acl) };
result?;
}
Ok(())
}

View File

@@ -0,0 +1,118 @@
//! Runs a rollout scan on one blocking worker, with cancellation and one reader observation.
//! Consumers may stop early; canceled reads do not contribute an EOF, failure, or duration.
use std::io;
use std::io::BufRead;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::time::Duration;
use std::time::Instant;
use super::BlockingLineReader;
use super::ReadFailureSource;
use super::ReadMetrics;
use super::RolloutLineReaderInner;
use super::open_rollout_line_reader;
/// Opens a fresh reader and processes its lines on the shared blocking worker.
pub(crate) async fn read_rollout_lines<T, F>(path: &Path, read: F) -> io::Result<T>
where
T: Send + 'static,
F: FnOnce(&mut dyn Iterator<Item = io::Result<String>>) -> io::Result<T> + Send + 'static,
{
let reader = open_rollout_line_reader(path).await?;
let lines: BlockingLineReader = match reader.inner {
RolloutLineReaderInner::Plain(lines) => {
// The fresh reader has no buffered data to preserve when converting the file.
let file = lines.into_inner().into_inner().into_std().await;
io::BufReader::new(Box::new(file) as Box<dyn io::Read + Send>).lines()
}
RolloutLineReaderInner::Blocking(Some(lines)) => lines,
RolloutLineReaderInner::Blocking(None) => {
return Err(io::Error::other("compressed rollout reader is busy"));
}
};
scan_lines(lines, reader.metrics, read).await
}
/// Runs a consumer over measured lines, retaining metrics if the caller drops the future.
pub(super) async fn scan_lines<T, F>(
lines: BlockingLineReader,
metrics: ReadMetrics,
scan: F,
) -> io::Result<T>
where
T: Send + 'static,
F: FnOnce(&mut dyn Iterator<Item = io::Result<String>>) -> io::Result<T> + Send + 'static,
{
// Include the initial queue wait, as the per-line reader does, but exclude consumer work.
let queued_at = Instant::now();
let metrics = Arc::new(Mutex::new(metrics));
let worker_metrics = Arc::clone(&metrics);
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
let span = tracing::Span::current();
let task = tokio::task::spawn_blocking(move || {
let queue_duration = queued_at.elapsed();
span.in_scope(|| {
let mut metrics = worker_metrics
.lock()
.unwrap_or_else(PoisonError::into_inner);
scan(&mut MeasuredLines {
lines,
metrics: &mut metrics,
stop,
queue_duration,
})
})
});
let result = task.await.map_err(|err| {
let err = io::Error::other(err);
metrics
.lock()
.unwrap_or_else(PoisonError::into_inner)
.failed("read", ReadFailureSource::TaskJoin, &err);
err
});
drop(keep_running);
result?
}
struct MeasuredLines<'a> {
lines: BlockingLineReader,
metrics: &'a mut ReadMetrics,
stop: tokio::sync::oneshot::Sender<()>,
queue_duration: Duration,
}
impl Iterator for MeasuredLines<'_> {
type Item = io::Result<String>;
fn next(&mut self) -> Option<Self::Item> {
if self.stop.is_closed() {
return None;
}
let started_at = Instant::now();
let line = self.lines.next();
if self.stop.is_closed() {
return None;
}
let metrics = &mut self.metrics;
metrics.duration = metrics
.duration
.saturating_add(std::mem::take(&mut self.queue_duration))
.saturating_add(started_at.elapsed());
metrics.reached_eof = line.is_none();
match &line {
Some(Ok(_)) => metrics.read_any_line = true,
Some(Err(err)) => metrics.failed("read", ReadFailureSource::Stream, err),
None => {}
}
line
}
}
#[cfg(test)]
#[path = "blocking_reader_tests.rs"]
mod tests;

View File

@@ -0,0 +1,99 @@
//! Exercises cancellation during reads and between records.
use std::io;
use std::io::BufRead;
use std::io::Read;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use super::ReadMetrics;
use super::read_rollout_lines;
use super::scan_lines;
struct PausedRead {
contents: io::Cursor<&'static [u8]>,
started: Option<tokio::sync::oneshot::Sender<()>>,
resume: std::sync::mpsc::Receiver<()>,
finished: Option<tokio::sync::oneshot::Sender<()>>,
}
impl Read for PausedRead {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
if let Some(started) = self.started.take() {
let _ = started.send(());
self.resume.recv().map_err(io::Error::other)?;
}
self.contents.read(buffer)
}
}
impl Drop for PausedRead {
fn drop(&mut self) {
if let Some(finished) = self.finished.take() {
let _ = finished.send(());
}
}
}
#[tokio::test]
async fn cancellation_during_read_does_not_deliver_the_record() -> anyhow::Result<()> {
let (started, waiting) = tokio::sync::oneshot::channel();
let (resume, paused) = std::sync::mpsc::channel();
let (finished, done) = tokio::sync::oneshot::channel();
let reader = Box::new(PausedRead {
contents: io::Cursor::new(b"first\n".as_slice()),
started: Some(started),
resume: paused,
finished: Some(finished),
}) as Box<dyn Read + Send>;
let calls = Arc::new(AtomicUsize::new(0));
let seen = Arc::clone(&calls);
let task = tokio::spawn(scan_lines(
io::BufReader::new(reader).lines(),
ReadMetrics::default(),
move |lines| {
for line in lines {
line?;
seen.fetch_add(1, Ordering::SeqCst);
}
Ok(())
},
));
waiting.await?;
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
resume.send(())?;
done.await?;
assert_eq!(calls.load(Ordering::SeqCst), 0);
Ok(())
}
#[tokio::test]
async fn cancelling_full_scan_stops_before_the_next_record() -> anyhow::Result<()> {
let home = TempDir::new()?;
let path = home.path().join("rollout.jsonl");
std::fs::write(&path, "first\nsecond\n")?;
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let (continue_tx, continue_rx) = std::sync::mpsc::channel();
let (finished_tx, finished_rx) = tokio::sync::oneshot::channel();
let task = tokio::spawn(async move {
read_rollout_lines(&path, move |lines| {
assert_eq!(lines.next().transpose()?, Some("first".to_string()));
let _ = started_tx.send(());
continue_rx.recv().map_err(io::Error::other)?;
let _ = finished_tx.send(lines.next().transpose());
Ok(())
})
.await
});
started_rx.await?;
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
continue_tx.send(())?;
assert_eq!(finished_rx.await??, None);
Ok(())
}

View File

@@ -0,0 +1,65 @@
//! Failure labels for rollout compression. Only static stages and bounded I/O kinds
//! are exported; error messages, paths, and rollout contents never become metric tags.
use std::io;
use super::RolloutCompressionTrigger;
use super::metrics;
pub(super) enum FailureMetric {
File(RolloutCompressionTrigger),
Materialize,
Run(RolloutCompressionTrigger),
Scan(RolloutCompressionTrigger),
TempCleanup(RolloutCompressionTrigger),
}
impl FailureMetric {
pub(super) fn record(self, stage: &'static str, error: &io::Error) {
let (name, outcome_key, trigger) = match self {
Self::File(trigger) => (metrics::FILE_COUNTER, "outcome", Some(trigger)),
Self::Materialize => (metrics::MATERIALIZE_COUNTER, "outcome", None),
Self::Run(trigger) => (metrics::RUN_COUNTER, "status", Some(trigger)),
Self::Scan(trigger) => ("codex.rollout_compression.scan", "outcome", Some(trigger)),
Self::TempCleanup(trigger) => (metrics::TEMP_CLEANUP_COUNTER, "outcome", Some(trigger)),
};
let Some(metrics) = codex_otel::global() else {
return;
};
let tags = [
(outcome_key, "failed"),
("stage", stage),
("error_kind", error_kind(error)),
(
"trigger",
trigger.map_or("", RolloutCompressionTrigger::tag),
),
];
let tags = if trigger.is_some() {
&tags[..]
} else {
&tags[..3]
};
let _ = metrics.counter(name, /*inc*/ 1, tags);
}
}
pub(super) fn error_kind(error: &io::Error) -> &'static str {
match error.kind() {
io::ErrorKind::NotFound => "not_found",
io::ErrorKind::PermissionDenied => "permission_denied",
io::ErrorKind::AlreadyExists => "already_exists",
io::ErrorKind::InvalidInput => "invalid_input",
io::ErrorKind::InvalidData => "invalid_data",
io::ErrorKind::TimedOut => "timed_out",
io::ErrorKind::WriteZero => "write_zero",
io::ErrorKind::Interrupted => "interrupted",
io::ErrorKind::Unsupported => "unsupported",
io::ErrorKind::UnexpectedEof => "unexpected_eof",
io::ErrorKind::StorageFull => "storage_full",
io::ErrorKind::ReadOnlyFilesystem => "read_only_filesystem",
io::ErrorKind::NotADirectory => "not_a_directory",
io::ErrorKind::IsADirectory => "is_a_directory",
_ => "other",
}
}

View File

@@ -0,0 +1,18 @@
//! Resolves rollout metadata with shared plain-before-compressed precedence.
use std::fs::Metadata;
use std::path::Path;
use std::path::PathBuf;
use super::path::compressed_rollout_path;
use super::path::plain_rollout_path;
/// Resolves a regular rollout file and its metadata without leaving the blocking worker.
pub(crate) fn existing_rollout_with_metadata_sync(path: &Path) -> Option<(PathBuf, Metadata)> {
let plain_path = plain_rollout_path(path);
let compressed_path = compressed_rollout_path(&plain_path);
[plain_path, compressed_path].into_iter().find_map(|path| {
let metadata = std::fs::metadata(&path).ok()?;
metadata.is_file().then_some((path, metadata))
})
}

View File

@@ -0,0 +1,125 @@
//! Captures byte counts and file changes on the first compressed-stream failure.
//! Healthy reads only retain the first frame header and count decoded bytes. Logs contain
//! no paths or contents and are limited to one failure per process per minute.
use std::fs::File;
use std::fs::Metadata;
use std::io;
use std::io::BufReader;
use std::io::Read;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::time::Duration;
use std::time::Instant;
use super::error_metrics::error_kind;
pub(super) struct DiagnosticDecoder {
decoder: zstd::stream::read::Decoder<'static, BufReader<Source>>,
decoded_bytes: u64,
failure: Option<FailureDetails>,
}
#[derive(Debug, PartialEq, Eq)]
struct FailureDetails {
compressed_bytes: Option<u64>,
first_frame_content_bytes: Option<u64>,
decoded_bytes: u64,
file_changed: Option<bool>,
}
struct Source {
file: File,
opened_metadata: Option<Metadata>,
header: [u8; 18],
header_len: usize,
}
impl DiagnosticDecoder {
pub(super) fn new(file: File) -> io::Result<Self> {
let source = Source {
opened_metadata: file.metadata().ok(),
file,
header: [0; 18],
header_len: 0,
};
Ok(Self {
decoder: zstd::stream::read::Decoder::new(source)?,
decoded_bytes: 0,
failure: None,
})
}
}
impl Read for DiagnosticDecoder {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
let result = self.decoder.read(buffer);
match &result {
Ok(bytes) => self.decoded_bytes = self.decoded_bytes.saturating_add(*bytes as u64),
Err(error) if self.failure.is_none() => {
let source = self.decoder.get_ref().get_ref();
let metadata = source.file.metadata().ok();
let details = FailureDetails {
compressed_bytes: metadata.as_ref().map(Metadata::len),
// This is the first frame's size, not the total for concatenated frames.
first_frame_content_bytes: zstd::zstd_safe::get_frame_content_size(
&source.header[..source.header_len],
)
.ok()
.flatten(),
decoded_bytes: self.decoded_bytes,
file_changed: source
.opened_metadata
.as_ref()
.zip(metadata.as_ref())
.and_then(|(before, after)| {
Some(
before.len() != after.len()
|| before.modified().ok()? != after.modified().ok()?,
)
}),
};
static LAST_REPORT: Mutex<Option<Instant>> = Mutex::new(None);
let report = {
let mut last = LAST_REPORT.lock().unwrap_or_else(PoisonError::into_inner);
if last
.is_none_or(|time| time.elapsed() >= Duration::from_secs(/*secs*/ 60))
{
*last = Some(Instant::now());
true
} else {
false
}
};
if report {
tracing::warn!(
error_kind = error_kind(error),
compressed_bytes = ?details.compressed_bytes,
first_frame_content_bytes = ?details.first_frame_content_bytes,
decoded_bytes = details.decoded_bytes,
file_changed = ?details.file_changed,
"compressed rollout read failed"
);
}
self.failure = Some(details);
}
Err(_) => {}
}
result
}
}
impl Read for Source {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
let bytes = self.file.read(buffer)?;
let header_bytes = bytes.min(self.header.len() - self.header_len);
self.header[self.header_len..self.header_len + header_bytes]
.copy_from_slice(&buffer[..header_bytes]);
self.header_len += header_bytes;
Ok(bytes)
}
}
#[cfg(test)]
#[path = "read_diagnostics_tests.rs"]
mod tests;

View File

@@ -0,0 +1,64 @@
//! Checks failure details against real truncated and concatenated zstd streams.
use std::fs;
use std::io::Read;
use std::io::Write;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn incomplete_frames_report_decoded_bytes_and_changes_to_the_open_file() -> io::Result<()> {
let contents = b"valid utf8\n";
let mut encoder = zstd::stream::write::Encoder::new(Vec::new(), /*level*/ 0)?;
encoder.set_pledged_src_size(Some(contents.len() as u64))?;
encoder.write_all(contents)?;
let complete = encoder.finish()?;
for (suffix, change_after_open, expected_contents) in [
(None, false, &contents[..contents.len() - 1]),
(None, true, &contents[..contents.len() - 1]),
(Some(0x28), false, contents.as_slice()),
] {
let home = tempfile::tempdir()?;
let path = home.path().join("rollout.jsonl.zst");
let mut damaged = complete.clone();
if let Some(byte) = suffix {
damaged.push(byte); // A complete payload followed by an unfinished frame header.
} else {
damaged.pop();
}
fs::write(
&path,
if change_after_open {
&complete
} else {
&damaged
},
)?;
let mut reader = DiagnosticDecoder::new(File::open(&path)?)?;
if change_after_open {
fs::OpenOptions::new()
.write(true)
.open(&path)?
.set_len(damaged.len() as u64)?;
}
let mut decoded = Vec::new();
let error = reader.read_to_end(&mut decoded).unwrap_err();
assert_eq!(
(error.kind(), decoded, reader.failure),
(
io::ErrorKind::UnexpectedEof,
expected_contents.to_vec(),
Some(FailureDetails {
compressed_bytes: Some(damaged.len() as u64),
first_frame_content_bytes: Some(contents.len() as u64),
decoded_bytes: expected_contents.len() as u64,
file_changed: Some(change_after_open),
}),
)
);
}
Ok(())
}

View File

@@ -0,0 +1,124 @@
//! One observation per rollout reader, including failed opens and partial reads.
//! Duration sums completed open/retry and read calls, excluding caller processing
//! and any canceled call. Partial readers must not be treated as successful EOFs.
//! Aggregate locally rather than exporting a metric for every JSONL record.
//! Failure reasons and progress are bounded labels captured at the first failure;
//! error messages, file paths, and rollout contents are never exported.
use std::io;
use std::time::Duration;
use super::error_metrics::error_kind;
pub(super) struct ReadMetrics {
pub(super) format: &'static str,
pub(super) reached_eof: bool,
pub(super) duration: Duration,
pub(super) read_any_line: bool,
failure: Option<ReadFailure>,
}
pub(super) enum ReadFailureSource {
Stream,
ReaderBusy,
TaskJoin,
}
struct ReadFailure {
stage: &'static str,
error_kind: &'static str,
reason: &'static str,
read_progress: &'static str,
}
impl Default for ReadMetrics {
fn default() -> Self {
Self {
format: "unknown",
reached_eof: false,
duration: Duration::ZERO,
read_any_line: false,
failure: None,
}
}
}
impl ReadMetrics {
pub(super) fn failed(
&mut self,
stage: &'static str,
source: ReadFailureSource,
error: &io::Error,
) {
self.failure.get_or_insert_with(|| ReadFailure {
stage,
error_kind: error_kind(error),
reason: match source {
ReadFailureSource::ReaderBusy => "reader_busy",
ReadFailureSource::TaskJoin => "task_join",
ReadFailureSource::Stream if error.raw_os_error().is_some() => "os_error",
ReadFailureSource::Stream
if self.format == "zstd" && error.kind() == io::ErrorKind::Other =>
{
// zstd converts its numeric error code to an io::Error containing
// only a message. Match exact known messages, never export that text.
// An unfamiliar message must remain a generic stream error.
match error.to_string().as_str() {
"Unknown frame descriptor" => "zstd_invalid_frame",
"Data corruption detected"
| "Header of Literals' block doesn't respect format specification" => {
"zstd_corrupt_block"
}
"Restored data doesn't match checksum" => "zstd_checksum",
"Frame requires too much memory for decoding"
| "Allocation error : not enough memory" => "zstd_resource_limit",
"Version not supported" | "Unsupported frame parameter" => {
"zstd_unsupported_frame"
}
"Dictionary is corrupted" | "Dictionary mismatch" => "zstd_dictionary",
_ => "stream_error",
}
}
ReadFailureSource::Stream => "stream_error",
},
read_progress: if self.read_any_line {
"after_first_line"
} else {
"before_first_line"
},
});
}
}
impl Drop for ReadMetrics {
fn drop(&mut self) {
let Some(metrics) = codex_otel::global() else {
return;
};
let (outcome, stage, error_kind, reason, read_progress) = match &self.failure {
Some(failure) => (
"failed",
failure.stage,
failure.error_kind,
failure.reason,
failure.read_progress,
),
None if self.reached_eof => ("eof", "none", "none", "none", "none"),
None => ("partial", "none", "none", "none", "none"),
};
let tags = [
("format", self.format),
("outcome", outcome),
("stage", stage),
("error_kind", error_kind),
("reason", reason),
("read_progress", read_progress),
];
let _ = metrics.counter("codex.rollout_compression.read", /*inc*/ 1, &tags);
let _ = metrics.record_duration(
"codex.rollout_compression.read.io_duration_ms",
self.duration,
&tags,
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,101 @@
use codex_state::SqliteConfig;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
pub trait RolloutConfigView {
fn codex_home(&self) -> &Path;
fn sqlite_config(&self) -> &SqliteConfig;
fn cwd(&self) -> &Path;
fn model_provider_id(&self) -> &str;
fn generate_memories(&self) -> bool;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RolloutConfig {
pub codex_home: PathBuf,
pub sqlite: SqliteConfig,
pub cwd: PathBuf,
pub model_provider_id: String,
pub generate_memories: bool,
}
pub type Config = RolloutConfig;
impl RolloutConfig {
pub fn from_view(view: &impl RolloutConfigView) -> Self {
Self {
codex_home: view.codex_home().to_path_buf(),
sqlite: view.sqlite_config().clone(),
cwd: view.cwd().to_path_buf(),
model_provider_id: view.model_provider_id().to_string(),
generate_memories: view.generate_memories(),
}
}
}
impl RolloutConfigView for RolloutConfig {
fn codex_home(&self) -> &Path {
self.codex_home.as_path()
}
fn sqlite_config(&self) -> &SqliteConfig {
&self.sqlite
}
fn cwd(&self) -> &Path {
self.cwd.as_path()
}
fn model_provider_id(&self) -> &str {
self.model_provider_id.as_str()
}
fn generate_memories(&self) -> bool {
self.generate_memories
}
}
impl<T: RolloutConfigView + ?Sized> RolloutConfigView for &T {
fn codex_home(&self) -> &Path {
(*self).codex_home()
}
fn sqlite_config(&self) -> &SqliteConfig {
(*self).sqlite_config()
}
fn cwd(&self) -> &Path {
(*self).cwd()
}
fn model_provider_id(&self) -> &str {
(*self).model_provider_id()
}
fn generate_memories(&self) -> bool {
(*self).generate_memories()
}
}
impl<T: RolloutConfigView + ?Sized> RolloutConfigView for Arc<T> {
fn codex_home(&self) -> &Path {
self.as_ref().codex_home()
}
fn sqlite_config(&self) -> &SqliteConfig {
self.as_ref().sqlite_config()
}
fn cwd(&self) -> &Path {
self.as_ref().cwd()
}
fn model_provider_id(&self) -> &str {
self.as_ref().model_provider_id()
}
fn generate_memories(&self) -> bool {
self.as_ref().generate_memories()
}
}

177
codex-rs/rollout/src/lib.rs Normal file
View File

@@ -0,0 +1,177 @@
//! Rollout persistence and discovery for Codex session files.
use std::sync::LazyLock;
use codex_protocol::protocol::SessionSource;
use serde::de::Error as _;
use serde_json::Value;
pub(crate) mod compression;
pub(crate) mod config;
pub(crate) mod list;
mod maintenance;
pub(crate) mod metadata;
mod model_context;
mod ordinal;
mod persistence_metrics;
pub(crate) mod policy;
pub(crate) mod recorder;
mod reverse_jsonl_scanner;
mod rollout_file_name;
mod rollout_reference_index;
pub(crate) mod search;
mod seekable_reader;
pub(crate) mod session_index;
mod sqlite_metrics;
pub mod state_db;
mod writer_lock;
pub use codex_history::CompactedItem;
pub use codex_history::CompactionResumeMetadata;
pub use codex_history::InitialHistory;
pub use codex_history::ResponseItemEnvelope;
pub use codex_history::ResumedHistory;
pub use codex_history::RetainedContextEntry;
pub use codex_history::RetainedContextEvent;
pub use codex_history::RetainedInputSource;
pub use codex_history::RolloutItem;
pub use codex_history::RolloutLine;
pub use codex_history::resume_multi_agent_version;
pub(crate) use codex_protocol::protocol;
/// Decodes a persisted rollout record without Serde's flattened-envelope buffering.
///
/// With `serde_json/arbitrary_precision`, Serde's generic buffer cannot replay
/// floating-point values nested inside flattened or internally tagged fields:
/// https://github.com/serde-rs/json/issues/721
/// https://github.com/serde-rs/serde/issues/1183
///
/// Keep this JSON-specific workaround at the persistence boundary so history
/// remains format-neutral and resume and projection use the same item decoder.
/// Remove it once Serde supports format-specific buffering.
pub fn decode_rollout_line(value: Value) -> serde_json::Result<RolloutLine> {
let Value::Object(mut fields) = value else {
return Err(serde_json::Error::custom(
"rollout line must be a JSON object",
));
};
let timestamp = fields
.remove("timestamp")
.ok_or_else(|| serde_json::Error::missing_field("timestamp"))
.and_then(serde_json::from_value)?;
let ordinal = fields
.remove("ordinal")
.map(serde_json::from_value::<Option<u64>>)
.transpose()?
.flatten();
let item = serde_json::from_value(Value::Object(fields))?;
Ok(RolloutLine {
timestamp,
ordinal,
item,
})
}
/// Parses a persisted JSONL rollout record through the canonical JSON decoder.
pub fn parse_rollout_line(line: &str) -> serde_json::Result<RolloutLine> {
serde_json::from_str::<Value>(line).and_then(decode_rollout_line)
}
/// Parses persisted JSONL rollout record bytes through the canonical JSON decoder.
pub fn parse_rollout_line_bytes(bytes: &[u8]) -> serde_json::Result<RolloutLine> {
serde_json::from_slice::<Value>(bytes).and_then(decode_rollout_line)
}
pub const SESSIONS_SUBDIR: &str = "sessions";
pub const ARCHIVED_SESSIONS_SUBDIR: &str = "archived_sessions";
pub static INTERACTIVE_SESSION_SOURCES: LazyLock<Vec<SessionSource>> = LazyLock::new(|| {
vec![
SessionSource::Cli,
SessionSource::VSCode,
SessionSource::Custom("atlas".to_string()),
SessionSource::Custom("chatgpt".to_string()),
]
});
pub use codex_protocol::protocol::SessionMeta;
pub use compression::RolloutCompressionTrigger;
pub use compression::RolloutLineReader;
pub use compression::existing_rollout_path;
pub use compression::open_rollout_line_reader;
pub use compression::plain_rollout_path;
pub use compression::spawn_rollout_compression_worker;
pub use seekable_reader::open_rollout_seekable_reader;
pub use seekable_reader::read_rollout_prefix;
pub use seekable_reader::rollout_contains_prefix;
/// Materializes a compressed rollout as plain JSONL before another rollout references it.
pub async fn materialize_rollout_for_reference(
path: &std::path::Path,
) -> std::io::Result<std::path::PathBuf> {
compression::materialize_rollout_for_append(path, /*writer_lock*/ None).await
}
pub use config::Config;
pub use config::RolloutConfig;
pub use config::RolloutConfigView;
pub use list::Cursor;
pub use list::SortDirection;
pub use list::ThreadItem;
pub use list::ThreadListConfig;
pub use list::ThreadListLayout;
pub use list::ThreadSortKey;
pub use list::ThreadsPage;
pub use list::find_archived_thread_path_by_id_str;
pub use list::find_rollout_path_by_rollout_id;
pub use list::find_rollout_path_by_rollout_id_excluding;
pub use list::find_rollout_paths_by_rollout_ids;
pub use list::find_thread_path_by_id_str;
#[deprecated(note = "use find_thread_path_by_id_str")]
pub use list::find_thread_path_by_id_str as find_conversation_path_by_id_str;
pub use list::get_threads;
pub use list::get_threads_in_root;
pub use list::parse_cursor;
pub use list::prefetch_sibling_rollout_paths;
pub use list::read_head_for_summary;
pub use list::read_session_meta_line;
pub use list::read_thread_item_from_rollout;
pub use list::rollout_date_parts;
pub use maintenance::RolloutMaintenanceGuard;
pub use maintenance::try_acquire_rollout_maintenance_lock;
pub use metadata::builder_from_items;
pub use metadata::forked_from_ordinal_exclusive;
pub use metadata::rollout_id_from_path;
pub use metadata::thread_id_from_rollout_path;
pub use model_context::ModelContextScan;
pub use model_context::ModelContextScanProgress;
pub use persistence_metrics::RolloutPersistenceBatchMeasurement;
pub use persistence_metrics::RolloutPersistenceTelemetry;
pub use persistence_metrics::measure_and_filter_rollout_items;
pub use policy::into_persisted_rollout_items;
pub use policy::persisted_rollout_item;
pub use policy::persisted_rollout_items;
pub use policy::should_persist_response_item;
pub use policy::should_persist_response_item_for_memories;
pub use recorder::RolloutRecorder;
pub use recorder::RolloutRecorderParams;
pub use recorder::append_rollout_item_to_path;
pub use reverse_jsonl_scanner::ReverseJsonlScanner;
pub use reverse_jsonl_scanner::ScanOutcome;
pub use rollout_reference_index::RolloutReferenceIndex;
pub use search::first_rollout_content_match_snippet;
pub use search::search_rollout_matches;
pub use search::search_rollout_paths;
pub use session_index::append_thread_name;
pub use session_index::find_thread_meta_by_name_str;
pub use session_index::find_thread_meta_candidates_by_name_str;
pub use session_index::find_thread_name_by_id;
pub use session_index::find_thread_name_entries_by_ids;
pub use session_index::find_thread_names_by_ids;
pub use session_index::remove_thread_name_entries;
pub use state_db::StateDbHandle;
pub use state_db::sqlite_telemetry_recorder;
pub use writer_lock::WriterLockCoordinator;
pub use writer_lock::WriterLockGuard;
#[cfg(test)]
mod tests;

1713
codex-rs/rollout/src/list.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,324 @@
//! Filesystem candidate collection for rollout listing.
//!
//! Keep directory scans and metadata lookups on blocking workers. Updated-time listings need
//! all candidates before sorting; creation-time listings retain directory-level early stopping.
//! Scans check cancellation between directory entries and candidate metadata lookups.
use codex_protocol::RolloutId;
use codex_protocol::ThreadId;
use std::cmp::Reverse;
use std::collections::HashSet;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use time::OffsetDateTime;
use uuid::Uuid;
use super::MAX_SCAN_FILES;
use super::ThreadCandidate;
use super::parse_timestamp_uuid_from_filename;
use super::truncate_to_millis;
use crate::compression;
use crate::rollout_file_name::RolloutFileName;
const MAX_SIBLING_ROLLOUT_IDS: usize = 64;
/// Runs a scan whose worker observes cancellation when its async waiter is dropped.
async fn run_scan<T, F>(read: F) -> io::Result<T>
where
T: Send + 'static,
F: FnOnce(&Scan) -> io::Result<T> + Send + 'static,
{
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
let result = tokio::task::spawn_blocking(move || {
let scan = Scan { stop };
scan.check_cancelled()?;
let result = read(&scan);
scan.check_cancelled()?;
result
})
.await
.map_err(io::Error::other)?;
drop(keep_running);
result
}
struct Scan {
stop: tokio::sync::oneshot::Sender<()>,
}
impl Scan {
fn check_cancelled(&self) -> io::Result<()> {
if self.stop.is_closed() {
return Err(io::Error::new(
io::ErrorKind::Interrupted,
"rollout scan cancelled",
));
}
Ok(())
}
}
pub(super) async fn collect_dirs_desc<T, F>(
parent: &Path,
parse: F,
) -> io::Result<Vec<(T, PathBuf)>>
where
T: Ord + Copy + Send + 'static,
F: Fn(&str) -> Option<T> + Send + 'static,
{
let parent = parent.to_path_buf();
run_scan(move |scan| collect_dirs_desc_sync(&parent, parse, scan)).await
}
pub(super) async fn collect_rollout_day_files(
day_path: &Path,
) -> io::Result<Vec<(OffsetDateTime, Uuid, PathBuf)>> {
let day_path = day_path.to_path_buf();
run_scan(move |scan| collect_rollout_day_files_sync(&day_path, scan)).await
}
pub(super) async fn collect_sibling_rollout_ids(
directory: &Path,
thread_id: ThreadId,
child_rollout_id: RolloutId,
first_ancestor_id: RolloutId,
) -> io::Result<HashSet<RolloutId>> {
let directory = directory.to_path_buf();
run_scan(move |scan| {
let mut ids = HashSet::new();
for entry in std::fs::read_dir(directory)?.take(MAX_SCAN_FILES) {
scan.check_cancelled()?;
let entry = entry?;
if entry.file_type()?.is_file()
&& let Some(file_name) = entry.file_name().to_str().and_then(RolloutFileName::parse)
&& file_name.thread_id() == thread_id
&& file_name.rollout_id() != child_rollout_id
{
// Reserve the last slot for the first ancestor until it is found.
if ids.len() == MAX_SIBLING_ROLLOUT_IDS - 1
&& file_name.rollout_id() != first_ancestor_id
&& !ids.contains(&first_ancestor_id)
{
continue;
}
ids.insert(file_name.rollout_id());
if ids.len() >= MAX_SIBLING_ROLLOUT_IDS {
break;
}
}
}
Ok(ids)
})
.await
}
pub(super) async fn collect_flat_rollout_files(
root: &Path,
scanned_files: &mut usize,
) -> io::Result<Vec<(OffsetDateTime, Uuid, PathBuf)>> {
let root = root.to_path_buf();
let mut scanned = *scanned_files;
let (result, scanned) = run_scan(move |scan| {
let result = collect_flat_rollout_files_sync(&root, &mut scanned, scan);
let result = result.and_then(|mut files| {
scan.check_cancelled()?;
files.sort_by_key(|(ts, sid, _path)| (Reverse(*ts), Reverse(*sid)));
Ok(files)
});
Ok((result, scanned))
})
.await?;
*scanned_files = scanned;
result
}
pub(super) async fn collect_files_by_updated_at(
root: &Path,
scanned_files: &mut usize,
) -> io::Result<Vec<ThreadCandidate>> {
let root = root.to_path_buf();
let mut scanned = *scanned_files;
let (result, scanned) = run_scan(move |scan| {
let result = (|| {
let mut candidates = Vec::new();
'outer: for (_, year_path) in
collect_dirs_desc_sync(&root, |s| s.parse::<u16>().ok(), scan)?
{
if scanned >= MAX_SCAN_FILES {
break;
}
for (_, month_path) in
collect_dirs_desc_sync(&year_path, |s| s.parse::<u8>().ok(), scan)?
{
if scanned >= MAX_SCAN_FILES {
break 'outer;
}
for (_, day_path) in
collect_dirs_desc_sync(&month_path, |s| s.parse::<u8>().ok(), scan)?
{
if scanned >= MAX_SCAN_FILES {
break 'outer;
}
for (_, id, path) in collect_rollout_day_files_sync(&day_path, scan)? {
scan.check_cancelled()?;
scanned += 1;
if scanned > MAX_SCAN_FILES {
break 'outer;
}
candidates.push(thread_candidate(path, id));
}
}
}
}
Ok(candidates)
})();
Ok((result, scanned))
})
.await?;
*scanned_files = scanned;
result
}
pub(super) async fn collect_flat_files_by_updated_at(
root: &Path,
scanned_files: &mut usize,
) -> io::Result<Vec<ThreadCandidate>> {
let root = root.to_path_buf();
let mut scanned = *scanned_files;
let (result, scanned) = run_scan(move |scan| {
let result = collect_flat_rollout_files_sync(&root, &mut scanned, scan).and_then(|files| {
files
.into_iter()
.map(|(_, id, path)| {
scan.check_cancelled()?;
Ok(thread_candidate(path, id))
})
.collect()
});
Ok((result, scanned))
})
.await?;
*scanned_files = scanned;
result
}
/// Resolves metadata in the same plain-before-compressed order as rollout readers.
fn thread_candidate(path: PathBuf, id: Uuid) -> ThreadCandidate {
let updated_at = compression::existing_rollout_with_metadata_sync(&path)
.map(|(_, metadata)| metadata)
.and_then(|metadata| metadata.modified().ok())
.map(OffsetDateTime::from)
.and_then(truncate_to_millis);
ThreadCandidate {
path,
id,
updated_at,
}
}
/// Collects immediate subdirectories of `parent`, parses their (string) names with `parse`,
/// and returns them sorted descending by the parsed key.
fn collect_dirs_desc_sync<T, F>(
parent: &Path,
parse: F,
scan: &Scan,
) -> io::Result<Vec<(T, PathBuf)>>
where
T: Ord + Copy,
F: Fn(&str) -> Option<T>,
{
scan.check_cancelled()?;
let dir = std::fs::read_dir(parent)?;
let mut vec: Vec<(T, PathBuf)> = Vec::new();
for entry in dir {
scan.check_cancelled()?;
let entry = entry?;
if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false)
&& let Some(s) = entry.file_name().to_str()
&& let Some(v) = parse(s)
{
vec.push((v, entry.path()));
}
}
scan.check_cancelled()?;
vec.sort_by_key(|(v, _)| Reverse(*v));
Ok(vec)
}
/// Collects files in a directory and parses them with `parse`.
fn collect_files<T, F>(parent: &Path, mut parse: F, scan: &Scan) -> io::Result<Vec<T>>
where
F: FnMut(&str, &Path) -> Option<T>,
{
scan.check_cancelled()?;
let dir = std::fs::read_dir(parent)?;
let mut collected: Vec<T> = Vec::new();
for entry in dir {
scan.check_cancelled()?;
let entry = entry?;
if entry.file_type().map(|ft| ft.is_file()).unwrap_or(false)
&& let Some(s) = entry.file_name().to_str()
&& let Some(v) = parse(s, &entry.path())
{
collected.push(v);
}
}
Ok(collected)
}
fn collect_flat_rollout_files_sync(
root: &Path,
scanned_files: &mut usize,
scan: &Scan,
) -> io::Result<Vec<(OffsetDateTime, Uuid, PathBuf)>> {
scan.check_cancelled()?;
let dir = std::fs::read_dir(root)?;
let mut collected = Vec::new();
for entry in dir {
scan.check_cancelled()?;
let entry = entry?;
if *scanned_files >= MAX_SCAN_FILES {
break;
}
if !entry.file_type().map(|ft| ft.is_file()).unwrap_or(false) {
continue;
}
let Some(rollout_file) = compression::RolloutFile::from_path(entry.path()) else {
continue;
};
let Some((ts, id)) = parse_timestamp_uuid_from_filename(rollout_file.plain_file_name())
else {
continue;
};
*scanned_files += 1;
if *scanned_files > MAX_SCAN_FILES {
break;
}
collected.push((ts, id, rollout_file.into_path()));
}
Ok(collected)
}
fn collect_rollout_day_files_sync(
day_path: &Path,
scan: &Scan,
) -> io::Result<Vec<(OffsetDateTime, Uuid, PathBuf)>> {
let mut day_files = collect_files(
day_path,
|_name_str, path| {
let rollout_file = compression::RolloutFile::from_path(path.to_path_buf())?;
parse_timestamp_uuid_from_filename(rollout_file.plain_file_name())
.map(|(ts, id)| (ts, id, rollout_file.into_path()))
},
scan,
)?;
// Stable ordering within the same second: (timestamp desc, uuid desc)
scan.check_cancelled()?;
day_files.sort_by_key(|(ts, sid, _path)| (Reverse(*ts), Reverse(*sid)));
Ok(day_files)
}
#[cfg(test)]
#[path = "list_files_tests.rs"]
mod tests;

View File

@@ -0,0 +1,134 @@
//! Candidate discovery coverage shared by flat and date-partitioned rollout layouts.
use super::*;
use crate::list::ThreadListLayout;
use pretty_assertions::assert_eq;
use std::fs::File;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::UNIX_EPOCH;
use tempfile::TempDir;
#[tokio::test]
async fn sibling_rollout_candidates_prioritize_first_ancestor_at_capacity() -> anyhow::Result<()> {
let directory = TempDir::new()?;
let thread_id = ThreadId::new();
let child_id = RolloutId::new();
let sibling_ids: Vec<_> = (0..=MAX_SIBLING_ROLLOUT_IDS)
.map(|_| RolloutId::new())
.collect();
for rollout_id in sibling_ids.iter().copied().chain([child_id]) {
let file_name = RolloutFileName::new(OffsetDateTime::UNIX_EPOCH, thread_id, rollout_id);
File::create(directory.path().join(file_name.render()?))?;
}
let initial =
collect_sibling_rollout_ids(directory.path(), thread_id, child_id, sibling_ids[0]).await?;
let omitted = sibling_ids
.into_iter()
.find(|id| !initial.contains(id))
.expect("one sibling must exceed the candidate limit");
let prioritized =
collect_sibling_rollout_ids(directory.path(), thread_id, child_id, omitted).await?;
assert_eq!(prioritized.len(), MAX_SIBLING_ROLLOUT_IDS);
assert!(prioritized.contains(&omitted));
Ok(())
}
#[tokio::test]
async fn dropping_scan_stops_directory_enumeration() -> anyhow::Result<()> {
let root = TempDir::new()?;
for name in ["first", "second"] {
File::create(root.path().join(name))?;
}
let path = root.path().to_path_buf();
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let (resume_tx, resume_rx) = std::sync::mpsc::channel();
let (finished_tx, finished_rx) = tokio::sync::oneshot::channel();
let visited = Arc::new(AtomicUsize::new(0));
let worker_visited = Arc::clone(&visited);
let task = tokio::spawn(run_scan(move |scan| {
let mut started_tx = Some(started_tx);
let result = collect_files(
&path,
|name, _| {
worker_visited.fetch_add(1, Ordering::SeqCst);
if let Some(started_tx) = started_tx.take() {
let _ = started_tx.send(());
resume_rx.recv().expect("resume scan");
}
Some(name.to_string())
},
scan,
);
let _ = finished_tx.send(result.as_ref().err().map(io::Error::kind));
result
}));
started_rx.await?;
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
resume_tx.send(())?;
assert_eq!(
(finished_rx.await?, visited.load(Ordering::SeqCst)),
(Some(io::ErrorKind::Interrupted), 1),
);
Ok(())
}
#[tokio::test]
async fn updated_candidates_preserve_layout_and_plain_sibling_preference() -> io::Result<()> {
for layout in [ThreadListLayout::Flat, ThreadListLayout::NestedByDate] {
let root = TempDir::new()?;
let directory = match layout {
ThreadListLayout::Flat => root.path().to_path_buf(),
ThreadListLayout::NestedByDate => root.path().join("2026/09/26"),
};
std::fs::create_dir_all(&directory)?;
let id = Uuid::from_u128(1);
let path = directory.join(format!("rollout-2026-09-26T10-00-00-{id}.jsonl"));
File::create(&path)?.set_modified(UNIX_EPOCH + Duration::from_secs(100))?;
File::create(compression::compressed_rollout_path(&path))?
.set_modified(UNIX_EPOCH + Duration::from_secs(200))?;
File::create(directory.join("unrelated.jsonl"))?;
std::fs::create_dir(directory.join("rollout-2026-09-26T10-00-01-invalid.jsonl"))?;
#[cfg(unix)]
std::os::unix::fs::symlink(
&path,
directory.join(format!(
"rollout-2026-09-26T10-00-02-{}.jsonl",
Uuid::from_u128(2)
)),
)?;
let mut scanned = 0;
let candidates = match layout {
ThreadListLayout::Flat => {
collect_flat_files_by_updated_at(root.path(), &mut scanned).await?
}
ThreadListLayout::NestedByDate => {
collect_files_by_updated_at(root.path(), &mut scanned).await?
}
};
assert_eq!(
(
scanned,
candidates
.into_iter()
.map(|candidate| (candidate.id, candidate.path, candidate.updated_at))
.collect::<Vec<_>>()
),
(
1,
vec![(
id,
path,
Some(OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(100))
)]
),
);
}
Ok(())
}

View File

@@ -0,0 +1,52 @@
//! Coordinates maintenance jobs that replace local rollout files.
//!
//! Rollout compression and legacy rollout migration both publish by renaming a replacement over an
//! existing rollout path. They must not do that at the same time for one Codex home, so they share
//! this process-scoped, nonblocking file lock.
//!
//! This is separate from per-thread writer locks, which protect live rollout appenders. It is also
//! separate from compression's durable run marker, which throttles how often compression scans.
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::io;
use std::path::Path;
const ROLLOUT_MAINTENANCE_LOCK: &str = "rollout-maintenance.lock";
#[cfg(test)]
#[path = "maintenance_tests.rs"]
mod tests;
/// Holds exclusive ownership of operations that replace local rollout files.
pub struct RolloutMaintenanceGuard {
file: File,
}
impl Drop for RolloutMaintenanceGuard {
fn drop(&mut self) {
// Release the lock even if a child inherited the file before exec.
let _ = self.file.unlock();
}
}
/// Try to exclude rollout compression and migration for one Codex home.
pub fn try_acquire_rollout_maintenance_lock(
codex_home: &Path,
) -> io::Result<Option<RolloutMaintenanceGuard>> {
let directory = codex_home.join(".tmp");
fs::create_dir_all(&directory)?;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(directory.join(ROLLOUT_MAINTENANCE_LOCK))?;
match file.try_lock() {
Ok(()) => Ok(Some(RolloutMaintenanceGuard { file })),
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
Err(std::fs::TryLockError::Error(error)) => Err(error),
}
}

View File

@@ -0,0 +1,32 @@
//! Tests maintenance ownership across shared guards and duplicated file handles.
use std::io;
use std::sync::Arc;
use tempfile::TempDir;
use super::try_acquire_rollout_maintenance_lock;
#[test]
fn dropping_last_guard_releases_lock_with_duplicated_handle() -> io::Result<()> {
let home = TempDir::new()?;
let guard = Arc::new(
try_acquire_rollout_maintenance_lock(home.path())?.expect("acquire maintenance lock"),
);
let retained_guard = Arc::clone(&guard);
let duplicated_file = guard.file.try_clone()?;
assert!(try_acquire_rollout_maintenance_lock(home.path())?.is_none());
drop(guard);
assert!(try_acquire_rollout_maintenance_lock(home.path())?.is_none());
drop(retained_guard);
let next_guard = try_acquire_rollout_maintenance_lock(home.path())?
.expect("dropping the last guard releases the lock despite the duplicated handle");
drop(duplicated_file);
assert!(try_acquire_rollout_maintenance_lock(home.path())?.is_none());
drop(next_guard);
assert!(try_acquire_rollout_maintenance_lock(home.path())?.is_some());
Ok(())
}

View File

@@ -0,0 +1,499 @@
use crate::ARCHIVED_SESSIONS_SUBDIR;
use crate::RolloutItem;
use crate::SESSIONS_SUBDIR;
use crate::compression;
use crate::recorder::RolloutRecorder;
use crate::rollout_file_name::RolloutFileName;
use crate::state_db::normalize_cwd_for_state_db;
use chrono::DateTime;
use chrono::NaiveDateTime;
use chrono::Timelike;
use chrono::Utc;
use codex_protocol::RolloutId;
use codex_protocol::ThreadId;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::protocol::SessionMeta;
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_state::BackfillState;
use codex_state::BackfillStats;
use codex_state::BackfillStatus;
use codex_state::DB_ERROR_METRIC;
use codex_state::DB_METRIC_BACKFILL;
use codex_state::DB_METRIC_BACKFILL_DURATION_MS;
use codex_state::ExtractionOutcome;
use codex_state::ThreadMetadataBuilder;
use codex_state::apply_rollout_item;
use std::path::Path;
use std::path::PathBuf;
use tracing::info;
use tracing::warn;
const BACKFILL_BATCH_SIZE: usize = 200;
#[cfg(not(test))]
const BACKFILL_LEASE_SECONDS: i64 = 900;
#[cfg(test)]
const BACKFILL_LEASE_SECONDS: i64 = 1;
pub(crate) fn builder_from_session_meta(
session_meta: &SessionMetaLine,
rollout_path: &Path,
) -> Option<ThreadMetadataBuilder> {
let created_at = parse_timestamp_to_utc(session_meta.meta.timestamp.as_str())?;
let mut builder = ThreadMetadataBuilder::new(
session_meta.meta.id,
rollout_path.to_path_buf(),
created_at,
session_meta.meta.source.clone(),
);
builder.creator_user_id = session_meta.meta.creator_user_id.clone();
builder.creator_account_id = session_meta.meta.creator_account_id.clone();
builder.history_mode = session_meta.meta.history_mode;
builder.originator =
(!session_meta.meta.originator.is_empty()).then(|| session_meta.meta.originator.clone());
builder.model_provider = session_meta.meta.model_provider.clone();
builder.agent_nickname = session_meta.meta.agent_nickname.clone();
builder.agent_role = session_meta.meta.agent_role.clone();
builder.agent_path = session_meta.meta.agent_path.clone();
builder.cwd = session_meta.meta.cwd.clone();
builder.cli_version = Some(session_meta.meta.cli_version.clone());
builder.sandbox_policy = SandboxPolicy::new_read_only_policy();
builder.approval_mode = AskForApproval::OnRequest;
if let Some(git) = session_meta.git.as_ref() {
builder.git_sha = git.commit_hash.as_ref().map(|sha| sha.0.clone());
builder.git_branch = git.branch.clone();
builder.git_origin_url = git.repository_url.clone();
}
Some(builder)
}
pub fn builder_from_items(
items: &[RolloutItem],
rollout_path: &Path,
) -> Option<ThreadMetadataBuilder> {
if let Some(session_meta) = items.iter().find_map(|item| match item {
RolloutItem::SessionMeta(meta_line) => Some(meta_line),
RolloutItem::ResponseItem(_)
| RolloutItem::InterAgentCommunication(_)
| RolloutItem::InterAgentCommunicationMetadata { .. }
| RolloutItem::Compacted(_)
| RolloutItem::TurnContext(_)
| RolloutItem::WorldState(_)
| RolloutItem::RealtimeItem(_)
| RolloutItem::TokenUsageRecord(_)
| RolloutItem::RetainedContext(_)
| RolloutItem::DynamicToolsUpdated { .. }
| RolloutItem::SecurityRiskScore(_)
| RolloutItem::EventMsg(_) => None,
}) && let Some(builder) = builder_from_session_meta(session_meta, rollout_path)
{
return Some(builder);
}
let file_name = rollout_path.file_name()?.to_str()?;
let file_name = RolloutFileName::parse(file_name)?;
let created_ts = file_name.timestamp();
let created_at =
DateTime::<Utc>::from_timestamp(created_ts.unix_timestamp(), 0)?.with_nanosecond(0)?;
Some(ThreadMetadataBuilder::new(
file_name.thread_id(),
rollout_path.to_path_buf(),
created_at,
SessionSource::default(),
))
}
/// Returns the stable thread ID from a canonical filename, including a reverted rollout's name.
pub fn thread_id_from_rollout_path(path: &Path) -> Option<ThreadId> {
Some(RolloutFileName::parse(path.file_name()?.to_str()?)?.thread_id())
}
/// Returns the rollout ID encoded in a canonical rollout filename.
///
/// Normal rollouts use `rollout-<timestamp>-<thread-id>.jsonl`, where the thread ID and rollout ID
/// are the same. Threads that have been `reverted` use
/// `rollout-<timestamp>-<thread-id>_<rollout-id>.jsonl`, where this returns the ID after `_`.
///
/// This can differ from [`SessionMeta::id`] when `thread/revert` keeps the thread ID stable while
/// switching to a new immutable rollout file.
pub fn rollout_id_from_path(rollout_path: &Path) -> Option<RolloutId> {
let file_name = rollout_path.file_name()?.to_str()?;
Some(RolloutFileName::parse(file_name)?.rollout_id())
}
/// Reads the logical fork cutoff without mistaking a revert's history base for its parent.
///
/// Older rollouts lack the explicit cutoff. Their history base is safe to use only when it
/// names the logical parent directly or the current file is the thread's original rollout.
/// An ambiguous legacy revert omits the cutoff rather than reporting another thread's boundary.
pub fn forked_from_ordinal_exclusive(
meta: &SessionMeta,
rollout_path: Option<&Path>,
) -> Option<u64> {
let parent_id = meta.forked_from_id?;
meta.forked_from_ordinal_exclusive.or_else(|| {
meta.history_base
.filter(|base| {
base.thread_id == parent_id
|| rollout_path.and_then(rollout_id_from_path) == Some(meta.id)
})
.map(|base| base.end_ordinal_exclusive)
})
}
pub async fn extract_metadata_from_rollout(
rollout_path: &Path,
default_provider: &str,
) -> anyhow::Result<ExtractionOutcome> {
let (items, _thread_id, parse_errors) =
RolloutRecorder::load_rollout_items(rollout_path).await?;
if items.is_empty() {
return Err(anyhow::anyhow!(
"empty session file: {}",
rollout_path.display()
));
}
let builder = builder_from_items(items.as_slice(), rollout_path).ok_or_else(|| {
anyhow::anyhow!(
"rollout missing metadata builder: {}",
rollout_path.display()
)
})?;
let mut metadata = builder.build(default_provider);
for item in &items {
apply_rollout_item(&mut metadata, item, default_provider);
}
if let Some(updated_at) = file_modified_time_utc(rollout_path).await {
metadata.updated_at = updated_at;
metadata.recency_at = updated_at;
}
Ok(ExtractionOutcome {
metadata,
memory_mode: items.iter().rev().find_map(|item| match item {
RolloutItem::SessionMeta(meta_line) => meta_line.meta.memory_mode.clone(),
RolloutItem::ResponseItem(_)
| RolloutItem::InterAgentCommunication(_)
| RolloutItem::InterAgentCommunicationMetadata { .. }
| RolloutItem::Compacted(_)
| RolloutItem::TurnContext(_)
| RolloutItem::WorldState(_)
| RolloutItem::RealtimeItem(_)
| RolloutItem::TokenUsageRecord(_)
| RolloutItem::RetainedContext(_)
| RolloutItem::DynamicToolsUpdated { .. }
| RolloutItem::SecurityRiskScore(_)
| RolloutItem::EventMsg(_) => None,
}),
parse_errors,
})
}
pub(crate) async fn backfill_sessions(
runtime: &codex_state::StateRuntime,
codex_home: &Path,
default_provider: &str,
) {
backfill_sessions_with_lease(
runtime,
codex_home,
default_provider,
BACKFILL_LEASE_SECONDS,
)
.await;
}
pub(crate) async fn backfill_sessions_with_lease(
runtime: &codex_state::StateRuntime,
codex_home: &Path,
default_provider: &str,
backfill_lease_seconds: i64,
) {
let metric_client = codex_otel::global();
let timer = metric_client
.as_ref()
.and_then(|otel| otel.start_timer(DB_METRIC_BACKFILL_DURATION_MS, &[]).ok());
let backfill_state = match runtime.get_backfill_state().await {
Ok(state) => state,
Err(err) => {
warn!(
"failed to read backfill state at {}: {err}",
codex_home.display()
);
BackfillState::default()
}
};
if backfill_state.status == BackfillStatus::Complete {
return;
}
let claimed = match runtime.try_claim_backfill(backfill_lease_seconds).await {
Ok(claimed) => claimed,
Err(err) => {
warn!(
"failed to claim backfill worker at {}: {err}",
codex_home.display()
);
return;
}
};
if !claimed {
info!(
"state db backfill already running at {}; skipping duplicate worker",
codex_home.display()
);
return;
}
let mut backfill_state = match runtime.get_backfill_state().await {
Ok(state) => state,
Err(err) => {
warn!(
"failed to read claimed backfill state at {}: {err}",
codex_home.display()
);
BackfillState {
status: BackfillStatus::Running,
..Default::default()
}
}
};
if backfill_state.status != BackfillStatus::Running {
if let Err(err) = runtime.mark_backfill_running().await {
warn!(
"failed to mark backfill running at {}: {err}",
codex_home.display()
);
} else {
backfill_state.status = BackfillStatus::Running;
}
}
let sessions_root = codex_home.join(SESSIONS_SUBDIR);
let archived_root = codex_home.join(ARCHIVED_SESSIONS_SUBDIR);
let mut rollout_paths: Vec<BackfillRolloutPath> = Vec::new();
for (root, archived) in [(sessions_root, false), (archived_root, true)] {
if !tokio::fs::try_exists(&root).await.unwrap_or(false) {
continue;
}
match collect_rollout_paths(&root).await {
Ok(paths) => {
rollout_paths.extend(paths.into_iter().map(|path| BackfillRolloutPath {
watermark: backfill_watermark_for_path(codex_home, &path),
path,
archived,
}));
}
Err(err) => {
warn!(
"failed to collect rollout paths under {}: {err}",
root.display()
);
}
}
}
rollout_paths.sort_by(|a, b| a.watermark.cmp(&b.watermark));
if let Some(last_watermark) = backfill_state.last_watermark.as_deref() {
rollout_paths.retain(|entry| entry.watermark.as_str() > last_watermark);
}
let mut stats = BackfillStats {
scanned: 0,
upserted: 0,
failed: 0,
};
let mut last_watermark = backfill_state.last_watermark.clone();
for batch in rollout_paths.chunks(BACKFILL_BATCH_SIZE) {
for rollout in batch {
stats.scanned = stats.scanned.saturating_add(1);
match extract_metadata_from_rollout(&rollout.path, default_provider).await {
Ok(outcome) => {
if outcome.parse_errors > 0
&& let Some(ref metric_client) = metric_client
{
let _ = metric_client.counter(
DB_ERROR_METRIC,
outcome.parse_errors as i64,
&[("stage", "backfill_sessions")],
);
}
let mut metadata = outcome.metadata;
metadata.cwd = normalize_cwd_for_state_db(&metadata.cwd);
let memory_mode = outcome.memory_mode.unwrap_or_else(|| "enabled".to_string());
let existing_metadata = runtime.get_thread(metadata.id).await.ok().flatten();
// Paginated metadata updates are SQLite-only. Use the rollout mode to seed a
// missing row, then keep the value from SQLite.
let restore_memory_mode_from_rollout = existing_metadata.is_none()
|| matches!(metadata.history_mode, ThreadHistoryMode::Legacy);
if let Some(existing_metadata) = existing_metadata.as_ref() {
metadata.prefer_existing_git_info(existing_metadata);
metadata.prefer_existing_explicit_title(existing_metadata);
}
if rollout.archived && metadata.archived_at.is_none() {
let fallback_archived_at = metadata.updated_at;
metadata.archived_at = file_modified_time_utc(&rollout.path)
.await
.or(Some(fallback_archived_at));
}
if let Err(err) = runtime.upsert_thread(&metadata).await {
stats.failed = stats.failed.saturating_add(1);
warn!("failed to upsert rollout {}: {err}", rollout.path.display());
} else {
if restore_memory_mode_from_rollout
&& let Err(err) = runtime
.set_thread_memory_mode(metadata.id, memory_mode.as_str())
.await
{
stats.failed = stats.failed.saturating_add(1);
warn!(
"failed to restore memory mode for {}: {err}",
rollout.path.display()
);
continue;
}
stats.upserted = stats.upserted.saturating_add(1);
}
}
Err(err) => {
stats.failed = stats.failed.saturating_add(1);
warn!(
"failed to extract rollout {}: {err}",
rollout.path.display()
);
}
}
}
if let Some(last_entry) = batch.last() {
if let Err(err) = runtime
.checkpoint_backfill(last_entry.watermark.as_str())
.await
{
warn!(
"failed to checkpoint backfill at {}: {err}",
codex_home.display()
);
} else {
last_watermark = Some(last_entry.watermark.clone());
}
}
}
if let Err(err) = runtime
.mark_backfill_complete(last_watermark.as_deref())
.await
{
warn!(
"failed to mark backfill complete at {}: {err}",
codex_home.display()
);
}
info!(
"state db backfill scanned={}, upserted={}, failed={}",
stats.scanned, stats.upserted, stats.failed
);
if let Some(metric_client) = metric_client {
let _ = metric_client.counter(
DB_METRIC_BACKFILL,
stats.upserted as i64,
&[("status", "upserted")],
);
let _ = metric_client.counter(
DB_METRIC_BACKFILL,
stats.failed as i64,
&[("status", "failed")],
);
}
if let Some(timer) = timer.as_ref() {
let status = if stats.failed == 0 {
"success"
} else if stats.upserted == 0 {
"failed"
} else {
"partial_failure"
};
let _ = timer.record(&[("status", status)]);
}
}
#[derive(Debug, Clone)]
struct BackfillRolloutPath {
watermark: String,
path: PathBuf,
archived: bool,
}
fn backfill_watermark_for_path(codex_home: &Path, path: &Path) -> String {
path.strip_prefix(codex_home)
.unwrap_or(path)
.to_string_lossy()
.replace('\\', "/")
}
async fn file_modified_time_utc(path: &Path) -> Option<DateTime<Utc>> {
let modified = compression::file_modified_time(path).await.ok()??;
DateTime::<Utc>::from_timestamp(modified.unix_timestamp(), modified.nanosecond())
}
fn parse_timestamp_to_utc(ts: &str) -> Option<DateTime<Utc>> {
const FILENAME_TS_FORMAT: &str = "%Y-%m-%dT%H-%M-%S";
if let Ok(naive) = NaiveDateTime::parse_from_str(ts, FILENAME_TS_FORMAT) {
let dt = DateTime::<Utc>::from_naive_utc_and_offset(naive, Utc);
return dt.with_nanosecond(0);
}
if let Ok(dt) = DateTime::parse_from_rfc3339(ts) {
return Some(dt.with_timezone(&Utc));
}
None
}
async fn collect_rollout_paths(root: &Path) -> std::io::Result<Vec<PathBuf>> {
let mut stack = vec![root.to_path_buf()];
let mut paths = Vec::new();
while let Some(dir) = stack.pop() {
let mut read_dir = match tokio::fs::read_dir(&dir).await {
Ok(read_dir) => read_dir,
Err(err) => {
warn!("failed to read directory {}: {err}", dir.display());
continue;
}
};
loop {
let next_entry = match read_dir.next_entry().await {
Ok(next_entry) => next_entry,
Err(err) => {
warn!(
"failed to read directory entry under {}: {err}",
dir.display()
);
continue;
}
};
let Some(entry) = next_entry else {
break;
};
let path = entry.path();
let file_type = match entry.file_type().await {
Ok(file_type) => file_type,
Err(err) => {
warn!("failed to read file type for {}: {err}", path.display());
continue;
}
};
if file_type.is_dir() {
stack.push(path);
continue;
}
if !file_type.is_file() {
continue;
}
if let Some(rollout_file) = compression::RolloutFile::from_path(path) {
paths.push(rollout_file.into_path());
}
}
}
Ok(paths)
}
#[cfg(test)]
#[path = "metadata_tests.rs"]
mod tests;

View File

@@ -0,0 +1,640 @@
#![allow(warnings, clippy::all)]
use super::*;
use crate::CompactedItem;
use crate::RolloutItem;
use crate::RolloutLine;
use chrono::DateTime;
use chrono::NaiveDateTime;
use chrono::Timelike;
use chrono::Utc;
use codex_protocol::SanitizedGitUrl;
use codex_protocol::ThreadId;
use codex_protocol::protocol::GitInfo;
use codex_protocol::protocol::HistoryPosition;
use codex_protocol::protocol::SessionMeta;
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_state::BackfillStatus;
use codex_state::ThreadMetadataBuilder;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use tempfile::tempdir;
use uuid::Uuid;
#[test]
fn fork_cutoff_distinguishes_logical_parent_from_reverted_rollout() {
let parent_id = ThreadId::new();
let thread_id = ThreadId::new();
let physical_id = ThreadId::new();
let replacement_id = ThreadId::new();
let original_path = PathBuf::from(format!("rollout-2026-01-27T12-34-56-{thread_id}.jsonl"));
let reverted_path = PathBuf::from(format!(
"rollout-2026-01-27T12-34-56-{thread_id}_{replacement_id}.jsonl"
));
for (name, parent, cutoff, base_id, path, expected) in [
(
"persisted revert",
Some(parent_id),
Some(20),
thread_id,
Some(reverted_path.as_path()),
Some(20),
),
(
"legacy direct fork",
Some(parent_id),
None,
parent_id,
None,
Some(40),
),
(
"legacy fork of reverted parent",
Some(parent_id),
None,
physical_id,
Some(original_path.as_path()),
Some(40),
),
(
"legacy child revert",
Some(parent_id),
None,
thread_id,
Some(reverted_path.as_path()),
None,
),
(
"legacy repeated revert",
Some(parent_id),
None,
physical_id,
Some(reverted_path.as_path()),
None,
),
(
"missing parent",
None,
Some(20),
parent_id,
Some(original_path.as_path()),
None,
),
] {
let meta = SessionMeta {
id: thread_id,
forked_from_id: parent,
forked_from_ordinal_exclusive: cutoff,
history_base: Some(HistoryPosition {
thread_id: base_id,
end_ordinal_exclusive: 40,
end_byte_offset: 100,
}),
..SessionMeta::default()
};
assert_eq!(
forked_from_ordinal_exclusive(&meta, path),
expected,
"{name}"
);
}
}
#[tokio::test]
async fn extract_metadata_from_rollout_uses_session_meta() {
let dir = tempdir().expect("tempdir");
let uuid = Uuid::new_v4();
let id = ThreadId::from_string(&uuid.to_string()).expect("thread id");
let path = dir
.path()
.join(format!("rollout-2026-01-27T12-34-56-{uuid}.jsonl"));
let session_meta = SessionMeta {
account_scoped: false,
creator_user_id: Some("creator-user".to_string()),
attached_thread: false,
creator_account_id: Some("creator-account".to_string()),
session_id: id.into(),
id,
forked_from_id: None,
forked_from_ordinal_exclusive: None,
parent_thread_id: None,
timestamp: "2026-01-27T12:34:56Z".to_string(),
cwd: dir.path().to_path_buf(),
runtime_workspace_roots: None,
originator: "cli".to_string(),
cli_version: "0.0.0".to_string(),
source: SessionSource::default(),
thread_source: None,
agent_path: None,
agent_nickname: None,
agent_role: None,
model_provider: Some("openai".to_string()),
base_instructions: None,
dynamic_tools: None,
selected_capability_roots: Vec::new(),
memory_mode: None,
history_mode: ThreadHistoryMode::Paginated,
history_base: None,
subagent_history_start_ordinal: None,
multi_agent_version: None,
context_window: None,
};
let session_meta_line = SessionMetaLine {
meta: session_meta,
git: None,
};
let rollout_line = RolloutLine {
timestamp: "2026-01-27T12:34:56Z".to_string(),
ordinal: Some(0),
item: RolloutItem::SessionMeta(Box::new(session_meta_line.clone())),
};
let json = serde_json::to_string(&rollout_line).expect("rollout json");
let mut file = File::create(&path).expect("create rollout");
writeln!(file, "{json}").expect("write rollout");
let mut parent = session_meta_line.clone();
parent.meta.id = ThreadId::new();
parent.meta.creator_user_id = Some("parent-user".to_string());
parent.meta.creator_account_id = Some("parent-account".to_string());
let parent_line = RolloutLine {
timestamp: rollout_line.timestamp.clone(),
ordinal: Some(1),
item: RolloutItem::SessionMeta(Box::new(parent)),
};
writeln!(
file,
"{}",
serde_json::to_string(&parent_line).expect("parent json")
)
.expect("write inherited metadata");
let outcome = extract_metadata_from_rollout(&path, "openai")
.await
.expect("extract");
let builder = builder_from_session_meta(&session_meta_line, path.as_path()).expect("builder");
let mut expected = builder.build("openai");
apply_rollout_item(&mut expected, &rollout_line.item, "openai");
expected.updated_at = file_modified_time_utc(&path).await.expect("mtime");
expected.recency_at = expected.updated_at;
assert_eq!(outcome.metadata, expected);
assert_eq!(
(
outcome.metadata.creator_user_id.as_deref(),
outcome.metadata.creator_account_id.as_deref()
),
(Some("creator-user"), Some("creator-account")),
);
assert_eq!(outcome.memory_mode, None);
assert_eq!(outcome.parse_errors, 0);
}
#[tokio::test]
async fn extract_metadata_from_rollout_rejects_unknown_history_mode() {
let dir = tempdir().expect("tempdir");
let uuid = Uuid::new_v4();
let id = ThreadId::from_string(&uuid.to_string()).expect("thread id");
let path = dir
.path()
.join(format!("rollout-2026-01-27T12-34-56-{uuid}.jsonl"));
let mut rollout_line = serde_json::to_value(RolloutLine {
timestamp: "2026-01-27T12:34:56Z".to_string(),
ordinal: None,
item: RolloutItem::SessionMeta(Box::new(SessionMetaLine {
meta: SessionMeta {
session_id: id.into(),
id,
timestamp: "2026-01-27T12:34:56Z".to_string(),
cwd: dir.path().to_path_buf(),
originator: "cli".to_string(),
cli_version: "0.0.0".to_string(),
..SessionMeta::default()
},
git: None,
})),
})
.expect("serialize rollout line");
rollout_line["payload"]["history_mode"] = serde_json::json!("future");
let mut file = File::create(&path).expect("create rollout");
writeln!(file, "{rollout_line}").expect("write rollout");
assert!(
extract_metadata_from_rollout(&path, "openai")
.await
.is_err()
);
}
#[tokio::test]
async fn extract_metadata_from_rollout_returns_latest_memory_mode() {
let dir = tempdir().expect("tempdir");
let uuid = Uuid::new_v4();
let id = ThreadId::from_string(&uuid.to_string()).expect("thread id");
let path = dir
.path()
.join(format!("rollout-2026-01-27T12-34-56-{uuid}.jsonl"));
let session_meta = SessionMeta {
account_scoped: false,
creator_user_id: None,
attached_thread: false,
creator_account_id: None,
session_id: id.into(),
id,
forked_from_id: None,
forked_from_ordinal_exclusive: None,
parent_thread_id: None,
timestamp: "2026-01-27T12:34:56Z".to_string(),
cwd: dir.path().to_path_buf(),
runtime_workspace_roots: None,
originator: "cli".to_string(),
cli_version: "0.0.0".to_string(),
source: SessionSource::default(),
thread_source: None,
agent_path: None,
agent_nickname: None,
agent_role: None,
model_provider: Some("openai".to_string()),
base_instructions: None,
dynamic_tools: None,
selected_capability_roots: Vec::new(),
memory_mode: None,
history_mode: Default::default(),
history_base: None,
subagent_history_start_ordinal: None,
multi_agent_version: None,
context_window: None,
};
let polluted_meta = SessionMeta {
memory_mode: Some("polluted".to_string()),
multi_agent_version: None,
..session_meta.clone()
};
let lines = vec![
RolloutLine {
timestamp: "2026-01-27T12:34:56Z".to_string(),
ordinal: None,
item: RolloutItem::SessionMeta(Box::new(SessionMetaLine {
meta: session_meta,
git: None,
})),
},
RolloutLine {
timestamp: "2026-01-27T12:35:00Z".to_string(),
ordinal: None,
item: RolloutItem::SessionMeta(Box::new(SessionMetaLine {
meta: polluted_meta,
git: None,
})),
},
];
let mut file = File::create(&path).expect("create rollout");
for line in lines {
writeln!(
file,
"{}",
serde_json::to_string(&line).expect("serialize rollout line")
)
.expect("write rollout line");
}
let outcome = extract_metadata_from_rollout(&path, "openai")
.await
.expect("extract");
assert_eq!(outcome.memory_mode.as_deref(), Some("polluted"));
}
#[test]
fn builder_from_items_falls_back_to_filename() {
let dir = tempdir().expect("tempdir");
let uuid = Uuid::new_v4();
let path = dir
.path()
.join(format!("rollout-2026-01-27T12-34-56-{uuid}.jsonl"));
let items = vec![RolloutItem::Compacted(Box::new(CompactedItem {
message: "noop".to_string(),
replacement_history: None,
retained_context: None,
guardian_history: None,
mcp_resource_origins: None,
window_number: None,
first_window_id: None,
previous_window_id: None,
window_id: None,
compaction_response_id: None,
latest_token_usage_record: None,
resume_metadata: None,
}))];
let builder = builder_from_items(items.as_slice(), path.as_path()).expect("builder");
let naive = NaiveDateTime::parse_from_str("2026-01-27T12-34-56", "%Y-%m-%dT%H-%M-%S")
.expect("timestamp");
let created_at = DateTime::<Utc>::from_naive_utc_and_offset(naive, Utc)
.with_nanosecond(0)
.expect("nanosecond");
let expected = ThreadMetadataBuilder::new(
ThreadId::from_string(&uuid.to_string()).expect("thread id"),
path,
created_at,
SessionSource::default(),
);
assert_eq!(builder, expected);
}
#[tokio::test]
async fn backfill_sessions_resumes_from_watermark_and_marks_complete() {
let dir = tempdir().expect("tempdir");
let codex_home = dir.path().to_path_buf();
let first_uuid = Uuid::new_v4();
let second_uuid = Uuid::new_v4();
let first_path = write_rollout_in_sessions(
codex_home.as_path(),
"2026-01-27T12-34-56",
"2026-01-27T12:34:56Z",
first_uuid,
/*git*/ None,
);
let second_path = write_rollout_in_sessions(
codex_home.as_path(),
"2026-01-27T12-35-56",
"2026-01-27T12:35:56Z",
second_uuid,
/*git*/ None,
);
let runtime = codex_state::StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
let first_watermark = backfill_watermark_for_path(codex_home.as_path(), first_path.as_path());
runtime.mark_backfill_running().await.expect("mark running");
runtime
.checkpoint_backfill(first_watermark.as_str())
.await
.expect("checkpoint first watermark");
tokio::time::sleep(std::time::Duration::from_secs(
(BACKFILL_LEASE_SECONDS + 1) as u64,
))
.await;
backfill_sessions(runtime.as_ref(), codex_home.as_path(), "test-provider").await;
let first_id = ThreadId::from_string(&first_uuid.to_string()).expect("first thread id");
let second_id = ThreadId::from_string(&second_uuid.to_string()).expect("second thread id");
assert_eq!(
runtime
.get_thread(first_id)
.await
.expect("get first thread"),
None
);
assert!(
runtime
.get_thread(second_id)
.await
.expect("get second thread")
.is_some()
);
let state = runtime
.get_backfill_state()
.await
.expect("get backfill state");
assert_eq!(state.status, BackfillStatus::Complete);
assert_eq!(
state.last_watermark,
Some(backfill_watermark_for_path(
codex_home.as_path(),
second_path.as_path()
))
);
assert!(state.last_success_at.is_some());
}
#[tokio::test]
async fn backfill_sessions_preserves_existing_git_branch_and_fills_missing_git_fields() {
let dir = tempdir().expect("tempdir");
let codex_home = dir.path().to_path_buf();
let thread_uuid = Uuid::new_v4();
let rollout_path = write_rollout_in_sessions(
codex_home.as_path(),
"2026-01-27T12-34-56",
"2026-01-27T12:34:56Z",
thread_uuid,
Some(GitInfo {
commit_hash: Some(codex_git_utils::GitSha::new("rollout-sha")),
branch: Some("rollout-branch".to_string()),
repository_url: Some(
SanitizedGitUrl::try_from("git@example.com:openai/codex.git")
.expect("valid git remote URL"),
),
}),
);
let runtime = codex_state::StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
let thread_id = ThreadId::from_string(&thread_uuid.to_string()).expect("thread id");
let mut existing = extract_metadata_from_rollout(&rollout_path, "test-provider")
.await
.expect("extract")
.metadata;
existing.git_sha = None;
existing.git_branch = Some("sqlite-branch".to_string());
existing.git_origin_url = None;
runtime
.upsert_thread(&existing)
.await
.expect("existing metadata upsert");
backfill_sessions(runtime.as_ref(), codex_home.as_path(), "test-provider").await;
let persisted = runtime
.get_thread(thread_id)
.await
.expect("get thread")
.expect("thread exists");
assert_eq!(persisted.git_sha.as_deref(), Some("rollout-sha"));
assert_eq!(persisted.git_branch.as_deref(), Some("sqlite-branch"));
assert_eq!(
persisted.git_origin_url.as_deref(),
Some("git@example.com:openai/codex.git")
);
}
#[tokio::test]
async fn backfill_sessions_preserves_existing_paginated_memory_mode() {
let dir = tempdir().expect("tempdir");
let codex_home = dir.path().to_path_buf();
let thread_uuid = Uuid::new_v4();
let rollout_path = write_rollout_in_sessions_with_cwd(
codex_home.as_path(),
"2026-01-27T12-34-56",
"2026-01-27T12:34:56Z",
thread_uuid,
codex_home.clone(),
/*git*/ None,
ThreadHistoryMode::Paginated,
);
let runtime = codex_state::StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
let thread_id = ThreadId::from_string(&thread_uuid.to_string()).expect("thread id");
let existing = extract_metadata_from_rollout(&rollout_path, "test-provider")
.await
.expect("extract")
.metadata;
runtime
.upsert_thread(&existing)
.await
.expect("existing metadata upsert");
assert!(
runtime
.set_thread_memory_mode(thread_id, "disabled")
.await
.expect("disable memory mode")
);
backfill_sessions(runtime.as_ref(), codex_home.as_path(), "test-provider").await;
assert_eq!(
runtime
.get_thread_memory_mode(thread_id)
.await
.expect("get memory mode")
.as_deref(),
Some("disabled")
);
}
#[tokio::test]
async fn backfill_sessions_normalizes_cwd_before_upsert() {
let dir = tempdir().expect("tempdir");
let codex_home = dir.path().to_path_buf();
let thread_uuid = Uuid::new_v4();
let session_cwd = codex_home.join(".");
let rollout_path = write_rollout_in_sessions_with_cwd(
codex_home.as_path(),
"2026-01-27T12-34-56",
"2026-01-27T12:34:56Z",
thread_uuid,
session_cwd.clone(),
/*git*/ None,
ThreadHistoryMode::Legacy,
);
let runtime = codex_state::StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(codex_home.as_path().abs()),
"test-provider".to_string(),
)
.await
.expect("initialize runtime");
backfill_sessions(runtime.as_ref(), codex_home.as_path(), "test-provider").await;
let thread_id = ThreadId::from_string(&thread_uuid.to_string()).expect("thread id");
let stored = runtime
.get_thread(thread_id)
.await
.expect("get thread")
.expect("thread should be backfilled");
assert_eq!(stored.rollout_path, rollout_path);
assert_eq!(stored.cwd, normalize_cwd_for_state_db(&session_cwd));
}
fn write_rollout_in_sessions(
codex_home: &Path,
filename_ts: &str,
event_ts: &str,
thread_uuid: Uuid,
git: Option<GitInfo>,
) -> PathBuf {
write_rollout_in_sessions_with_cwd(
codex_home,
filename_ts,
event_ts,
thread_uuid,
codex_home.to_path_buf(),
git,
ThreadHistoryMode::Legacy,
)
}
fn write_rollout_in_sessions_with_cwd(
codex_home: &Path,
filename_ts: &str,
event_ts: &str,
thread_uuid: Uuid,
cwd: PathBuf,
git: Option<GitInfo>,
history_mode: ThreadHistoryMode,
) -> PathBuf {
let id = ThreadId::from_string(&thread_uuid.to_string()).expect("thread id");
let sessions_dir = codex_home.join("sessions");
std::fs::create_dir_all(sessions_dir.as_path()).expect("create sessions dir");
let path = sessions_dir.join(format!("rollout-{filename_ts}-{thread_uuid}.jsonl"));
let session_meta = SessionMeta {
account_scoped: false,
creator_user_id: None,
attached_thread: false,
creator_account_id: None,
session_id: id.into(),
id,
forked_from_id: None,
forked_from_ordinal_exclusive: None,
parent_thread_id: None,
timestamp: event_ts.to_string(),
cwd,
runtime_workspace_roots: None,
originator: "cli".to_string(),
cli_version: "0.0.0".to_string(),
source: SessionSource::default(),
thread_source: None,
agent_path: None,
agent_nickname: None,
agent_role: None,
model_provider: Some("test-provider".to_string()),
base_instructions: None,
dynamic_tools: None,
selected_capability_roots: Vec::new(),
memory_mode: None,
history_mode,
history_base: None,
subagent_history_start_ordinal: None,
multi_agent_version: None,
context_window: None,
};
let session_meta_line = SessionMetaLine {
meta: session_meta,
git,
};
let rollout_line = RolloutLine {
timestamp: event_ts.to_string(),
ordinal: None,
item: RolloutItem::SessionMeta(Box::new(session_meta_line)),
};
let json = serde_json::to_string(&rollout_line).expect("serialize rollout");
let mut file = File::create(&path).expect("create rollout");
writeln!(file, "{json}").expect("write rollout");
path
}

View File

@@ -0,0 +1,59 @@
//! Collects persisted rollout items needed to reconstruct the most recent context window.
//!
//! Storage readers feed items newest-to-oldest. The scan stops at the newest compaction that has
//! both replacement history and a window number, or at the beginning of the rollout when no such
//! compaction exists. Items are returned in chronological order.
use crate::RolloutItem;
/// Whether a reverse model-context scan needs more rollout items.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ModelContextScanProgress {
/// The reader should provide the next older rollout item.
Continue,
/// The scan has collected a safe bounded suffix.
Complete,
}
/// Finds a bounded suffix for reconstructing the most recent context window.
///
/// A compaction with replacement history and a window number is a complete conversation-history
/// boundary. Records after it provide any companion state that was persisted. Older compactions
/// missing either field require the complete rollout so reconstruction can rebuild their history
/// or window number.
#[derive(Debug, Default)]
pub struct ModelContextScan {
items_newest_first: Vec<RolloutItem>,
requires_full_replay: bool,
}
impl ModelContextScan {
/// Adds the next newest-to-oldest rollout item and reports whether the reader can stop.
pub fn push(&mut self, item: RolloutItem) -> ModelContextScanProgress {
let progress = if self.requires_full_replay {
ModelContextScanProgress::Continue
} else if let RolloutItem::Compacted(compacted) = &item {
if compacted.replacement_history.is_some() && compacted.window_number.is_some() {
ModelContextScanProgress::Complete
} else {
// This compaction cannot be reconstructed from a bounded suffix. Do not stop at
// an older compaction because this newer one still affects the surviving history.
self.requires_full_replay = true;
ModelContextScanProgress::Continue
}
} else {
ModelContextScanProgress::Continue
};
self.items_newest_first.push(item);
progress
}
/// Returns the collected items in chronological order.
///
/// Call this after the reader reaches the beginning of its source or after [`Self::push`]
/// returns [`ModelContextScanProgress::Complete`].
pub fn finish(mut self) -> Vec<RolloutItem> {
self.items_newest_first.reverse();
self.items_newest_first
}
}

View File

@@ -0,0 +1,131 @@
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Seek;
use std::io::SeekFrom;
use std::path::Path;
use codex_protocol::protocol::HistoryPosition;
use codex_protocol::protocol::ThreadHistoryMode;
use crate::RolloutItem;
use crate::reverse_jsonl_scanner::ReverseJsonlScanner;
use crate::reverse_jsonl_scanner::ScanOutcome;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum RolloutOrdinalState {
Legacy,
Paginated { next: Option<u64> },
}
impl RolloutOrdinalState {
pub(crate) fn for_new_rollout(
history_mode: ThreadHistoryMode,
history_base: Option<HistoryPosition>,
) -> Self {
match history_mode {
ThreadHistoryMode::Legacy => Self::Legacy,
ThreadHistoryMode::Paginated => Self::Paginated {
next: Some(history_base.map_or(0, |base| base.end_ordinal_exclusive)),
},
}
}
pub(crate) fn current(&self) -> io::Result<Option<u64>> {
match self {
Self::Legacy => Ok(None),
Self::Paginated { next } => {
let ordinal = (*next)
.ok_or_else(|| io::Error::other("paginated rollout record ordinal overflow"))?;
Ok(Some(ordinal))
}
}
}
pub(crate) fn advance(&mut self) {
if let Self::Paginated { next } = self
&& let Some(ordinal) = *next
{
*next = ordinal.checked_add(1);
}
}
}
pub(crate) fn ordinal_state_for_rollout(
file: &mut File,
path: &Path,
) -> io::Result<RolloutOrdinalState> {
let Some((history_mode, subagent_history_start_ordinal)) = read_history_metadata(file, path)?
else {
return Ok(RolloutOrdinalState::Legacy);
};
if matches!(history_mode, ThreadHistoryMode::Legacy) {
return Ok(RolloutOrdinalState::Legacy);
}
let mut scanner = ReverseJsonlScanner::new(file)?;
let record = loop {
match scanner.scan_next_rollout_line()? {
Some(ScanOutcome::Parsed(record)) => break record,
Some(ScanOutcome::Rejected(_)) => continue,
None => {
return Err(io::Error::other(format!(
"rollout at {} contains no valid records",
path.display()
)));
}
}
};
let ordinal = record.ordinal.ok_or_else(|| {
io::Error::other(format!(
"final paginated rollout record at {} is missing an ordinal",
path.display()
))
})?;
// Child records must start at `subagent_history_start_ordinal`. If initialization died while
// copying the inherited parent records, resuming would append child records before that
// boundary.
if let Some(prefix_end) = subagent_history_start_ordinal.and_then(|start| start.checked_sub(1))
&& ordinal < prefix_end
{
return Err(io::Error::other(format!(
"paginated subagent rollout at {} is incomplete: expected inherited prefix through ordinal {prefix_end}, found final durable ordinal {ordinal}",
path.display()
)));
}
Ok(RolloutOrdinalState::Paginated {
next: ordinal.checked_add(1),
})
}
fn read_history_metadata(
file: &mut File,
path: &Path,
) -> io::Result<Option<(ThreadHistoryMode, Option<u64>)>> {
file.seek(SeekFrom::Start(0))?;
let reader = BufReader::new(file);
for line in reader.lines() {
let line = line?;
if line.trim().is_empty() {
continue;
}
let record = crate::parse_rollout_line(line.as_str()).map_err(|error| {
io::Error::other(format!(
"failed to parse first rollout record at {}: {error}",
path.display()
))
})?;
let RolloutItem::SessionMeta(session_meta) = record.item else {
return Err(io::Error::other(format!(
"rollout at {} does not start with session metadata",
path.display()
)));
};
return Ok(Some((
session_meta.meta.history_mode,
session_meta.meta.subagent_history_start_ordinal,
)));
}
Ok(None)
}

View File

@@ -0,0 +1,515 @@
use std::borrow::Cow;
use std::io::Write;
use std::sync::Arc;
use std::sync::Mutex;
use codex_otel::MetricsClient;
use codex_protocol::ThreadId;
use codex_protocol::items::TurnItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ThreadHistoryMode;
use crate::ResponseItemEnvelope;
use crate::RolloutItem;
use crate::policy::persisted_rollout_item;
const ITEM_BYTES_METRIC: &str = "codex.rollout.persistence.item_bytes_v2";
const BYTES_REMOVED_METRIC: &str = "codex.rollout.persistence.bytes_removed";
const APPEND_METRIC: &str = "codex.rollout.persistence.append";
const TURN_BYTES_METRIC: &str = "codex.rollout.persistence.turn_bytes_v2";
const MEASUREMENT_ERROR_METRIC: &str = "codex.rollout.persistence.measurement_error";
const SAMPLE_DENOMINATOR: u64 = 100;
const SAMPLE_RATE_LABEL: &str = "0.01";
const KIB: f64 = 1_024.0;
const MIB: f64 = 1_024.0 * KIB;
// Cover the persistence cap while retaining enough range for large items and turns. Values above
// 64 MiB remain visible in the overflow bucket and histogram sum.
const ROLLOUT_BYTES_BOUNDARIES: &[f64] = &[
KIB,
4.0 * KIB,
16.0 * KIB,
64.0 * KIB,
256.0 * KIB,
MIB,
4.0 * MIB,
16.0 * MIB,
64.0 * MIB,
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PersistenceDecision {
Kept,
Dropped,
}
impl PersistenceDecision {
fn as_str(self) -> &'static str {
match self {
Self::Kept => "kept",
Self::Dropped => "dropped",
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RolloutSizeTotals {
pub items: u64,
pub payload_bytes: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RolloutItemMeasurement {
pub decision: PersistenceDecision,
pub rollout_item_type: String,
pub payload_bytes: Option<u64>,
pub persisted_payload_bytes: Option<u64>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RolloutPersistenceBatchMeasurement {
pub pre_filter: RolloutSizeTotals,
pub post_filter: RolloutSizeTotals,
pub items: Vec<RolloutItemMeasurement>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct TurnSizeTotals {
pre_filter: RolloutSizeTotals,
post_filter: RolloutSizeTotals,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TurnOutcome {
Completed,
Aborted,
}
impl TurnOutcome {
fn as_str(self) -> &'static str {
match self {
Self::Completed => "completed",
Self::Aborted => "aborted",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CompletedTurnMeasurement {
totals: TurnSizeTotals,
outcome: TurnOutcome,
}
#[derive(Debug, Default, PartialEq, Eq)]
struct TurnMeasurementState {
pending: TurnSizeTotals,
active: Option<TurnSizeTotals>,
}
#[derive(Debug, Default, PartialEq, Eq)]
struct TurnMeasurementUpdate {
completed: Vec<CompletedTurnMeasurement>,
boundary_errors: Vec<&'static str>,
}
/// Measures logical JSON sizes while applying the shared rollout persistence policy once.
pub fn measure_and_filter_rollout_items(
items: &[RolloutItem],
history_mode: ThreadHistoryMode,
) -> (Vec<RolloutItem>, RolloutPersistenceBatchMeasurement) {
let mut persisted = Vec::new();
let mut measurement = RolloutPersistenceBatchMeasurement {
items: Vec::with_capacity(items.len()),
..Default::default()
};
for item in items {
let projected = persisted_rollout_item(item, history_mode);
let decision = if projected.is_some() {
PersistenceDecision::Kept
} else {
PersistenceDecision::Dropped
};
let payload_bytes = serialized_len(item).ok();
let persisted_payload_bytes = match projected.as_ref() {
Some(Cow::Borrowed(_)) => payload_bytes,
Some(Cow::Owned(item)) => serialized_len(item).ok(),
None => None,
};
add_to_totals(&mut measurement.pre_filter, payload_bytes);
if let Some(projected) = projected {
add_to_totals(&mut measurement.post_filter, persisted_payload_bytes);
persisted.push(projected.into_owned());
}
measurement.items.push(RolloutItemMeasurement {
decision,
rollout_item_type: rollout_item_type(item),
payload_bytes,
persisted_payload_bytes,
});
}
(persisted, measurement)
}
fn add_to_totals(totals: &mut RolloutSizeTotals, payload_bytes: Option<u64>) {
totals.items = totals.items.saturating_add(1);
if let Some(payload_bytes) = payload_bytes {
totals.payload_bytes = totals.payload_bytes.saturating_add(payload_bytes);
}
}
fn update_turn_measurements(
state: &mut TurnMeasurementState,
items: &[RolloutItem],
measurement: &RolloutPersistenceBatchMeasurement,
) -> TurnMeasurementUpdate {
let mut update = TurnMeasurementUpdate::default();
for (item, item_measurement) in items.iter().zip(&measurement.items) {
match item {
RolloutItem::EventMsg(EventMsg::TurnStarted(_)) => {
if state.active.take().is_some() {
update.boundary_errors.push("event.turn_started");
}
let mut totals = std::mem::take(&mut state.pending);
add_item_to_turn(&mut totals, item_measurement);
state.active = Some(totals);
}
RolloutItem::EventMsg(EventMsg::TurnComplete(_)) => {
finish_turn(
state,
item_measurement,
TurnOutcome::Completed,
"event.turn_complete",
&mut update,
);
}
RolloutItem::EventMsg(EventMsg::TurnAborted(_)) => {
finish_turn(
state,
item_measurement,
TurnOutcome::Aborted,
"event.turn_aborted",
&mut update,
);
}
_ => match state.active.as_mut() {
Some(totals) => add_item_to_turn(totals, item_measurement),
None => add_item_to_turn(&mut state.pending, item_measurement),
},
}
}
update
}
fn finish_turn(
state: &mut TurnMeasurementState,
item: &RolloutItemMeasurement,
outcome: TurnOutcome,
boundary_type: &'static str,
update: &mut TurnMeasurementUpdate,
) {
let Some(mut totals) = state.active.take() else {
state.pending = TurnSizeTotals::default();
update.boundary_errors.push(boundary_type);
return;
};
add_item_to_turn(&mut totals, item);
update
.completed
.push(CompletedTurnMeasurement { totals, outcome });
}
fn add_item_to_turn(totals: &mut TurnSizeTotals, item: &RolloutItemMeasurement) {
add_to_totals(&mut totals.pre_filter, item.payload_bytes);
if item.decision == PersistenceDecision::Kept {
add_to_totals(&mut totals.post_filter, item.persisted_payload_bytes);
}
}
fn serialized_len(item: &RolloutItem) -> serde_json::Result<u64> {
let mut writer = CountingWriter::default();
serde_json::to_writer(&mut writer, item)?;
Ok(writer.bytes)
}
#[derive(Default)]
struct CountingWriter {
bytes: u64,
}
impl Write for CountingWriter {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.bytes = self.bytes.saturating_add(buf.len() as u64);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
fn rollout_item_type(item: &RolloutItem) -> String {
match item {
RolloutItem::DynamicToolsUpdated { .. } => "dynamic_tools_updated".to_string(),
RolloutItem::SessionMeta(_) => "session_meta".to_string(),
RolloutItem::ResponseItem(item) => response_item_type(item).to_string(),
RolloutItem::InterAgentCommunication(_) => "inter_agent_communication".to_string(),
RolloutItem::InterAgentCommunicationMetadata { .. } => {
"inter_agent_communication_metadata".to_string()
}
RolloutItem::Compacted(_) => "compacted".to_string(),
RolloutItem::TurnContext(_) => "turn_context".to_string(),
RolloutItem::TokenUsageRecord(_) => "token_usage_record".to_string(),
RolloutItem::WorldState(_) => "world_state".to_string(),
RolloutItem::RetainedContext(_) => "retained_context".to_string(),
RolloutItem::SecurityRiskScore(_) => "security_risk_score".to_string(),
RolloutItem::RealtimeItem(item) => match &item.content {
codex_protocol::realtime::RealtimeItemContent::RealtimeSessionStarted => {
"realtime.session_started".to_string()
}
codex_protocol::realtime::RealtimeItemContent::TranscriptSegment { .. } => {
"realtime.transcript_segment".to_string()
}
codex_protocol::realtime::RealtimeItemContent::BemItemPromoted { .. } => {
"realtime.bem_item_promoted".to_string()
}
codex_protocol::realtime::RealtimeItemContent::RealtimeSessionClosed { .. } => {
"realtime.session_closed".to_string()
}
},
RolloutItem::EventMsg(EventMsg::ItemCompleted(event)) => {
format!("event.item_completed.{}", turn_item_type(&event.item))
}
RolloutItem::EventMsg(event) => format!("event.{event}"),
}
}
fn turn_item_type(item: &TurnItem) -> &'static str {
match item {
TurnItem::UserMessage(_) => "user_message",
TurnItem::FunctionCallOutput(_) => "function_call_output",
TurnItem::HookPrompt(_) => "hook_prompt",
TurnItem::AgentMessage(_) => "agent_message",
TurnItem::Plan(_) => "plan",
TurnItem::Reasoning(_) => "reasoning",
TurnItem::CommandExecution(_) => "command_execution",
TurnItem::DynamicToolCall(_) => "dynamic_tool_call",
TurnItem::CollabAgentToolCall(_) => "collab_agent_tool_call",
TurnItem::SubAgentActivity(_) => "sub_agent_activity",
TurnItem::WebSearch(_) => "web_search",
TurnItem::ImageView(_) => "image_view",
TurnItem::Extension(_) => "extension",
TurnItem::ImageGeneration(_) => "image_generation",
TurnItem::EnteredReviewMode(_) => "entered_review_mode",
TurnItem::ExitedReviewMode(_) => "exited_review_mode",
TurnItem::FileChange(_) => "file_change",
TurnItem::McpToolCall(_) => "mcp_tool_call",
TurnItem::ContextCompaction(_) => "context_compaction",
}
}
fn response_item_type(item: &ResponseItemEnvelope) -> &'static str {
match &item.item {
ResponseItem::Message { .. } => "response.message",
ResponseItem::AdditionalTools { .. } => "response.additional_tools",
ResponseItem::AgentMessage { .. } => "response.agent_message",
ResponseItem::Reasoning { .. } => "response.reasoning",
ResponseItem::LocalShellCall { .. } => "response.local_shell_call",
ResponseItem::FunctionCall { .. } => "response.function_call",
ResponseItem::ToolSearchCall { .. } => "response.tool_search_call",
ResponseItem::FunctionCallOutput { .. } => "response.function_call_output",
ResponseItem::ToolSearchOutput { .. } => "response.tool_search_output",
ResponseItem::CustomToolCall { .. } => "response.custom_tool_call",
ResponseItem::CustomToolCallOutput { .. } => "response.custom_tool_call_output",
ResponseItem::WebSearchCall { .. } => "response.web_search_call",
ResponseItem::ImageGenerationCall { .. } => "response.image_generation_call",
ResponseItem::Compaction { .. } => "response.compaction",
ResponseItem::ConfigurationUpdate { .. } => "response.configuration_update",
ResponseItem::CompactionTrigger { .. } => "response.compaction_trigger",
ResponseItem::ContextCompaction { .. } => "response.context_compaction",
ResponseItem::Other => "response.other",
}
}
fn record_item_bytes(
metrics: &MetricsClient,
stage: &'static str,
item: &RolloutItemMeasurement,
payload_bytes: u64,
) {
let _ = metrics.histogram_with_boundaries(
ITEM_BYTES_METRIC,
saturating_i64(payload_bytes),
ROLLOUT_BYTES_BOUNDARIES,
&[
("stage", stage),
("decision", item.decision.as_str()),
("rollout_item_type", item.rollout_item_type.as_str()),
("encoding", "rollout_item_json_v1"),
("sample_rate", SAMPLE_RATE_LABEL),
],
);
}
#[derive(Clone)]
pub struct RolloutPersistenceTelemetry {
metrics: Option<MetricsClient>,
sampled: bool,
turn_state: Option<Arc<Mutex<TurnMeasurementState>>>,
}
impl RolloutPersistenceTelemetry {
pub fn new(thread_id: ThreadId) -> Self {
let metrics = codex_otel::global();
let sampled = metrics.is_some() && is_thread_sampled(thread_id);
Self {
metrics,
sampled,
turn_state: sampled.then(|| Arc::new(Mutex::new(TurnMeasurementState::default()))),
}
}
pub fn is_enabled(&self) -> bool {
self.enabled_metrics().is_some()
}
pub fn record_batch(
&self,
items: &[RolloutItem],
measurement: &RolloutPersistenceBatchMeasurement,
) {
let Some(metrics) = self.enabled_metrics() else {
return;
};
for item in &measurement.items {
if let Some(payload_bytes) = item.payload_bytes {
record_item_bytes(metrics, "before_projection", item, payload_bytes);
let persisted_payload_bytes = match item.persisted_payload_bytes {
Some(persisted_payload_bytes) => {
record_item_bytes(
metrics,
"after_projection",
item,
persisted_payload_bytes,
);
persisted_payload_bytes
}
None if item.decision == PersistenceDecision::Dropped => 0,
None => {
let _ = metrics.counter(
MEASUREMENT_ERROR_METRIC,
/*inc*/ 1,
&[
("rollout_item_type", item.rollout_item_type.as_str()),
("phase", "serialize_projection"),
],
);
continue;
}
};
let bytes_removed = payload_bytes.saturating_sub(persisted_payload_bytes);
if bytes_removed > 0 {
let _ = metrics.histogram_with_boundaries(
BYTES_REMOVED_METRIC,
saturating_i64(bytes_removed),
ROLLOUT_BYTES_BOUNDARIES,
&[
("decision", item.decision.as_str()),
("rollout_item_type", item.rollout_item_type.as_str()),
("encoding", "rollout_item_json_v1"),
("sample_rate", SAMPLE_RATE_LABEL),
],
);
}
} else {
let _ = metrics.counter(
MEASUREMENT_ERROR_METRIC,
/*inc*/ 1,
&[
("rollout_item_type", item.rollout_item_type.as_str()),
("phase", "serialize"),
],
);
}
}
// Count successful input appends and the subset that remain storage operations after the
// persistence policy removes filtered items.
let _ = metrics.counter(
APPEND_METRIC,
/*inc*/ 1,
&[("stage", "pre_filter"), ("sample_rate", SAMPLE_RATE_LABEL)],
);
if measurement.post_filter.items > 0 {
let _ = metrics.counter(
APPEND_METRIC,
/*inc*/ 1,
&[("stage", "post_filter"), ("sample_rate", SAMPLE_RATE_LABEL)],
);
}
let Some(turn_state) = self.turn_state.as_ref() else {
return;
};
let turn_update = update_turn_measurements(
&mut turn_state
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
items,
measurement,
);
for boundary_type in turn_update.boundary_errors {
let _ = metrics.counter(
MEASUREMENT_ERROR_METRIC,
/*inc*/ 1,
&[
("rollout_item_type", boundary_type),
("phase", "turn_boundary"),
],
);
}
for turn in turn_update.completed {
for (stage, totals) in [
("before_projection", turn.totals.pre_filter),
("after_projection", turn.totals.post_filter),
] {
let _ = metrics.histogram_with_boundaries(
TURN_BYTES_METRIC,
saturating_i64(totals.payload_bytes),
ROLLOUT_BYTES_BOUNDARIES,
&[
("stage", stage),
("outcome", turn.outcome.as_str()),
("encoding", "rollout_item_json_v1"),
("sample_rate", SAMPLE_RATE_LABEL),
],
);
}
}
}
fn enabled_metrics(&self) -> Option<&MetricsClient> {
self.sampled.then_some(self.metrics.as_ref()).flatten()
}
}
fn saturating_i64(value: u64) -> i64 {
value.try_into().unwrap_or(i64::MAX)
}
fn is_thread_sampled(thread_id: ThreadId) -> bool {
let hash = thread_id
.to_string()
.bytes()
.fold(0xcbf29ce484222325_u64, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x100000001b3)
});
hash % SAMPLE_DENOMINATOR == 0
}
#[cfg(test)]
#[path = "persistence_metrics_tests.rs"]
mod tests;

View File

@@ -0,0 +1,427 @@
use std::time::Duration;
use codex_protocol::ThreadId;
use codex_protocol::items::CommandExecutionItem;
use codex_protocol::items::CommandExecutionStatus;
use codex_protocol::items::EnteredReviewModeItem;
use codex_protocol::items::ExitedReviewModeItem;
use codex_protocol::items::TurnItem;
use codex_protocol::items::UserMessageItem;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::parse_command::ParsedCommand;
use codex_protocol::protocol::EnteredReviewModeEvent;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ExecCommandSource;
use codex_protocol::protocol::ExitedReviewModeEvent;
use codex_protocol::protocol::ItemCompletedEvent;
use codex_protocol::protocol::ReviewTarget;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_protocol::protocol::TurnAbortReason;
use codex_protocol::protocol::TurnAbortedEvent;
use codex_protocol::protocol::TurnCompleteEvent;
use codex_protocol::protocol::TurnStartedEvent;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use super::CompletedTurnMeasurement;
use super::TurnMeasurementState;
use super::TurnOutcome;
use super::TurnSizeTotals;
use super::is_thread_sampled;
use super::measure_and_filter_rollout_items;
use super::update_turn_measurements;
use crate::ResponseItemEnvelope;
use crate::RolloutItem;
use crate::policy::PERSISTED_COMMAND_OUTPUT_MAX_BYTES;
fn retained_message(text: &str) -> RolloutItem {
RolloutItem::ResponseItem(ResponseItemEnvelope::new(ResponseItem::Message {
status: None,
encrypted_content: None,
id: None,
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: text.to_string(),
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
}))
}
fn turn_started(turn_id: &str) -> RolloutItem {
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
turn_attribution: None,
turn_id: turn_id.to_string(),
root_turn_id: None,
trace_id: None,
started_at: None,
model_context_window: None,
collaboration_mode_kind: Default::default(),
}))
}
fn turn_complete(turn_id: &str) -> RolloutItem {
RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent {
root_turn_id: None,
turn_id: turn_id.to_string(),
started_at: None,
last_agent_message: None,
error: None,
completed_at: None,
duration_ms: None,
time_to_first_token_ms: None,
}))
}
fn turn_aborted(turn_id: &str) -> RolloutItem {
RolloutItem::EventMsg(EventMsg::TurnAborted(TurnAbortedEvent {
root_turn_id: None,
turn_id: Some(turn_id.to_string()),
started_at: None,
reason: TurnAbortReason::Interrupted,
error: None,
completed_at: None,
duration_ms: None,
}))
}
fn update_for_batch(
state: &mut TurnMeasurementState,
items: &[RolloutItem],
) -> super::TurnMeasurementUpdate {
let (_, measurement) = measure_and_filter_rollout_items(items, ThreadHistoryMode::Legacy);
update_turn_measurements(state, items, &measurement)
}
#[test]
fn thread_sampling_is_stable_and_selects_whole_threads() {
let mut sampled = None;
let mut unsampled = None;
for value in 0..10_000_u128 {
let thread_id = ThreadId::from_string(&format!("00000000-0000-0000-0000-{value:012x}"))
.expect("valid thread id");
if is_thread_sampled(thread_id) {
sampled.get_or_insert(thread_id);
} else {
unsampled.get_or_insert(thread_id);
}
if sampled.is_some() && unsampled.is_some() {
break;
}
}
let sampled = sampled.expect("at least one sampled thread");
let unsampled = unsampled.expect("at least one unsampled thread");
assert!(is_thread_sampled(sampled));
assert!(is_thread_sampled(sampled));
assert!(!is_thread_sampled(unsampled));
assert!(!is_thread_sampled(unsampled));
}
#[test]
fn mixed_batch_reports_exact_policy_counts_and_bytes() {
let kept = retained_message("hello");
let dropped = RolloutItem::ResponseItem(ResponseItemEnvelope::new(ResponseItem::Other));
let items = vec![kept.clone(), dropped.clone()];
let (persisted, measurement) =
measure_and_filter_rollout_items(&items, ThreadHistoryMode::Legacy);
let kept_bytes = serde_json::to_vec(&kept)
.expect("serialize kept item")
.len() as u64;
let dropped_bytes = serde_json::to_vec(&dropped)
.expect("serialize dropped item")
.len() as u64;
assert_eq!(
serde_json::to_value(persisted).expect("serialize persisted items"),
serde_json::to_value([kept]).expect("serialize expected items")
);
assert_eq!(measurement.pre_filter.items, 2);
assert_eq!(
measurement.pre_filter.payload_bytes,
kept_bytes + dropped_bytes
);
assert_eq!(measurement.post_filter.items, 1);
assert_eq!(measurement.post_filter.payload_bytes, kept_bytes);
assert_eq!(measurement.items[0].payload_bytes, Some(kept_bytes));
assert_eq!(measurement.items[1].payload_bytes, Some(dropped_bytes));
assert_eq!(measurement.items[0].rollout_item_type, "response.message");
assert_eq!(measurement.items[1].rollout_item_type, "response.other");
}
#[test]
fn retained_items_are_byte_identical() {
let item = retained_message("a moderately sized payload");
let (persisted, measurement) =
measure_and_filter_rollout_items(std::slice::from_ref(&item), ThreadHistoryMode::Legacy);
assert_eq!(
serde_json::to_vec(&persisted[0]).expect("serialize persisted item"),
serde_json::to_vec(&item).expect("serialize candidate item")
);
assert_eq!(
measurement.post_filter.payload_bytes,
measurement.items[0].payload_bytes.expect("payload bytes")
);
}
#[test]
fn turn_measurements_span_batches_and_include_items_before_start() {
let first_turn = vec![
retained_message("first prompt"),
turn_started("turn-1"),
retained_message("first response"),
RolloutItem::ResponseItem(ResponseItemEnvelope::new(ResponseItem::Other)),
turn_complete("turn-1"),
];
let second_turn = vec![
retained_message("second prompt"),
turn_started("turn-2"),
retained_message("second response"),
turn_aborted("turn-2"),
];
let (_, first_expected) =
measure_and_filter_rollout_items(&first_turn, ThreadHistoryMode::Legacy);
let (_, second_expected) =
measure_and_filter_rollout_items(&second_turn, ThreadHistoryMode::Legacy);
let batches = [
first_turn[..1].to_vec(),
first_turn[1..3].to_vec(),
vec![
first_turn[3].clone(),
first_turn[4].clone(),
second_turn[0].clone(),
],
second_turn[1..].to_vec(),
];
let mut state = TurnMeasurementState::default();
let mut completed = Vec::new();
let mut boundary_errors = Vec::new();
for batch in batches {
let update = update_for_batch(&mut state, &batch);
completed.extend(update.completed);
boundary_errors.extend(update.boundary_errors);
}
assert_eq!(
completed,
vec![
CompletedTurnMeasurement {
totals: TurnSizeTotals {
pre_filter: first_expected.pre_filter,
post_filter: first_expected.post_filter,
},
outcome: TurnOutcome::Completed,
},
CompletedTurnMeasurement {
totals: TurnSizeTotals {
pre_filter: second_expected.pre_filter,
post_filter: second_expected.post_filter,
},
outcome: TurnOutcome::Aborted,
},
]
);
assert_eq!(boundary_errors, Vec::<&str>::new());
assert_eq!(state, TurnMeasurementState::default());
}
#[test]
fn invalid_turn_boundaries_reset_partial_measurements() {
let mut state = TurnMeasurementState::default();
let unmatched_completion = vec![retained_message("orphan"), turn_complete("turn-1")];
let update = update_for_batch(&mut state, &unmatched_completion);
assert_eq!(update.completed, Vec::new());
assert_eq!(update.boundary_errors, vec!["event.turn_complete"]);
assert_eq!(state, TurnMeasurementState::default());
let replacement = vec![
turn_started("turn-1"),
retained_message("discarded partial turn"),
turn_started("turn-2"),
retained_message("retained turn"),
turn_complete("turn-2"),
];
let (_, expected) =
measure_and_filter_rollout_items(&replacement[2..], ThreadHistoryMode::Legacy);
let update = update_for_batch(&mut state, &replacement);
assert_eq!(
update.completed,
vec![CompletedTurnMeasurement {
totals: TurnSizeTotals {
pre_filter: expected.pre_filter,
post_filter: expected.post_filter,
},
outcome: TurnOutcome::Completed,
}]
);
assert_eq!(update.boundary_errors, vec!["event.turn_started"]);
assert_eq!(state, TurnMeasurementState::default());
}
#[test]
fn item_completion_persistence_depends_on_history_mode() {
let item = RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
content_token_count: None,
thread_id: ThreadId::default(),
turn_id: "turn".to_string(),
item: TurnItem::UserMessage(UserMessageItem {
id: "item".to_string(),
client_id: None,
content: Vec::new(),
}),
started_at_ms: Some(0),
completed_at_ms: 0,
}));
let (_, legacy_measurement) =
measure_and_filter_rollout_items(std::slice::from_ref(&item), ThreadHistoryMode::Legacy);
assert_eq!(
legacy_measurement.items[0].rollout_item_type,
"event.item_completed.user_message"
);
assert_eq!(
legacy_measurement.items[0].decision,
super::PersistenceDecision::Dropped
);
let (persisted, paginated_measurement) =
measure_and_filter_rollout_items(std::slice::from_ref(&item), ThreadHistoryMode::Paginated);
assert_eq!(
serde_json::to_value(persisted).expect("serialize persisted items"),
serde_json::to_value([item]).expect("serialize expected items")
);
assert_eq!(
paginated_measurement.items[0].decision,
super::PersistenceDecision::Kept
);
}
#[test]
fn projected_items_report_post_projection_bytes() {
let original_output = "x".repeat(PERSISTED_COMMAND_OUTPUT_MAX_BYTES * 2);
let item = RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
content_token_count: None,
thread_id: ThreadId::default(),
turn_id: "turn".to_string(),
item: TurnItem::CommandExecution(CommandExecutionItem {
sandbox_type: None,
model_context: None,
id: "exec".to_string(),
plugin_id: None,
script_path: None,
process_id: None,
command: vec!["echo".to_string()],
cwd: std::env::temp_dir().abs().into(),
parsed_cmd: vec![ParsedCommand::Unknown {
cmd: "echo".to_string(),
}],
source: ExecCommandSource::Agent,
interaction_input: None,
status: CommandExecutionStatus::Completed,
aggregated_output: Some(original_output),
exit_code: Some(0),
duration: Some(Duration::ZERO),
}),
started_at_ms: Some(0),
completed_at_ms: 0,
}));
let original_bytes = serde_json::to_vec(&item)
.expect("serialize original command")
.len() as u64;
let (persisted, measurement) =
measure_and_filter_rollout_items(std::slice::from_ref(&item), ThreadHistoryMode::Paginated);
let persisted_bytes = serde_json::to_vec(&persisted[0])
.expect("serialize persisted command")
.len() as u64;
assert_eq!(
measurement.pre_filter,
super::RolloutSizeTotals {
items: 1,
payload_bytes: original_bytes,
}
);
assert_eq!(
measurement.post_filter,
super::RolloutSizeTotals {
items: 1,
payload_bytes: persisted_bytes,
}
);
assert!(
persisted_bytes < original_bytes,
"projection should reduce serialized bytes"
);
}
#[test]
fn review_mode_persistence_depends_on_history_mode() {
let completed_items = vec![
RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
content_token_count: None,
thread_id: ThreadId::default(),
turn_id: "turn".to_string(),
item: TurnItem::EnteredReviewMode(EnteredReviewModeItem {
id: "entered-review".to_string(),
target: ReviewTarget::Custom {
instructions: "review this".to_string(),
},
user_facing_hint: "Review requested.".to_string(),
}),
started_at_ms: Some(0),
completed_at_ms: 0,
})),
RolloutItem::EventMsg(EventMsg::ItemCompleted(ItemCompletedEvent {
content_token_count: None,
thread_id: ThreadId::default(),
turn_id: "turn".to_string(),
item: TurnItem::ExitedReviewMode(ExitedReviewModeItem {
id: "exited-review".to_string(),
review_output: None,
}),
started_at_ms: Some(0),
completed_at_ms: 0,
})),
];
let legacy_events = vec![
RolloutItem::EventMsg(EventMsg::EnteredReviewMode(EnteredReviewModeEvent {
target: ReviewTarget::Custom {
instructions: "review this".to_string(),
},
user_facing_hint: Some("Review requested.".to_string()),
turn_id: Some("turn".to_string()),
item_id: Some("entered-review".to_string()),
})),
RolloutItem::EventMsg(EventMsg::ExitedReviewMode(ExitedReviewModeEvent {
turn_id: Some("turn".to_string()),
item_id: Some("exited-review".to_string()),
review_output: None,
})),
];
let items = completed_items
.iter()
.chain(&legacy_events)
.cloned()
.collect::<Vec<_>>();
let (persisted_legacy, _) = measure_and_filter_rollout_items(&items, ThreadHistoryMode::Legacy);
assert_eq!(
serde_json::to_value(persisted_legacy).expect("serialize persisted items"),
serde_json::to_value(legacy_events).expect("serialize expected items")
);
let (persisted_paginated, _) =
measure_and_filter_rollout_items(&items, ThreadHistoryMode::Paginated);
assert_eq!(
serde_json::to_value(persisted_paginated).expect("serialize persisted items"),
serde_json::to_value(completed_items).expect("serialize expected items")
);
}

View File

@@ -0,0 +1,291 @@
use std::borrow::Cow;
use crate::RolloutItem;
use crate::protocol::EventMsg;
use codex_extension_items::ExtensionItem;
use codex_protocol::items::CommandExecutionItem;
use codex_protocol::items::McpToolCallItem;
use codex_protocol::items::TurnItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::ItemCompletedEvent;
use codex_protocol::protocol::SubAgentActivityKind;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_utils_output_truncation::truncate_mcp_tool_result;
use codex_utils_string::truncate_middle_with_marker;
const PERSISTED_MCP_RESULT_MAX_BYTES: usize = 64 * 1024;
pub(super) const PERSISTED_COMMAND_OUTPUT_MAX_BYTES: usize = 64 * 1024;
const PERSISTED_COMMAND_OUTPUT_TRUNCATION_MARKER: &str =
"\n... command output truncated for persistence ...\n";
/// Returns the authoritative durable representation of a rollout item.
pub fn persisted_rollout_item(
item: &RolloutItem,
history_mode: ThreadHistoryMode,
) -> Option<Cow<'_, RolloutItem>> {
match item {
RolloutItem::ResponseItem(response_item) => {
should_persist_response_item(&response_item.item).then_some(Cow::Borrowed(item))
}
RolloutItem::InterAgentCommunication(_)
| RolloutItem::InterAgentCommunicationMetadata { .. } => Some(Cow::Borrowed(item)),
RolloutItem::EventMsg(ev) => {
persisted_event_msg(ev, history_mode).map(|event| match event {
Cow::Borrowed(_) => Cow::Borrowed(item),
Cow::Owned(event) => Cow::Owned(RolloutItem::EventMsg(event)),
})
}
RolloutItem::RealtimeItem(_) => {
matches!(history_mode, ThreadHistoryMode::Paginated).then_some(Cow::Borrowed(item))
}
// Persist Codex executive markers so we can analyze flows (e.g., compaction, API turns).
RolloutItem::Compacted(_)
| RolloutItem::TurnContext(_)
| RolloutItem::TokenUsageRecord(_)
| RolloutItem::WorldState(_)
| RolloutItem::RetainedContext(_)
| RolloutItem::SecurityRiskScore(_)
| RolloutItem::DynamicToolsUpdated { .. }
| RolloutItem::SessionMeta(_) => Some(Cow::Borrowed(item)),
}
}
/// Return the rollout items that should be persisted for a live append.
pub fn persisted_rollout_items(
items: &[RolloutItem],
history_mode: ThreadHistoryMode,
) -> Vec<RolloutItem> {
items
.iter()
.filter_map(|item| persisted_rollout_item(item, history_mode).map(Cow::into_owned))
.collect()
}
/// Return the owned rollout items that should be persisted for a live append.
pub fn into_persisted_rollout_items(
items: Vec<RolloutItem>,
history_mode: ThreadHistoryMode,
) -> Vec<RolloutItem> {
items
.into_iter()
.filter_map(|item| match persisted_rollout_item(&item, history_mode) {
Some(Cow::Borrowed(_)) => Some(item),
Some(Cow::Owned(item)) => Some(item),
None => None,
})
.collect()
}
/// Whether a `ResponseItem` should be persisted in rollout files.
#[inline]
pub fn should_persist_response_item(item: &ResponseItem) -> bool {
match item {
ResponseItem::AdditionalTools { .. }
| ResponseItem::Message { .. }
| ResponseItem::AgentMessage { .. }
| ResponseItem::Reasoning { .. }
| ResponseItem::LocalShellCall { .. }
| ResponseItem::FunctionCall { .. }
| ResponseItem::ToolSearchCall { .. }
| ResponseItem::FunctionCallOutput { .. }
| ResponseItem::ToolSearchOutput { .. }
| ResponseItem::CustomToolCall { .. }
| ResponseItem::CustomToolCallOutput { .. }
| ResponseItem::WebSearchCall { .. }
| ResponseItem::ImageGenerationCall { .. }
| ResponseItem::ConfigurationUpdate { .. }
| ResponseItem::Compaction { .. }
| ResponseItem::ContextCompaction { .. } => true,
ResponseItem::CompactionTrigger { .. } | ResponseItem::Other => false,
}
}
/// Whether a `ResponseItem` should be persisted for the memories.
#[inline]
pub fn should_persist_response_item_for_memories(item: &ResponseItem) -> bool {
match item {
ResponseItem::Message { role, .. } => role != "developer",
ResponseItem::AgentMessage { .. }
| ResponseItem::LocalShellCall { .. }
| ResponseItem::FunctionCall { .. }
| ResponseItem::ToolSearchCall { .. }
| ResponseItem::FunctionCallOutput { .. }
| ResponseItem::ToolSearchOutput { .. }
| ResponseItem::CustomToolCall { .. }
| ResponseItem::CustomToolCallOutput { .. }
| ResponseItem::WebSearchCall { .. } => true,
ResponseItem::AdditionalTools { .. }
| ResponseItem::Reasoning { .. }
| ResponseItem::ConfigurationUpdate { .. }
| ResponseItem::ImageGenerationCall { .. }
| ResponseItem::Compaction { .. }
| ResponseItem::CompactionTrigger { .. }
| ResponseItem::ContextCompaction { .. }
| ResponseItem::Other => false,
}
}
fn persisted_event_msg(
ev: &EventMsg,
history_mode: ThreadHistoryMode,
) -> Option<Cow<'_, EventMsg>> {
match ev {
EventMsg::ItemCompleted(event) => persisted_item_completed_event(ev, event, history_mode),
EventMsg::TokenCount(_)
| EventMsg::ThreadGoalUpdated(_)
| EventMsg::ThreadRolledBack(_)
| EventMsg::TurnAborted(_)
| EventMsg::TurnStarted(_)
| EventMsg::TurnComplete(_)
| EventMsg::ThreadSettingsApplied(_) => Some(Cow::Borrowed(ev)),
// Only persist these legacy events when the thread's history mode is Legacy.
// New, paginated rollouts persist ItemCompleted events with TurnItems.
EventMsg::UserMessage(_)
| EventMsg::AgentMessage(_)
| EventMsg::AgentReasoning(_)
| EventMsg::AgentReasoningRawContent(_)
| EventMsg::EnteredReviewMode(_)
| EventMsg::ExitedReviewMode(_)
| EventMsg::PatchApplyEnd(_)
| EventMsg::ContextCompacted(_)
| EventMsg::McpToolCallEnd(_)
| EventMsg::WebSearchEnd(_)
| EventMsg::ImageGenerationEnd(_) => {
matches!(history_mode, ThreadHistoryMode::Legacy).then_some(Cow::Borrowed(ev))
}
EventMsg::SubAgentActivity(event) => (matches!(history_mode, ThreadHistoryMode::Legacy)
&& event.kind != SubAgentActivityKind::Completed)
.then_some(Cow::Borrowed(ev)),
// Transient, non-durable events.
EventMsg::Error(_)
| EventMsg::ThreadQueueChanged(_)
| EventMsg::GuardianAssessment(_)
| EventMsg::ExecCommandEnd(_)
| EventMsg::ViewImageToolCall(_)
| EventMsg::CollabAgentSpawnEnd(_)
| EventMsg::CollabAgentInteractionEnd(_)
| EventMsg::CollabWaitingEnd(_)
| EventMsg::CollabCloseEnd(_)
| EventMsg::CollabResumeEnd(_)
| EventMsg::DynamicToolCallRequest(_)
| EventMsg::DynamicToolCallResponse(_)
| EventMsg::Warning(_)
| EventMsg::AuthRecoveryStarted(_)
| EventMsg::AuthRecoveryCompleted(_)
| EventMsg::GuardianWarning(_)
| EventMsg::RealtimeConversationStarted(_)
| EventMsg::RealtimeConversationSdp(_)
| EventMsg::RealtimeConversationRealtime(_)
| EventMsg::RealtimeConversationClosed(_)
| EventMsg::SafetyBuffering(_)
| EventMsg::ModelReroute(_)
| EventMsg::ModelVerification(_)
| EventMsg::TurnModerationMetadata(_)
| EventMsg::AgentReasoningSectionBreak(_)
| EventMsg::PrivateSessionEvent(_)
| EventMsg::RawResponseItem(_)
| EventMsg::RawResponseCompleted(_)
| EventMsg::SessionConfigured(_)
| EventMsg::EnvironmentConnected(_)
| EventMsg::EnvironmentDisconnected(_)
| EventMsg::McpToolCallBegin(_)
| EventMsg::ExecCommandBegin(_)
| EventMsg::TerminalInteraction(_)
| EventMsg::ExecCommandOutputDelta(_)
| EventMsg::ExecApprovalRequest(_)
| EventMsg::RequestPermissions(_)
| EventMsg::RequestUserInput(_)
| EventMsg::ElicitationRequest(_)
| EventMsg::ElicitationAbandoned(_)
| EventMsg::NetworkApprovalResolved { .. }
| EventMsg::ApplyPatchApprovalRequest(_)
| EventMsg::StreamError(_)
| EventMsg::PatchApplyBegin(_)
| EventMsg::PatchApplyUpdated(_)
| EventMsg::TurnDiff(_)
| EventMsg::RealtimeConversationListVoicesResponse(_)
| EventMsg::McpStartupUpdate(_)
| EventMsg::McpStartupComplete(_)
| EventMsg::WebSearchBegin(_)
| EventMsg::PlanUpdate(_)
| EventMsg::ShutdownComplete
| EventMsg::DeprecationNotice(_)
| EventMsg::ItemStarted(_)
| EventMsg::HookStarted(_)
| EventMsg::HookCompleted(_)
| EventMsg::AgentMessageContentDelta(_)
| EventMsg::PlanDelta(_)
| EventMsg::ReasoningContentDelta(_)
| EventMsg::ReasoningRawContentDelta(_)
| EventMsg::ImageGenerationBegin(_)
| EventMsg::CollabAgentSpawnBegin(_)
| EventMsg::CollabAgentInteractionBegin(_)
| EventMsg::CollabWaitingBegin(_)
| EventMsg::CollabCloseBegin(_)
| EventMsg::CollabResumeBegin(_) => None,
}
}
/// Returns the persisted representation of an `ItemCompleted` event.
fn persisted_item_completed_event<'a>(
ev: &'a EventMsg,
event: &ItemCompletedEvent,
history_mode: ThreadHistoryMode,
) -> Option<Cow<'a, EventMsg>> {
match history_mode {
ThreadHistoryMode::Legacy => {
// Legacy rollouts keep only items with no lossless raw ResponseItem or legacy
// equivalent.
(matches!(
event.item,
TurnItem::FunctionCallOutput(_)
| TurnItem::Plan(_)
| TurnItem::Extension(ExtensionItem::Sleep(_))
) || matches!(
&event.item,
TurnItem::SubAgentActivity(item)
if item.kind == SubAgentActivityKind::Completed
))
.then_some(Cow::Borrowed(ev))
}
ThreadHistoryMode::Paginated => match &event.item {
TurnItem::CommandExecution(CommandExecutionItem {
aggregated_output: Some(aggregated_output),
..
}) if aggregated_output.len() > PERSISTED_COMMAND_OUTPUT_MAX_BYTES => {
let aggregated_output = truncate_middle_with_marker(
aggregated_output,
PERSISTED_COMMAND_OUTPUT_MAX_BYTES,
PERSISTED_COMMAND_OUTPUT_TRUNCATION_MARKER,
);
let mut event = event.clone();
if let TurnItem::CommandExecution(command) = &mut event.item {
command.aggregated_output = Some(aggregated_output);
}
Some(Cow::Owned(EventMsg::ItemCompleted(event)))
}
TurnItem::McpToolCall(McpToolCallItem {
result: Some(result),
..
}) => {
let Cow::Owned(result) =
truncate_mcp_tool_result(result, PERSISTED_MCP_RESULT_MAX_BYTES)
else {
return Some(Cow::Borrowed(ev));
};
let mut event = event.clone();
if let TurnItem::McpToolCall(tool_call) = &mut event.item {
tool_call.result = Some(result);
}
Some(Cow::Owned(EventMsg::ItemCompleted(event)))
}
_ => Some(Cow::Borrowed(ev)),
},
}
}
#[cfg(test)]
#[path = "policy_tests.rs"]
mod tests;

View File

@@ -0,0 +1,120 @@
use codex_extension_items::ExtensionItem;
use codex_extension_items::image_generation::GeneratedImageRef;
use codex_extension_items::image_generation::ImageGenerationItem;
use codex_protocol::ThreadId;
use codex_protocol::items::TurnItem;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ImageGenerationEndEvent;
use codex_protocol::protocol::ItemCompletedEvent;
use codex_protocol::protocol::ThreadHistoryMode;
use super::persisted_event_msg;
fn image_item(image: GeneratedImageRef) -> ImageGenerationItem {
ImageGenerationItem {
id: "image-1".to_string(),
status: "completed".to_string(),
revised_prompt: Some("paint a blue whale".to_string()),
image,
transparent_background: Some(false),
failure: None,
saved_path: None,
input_images: Vec::new(),
imagegen_request_id: None,
generation_id: None,
}
}
#[test]
fn paginated_image_generation_preserves_file_reference() {
let event = EventMsg::ItemCompleted(ItemCompletedEvent {
content_token_count: None,
thread_id: ThreadId::new(),
turn_id: "turn-1".to_string(),
item: TurnItem::Extension(ExtensionItem::ImageGeneration(image_item(
GeneratedImageRef::File {
file_id: "file-1".to_string(),
},
))),
started_at_ms: Some(1),
completed_at_ms: 2,
});
let persisted = persisted_event_msg(&event, ThreadHistoryMode::Paginated)
.expect("expected persisted image-generation item");
let EventMsg::ItemCompleted(persisted) = persisted.as_ref() else {
panic!("expected persisted image-generation item");
};
let TurnItem::Extension(ExtensionItem::ImageGeneration(image)) = &persisted.item else {
panic!("expected image-generation extension item");
};
assert_eq!(
image,
&image_item(GeneratedImageRef::File {
file_id: "file-1".to_string(),
})
);
}
#[test]
fn legacy_image_generation_preserves_file_reference() {
let event = EventMsg::ImageGenerationEnd(ImageGenerationEndEvent {
call_id: "image-1".to_string(),
status: "completed".to_string(),
revised_prompt: Some("paint a blue whale".to_string()),
image: GeneratedImageRef::File {
file_id: "file-1".to_string(),
},
transparent_background: Some(false),
failure: None,
saved_path: None,
input_images: Vec::new(),
generation_id: None,
});
let persisted = persisted_event_msg(&event, ThreadHistoryMode::Legacy)
.expect("expected persisted legacy image-generation event");
let EventMsg::ImageGenerationEnd(persisted) = persisted.as_ref() else {
panic!("expected persisted legacy image-generation event");
};
assert_eq!(
persisted.image,
GeneratedImageRef::File {
file_id: "file-1".to_string(),
}
);
}
#[test]
fn inline_image_generation_result_is_preserved() {
let event = EventMsg::ItemCompleted(ItemCompletedEvent {
content_token_count: None,
thread_id: ThreadId::new(),
turn_id: "turn-1".to_string(),
item: TurnItem::Extension(ExtensionItem::ImageGeneration(image_item(
GeneratedImageRef::Inline {
result: "base64-image".to_string(),
},
))),
started_at_ms: Some(1),
completed_at_ms: 2,
});
let persisted = persisted_event_msg(&event, ThreadHistoryMode::Paginated)
.expect("expected persisted inline image-generation item");
let EventMsg::ItemCompleted(persisted) = persisted.as_ref() else {
panic!("expected persisted inline image-generation item");
};
let TurnItem::Extension(ExtensionItem::ImageGeneration(image)) = &persisted.item else {
panic!("expected inline image-generation extension item");
};
assert_eq!(
image,
&image_item(GeneratedImageRef::Inline {
result: "base64-image".to_string(),
})
);
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,165 @@
use std::io;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::RolloutLine;
const READ_CHUNK_SIZE: usize = 64 * 1024;
#[derive(Debug)]
pub enum ScanOutcome<T> {
/// The record was valid JSON and deserialized as the requested type.
Parsed(T),
/// The record was not valid JSON for the requested type.
#[allow(dead_code)]
Rejected(serde_json::Error),
}
/// Read-only scanner for newline-delimited JSON records, starting from the end.
pub struct ReverseJsonlScanner<R> {
reader: R,
next_chunk_end: u64,
chunk_position: usize,
chunk: Vec<u8>,
record_reversed: Vec<u8>,
max_record_bytes: Option<usize>,
discarding_oversized_record: bool,
}
impl<R> ReverseJsonlScanner<R>
where
R: Read + Seek,
{
pub fn new(mut reader: R) -> io::Result<Self> {
let next_chunk_end = reader.seek(SeekFrom::End(0))?;
Self::new_at(reader, next_chunk_end)
}
/// Creates a reverse scanner whose logical end is the given byte offset.
///
/// This lets callers scan a frozen JSONL prefix without reading records appended after that
/// prefix was captured.
pub fn new_at(mut reader: R, end_byte_offset: u64) -> io::Result<Self> {
let file_len = reader.seek(SeekFrom::End(0))?;
if end_byte_offset > file_len {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"reverse JSONL scan end is past the file",
));
}
Ok(Self {
reader,
next_chunk_end: end_byte_offset,
chunk_position: 0,
chunk: vec![0; READ_CHUNK_SIZE],
record_reversed: Vec::new(),
max_record_bytes: None,
discarding_oversized_record: false,
})
}
/// Skips records larger than the configured limit without buffering or parsing them.
pub fn with_max_record_bytes(mut self, max_record_bytes: usize) -> Self {
self.max_record_bytes = Some(max_record_bytes);
self
}
/// Scans the next nonblank record.
///
/// I/O failures are returned as [`Err`]. Invalid JSON records are returned as
/// [`ScanOutcome::Rejected`], and the scanner remains usable.
pub fn scan_next<T>(&mut self) -> io::Result<Option<ScanOutcome<T>>>
where
T: DeserializeOwned,
{
loop {
if self.chunk_position == 0 {
if self.next_chunk_end == 0 {
if self.discarding_oversized_record {
self.discarding_oversized_record = false;
return Ok(None);
}
return Ok(self.finish_record());
}
let read_size = usize::try_from(self.next_chunk_end.min(READ_CHUNK_SIZE as u64))
.map_err(io::Error::other)?;
self.next_chunk_end -= read_size as u64;
self.reader.seek(SeekFrom::Start(self.next_chunk_end))?;
self.reader.read_exact(&mut self.chunk[..read_size])?;
self.chunk_position = read_size;
}
let chunk = &self.chunk[..self.chunk_position];
if let Some(newline_position) = memchr::memrchr(b'\n', chunk) {
let fragment = &chunk[newline_position + 1..];
if !self.discarding_oversized_record {
if self.max_record_bytes.is_some_and(|max_record_bytes| {
self.record_reversed.len().saturating_add(fragment.len()) > max_record_bytes
}) {
self.record_reversed.clear();
self.discarding_oversized_record = true;
} else {
self.record_reversed.extend(fragment.iter().rev().copied());
}
}
self.chunk_position = newline_position;
if self.discarding_oversized_record {
self.discarding_oversized_record = false;
continue;
}
if let Some(outcome) = self.finish_record() {
return Ok(Some(outcome));
}
} else {
if !self.discarding_oversized_record {
if self.max_record_bytes.is_some_and(|max_record_bytes| {
self.record_reversed.len().saturating_add(chunk.len()) > max_record_bytes
}) {
self.record_reversed.clear();
self.discarding_oversized_record = true;
} else {
self.record_reversed.extend(chunk.iter().rev().copied());
}
}
self.chunk_position = 0;
}
}
}
/// Scans the next rollout record through the canonical persisted JSON decoder.
pub fn scan_next_rollout_line(&mut self) -> io::Result<Option<ScanOutcome<RolloutLine>>> {
Ok(self.scan_next::<Value>()?.map(|outcome| match outcome {
ScanOutcome::Parsed(value) => match crate::decode_rollout_line(value) {
Ok(line) => ScanOutcome::Parsed(line),
Err(error) => ScanOutcome::Rejected(error),
},
ScanOutcome::Rejected(error) => ScanOutcome::Rejected(error),
}))
}
fn finish_record<T>(&mut self) -> Option<ScanOutcome<T>>
where
T: DeserializeOwned,
{
self.record_reversed.reverse();
let outcome = if self.record_reversed.iter().all(u8::is_ascii_whitespace) {
None
} else {
Some(match serde_json::from_slice::<T>(&self.record_reversed) {
Ok(value) => ScanOutcome::Parsed(value),
Err(error) => ScanOutcome::Rejected(error),
})
};
self.record_reversed.clear();
outcome
}
}
#[cfg(test)]
#[path = "reverse_jsonl_scanner_tests.rs"]
mod tests;

View File

@@ -0,0 +1,168 @@
use std::io::Cursor;
use std::io::Read;
use std::io::Seek;
use pretty_assertions::assert_eq;
use serde::Deserialize;
use serde::Serialize;
use super::ReverseJsonlScanner;
use super::ScanOutcome;
#[derive(Debug, Deserialize, Serialize, PartialEq)]
struct TestRecord {
value: String,
}
fn record(value: &str) -> TestRecord {
TestRecord {
value: value.to_string(),
}
}
fn parsed<T>(outcome: Option<ScanOutcome<T>>) -> T {
let Some(ScanOutcome::Parsed(record)) = outcome else {
panic!("expected parsed record");
};
record
}
fn assert_records<R>(scanner: &mut ReverseJsonlScanner<R>, expected: &[&str]) -> std::io::Result<()>
where
R: Read + Seek,
{
for value in expected {
assert_eq!(parsed(scanner.scan_next::<TestRecord>()?), record(value));
}
assert!(scanner.scan_next::<TestRecord>()?.is_none());
Ok(())
}
#[test]
fn scans_jsonl_records_from_end() -> std::io::Result<()> {
let input = br#"{"value":"first"}
{"value":"second"}
{"value":"third"}
"#;
assert_records(
&mut ReverseJsonlScanner::new(Cursor::new(input))?,
&["third", "second", "first"],
)
}
#[test]
fn rejects_invalid_json_and_continues_scanning() -> std::io::Result<()> {
let input = br#"{"value":"first"}
not-json
{"value":"third"}
"#;
let mut scanner = ReverseJsonlScanner::new(Cursor::new(input))?;
assert_eq!(parsed(scanner.scan_next::<TestRecord>()?), record("third"));
let Some(ScanOutcome::Rejected(error)) = scanner.scan_next::<TestRecord>()? else {
panic!("expected rejected record");
};
assert!(error.is_syntax());
assert_eq!(parsed(scanner.scan_next::<TestRecord>()?), record("first"));
Ok(())
}
#[test]
fn skips_records_over_the_configured_limit() -> std::io::Result<()> {
let oversized = record(&"x".repeat(128));
let input = format!(
"{}\n{}\n{}\n",
serde_json::to_string(&record("first"))?,
serde_json::to_string(&oversized)?,
serde_json::to_string(&record("third"))?
);
let mut scanner = ReverseJsonlScanner::new(Cursor::new(input.into_bytes()))?
.with_max_record_bytes(/*max_record_bytes*/ 32);
assert_records(&mut scanner, &["third", "first"])
}
#[test]
fn accepts_valid_json_at_eof() -> std::io::Result<()> {
let input = b"{\"value\":\"first\"}\n{\"value\":\"second\"}";
assert_records(
&mut ReverseJsonlScanner::new(Cursor::new(input))?,
&["second", "first"],
)
}
#[test]
fn scans_from_a_frozen_prefix_end() -> std::io::Result<()> {
let prefix = b"{\"value\":\"first\"}\n{\"value\":\"second\"}\n";
let mut input = prefix.to_vec();
input.extend_from_slice(b"{\"value\":\"later\"}\n");
assert_records(
&mut ReverseJsonlScanner::new_at(Cursor::new(input), prefix.len() as u64)?,
&["second", "first"],
)
}
#[test]
fn rejects_invalid_json_at_eof_and_continues_scanning() -> std::io::Result<()> {
let input = b"{\"value\":\"first\"}\n{\"value\":";
let mut scanner = ReverseJsonlScanner::new(Cursor::new(input))?;
let Some(ScanOutcome::Rejected(error)) = scanner.scan_next::<TestRecord>()? else {
panic!("expected rejected record");
};
assert!(error.is_eof());
assert_eq!(parsed(scanner.scan_next::<TestRecord>()?), record("first"));
Ok(())
}
#[test]
fn skips_blank_lines_with_or_without_termination() -> std::io::Result<()> {
let input = b"{\"value\":\"first\"}\r\n\n \t\r";
assert_records(
&mut ReverseJsonlScanner::new(Cursor::new(input))?,
&["first"],
)
}
#[test]
fn scans_across_read_chunk_boundaries() -> std::io::Result<()> {
let empty_record_len = serde_json::to_string(&record(""))?.len();
for distance_from_eof in [
super::READ_CHUNK_SIZE - 1,
super::READ_CHUNK_SIZE,
super::READ_CHUNK_SIZE + 1,
] {
let large_value = "x".repeat(distance_from_eof - empty_record_len - 2);
let input = format!(
"{}\n{}\n",
serde_json::to_string(&record("first"))?,
serde_json::to_string(&record(&large_value))?
);
let mut scanner = ReverseJsonlScanner::new(Cursor::new(input.into_bytes()))?;
assert_eq!(
parsed(scanner.scan_next::<TestRecord>()?),
record(&large_value)
);
assert_eq!(parsed(scanner.scan_next::<TestRecord>()?), record("first"));
}
Ok(())
}
#[test]
fn scans_record_spanning_three_read_chunks() -> std::io::Result<()> {
let large_value = "x".repeat(super::READ_CHUNK_SIZE * 2);
let input = format!(
"{}\n{}\n{}\n",
serde_json::to_string(&record("first"))?,
serde_json::to_string(&record(&large_value))?,
serde_json::to_string(&record("third"))?
);
let mut scanner = ReverseJsonlScanner::new(Cursor::new(input.into_bytes()))?;
assert_records(&mut scanner, &["third", &large_value, "first"])
}

View File

@@ -0,0 +1,87 @@
use codex_protocol::RolloutId;
use codex_protocol::ThreadId;
use time::OffsetDateTime;
use time::PrimitiveDateTime;
use time::format_description::FormatItem;
use time::macros::format_description;
use crate::compression;
/// Parsed canonical rollout basename.
///
/// Ordinary rollout filenames encode one ID, which is both the thread ID and rollout ID.
/// Filenames for reverted threads append an underscore and a distinct rollout ID after the stable
/// thread ID.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct RolloutFileName {
timestamp: OffsetDateTime,
thread_id: ThreadId,
rollout_id: RolloutId,
}
#[cfg(test)]
#[path = "rollout_file_name_tests.rs"]
mod tests;
impl RolloutFileName {
pub(crate) fn new(
timestamp: OffsetDateTime,
thread_id: ThreadId,
rollout_id: RolloutId,
) -> Self {
Self {
timestamp,
thread_id,
rollout_id,
}
}
pub(crate) fn parse(name: &str) -> Option<Self> {
let name = compression::parse_rollout_file_name(name)?;
let core = name.strip_prefix("rollout-")?.strip_suffix(".jsonl")?;
let timestamp = core.get(..19)?;
if core.get(19..20)? != "-" {
return None;
}
let ids = core.get(20..)?;
let (thread_id, rollout_id) = ids.split_once('_').unwrap_or((ids, ids));
let thread_id = ThreadId::from_string(thread_id).ok()?;
let rollout_id = RolloutId::from_string(rollout_id).ok()?;
let format: &[FormatItem] =
format_description!("[year]-[month]-[day]T[hour]-[minute]-[second]");
let timestamp = PrimitiveDateTime::parse(timestamp, format)
.ok()?
.assume_utc();
Some(Self {
timestamp,
thread_id,
rollout_id,
})
}
pub(crate) fn render(&self) -> Result<String, time::error::Format> {
let format: &[FormatItem] =
format_description!("[year]-[month]-[day]T[hour]-[minute]-[second]");
let timestamp = self.timestamp.format(format)?;
Ok(if self.thread_id == self.rollout_id {
format!("rollout-{timestamp}-{}.jsonl", self.thread_id)
} else {
format!(
"rollout-{timestamp}-{}_{}.jsonl",
self.thread_id, self.rollout_id
)
})
}
pub(crate) fn timestamp(&self) -> OffsetDateTime {
self.timestamp
}
pub(crate) fn thread_id(&self) -> ThreadId {
self.thread_id
}
pub(crate) fn rollout_id(&self) -> RolloutId {
self.rollout_id
}
}

View File

@@ -0,0 +1,29 @@
use codex_protocol::ThreadId;
use pretty_assertions::assert_eq;
use time::macros::datetime;
use super::RolloutFileName;
#[test]
fn canonical_rollout_file_names_round_trip() {
let timestamp = datetime!(2026-08-11 18:42:07 UTC);
let thread_id =
ThreadId::from_string("019ff1a2-b3c4-7d5e-8f60-112233445566").expect("valid thread id");
let rollout_id =
ThreadId::from_string("019ff1a2-b3c4-7d5e-8f60-667788990011").expect("valid rollout id");
for (file_name, expected) in [
(
RolloutFileName::new(timestamp, thread_id, thread_id),
"rollout-2026-08-11T18-42-07-019ff1a2-b3c4-7d5e-8f60-112233445566.jsonl",
),
(
RolloutFileName::new(timestamp, thread_id, rollout_id),
"rollout-2026-08-11T18-42-07-019ff1a2-b3c4-7d5e-8f60-112233445566_019ff1a2-b3c4-7d5e-8f60-667788990011.jsonl",
),
] {
let rendered = file_name.render().expect("timestamp should format");
assert_eq!(rendered, expected);
assert_eq!(RolloutFileName::parse(&rendered), Some(file_name));
}
}

View File

@@ -0,0 +1,200 @@
//! Indexes direct fork references and attached children found in local rollout files.
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::hash_map::Entry;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use codex_protocol::RolloutId;
use codex_protocol::ThreadId;
use codex_protocol::protocol::HistoryPosition;
use crate::ARCHIVED_SESSIONS_SUBDIR;
use crate::SESSIONS_SUBDIR;
use crate::compression::RolloutFile;
use crate::rollout_file_name::RolloutFileName;
/// Fork relationships discovered from local rollout metadata.
///
/// Rollouts are indexed by immutable rollout IDs, not a thread's selected lineage. Attached
/// children refer to their parent's stable thread ID.
#[derive(Debug, Default)]
pub struct RolloutReferenceIndex {
rollouts_by_id: HashMap<RolloutId, IndexedRollout>,
reference_counts_by_rollout: HashMap<RolloutId, usize>,
}
#[derive(Debug)]
struct IndexedRollout {
thread_id: ThreadId,
path: PathBuf,
history_base: Option<HistoryPosition>,
attached_to_thread_id: Option<ThreadId>,
}
impl RolloutReferenceIndex {
/// Scans active and archived local rollout metadata.
pub async fn scan(codex_home: &Path) -> io::Result<Self> {
Self::scan_paths(
vec![
codex_home.join(ARCHIVED_SESSIONS_SUBDIR),
codex_home.join(SESSIONS_SUBDIR),
],
/*thread_ids*/ None,
)
.await
}
/// Scans only unarchived rollouts to locate files that still need to be archived.
///
/// Reference counts exclude archived history and must not be used to decide whether a
/// rollout can be deleted or compressed.
pub async fn scan_unarchived(codex_home: &Path) -> io::Result<Self> {
Self::scan_paths(
vec![codex_home.join(SESSIONS_SUBDIR)],
/*thread_ids*/ None,
)
.await
}
/// Scans unarchived files whose canonical filenames belong to the requested threads.
///
/// Skips unrelated rollout contents, including compressed files. Metadata still determines
/// ownership among the candidates. Reference counts are partial and must not be used to
/// decide whether a rollout can be deleted or compressed.
pub async fn scan_unarchived_threads(
codex_home: &Path,
thread_ids: &[ThreadId],
) -> io::Result<Self> {
let thread_ids = thread_ids.iter().copied().collect();
Self::scan_paths(vec![codex_home.join(SESSIONS_SUBDIR)], Some(&thread_ids)).await
}
/// Scans archived files whose canonical filenames belong to the requested threads.
///
/// Metadata still determines ownership among the candidates. Reference counts are partial
/// and must not be used to decide whether a rollout can be deleted or compressed.
pub async fn scan_archived_threads(
codex_home: &Path,
thread_ids: &[ThreadId],
) -> io::Result<Self> {
let thread_ids = thread_ids.iter().copied().collect();
Self::scan_paths(
vec![codex_home.join(ARCHIVED_SESSIONS_SUBDIR)],
Some(&thread_ids),
)
.await
}
async fn scan_paths(
mut stack: Vec<PathBuf>,
thread_ids: Option<&HashSet<ThreadId>>,
) -> io::Result<Self> {
let mut rollouts_by_id = HashMap::new();
while let Some(directory) = stack.pop() {
let mut entries = match tokio::fs::read_dir(directory.as_path()).await {
Ok(entries) => entries,
Err(err) if err.kind() == io::ErrorKind::NotFound => continue,
Err(err) => return Err(err),
};
loop {
let Some(entry) = entries.next_entry().await? else {
break;
};
let path = entry.path();
let file_type = entry.file_type().await?;
if file_type.is_dir() {
stack.push(path);
continue;
}
if !file_type.is_file() {
continue;
}
let Some(rollout_file) = RolloutFile::from_path(path) else {
continue;
};
let Some(file_name) = RolloutFileName::parse(rollout_file.plain_file_name()) else {
continue;
};
if thread_ids.is_some_and(|ids| !ids.contains(&file_name.thread_id())) {
continue;
}
let rollout_id = file_name.rollout_id();
let Ok(meta) = crate::read_session_meta_line(rollout_file.path()).await else {
continue;
};
if let Entry::Vacant(entry) = rollouts_by_id.entry(rollout_id) {
entry.insert(IndexedRollout {
thread_id: meta.meta.id,
path: rollout_file.into_path(),
history_base: meta.meta.history_base,
attached_to_thread_id: meta
.meta
.forked_from_id
.filter(|_| meta.meta.attached_thread),
});
}
}
}
let mut reference_counts_by_rollout = HashMap::new();
for (rollout_id, rollout) in &rollouts_by_id {
let Some(history_base) = rollout.history_base else {
continue;
};
if history_base.thread_id == *rollout_id {
continue;
}
*reference_counts_by_rollout
.entry(history_base.thread_id)
.or_default() += 1;
}
Ok(Self {
rollouts_by_id,
reference_counts_by_rollout,
})
}
/// Returns how many other discovered rollouts directly reference `rollout_id`.
pub fn reference_count(&self, rollout_id: RolloutId) -> usize {
self.reference_counts_by_rollout
.get(&rollout_id)
.copied()
.unwrap_or_default()
}
/// Returns the direct history-base edge for `rollout_id`, if one was discovered.
pub fn history_base(&self, rollout_id: RolloutId) -> Option<&HistoryPosition> {
self.rollouts_by_id
.get(&rollout_id)
.and_then(|rollout| rollout.history_base.as_ref())
}
/// Find an indexed attached child of any candidate parent.
pub fn attached_child(&self, parent_thread_ids: &[ThreadId]) -> Option<ThreadId> {
let parents: HashSet<_> = parent_thread_ids.iter().copied().collect();
self.rollouts_by_id.values().find_map(|rollout| {
rollout
.attached_to_thread_id
.filter(|parent| parents.contains(parent))
.map(|_| rollout.thread_id)
})
}
/// Returns rollout IDs and paths whose session metadata belongs to `thread_id`.
pub fn rollouts_for_thread(
&self,
thread_id: ThreadId,
) -> impl Iterator<Item = (RolloutId, &Path)> {
self.rollouts_by_id
.iter()
.filter(move |(_, rollout)| rollout.thread_id == thread_id)
.map(|(rollout_id, rollout)| (*rollout_id, rollout.path.as_path()))
}
}
#[cfg(test)]
#[path = "rollout_reference_index_tests.rs"]
mod tests;

View File

@@ -0,0 +1,379 @@
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use codex_protocol::ThreadId;
use codex_protocol::protocol::HistoryPosition;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
use uuid::Uuid;
use super::RolloutReferenceIndex;
#[tokio::test]
async fn scans_active_archived_and_compressed_history_bases() -> anyhow::Result<()> {
let home = TempDir::new()?;
let source_id = thread_id(Uuid::from_u128(1))?;
let active_base = history_position(source_id);
let archived_base = history_position(source_id);
let compressed_base = history_position(source_id);
let active_child_id = thread_id(Uuid::from_u128(2))?;
let archived_child_id = thread_id(Uuid::from_u128(3))?;
let compressed_child_id = thread_id(Uuid::from_u128(4))?;
write_rollout(
active_rollout_path(home.path(), Uuid::from_u128(2)),
active_child_id,
Some(active_base),
)?;
write_rollout(
archived_rollout_path(home.path(), Uuid::from_u128(3)),
archived_child_id,
Some(archived_base),
)?;
let compressed_path = archived_rollout_path(home.path(), Uuid::from_u128(4));
write_rollout(
compressed_path.clone(),
compressed_child_id,
Some(compressed_base),
)?;
compress_now(compressed_path.as_path())?;
let index = RolloutReferenceIndex::scan(home.path()).await?;
assert_eq!(index.reference_count(source_id), 3);
assert_eq!(index.history_base(active_child_id), Some(&active_base));
assert_eq!(index.history_base(archived_child_id), Some(&archived_base));
assert_eq!(
index.history_base(compressed_child_id),
Some(&compressed_base)
);
Ok(())
}
#[tokio::test]
async fn active_duplicate_wins_without_double_counting() -> anyhow::Result<()> {
let home = TempDir::new()?;
let active_source_id = thread_id(Uuid::from_u128(8))?;
let archived_source_id = thread_id(Uuid::from_u128(9))?;
let child_uuid = Uuid::from_u128(10);
let child_id = thread_id(Uuid::from_u128(10))?;
let active_base = history_position(active_source_id);
write_rollout(
active_rollout_path(home.path(), child_uuid),
child_id,
Some(active_base),
)?;
write_rollout(
archived_rollout_path(home.path(), child_uuid),
child_id,
Some(history_position(archived_source_id)),
)?;
let index = RolloutReferenceIndex::scan(home.path()).await?;
assert_eq!(index.history_base(child_id), Some(&active_base));
assert_eq!(index.reference_count(active_source_id), 1);
assert_eq!(index.reference_count(archived_source_id), 0);
Ok(())
}
#[tokio::test]
async fn indexes_multiple_rollouts_for_the_same_thread() -> anyhow::Result<()> {
let home = TempDir::new()?;
let source_rollout_id = thread_id(Uuid::from_u128(21))?;
let replacement_rollout_id = thread_id(Uuid::from_u128(22))?;
let thread_id = thread_id(Uuid::from_u128(20))?;
let history_base = history_position(source_rollout_id);
write_rollout(
active_rollout_path(home.path(), Uuid::from_u128(21)),
thread_id,
Some(history_base),
)?;
write_rollout(
active_rollout_path(home.path(), Uuid::from_u128(22)),
thread_id,
Some(history_base),
)?;
let index = RolloutReferenceIndex::scan(home.path()).await?;
assert_eq!(index.history_base(source_rollout_id), Some(&history_base));
assert_eq!(
index.history_base(replacement_rollout_id),
Some(&history_base)
);
assert_eq!(index.reference_count(source_rollout_id), 1);
Ok(())
}
#[tokio::test]
async fn unarchived_scan_finds_all_active_rollouts_owned_by_a_thread() -> anyhow::Result<()> {
let home = TempDir::new()?;
let owner_id = thread_id(Uuid::from_u128(30))?;
let original_uuid = Uuid::from_u128(31);
let replacement_uuid = Uuid::from_u128(32);
let original_path = active_rollout_path(home.path(), original_uuid);
let replacement_path = active_rollout_path(home.path(), replacement_uuid);
write_rollout(original_path.clone(), owner_id, /*history_base*/ None)?;
compress_now(&original_path)?;
write_rollout(
replacement_path.clone(),
owner_id,
/*history_base*/ None,
)?;
write_rollout(
archived_rollout_path(home.path(), Uuid::from_u128(33)),
owner_id,
/*history_base*/ None,
)?;
write_rollout(
active_rollout_path(home.path(), Uuid::from_u128(34)),
thread_id(Uuid::from_u128(34))?,
/*history_base*/ None,
)?;
let index = RolloutReferenceIndex::scan_unarchived(home.path()).await?;
let mut owned: Vec<_> = index
.rollouts_for_thread(owner_id)
.map(|(id, path)| (id, path.to_path_buf()))
.collect();
owned.sort_by_key(|(_, path)| path.clone());
assert_eq!(
owned,
vec![
(
thread_id(original_uuid)?,
original_path.with_extension("jsonl.zst")
),
(thread_id(replacement_uuid)?, replacement_path),
]
);
Ok(())
}
#[tokio::test]
async fn filtered_unarchived_scan_includes_reverts_and_requested_descendants() -> anyhow::Result<()>
{
let home = TempDir::new()?;
let owner_uuid = Uuid::from_u128(40);
let owner_id = thread_id(owner_uuid)?;
let replacement_id = thread_id(Uuid::from_u128(41))?;
let descendant_uuid = Uuid::from_u128(42);
let descendant_id = thread_id(descendant_uuid)?;
let unrelated_uuid = Uuid::from_u128(43);
let unrelated_id = thread_id(unrelated_uuid)?;
let original_path = active_rollout_path(home.path(), owner_uuid);
let replacement_path = original_path.with_file_name(format!(
"rollout-2025-01-03T12-00-00-{owner_id}_{replacement_id}.jsonl"
));
let descendant_path = active_rollout_path(home.path(), descendant_uuid);
write_rollout(original_path.clone(), owner_id, /*history_base*/ None)?;
compress_now(&original_path)?;
write_rollout(
replacement_path.clone(),
owner_id,
/*history_base*/ None,
)?;
// A leftover compressed sibling must not supersede the plain rollout.
compress_now(&replacement_path)?;
write_rollout(
replacement_path.clone(),
owner_id,
/*history_base*/ None,
)?;
write_rollout(
descendant_path.clone(),
descendant_id,
Some(history_position(owner_id)),
)?;
write_rollout(
archived_rollout_path(home.path(), owner_uuid),
owner_id,
/*history_base*/ None,
)?;
let unrelated_path = active_rollout_path(home.path(), unrelated_uuid);
write_rollout(
unrelated_path.clone(),
unrelated_id,
/*history_base*/ None,
)?;
compress_now(&unrelated_path)?;
let index =
RolloutReferenceIndex::scan_unarchived_threads(home.path(), &[owner_id, descendant_id])
.await?;
let mut owned: Vec<_> = index
.rollouts_for_thread(owner_id)
.map(|(id, path)| (id, path.to_path_buf()))
.collect();
owned.sort_by_key(|(id, _)| id.to_string());
assert_eq!(
owned,
vec![
(owner_id, original_path.with_extension("jsonl.zst")),
(replacement_id, replacement_path),
]
);
assert_eq!(
index.rollouts_for_thread(descendant_id).collect::<Vec<_>>(),
vec![(descendant_id, descendant_path.as_path())]
);
assert_eq!(
index.rollouts_for_thread(unrelated_id).collect::<Vec<_>>(),
Vec::new()
);
Ok(())
}
#[tokio::test]
async fn filtered_unarchived_scan_validates_candidate_ownership() -> anyhow::Result<()> {
let home = TempDir::new()?;
let requested_uuid = Uuid::from_u128(50);
let requested_id = thread_id(requested_uuid)?;
let actual_owner = thread_id(Uuid::from_u128(51))?;
write_rollout(
active_rollout_path(home.path(), requested_uuid),
actual_owner,
/*history_base*/ None,
)?;
let index =
RolloutReferenceIndex::scan_unarchived_threads(home.path(), &[requested_id]).await?;
assert_eq!(
index.rollouts_for_thread(requested_id).collect::<Vec<_>>(),
Vec::new()
);
Ok(())
}
/// Restoring a thread must include its compressed/reverted files without scanning other history.
#[tokio::test]
async fn filtered_archived_scan_includes_only_owned_archived_candidates() -> anyhow::Result<()> {
let home = TempDir::new()?;
let owner_uuid = Uuid::from_u128(60);
let owner_id = thread_id(owner_uuid)?;
let replacement_id = thread_id(Uuid::from_u128(61))?;
let other_uuid = Uuid::from_u128(62);
let other_id = thread_id(other_uuid)?;
let mismatched_id = thread_id(Uuid::from_u128(63))?;
let original_path = archived_rollout_path(home.path(), owner_uuid);
let replacement_path = original_path.with_file_name(format!(
"rollout-2025-01-03T12-00-00-{owner_id}_{replacement_id}.jsonl"
));
write_rollout(original_path.clone(), owner_id, /*history_base*/ None)?;
compress_now(&original_path)?;
write_rollout(
replacement_path.clone(),
owner_id,
Some(history_position(owner_id)),
)?;
// A matching filename is only a candidate: metadata must confirm ownership.
let mismatched_path = original_path.with_file_name(format!(
"rollout-2025-01-03T12-00-00-{owner_id}_{mismatched_id}.jsonl"
));
write_rollout(mismatched_path, other_id, /*history_base*/ None)?;
// Unrelated filenames are excluded before reading their metadata.
write_rollout(
archived_rollout_path(home.path(), other_uuid),
owner_id,
/*history_base*/ None,
)?;
write_rollout(
active_rollout_path(home.path(), owner_uuid),
owner_id,
/*history_base*/ None,
)?;
let index = RolloutReferenceIndex::scan_archived_threads(home.path(), &[owner_id]).await?;
let mut owned: Vec<_> = index
.rollouts_for_thread(owner_id)
.map(|(id, path)| (id, path.to_path_buf()))
.collect();
owned.sort_by_key(|(id, _)| id.to_string());
assert_eq!(
owned,
vec![
(owner_id, original_path.with_extension("jsonl.zst")),
(replacement_id, replacement_path),
]
);
Ok(())
}
#[tokio::test]
async fn self_history_base_does_not_count_as_reference() -> anyhow::Result<()> {
let home = TempDir::new()?;
let thread_id = thread_id(Uuid::from_u128(11))?;
let history_base = history_position(thread_id);
write_rollout(
active_rollout_path(home.path(), Uuid::from_u128(11)),
thread_id,
Some(history_base),
)?;
let index = RolloutReferenceIndex::scan(home.path()).await?;
assert_eq!(index.history_base(thread_id), Some(&history_base));
assert_eq!(index.reference_count(thread_id), 0);
Ok(())
}
fn active_rollout_path(home: &Path, uuid: Uuid) -> PathBuf {
home.join("sessions/2025/01/03")
.join(format!("rollout-2025-01-03T12-00-00-{uuid}.jsonl"))
}
fn archived_rollout_path(home: &Path, uuid: Uuid) -> PathBuf {
home.join("archived_sessions")
.join(format!("rollout-2025-01-03T12-00-00-{uuid}.jsonl"))
}
fn write_rollout(
path: PathBuf,
thread_id: ThreadId,
history_base: Option<HistoryPosition>,
) -> anyhow::Result<()> {
fs::create_dir_all(path.parent().expect("rollout parent"))?;
let session_meta = serde_json::json!({
"timestamp": "2025-01-03T12:00:00Z",
"type": "session_meta",
"payload": {
"id": thread_id,
"timestamp": "2025-01-03T12:00:00Z",
"cwd": path.parent().expect("rollout parent"),
"originator": "test",
"cli_version": "test",
"source": "cli",
"model_provider": "test-provider",
"history_mode": "paginated",
"history_base": history_base,
},
});
fs::write(path, format!("{session_meta}\n"))?;
Ok(())
}
fn history_position(rollout_id: ThreadId) -> HistoryPosition {
HistoryPosition {
thread_id: rollout_id,
end_ordinal_exclusive: 2,
end_byte_offset: 100,
}
}
fn thread_id(uuid: Uuid) -> anyhow::Result<ThreadId> {
Ok(ThreadId::from_string(&uuid.to_string())?)
}
fn compress_now(path: &Path) -> anyhow::Result<()> {
let compressed_path = path.with_extension("jsonl.zst");
let input = fs::File::open(path)?;
let output = fs::File::create(compressed_path)?;
let mut encoder = zstd::stream::write::Encoder::new(output, 3)?;
std::io::copy(&mut std::io::BufReader::new(input), &mut encoder)?;
encoder.finish()?;
fs::remove_file(path)?;
Ok(())
}

View File

@@ -0,0 +1,410 @@
use std::collections::HashMap;
use std::collections::HashSet;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::process::Stdio;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::strip_user_message_prefix;
use futures::future::join_all;
use regex::Regex;
use regex::RegexBuilder;
use tokio::process::Command;
use super::ARCHIVED_SESSIONS_SUBDIR;
use super::SESSIONS_SUBDIR;
use super::compression;
use crate::ResponseItemEnvelope;
use crate::RolloutItem;
const MATCH_CONTEXT_BEFORE_CHARS: usize = 48;
const MATCH_CONTEXT_AFTER_CHARS: usize = 96;
/// Search matches keyed by the canonical `.jsonl` path for each rollout.
pub type RolloutSearchMatches = HashMap<PathBuf, Option<String>>;
pub async fn search_rollout_paths(
rg_command: &Path,
codex_home: &Path,
archived: bool,
search_term: &str,
) -> io::Result<HashSet<PathBuf>> {
Ok(
search_rollout_matches(rg_command, codex_home, archived, search_term)
.await?
.into_keys()
.collect(),
)
}
pub async fn search_rollout_matches(
rg_command: &Path,
codex_home: &Path,
archived: bool,
search_term: &str,
) -> io::Result<RolloutSearchMatches> {
let root = codex_home.join(if archived {
ARCHIVED_SESSIONS_SUBDIR
} else {
SESSIONS_SUBDIR
});
let json_search_term = json_escaped_search_term(search_term)?;
let Some(plain_matches) =
ripgrep_rollout_paths(rg_command, root.as_path(), json_search_term.as_str()).await?
else {
return scan_rollout_matches(root.as_path(), json_search_term.as_str(), search_term).await;
};
let mut matches: RolloutSearchMatches =
plain_matches.into_iter().map(|path| (path, None)).collect();
matches.extend(scan_compressed_rollout_matches(root.as_path(), search_term).await?);
Ok(matches)
}
async fn ripgrep_rollout_paths(
rg_command: &Path,
root: &Path,
search_term: &str,
) -> io::Result<Option<HashSet<PathBuf>>> {
if !tokio::fs::try_exists(root).await.unwrap_or(false) {
return Ok(Some(HashSet::new()));
}
let output = match Command::from(codex_utils_process::background_command(rg_command))
.arg("-l")
.arg("--fixed-strings")
.arg("--ignore-case")
.arg("--no-ignore")
.arg("--glob")
.arg("*.jsonl")
.arg("--")
.arg(search_term)
.arg(root)
.stdin(Stdio::null())
.output()
.await
{
Ok(output) => output,
Err(err) if err.kind() == io::ErrorKind::NotFound => {
return Ok(None);
}
Err(err) => return Err(err),
};
if !output.status.success() {
if output.status.code() == Some(1) && output.stderr.is_empty() {
return Ok(Some(HashSet::new()));
}
return Err(io::Error::other(format!(
"ripgrep rollout search failed under {}",
root.display()
)));
}
let mut matches = HashSet::new();
for line in String::from_utf8_lossy(output.stdout.as_slice()).lines() {
let path = PathBuf::from(line);
let path = if path.is_absolute() {
path
} else {
root.join(path)
};
matches.insert(path);
}
Ok(Some(matches))
}
async fn scan_rollout_matches(
root: &Path,
json_search_term: &str,
search_term: &str,
) -> io::Result<RolloutSearchMatches> {
let mut matches = HashMap::new();
let mut dirs = vec![root.to_path_buf()];
let json_search_term = case_insensitive_literal_regex(json_search_term)?;
let mut patterns = None;
while let Some(dir) = dirs.pop() {
let mut entries = match tokio::fs::read_dir(dir).await {
Ok(entries) => entries,
Err(err) if err.kind() == io::ErrorKind::NotFound => continue,
Err(err) => return Err(err),
};
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
let file_type = entry.file_type().await?;
if file_type.is_dir() {
dirs.push(path);
continue;
}
if !file_type.is_file() {
continue;
}
let Some(rollout_file) = compression::RolloutFile::from_path(path) else {
continue;
};
if rollout_file.is_compressed() {
if let Some(snippet) =
first_content_match_snippet(rollout_file.path(), search_term, &mut patterns)
.await
.unwrap_or_else(|err| {
tracing::warn!(
path = %rollout_file.path().display(),
%err,
"Failed to search compressed rollout"
);
None
})
{
matches.insert(
compression::plain_rollout_path(rollout_file.path()),
Some(snippet),
);
}
continue;
}
if rollout_contains(rollout_file.path(), &json_search_term).await? {
matches.insert(rollout_file.into_path(), None);
}
}
}
Ok(matches)
}
async fn rollout_contains(path: &Path, search_term: &Regex) -> io::Result<bool> {
let mut lines = compression::open_rollout_line_reader(path).await?;
while let Some(line) = lines.next_line().await? {
if search_term.is_match(line.as_str()) {
return Ok(true);
}
}
Ok(false)
}
pub async fn first_rollout_content_match_snippet(
path: &Path,
search_term: &str,
) -> io::Result<Option<String>> {
first_content_match_snippet(path, search_term, &mut None).await
}
async fn first_content_match_snippet(
path: &Path,
search_term: &str,
patterns: &mut Option<(Regex, Regex)>,
) -> io::Result<Option<String>> {
let lines = compression::open_rollout_line_reader(path).await?;
// Keep compilation errors inside the caller's per-file error handler.
let (json_search_term, search_term) = match patterns {
Some(patterns) => patterns,
None => patterns.insert((
case_insensitive_literal_regex(json_escaped_search_term(search_term)?)?,
case_insensitive_literal_regex(search_term)?,
)),
};
let json_search_term = json_search_term.clone();
let search_term = search_term.clone();
lines
.find_map(move |line| {
if json_search_term.is_match(line) {
content_match_snippet(line, &search_term)
} else {
None
}
})
.await
}
async fn scan_compressed_rollout_matches(
root: &Path,
search_term: &str,
) -> io::Result<RolloutSearchMatches> {
let mut matches = HashMap::new();
let mut paths = Vec::new();
let mut dirs = vec![root.to_path_buf()];
while let Some(dir) = dirs.pop() {
let mut entries = match tokio::fs::read_dir(dir).await {
Ok(entries) => entries,
Err(err) if err.kind() == io::ErrorKind::NotFound => continue,
Err(err) => return Err(err),
};
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
let file_type = entry.file_type().await?;
if file_type.is_dir() {
dirs.push(path);
continue;
}
if !file_type.is_file() {
continue;
}
let Some(rollout_file) = compression::RolloutFile::from_path(path) else {
continue;
};
if !rollout_file.is_compressed() {
continue;
}
paths.push(rollout_file.into_path());
}
}
const COMPRESSED_SEARCH_WORKERS: usize = 4;
let scan = async |paths: &[PathBuf]| {
let mut matches = HashMap::new();
let mut patterns = None;
for path in paths {
if let Some(snippet) =
first_content_match_snippet(path.as_path(), search_term, &mut patterns)
.await
.unwrap_or_else(|err| {
tracing::warn!(
path = %path.as_path().display(),
%err,
"Failed to search compressed rollout"
);
None
})
{
matches.insert(
compression::plain_rollout_path(path.as_path()),
Some(snippet),
);
}
}
matches
};
let chunk_size = paths.len().div_ceil(COMPRESSED_SEARCH_WORKERS).max(1);
for batch in join_all(paths.chunks(chunk_size).map(scan)).await {
matches.extend(batch);
}
Ok(matches)
}
fn json_escaped_search_term(search_term: &str) -> io::Result<String> {
let serialized = serde_json::to_string(search_term).map_err(io::Error::other)?;
Ok(serialized[1..serialized.len() - 1].to_string())
}
fn case_insensitive_literal_regex(search_term: impl AsRef<str>) -> io::Result<Regex> {
RegexBuilder::new(regex::escape(search_term.as_ref()).as_str())
.case_insensitive(true)
.build()
.map_err(io::Error::other)
}
fn content_match_snippet(jsonl_line: &str, search_term: &Regex) -> Option<String> {
let rollout_line = crate::parse_rollout_line(jsonl_line.trim()).ok()?;
let text = conversation_text_from_item(&rollout_line.item)?;
excerpt_around_match(text.as_str(), search_term)
}
fn conversation_text_from_item(item: &RolloutItem) -> Option<String> {
match item {
RolloutItem::EventMsg(EventMsg::UserMessage(user)) => {
let text = strip_user_message_prefix(user.message.as_str());
if text.is_empty() {
None
} else {
Some(text.to_string())
}
}
RolloutItem::EventMsg(EventMsg::AgentMessage(agent)) => {
if agent.message.trim().is_empty() {
None
} else {
Some(agent.message.trim().to_string())
}
}
RolloutItem::ResponseItem(ResponseItemEnvelope {
item: ResponseItem::Message { role, content, .. },
..
}) => {
let text = content
.iter()
.filter_map(content_item_text)
.collect::<Vec<_>>()
.join(" ");
if text.trim().is_empty() || (role != "user" && role != "assistant") {
None
} else {
Some(text)
}
}
RolloutItem::DynamicToolsUpdated { .. }
| RolloutItem::SessionMeta(_)
| RolloutItem::TurnContext(_)
| RolloutItem::EventMsg(_)
| RolloutItem::ResponseItem(_)
| RolloutItem::InterAgentCommunication(_)
| RolloutItem::InterAgentCommunicationMetadata { .. }
| RolloutItem::Compacted(_)
| RolloutItem::RealtimeItem(_)
| RolloutItem::RetainedContext(_)
| RolloutItem::SecurityRiskScore(_)
| RolloutItem::TokenUsageRecord(_)
| RolloutItem::WorldState(_) => None,
}
}
fn content_item_text(item: &ContentItem) -> Option<&str> {
match item {
ContentItem::InputText { text } | ContentItem::OutputText { text, .. } => {
Some(text.as_str())
}
ContentItem::InputImage { .. } | ContentItem::InputAudio { .. } => None,
}
}
fn excerpt_around_match(text: &str, search_term: &Regex) -> Option<String> {
let normalized = normalize_preview_text(text);
let matched = search_term.find(normalized.as_str())?;
let match_start = matched.start();
let match_end = matched.end();
let excerpt_start =
char_start_before(normalized.as_str(), match_start, MATCH_CONTEXT_BEFORE_CHARS);
let excerpt_end = char_end_after(normalized.as_str(), match_end, MATCH_CONTEXT_AFTER_CHARS);
let excerpt = normalized[excerpt_start..excerpt_end].trim();
if excerpt.is_empty() {
return None;
}
let mut snippet = String::new();
if excerpt_start > 0 {
snippet.push_str("... ");
}
snippet.push_str(excerpt);
if excerpt_end < normalized.len() {
snippet.push_str(" ...");
}
Some(snippet)
}
fn normalize_preview_text(text: &str) -> String {
text.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn char_start_before(text: &str, byte_index: usize, chars_before: usize) -> usize {
text[..byte_index]
.char_indices()
.rev()
.nth(chars_before)
.map(|(idx, _)| idx)
.unwrap_or(0)
}
fn char_end_after(text: &str, byte_index: usize, chars_after: usize) -> usize {
text[byte_index..]
.char_indices()
.nth(chars_after)
.map(|(offset, _)| byte_index.saturating_add(offset))
.unwrap_or(text.len())
}
#[cfg(test)]
#[path = "search_tests.rs"]
mod tests;

View File

@@ -0,0 +1,38 @@
//! Regression coverage for rollout search error handling.
use super::*;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
#[tokio::test]
async fn compressed_search_preserves_error_handling() -> io::Result<()> {
let root = TempDir::new()?;
let line = br#"{"timestamp":"2025-01-01T00:00:00Z","type":"event_msg","payload":{"type":"agent_message","message":"needle"}}"#;
let compressed = zstd::stream::encode_all(&line[..], 3)?;
let mut expected = RolloutSearchMatches::new();
for index in 0..7 {
let path = root.path().join(format!("rollout-{index:04}.jsonl"));
std::fs::write(path.with_extension("jsonl.zst"), &compressed)?;
expected.insert(path, Some("needle".to_string()));
}
std::fs::write(root.path().join("rollout-broken.jsonl.zst"), b"not zstd")?;
assert_eq!(
scan_compressed_rollout_matches(root.path(), "needle").await?,
expected
);
let query = "a".repeat(500_000);
assert!(case_insensitive_literal_regex(&query).is_err());
assert_eq!(
scan_compressed_rollout_matches(root.path(), &query).await?,
RolloutSearchMatches::new()
);
assert_eq!(
first_rollout_content_match_snippet(&root.path().join("missing.jsonl"), &query)
.await
.unwrap_err()
.kind(),
io::ErrorKind::NotFound
);
Ok(())
}

View File

@@ -0,0 +1,180 @@
//! Reads rollout bytes and positions independently of their plain or compressed representation.
//!
//! Offsets always address the original JSONL bytes. Readers retain an open file, or an anonymous
//! decoded snapshot, so a concurrent compression cannot invalidate an in-progress scan.
//! Cancellation is checked during decompression and subsequent bounded reads and seeks.
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::path::Path;
use std::time::Duration;
use crate::plain_rollout_path;
enum RolloutReader {
Plain(File),
Compressed(File),
}
impl RolloutReader {
fn open(path: &Path) -> io::Result<Self> {
let plain_path = plain_rollout_path(path);
let compressed_path = plain_path.with_extension("jsonl.zst");
for attempt in 0..4 {
match File::open(&plain_path) {
Ok(file) => return Ok(Self::Plain(file)),
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
Err(err) => return Err(err),
}
match File::open(&compressed_path) {
Ok(file) => return Ok(Self::Compressed(file)),
Err(err) if err.kind() == io::ErrorKind::NotFound && attempt < 3 => {
std::thread::sleep(Duration::from_millis(50));
}
Err(err) => return Err(err),
}
}
unreachable!("the final open attempt returns its error")
}
}
/// Reads at most `max_bytes` decoded rollout bytes without materializing the durable file.
///
/// Returns `None` for nonregular files. This retains an open representation while reading, so
/// compression or materialization cannot invalidate the read after resolution.
pub fn read_rollout_prefix(path: &Path, max_bytes: usize) -> io::Result<Option<Vec<u8>>> {
if std::fs::metadata(path).is_ok_and(|metadata| !metadata.is_file()) {
return Ok(None);
}
let source = RolloutReader::open(path)?;
let file = match &source {
RolloutReader::Plain(file) | RolloutReader::Compressed(file) => file,
};
if !file.metadata()?.is_file() {
return Ok(None);
}
let reader: Box<dyn Read> = match source {
RolloutReader::Plain(file) => Box::new(file),
RolloutReader::Compressed(file) => Box::new(zstd::stream::read::Decoder::new(file)?),
};
let mut bytes = Vec::new();
reader.take(max_bytes as u64).read_to_end(&mut bytes)?;
Ok(Some(bytes))
}
/// Opens the original JSONL bytes for blocking offset reads without changing the rollout on disk.
///
/// Compressed files are decoded into an anonymous temporary file, keeping memory use bounded and
/// preserving read-only access to the Codex home. Plain files retain their existing seek fast path.
/// `is_cancelled` must observe the lifetime of the calling task. Cancellation returns an error,
/// never EOF, so callers cannot mistake a partial read for a complete history.
pub fn open_rollout_seekable_reader(
path: &Path,
is_cancelled: impl Fn() -> bool,
) -> io::Result<impl Read + Seek> {
if is_cancelled() {
return Err(io::Error::other("rollout read cancelled"));
}
let file = match RolloutReader::open(path)? {
RolloutReader::Plain(file) => file,
RolloutReader::Compressed(file) => {
let mut decoded = tempfile::tempfile()?;
// Empty and skippable frames can consume input without producing decoded bytes.
let file = CancellableReader {
inner: file,
is_cancelled: &is_cancelled,
};
let mut reader = CancellableReader {
inner: zstd::stream::read::Decoder::new(file)?,
is_cancelled: &is_cancelled,
};
io::copy(&mut reader, &mut decoded)?;
decoded.rewind()?;
decoded
}
};
Ok(CancellableReader {
inner: file,
is_cancelled,
})
}
struct CancellableReader<R, F> {
inner: R,
is_cancelled: F,
}
impl<R, F: Fn() -> bool> CancellableReader<R, F> {
fn check_cancelled(&self) -> io::Result<()> {
if (self.is_cancelled)() {
// Interrupted is retried by io::copy and read_exact, defeating cancellation.
return Err(io::Error::other("rollout read cancelled"));
}
Ok(())
}
}
impl<R: Read, F: Fn() -> bool> Read for CancellableReader<R, F> {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
self.check_cancelled()?;
let limit = buffer.len().min(64 * 1024);
let read = self.inner.read(&mut buffer[..limit])?;
self.check_cancelled()?;
Ok(read)
}
}
impl<R: Seek, F: Fn() -> bool> Seek for CancellableReader<R, F> {
fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
self.check_cancelled()?;
self.inner.seek(position)
}
}
/// Checks a frozen prefix's byte bound using a blocking read of the logical JSONL representation.
///
/// A known first-frame size is a lower bound even for concatenated zstd frames. New compressed
/// rollouts include that size, so ordinary lineage validation only reads the header. Older frames
/// without a size, and prefixes extending beyond the first frame, are decoded up to the bound.
pub fn rollout_contains_prefix(
path: &Path,
end_byte_offset: u64,
is_cancelled: impl Fn() -> bool,
) -> io::Result<bool> {
if is_cancelled() {
return Err(io::Error::other("rollout read cancelled"));
}
match RolloutReader::open(path)? {
RolloutReader::Plain(file) => Ok(end_byte_offset <= file.metadata()?.len()),
RolloutReader::Compressed(file) => {
let mut file = CancellableReader {
inner: file,
is_cancelled: &is_cancelled,
};
// A zstd frame header occupies at most 18 bytes.
let mut header = [0; 18];
let read = file.read(&mut header)?;
if zstd::zstd_safe::get_frame_content_size(&header[..read])
.ok()
.flatten()
.is_some_and(|size| end_byte_offset <= size)
{
return Ok(true);
}
file.rewind()?;
let mut prefix = CancellableReader {
inner: zstd::stream::read::Decoder::new(file)?,
is_cancelled: &is_cancelled,
}
.take(end_byte_offset);
Ok(io::copy(&mut prefix, &mut io::sink())? == end_byte_offset)
}
}
}
#[cfg(test)]
#[path = "seekable_reader_tests.rs"]
mod tests;

View File

@@ -0,0 +1,163 @@
use std::cell::Cell;
use std::fs;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Write;
use pretty_assertions::assert_eq;
use super::*;
#[tokio::test]
async fn dropping_the_caller_stops_compressed_materialization() -> anyhow::Result<()> {
let home = tempfile::tempdir()?;
let path = home.path().join("rollout.jsonl.zst");
let original = vec![b'x'; 1024 * 1024];
let compressed = zstd::stream::encode_all(original.as_slice(), /*level*/ 3)?;
fs::write(&path, &compressed)?;
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
let (resume_tx, resume_rx) = std::sync::mpsc::channel();
let (finished_tx, finished_rx) = tokio::sync::oneshot::channel();
let read_path = path.clone();
let task = tokio::spawn(async move {
let (stop, keep_running) = tokio::sync::oneshot::channel::<()>();
let worker = tokio::task::spawn_blocking(move || {
let checks = Cell::new(0);
let started = Cell::new(Some(started_tx));
let result = open_rollout_seekable_reader(&read_path, || {
checks.set(checks.get() + 1);
// Check on open and around the first source read and decoded chunk.
// Pause after that chunk so a check only before decompression cannot pass.
if checks.get() >= 5
&& let Some(started) = started.take()
{
let _ = started.send(());
let _ = resume_rx.recv();
}
stop.is_closed()
});
let _ = finished_tx.send(result.err().map(|error| error.kind()));
});
let result = worker.await;
drop(keep_running);
result
});
started_rx.await?;
task.abort();
assert!(task.await.unwrap_err().is_cancelled());
resume_tx.send(())?;
assert_eq!(finished_rx.await?, Some(io::ErrorKind::Other));
assert_eq!(fs::read(&path)?, compressed);
assert!(!path.with_extension("").exists());
Ok(())
}
#[test]
fn cancellation_stops_compressed_input_and_output() -> io::Result<()> {
let home = tempfile::tempdir()?;
let path = home.path().join("rollout.jsonl.zst");
let original = vec![b'x'; 1024 * 1024];
let mut skippable = 0x184D2A50_u32.to_le_bytes().to_vec();
skippable.extend((original.len() as u32).to_le_bytes());
skippable.extend(&original);
// Exercise many input reads with no output, and many output reads from little input.
for bytes in [
skippable,
zstd::stream::encode_all(original.as_slice(), /*level*/ 3)?,
] {
fs::write(&path, bytes)?;
drop(open_rollout_seekable_reader(&path, || false)?);
let checks = Cell::new(0);
let cancelled = || checks.replace(checks.get() + 1) >= 10;
assert!(open_rollout_seekable_reader(&path, cancelled).is_err());
checks.set(0);
assert!(rollout_contains_prefix(&path, original.len() as u64, cancelled).is_err());
}
Ok(())
}
#[test]
fn read_snapshots_preserve_bytes_and_report_cancellation() -> io::Result<()> {
let home = tempfile::tempdir()?;
let path = home.path().join("rollout.jsonl");
let compressed = path.with_extension("jsonl.zst");
let original = "first\r\nsecond 🦀\nthird\n".as_bytes();
fs::write(
&compressed,
zstd::stream::encode_all(original, /*level*/ 3)?,
)?;
let cancelled = Cell::new(false);
let is_cancelled = || cancelled.get();
let mut reader = open_rollout_seekable_reader(&path, is_cancelled)?;
// The retained snapshot must remain valid after another caller materializes the logical path.
fs::write(&path, b"replacement\n")?;
fs::remove_file(&compressed)?;
reader.seek(SeekFrom::Start(7))?;
let mut suffix = Vec::new();
reader.read_to_end(&mut suffix)?;
assert_eq!(suffix, original[7..]);
let mut current = Vec::new();
open_rollout_seekable_reader(&compressed, || false)?.read_to_end(&mut current)?;
assert_eq!(current, b"replacement\n");
let mut plain_snapshot = open_rollout_seekable_reader(&path, is_cancelled)?;
fs::write(
&compressed,
zstd::stream::encode_all(current.as_slice(), /*level*/ 3)?,
)?;
fs::remove_file(&path)?;
let mut retained = Vec::new();
plain_snapshot.read_to_end(&mut retained)?;
assert_eq!(retained, current);
reader.rewind()?;
plain_snapshot.rewind()?;
cancelled.set(true);
for mut reader in [reader, plain_snapshot] {
assert_eq!(
reader.read_to_end(&mut Vec::new()).unwrap_err().kind(),
io::ErrorKind::Other
);
assert_eq!(reader.rewind().unwrap_err().kind(), io::ErrorKind::Other);
}
Ok(())
}
#[test]
fn prefix_bounds_support_sized_unsized_and_concatenated_frames() -> io::Result<()> {
let home = tempfile::tempdir()?;
let path = home.path().join("rollout.jsonl.zst");
let first = "first 🦀\n".as_bytes();
let second = b"second\n";
let mut encoder = zstd::stream::write::Encoder::new(Vec::new(), /*level*/ 3)?;
encoder.set_pledged_src_size(Some(first.len() as u64))?;
encoder.write_all(first)?;
let sized = encoder.finish()?;
let without_size = zstd::stream::encode_all(first, /*level*/ 3)?;
let mut concatenated = sized.clone();
concatenated.extend(zstd::stream::encode_all(
second.as_slice(),
/*level*/ 3,
)?);
for (compressed, expected) in [
(sized, first.to_vec()),
(without_size, first.to_vec()),
(concatenated, [first, second].concat()),
] {
fs::write(&path, compressed)?;
let contains = |end| rollout_contains_prefix(&path, end, || false);
assert!(contains(first.len() as u64)?);
assert!(contains(expected.len() as u64)?);
assert!(!contains(expected.len() as u64 + 1)?);
let mut actual = Vec::new();
open_rollout_seekable_reader(&path, || false)?.read_to_end(&mut actual)?;
assert_eq!(actual, expected);
assert!(!path.with_extension("").exists());
}
Ok(())
}

View File

@@ -0,0 +1,364 @@
//! Store session names in an append-only index and serialize index rewrites.
//! Writers must share the filesystem lock namespace and use this locking protocol.
use std::collections::HashMap;
use std::collections::HashSet;
use std::fs::File;
use std::io::ErrorKind;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use std::time::Instant;
use std::time::SystemTime;
use crate::reverse_jsonl_scanner::ReverseJsonlScanner;
use crate::reverse_jsonl_scanner::ScanOutcome;
use codex_protocol::ThreadId;
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::SessionSource;
use serde::Deserialize;
use serde::Serialize;
const SESSION_INDEX_FILE: &str = "session_index.jsonl";
const SESSION_INDEX_LOCK_FILE: &str = "session_index.jsonl.lock";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SessionIndexEntry {
pub id: ThreadId,
pub thread_name: String,
pub updated_at: String,
}
/// Append a thread name update to the session index.
/// Name updates are append-only; the most recent entry wins when resolving names or ids.
pub async fn append_thread_name(
codex_home: &Path,
thread_id: ThreadId,
name: &str,
) -> std::io::Result<()> {
use time::OffsetDateTime;
use time::format_description::well_known::Rfc3339;
let updated_at = OffsetDateTime::now_utc()
.format(&Rfc3339)
.unwrap_or_else(|_| "unknown".to_string());
let entry = SessionIndexEntry {
id: thread_id,
thread_name: name.to_string(),
updated_at,
};
append_session_index_entry(codex_home, entry).await
}
/// Append a raw session index entry to `session_index.jsonl`.
/// Consumers scan from the end to find the newest match.
pub async fn append_session_index_entry(
codex_home: &Path,
entry: SessionIndexEntry,
) -> std::io::Result<()> {
let path = session_index_path(codex_home);
with_session_index_lock(codex_home, move || {
let mut file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)?;
let mut line = serde_json::to_string(&entry).map_err(std::io::Error::other)?;
line.push('\n');
file.write_all(line.as_bytes())?;
file.flush()?;
Ok(())
})
.await
}
/// Remove all recorded names for a thread from the session index.
pub async fn remove_thread_name_entries(
codex_home: &Path,
thread_id: ThreadId,
) -> std::io::Result<()> {
let path = session_index_path(codex_home);
if !path.try_exists()? {
return Ok(());
}
with_session_index_lock(codex_home, move || {
let contents = match std::fs::read_to_string(&path) {
Ok(contents) => contents,
Err(err) if err.kind() == ErrorKind::NotFound => return Ok(()),
Err(err) => return Err(err),
};
let mut removed = false;
let mut remaining = String::with_capacity(contents.len());
for line in contents.lines() {
let should_remove = serde_json::from_str::<SessionIndexEntry>(line.trim())
.is_ok_and(|entry| entry.id == thread_id);
if should_remove {
removed = true;
} else {
remaining.push_str(line);
remaining.push('\n');
}
}
if !removed {
return Ok(());
}
let mut temporary = tempfile::Builder::new()
.prefix("session-index-")
.tempfile_in(path.parent().unwrap_or(Path::new(".")))?;
temporary
.as_file()
.set_permissions(std::fs::metadata(&path)?.permissions())?;
temporary.write_all(remaining.as_bytes())?;
temporary.persist(&path).map_err(|error| error.error)?;
Ok(())
})
.await
}
/// Serialize index mutations within and across processes, including cancelled updates.
async fn with_session_index_lock(
codex_home: &Path,
update: impl FnOnce() -> std::io::Result<()> + Send + 'static,
) -> std::io::Result<()> {
let lock_path = codex_home.join(SESSION_INDEX_LOCK_FILE);
tokio::task::spawn_blocking(move || {
// Keep this file in place. If we replace it, another process can lock a new
// file while this update still holds the old file's lock.
let file_lock = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(lock_path)?;
let deadline = Instant::now() + Duration::from_secs(/*secs*/ 30);
loop {
match file_lock.try_lock() {
Ok(()) => break,
Err(std::fs::TryLockError::WouldBlock) if Instant::now() < deadline => {
std::thread::sleep(Duration::from_millis(/*millis*/ 50));
}
Err(std::fs::TryLockError::WouldBlock) => {
return Err(std::io::Error::new(
ErrorKind::TimedOut,
"timed out waiting for the session index lock; another Codex process may be suspended on this or another host",
));
}
Err(std::fs::TryLockError::Error(err)) => return Err(err),
}
}
update()
})
.await
.map_err(std::io::Error::other)?
}
/// Find the latest thread name for a thread id, if any.
pub async fn find_thread_name_by_id(
codex_home: &Path,
thread_id: &ThreadId,
) -> std::io::Result<Option<String>> {
let path = session_index_path(codex_home);
if !path.exists() {
return Ok(None);
}
let id = *thread_id;
let entry = tokio::task::spawn_blocking(move || scan_index_from_end_by_id(&path, &id))
.await
.map_err(std::io::Error::other)??;
Ok(entry.map(|entry| entry.thread_name))
}
/// Find the latest thread names for a batch of thread ids.
pub async fn find_thread_names_by_ids(
codex_home: &Path,
thread_ids: &HashSet<ThreadId>,
) -> std::io::Result<HashMap<ThreadId, String>> {
Ok(find_thread_name_entries_by_ids(codex_home, thread_ids)
.await?
.into_iter()
.map(|(id, entry)| (id, entry.thread_name.trim().to_owned()))
.collect())
}
/// Returns each thread's latest indexed name and when it was written.
pub async fn find_thread_name_entries_by_ids(
codex_home: &Path,
thread_ids: &HashSet<ThreadId>,
) -> std::io::Result<HashMap<ThreadId, SessionIndexEntry>> {
if thread_ids.is_empty() {
return Ok(HashMap::new());
}
let path = session_index_path(codex_home);
let mut remaining_ids = thread_ids.clone();
tokio::task::spawn_blocking(move || {
if !path.exists() {
return Ok(HashMap::new());
}
let mut scanner = ReverseJsonlScanner::new(File::open(path)?)?;
let mut names = HashMap::with_capacity(remaining_ids.len());
while let Some(outcome) = scanner.scan_next::<SessionIndexEntry>()? {
let ScanOutcome::Parsed(entry) = outcome else {
continue;
};
let name = entry.thread_name.trim();
// The first nonempty name seen for an id is its latest usable name.
if !name.is_empty() && remaining_ids.remove(&entry.id) {
names.insert(entry.id, entry);
if remaining_ids.is_empty() {
break;
}
}
}
Ok(names)
})
.await
.map_err(std::io::Error::other)?
}
/// Locate the readable rollout with the newest modification time for a recorded thread name.
pub async fn find_thread_meta_by_name_str(
codex_home: &Path,
name: &str,
state_db_ctx: Option<&codex_state::StateRuntime>,
) -> std::io::Result<Option<(PathBuf, SessionMetaLine)>> {
Ok(find_thread_meta_candidates_by_name_str(
codex_home,
name,
state_db_ctx,
/*allowed_sources*/ &[],
/*allowed_model_providers*/ &[],
)
.await?
.into_iter()
.next())
}
/// Locate readable rollouts for a recorded thread name, newest modification time first.
///
/// Empty filter slices disable their respective filters. Provider filtering only rejects explicit
/// mismatches because older rollouts omitted provider metadata. Filtering happens before ranking,
/// so an ineligible newer duplicate cannot hide an older usable session.
pub async fn find_thread_meta_candidates_by_name_str(
codex_home: &Path,
name: &str,
state_db_ctx: Option<&codex_state::StateRuntime>,
allowed_sources: &[SessionSource],
allowed_model_providers: &[String],
) -> std::io::Result<Vec<(PathBuf, SessionMetaLine)>> {
if name.trim().is_empty() {
return Ok(Vec::new());
}
let path = session_index_path(codex_home);
if !path.exists() {
return Ok(Vec::new());
}
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
let name = name.to_string();
// Stream matching ids newest-first instead of stopping at the first name hit: the newest entry
// may point at a thread whose rollout was never materialized.
let scan =
tokio::task::spawn_blocking(move || stream_thread_ids_from_end_by_name(&path, &name, tx));
let mut candidates = Vec::new();
while let Some(thread_id) = rx.recv().await {
// Keep walking until a matching id resolves to a loadable rollout so an unsaved or partial
// rename cannot shadow an older persisted session with the same name.
if let Some(path) = super::list::find_thread_path_by_id_str(
codex_home,
&thread_id.to_string(),
state_db_ctx,
)
.await?
&& let Ok(session_meta) = super::list::read_session_meta_line(&path).await
&& !session_meta.meta.attached_thread
&& (allowed_sources.is_empty() || allowed_sources.contains(&session_meta.meta.source))
&& session_meta
.meta
.model_provider
.as_ref()
.is_none_or(|provider| {
allowed_model_providers.is_empty() || allowed_model_providers.contains(provider)
})
{
let modified = tokio::fs::metadata(&path)
.await
.and_then(|metadata| metadata.modified())
.unwrap_or(SystemTime::UNIX_EPOCH);
candidates.push((modified, path, session_meta));
}
}
scan.await.map_err(std::io::Error::other)??;
candidates.sort_by(|(left, _, _), (right, _, _)| right.cmp(left));
Ok(candidates
.into_iter()
.map(|(_, path, session_meta)| (path, session_meta))
.collect())
}
fn session_index_path(codex_home: &Path) -> PathBuf {
codex_home.join(SESSION_INDEX_FILE)
}
fn scan_index_from_end_by_id(
path: &Path,
thread_id: &ThreadId,
) -> std::io::Result<Option<SessionIndexEntry>> {
scan_index_from_end(path, |entry| entry.id == *thread_id)
}
fn stream_thread_ids_from_end_by_name(
path: &Path,
name: &str,
tx: tokio::sync::mpsc::Sender<ThreadId>,
) -> std::io::Result<()> {
let mut seen = HashSet::new();
scan_index_from_end_for_each(path, |entry| {
// The first row seen for an id is its latest name. Ignore older rows for that id so a
// historical name cannot be treated as the current one after the thread is renamed.
if seen.insert(entry.id) && entry.thread_name == name && tx.blocking_send(entry.id).is_err()
{
return Ok(Some(entry.clone()));
}
Ok(None)
})?;
Ok(())
}
fn scan_index_from_end<F>(
path: &Path,
mut predicate: F,
) -> std::io::Result<Option<SessionIndexEntry>>
where
F: FnMut(&SessionIndexEntry) -> bool,
{
scan_index_from_end_for_each(path, |entry| {
if predicate(entry) {
return Ok(Some(entry.clone()));
}
Ok(None)
})
}
fn scan_index_from_end_for_each<F>(
path: &Path,
mut visit_entry: F,
) -> std::io::Result<Option<SessionIndexEntry>>
where
F: FnMut(&SessionIndexEntry) -> std::io::Result<Option<SessionIndexEntry>>,
{
let mut scanner = ReverseJsonlScanner::new(File::open(path)?)?;
while let Some(outcome) = scanner.scan_next::<SessionIndexEntry>()? {
let ScanOutcome::Parsed(entry) = outcome else {
continue;
};
if let Some(entry) = visit_entry(&entry)? {
return Ok(Some(entry));
}
}
Ok(None)
}
#[cfg(test)]
#[path = "session_index_tests.rs"]
mod tests;

View File

@@ -0,0 +1,655 @@
#![allow(warnings, clippy::all)]
use super::*;
use crate::RolloutItem;
use crate::RolloutLine;
use codex_protocol::protocol::SessionMeta;
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::SessionSource;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::collections::HashSet;
use tempfile::TempDir;
fn write_index(path: &Path, lines: &[SessionIndexEntry]) -> std::io::Result<()> {
let mut out = String::new();
for entry in lines {
out.push_str(&serde_json::to_string(entry).unwrap());
out.push('\n');
}
std::fs::write(path, out)
}
fn write_rollout_with_metadata(path: &Path, thread_id: ThreadId) -> std::io::Result<()> {
write_rollout_with_source_and_provider(path, thread_id, SessionSource::Cli, "test-provider")
}
fn write_rollout_with_source_and_provider(
path: &Path,
thread_id: ThreadId,
source: SessionSource,
model_provider: &str,
) -> std::io::Result<()> {
let timestamp = "2024-01-01T00-00-00Z".to_string();
let line = RolloutLine {
timestamp: timestamp.clone(),
ordinal: None,
item: RolloutItem::SessionMeta(Box::new(SessionMetaLine {
meta: SessionMeta {
account_scoped: false,
attached_thread: false,
creator_user_id: None,
creator_account_id: None,
session_id: thread_id.into(),
id: thread_id,
forked_from_id: None,
forked_from_ordinal_exclusive: None,
parent_thread_id: None,
timestamp,
cwd: ".".into(),
runtime_workspace_roots: None,
originator: "test_originator".into(),
cli_version: "test_version".into(),
source,
thread_source: None,
agent_path: None,
agent_nickname: None,
agent_role: None,
model_provider: Some(model_provider.to_string()),
base_instructions: None,
dynamic_tools: None,
selected_capability_roots: Vec::new(),
memory_mode: None,
history_mode: Default::default(),
history_base: None,
subagent_history_start_ordinal: None,
multi_agent_version: None,
context_window: None,
},
git: None,
})),
};
let body = serde_json::to_string(&line).map_err(std::io::Error::other)?;
std::fs::write(path, format!("{body}\n"))
}
#[test]
fn find_thread_id_by_name_prefers_latest_entry() -> std::io::Result<()> {
let temp = TempDir::new()?;
let path = session_index_path(temp.path());
let id1 = ThreadId::new();
let id2 = ThreadId::new();
let lines = vec![
SessionIndexEntry {
id: id1,
thread_name: "same".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
},
SessionIndexEntry {
id: id2,
thread_name: "same".to_string(),
updated_at: "2024-01-02T00:00:00Z".to_string(),
},
];
write_index(&path, &lines)?;
let found = scan_index_from_end(&path, |entry| entry.thread_name == "same")?;
assert_eq!(found.map(|entry| entry.id), Some(id2));
Ok(())
}
#[tokio::test]
async fn find_thread_meta_by_name_str_skips_newest_entry_without_rollout() -> std::io::Result<()> {
// A newer unsaved name entry should not shadow an older persisted rollout with the same name.
let temp = TempDir::new()?;
let path = session_index_path(temp.path());
let saved_id = ThreadId::new();
let unsaved_id = ThreadId::new();
let saved_rollout_path = temp
.path()
.join("sessions/2024/01/01")
.join(format!("rollout-2024-01-01T00-00-00-{saved_id}.jsonl"));
std::fs::create_dir_all(saved_rollout_path.parent().expect("rollout parent"))?;
write_rollout_with_metadata(&saved_rollout_path, saved_id)?;
let lines = vec![
SessionIndexEntry {
id: saved_id,
thread_name: "same".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
},
SessionIndexEntry {
id: unsaved_id,
thread_name: "same".to_string(),
updated_at: "2024-01-02T00:00:00Z".to_string(),
},
];
write_index(&path, &lines)?;
let found = find_thread_meta_by_name_str(temp.path(), "same", /*state_db_ctx*/ None).await?;
assert_eq!(
found.map(|(path, session_meta)| (path, session_meta.meta.id)),
Some((saved_rollout_path, saved_id))
);
Ok(())
}
#[tokio::test]
async fn find_thread_meta_by_name_str_skips_partial_rollout() -> std::io::Result<()> {
let temp = TempDir::new()?;
let path = session_index_path(temp.path());
let saved_id = ThreadId::new();
let partial_id = ThreadId::new();
let rollout_dir = temp.path().join("sessions/2024/01/01");
let saved_rollout_path =
rollout_dir.join(format!("rollout-2024-01-01T00-00-00-{saved_id}.jsonl"));
let partial_rollout_path =
rollout_dir.join(format!("rollout-2024-01-01T00-00-01-{partial_id}.jsonl"));
std::fs::create_dir_all(&rollout_dir)?;
write_rollout_with_metadata(&saved_rollout_path, saved_id)?;
std::fs::write(&partial_rollout_path, "")?;
let lines = vec![
SessionIndexEntry {
id: saved_id,
thread_name: "same".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
},
SessionIndexEntry {
id: partial_id,
thread_name: "same".to_string(),
updated_at: "2024-01-02T00:00:00Z".to_string(),
},
];
write_index(&path, &lines)?;
let found = find_thread_meta_by_name_str(temp.path(), "same", /*state_db_ctx*/ None).await?;
assert_eq!(found.map(|(path, _)| path), Some(saved_rollout_path));
Ok(())
}
#[tokio::test]
async fn find_thread_meta_by_name_str_ignores_historical_name_after_rename() -> std::io::Result<()>
{
let temp = TempDir::new()?;
let path = session_index_path(temp.path());
let renamed_id = ThreadId::new();
let current_id = ThreadId::new();
let current_rollout_path = temp
.path()
.join("sessions/2024/01/01")
.join(format!("rollout-2024-01-01T00-00-00-{current_id}.jsonl"));
std::fs::create_dir_all(current_rollout_path.parent().expect("rollout parent"))?;
write_rollout_with_metadata(&current_rollout_path, current_id)?;
let lines = vec![
SessionIndexEntry {
id: renamed_id,
thread_name: "same".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
},
SessionIndexEntry {
id: current_id,
thread_name: "same".to_string(),
updated_at: "2024-01-02T00:00:00Z".to_string(),
},
SessionIndexEntry {
id: renamed_id,
thread_name: "different".to_string(),
updated_at: "2024-01-03T00:00:00Z".to_string(),
},
];
write_index(&path, &lines)?;
let found = find_thread_meta_by_name_str(temp.path(), "same", /*state_db_ctx*/ None).await?;
assert_eq!(found.map(|(path, _)| path), Some(current_rollout_path));
Ok(())
}
#[tokio::test]
async fn find_thread_meta_candidates_filter_metadata_before_ranking() -> std::io::Result<()> {
let temp = TempDir::new()?;
let index_path = session_index_path(temp.path());
let allowed_id = ThreadId::new();
let other_id = ThreadId::new();
let noninteractive_id = ThreadId::new();
let rollout_dir = temp.path().join("sessions/2024/01/01");
let allowed_path = rollout_dir.join(format!("rollout-2024-01-01T00-00-00-{allowed_id}.jsonl"));
let other_path = rollout_dir.join(format!("rollout-2024-01-01T00-00-01-{other_id}.jsonl"));
let noninteractive_path = rollout_dir.join(format!(
"rollout-2024-01-01T00-00-02-{noninteractive_id}.jsonl"
));
std::fs::create_dir_all(&rollout_dir)?;
write_rollout_with_metadata(&allowed_path, allowed_id)?;
write_rollout_with_source_and_provider(
&other_path,
other_id,
SessionSource::Cli,
"other-provider",
)?;
write_rollout_with_source_and_provider(
&noninteractive_path,
noninteractive_id,
SessionSource::Exec,
"test-provider",
)?;
write_index(
&index_path,
&[
SessionIndexEntry {
id: allowed_id,
thread_name: "same".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
},
SessionIndexEntry {
id: other_id,
thread_name: "same".to_string(),
updated_at: "2024-01-02T00:00:00Z".to_string(),
},
SessionIndexEntry {
id: noninteractive_id,
thread_name: "same".to_string(),
updated_at: "2024-01-03T00:00:00Z".to_string(),
},
],
)?;
std::fs::OpenOptions::new()
.append(true)
.open(&allowed_path)?
.set_times(std::fs::FileTimes::new().set_modified(std::time::UNIX_EPOCH))?;
let allowed_model_providers = vec!["test-provider".to_string()];
let found = find_thread_meta_candidates_by_name_str(
temp.path(),
"same",
/*state_db_ctx*/ None,
&[SessionSource::Cli],
&allowed_model_providers,
)
.await?;
assert_eq!(
found
.into_iter()
.map(|(path, session_meta)| (path, session_meta.meta.id))
.collect::<Vec<_>>(),
vec![(allowed_path, allowed_id)],
);
Ok(())
}
#[test]
fn find_thread_name_by_id_prefers_latest_entry() -> std::io::Result<()> {
let temp = TempDir::new()?;
let path = session_index_path(temp.path());
let id = ThreadId::new();
let lines = vec![
SessionIndexEntry {
id,
thread_name: "first".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
},
SessionIndexEntry {
id,
thread_name: "second".to_string(),
updated_at: "2024-01-02T00:00:00Z".to_string(),
},
];
write_index(&path, &lines)?;
let found = scan_index_from_end_by_id(&path, &id)?;
assert_eq!(
found.map(|entry| entry.thread_name),
Some("second".to_string())
);
Ok(())
}
#[test]
fn scan_index_returns_none_when_entry_missing() -> std::io::Result<()> {
let temp = TempDir::new()?;
let path = session_index_path(temp.path());
let id = ThreadId::new();
let lines = vec![SessionIndexEntry {
id,
thread_name: "present".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
}];
write_index(&path, &lines)?;
let missing_name = scan_index_from_end(&path, |entry| entry.thread_name == "missing")?;
assert_eq!(missing_name, None);
let missing_id = scan_index_from_end_by_id(&path, &ThreadId::new())?;
assert_eq!(missing_id, None);
Ok(())
}
#[tokio::test]
async fn reverse_lookup_accepts_valid_eof_json_and_skips_invalid() -> std::io::Result<()> {
let temp = TempDir::new()?;
let path = session_index_path(temp.path());
let expected = SessionIndexEntry {
id: ThreadId::new(),
thread_name: "expected".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
};
let unterminated = SessionIndexEntry {
id: ThreadId::new(),
thread_name: "unterminated".to_string(),
updated_at: "2024-01-02T00:00:00Z".to_string(),
};
std::fs::write(
&path,
format!(
"{}\nnot-json\n{}",
serde_json::to_string(&expected)?,
serde_json::to_string(&unterminated)?
),
)?;
assert_eq!(
find_thread_name_by_id(temp.path(), &unterminated.id).await?,
Some("unterminated".to_string())
);
assert_eq!(
find_thread_name_by_id(temp.path(), &expected.id).await?,
Some("expected".to_string())
);
Ok(())
}
#[tokio::test]
async fn append_and_remove_thread_names_preserves_other_entries() -> std::io::Result<()> {
let temp = TempDir::new()?;
let removed_id = ThreadId::new();
let retained = SessionIndexEntry {
id: ThreadId::new(),
thread_name: "retained".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
};
for entry in [
SessionIndexEntry {
id: removed_id,
thread_name: "original".to_string(),
..retained.clone()
},
retained.clone(),
SessionIndexEntry {
id: removed_id,
thread_name: "renamed".to_string(),
..retained.clone()
},
] {
append_session_index_entry(temp.path(), entry).await?;
}
assert_eq!(
find_thread_name_by_id(temp.path(), &removed_id).await?,
Some("renamed".to_string()),
);
remove_thread_name_entries(temp.path(), removed_id).await?;
assert_eq!(
std::fs::read_to_string(session_index_path(temp.path()))?,
format!("{}\n", serde_json::to_string(&retained)?),
);
Ok(())
}
#[tokio::test]
async fn find_thread_names_by_ids_prefers_latest_entry() -> std::io::Result<()> {
let temp = TempDir::new()?;
let path = session_index_path(temp.path());
let id1 = ThreadId::new();
let id2 = ThreadId::new();
let lines = vec![
SessionIndexEntry {
id: id1,
thread_name: "first".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
},
SessionIndexEntry {
id: id2,
thread_name: "other".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
},
SessionIndexEntry {
id: id1,
thread_name: "latest".to_string(),
updated_at: "2024-01-02T00:00:00Z".to_string(),
},
];
write_index(&path, &lines)?;
let mut ids = HashSet::new();
ids.insert(id1);
ids.insert(id2);
let mut expected = HashMap::new();
expected.insert(id1, "latest".to_string());
expected.insert(id2, "other".to_string());
let found = find_thread_names_by_ids(temp.path(), &ids).await?;
assert_eq!(found, expected);
Ok(())
}
#[tokio::test]
async fn find_thread_names_by_ids_skips_unusable_names_and_reads_across_chunks()
-> std::io::Result<()> {
let temp = TempDir::new()?;
let path = session_index_path(temp.path());
let renamed = ThreadId::new();
let older = ThreadId::new();
let missing = ThreadId::new();
let mut contents = String::new();
for (id, thread_name) in [
(renamed, "original".to_string()),
(older, " older name ".to_string()),
(ThreadId::new(), "unrelated".repeat(/*n*/ 10_000)),
(renamed, " 最新 café ".to_string()),
(renamed, " \t ".to_string()),
] {
let entry = SessionIndexEntry {
id,
thread_name,
updated_at: "2024-01-01T00:00:00Z".to_string(),
};
contents.push_str(&serde_json::to_string(&entry)?);
contents.push_str("\n\nnot json\n");
}
// A partial final write must not hide the latest complete name.
contents.push_str("{\"id\":");
std::fs::write(path, contents)?;
for (ids, expected) in [
(
HashSet::from([renamed]),
HashMap::from([(renamed, "最新 café".to_string())]),
),
(
HashSet::from([renamed, older]),
HashMap::from([
(renamed, "最新 café".to_string()),
(older, "older name".to_string()),
]),
),
(
HashSet::from([renamed, older, missing]),
HashMap::from([
(renamed, "最新 café".to_string()),
(older, "older name".to_string()),
]),
),
] {
assert_eq!(find_thread_names_by_ids(temp.path(), &ids).await?, expected);
}
Ok(())
}
#[tokio::test]
async fn removal_preserves_other_names_and_malformed_lines() -> std::io::Result<()> {
let absent_home = TempDir::new()?;
remove_thread_name_entries(&absent_home.path().join("missing"), ThreadId::new()).await?;
let temp = TempDir::new()?;
let removed_id = ThreadId::new();
let kept_id = ThreadId::new();
append_thread_name(temp.path(), removed_id, "old").await?;
append_thread_name(temp.path(), removed_id, "new").await?;
append_thread_name(temp.path(), kept_id, "kept").await?;
let path = session_index_path(temp.path());
std::fs::OpenOptions::new()
.append(true)
.open(&path)?
.write_all(b"malformed\n")?;
remove_thread_name_entries(temp.path(), removed_id).await?;
assert_eq!(
find_thread_names_by_ids(temp.path(), &HashSet::from([removed_id, kept_id])).await?,
HashMap::from([(kept_id, "kept".to_string())]),
);
assert!(
std::fs::read_to_string(path)?
.lines()
.any(|line| line == "malformed")
);
Ok(())
}
#[tokio::test]
async fn index_lock_survives_cancellation_and_times_out_without_writing() -> std::io::Result<()> {
let home = TempDir::new()?;
let update_home = home.path().to_path_buf();
let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
let (resume_tx, resume_rx) = std::sync::mpsc::channel();
let update = tokio::spawn(async move {
with_session_index_lock(&update_home, move || {
let _ = reached_tx.send(());
// Dropping the sender on a test failure also releases the blocking worker.
let _ = resume_rx.recv();
Ok(())
})
.await
});
reached_rx.await.unwrap();
update.abort();
assert!(update.await.unwrap_err().is_cancelled());
let independent_file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(home.path().join(SESSION_INDEX_LOCK_FILE))?;
let file_lock_is_held = match independent_file.try_lock() {
Ok(()) => {
independent_file.unlock()?;
false
}
Err(std::fs::TryLockError::WouldBlock) => true,
Err(std::fs::TryLockError::Error(error)) => return Err(error),
};
resume_tx.send(()).unwrap();
with_session_index_lock(home.path(), || Ok(())).await?;
assert!(
file_lock_is_held,
"cancellation released a running index mutation's lock"
);
independent_file
.try_lock()
.expect("the completed mutation must release its file lock");
// A busy file lock must not allow an append to run without ownership.
let error = append_thread_name(home.path(), ThreadId::new(), "blocked")
.await
.unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::TimedOut);
assert!(!session_index_path(home.path()).exists());
drop(independent_file);
append_thread_name(home.path(), ThreadId::new(), "after contention").await?;
assert!(session_index_path(home.path()).is_file());
Ok(())
}
#[test]
fn cancelled_queued_index_update_preserves_the_next_write() -> std::io::Result<()> {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.max_blocking_threads(1)
.build()?;
runtime.block_on(async {
let home = TempDir::new()?;
let path = home.path().join("thread-name");
let (reached_tx, reached_rx) = tokio::sync::oneshot::channel();
let (resume_tx, resume_rx) = std::sync::mpsc::channel::<()>();
let blocker = tokio::task::spawn_blocking(move || {
let _ = reached_tx.send(());
// Dropping the sender on a failure also lets runtime teardown finish.
let _ = resume_rx.recv();
});
reached_rx.await.unwrap();
let queued_path = path.clone();
let mut update = Box::pin(with_session_index_lock(home.path(), move || {
std::fs::write(queued_path, "obsolete")
}));
let state = std::future::poll_fn(|cx| {
std::task::Poll::Ready(std::future::Future::poll(update.as_mut(), cx))
})
.await;
assert!(
state.is_pending(),
"the blocking pool should hold the update queued"
);
drop(update);
drop(resume_tx);
blocker.await.unwrap();
let next_path = path.clone();
with_session_index_lock(home.path(), move || std::fs::write(next_path, "latest")).await?;
assert_eq!(std::fs::read_to_string(path)?, "latest".to_string());
Ok(())
})
}
#[test]
fn scan_index_finds_latest_match_among_mixed_entries() -> std::io::Result<()> {
let temp = TempDir::new()?;
let path = session_index_path(temp.path());
let id_target = ThreadId::new();
let id_other = ThreadId::new();
let expected = SessionIndexEntry {
id: id_target,
thread_name: "target".to_string(),
updated_at: "2024-01-03T00:00:00Z".to_string(),
};
let expected_other = SessionIndexEntry {
id: id_other,
thread_name: "target".to_string(),
updated_at: "2024-01-02T00:00:00Z".to_string(),
};
// Resolution is based on append order (scan from end), not updated_at.
let lines = vec![
SessionIndexEntry {
id: id_target,
thread_name: "target".to_string(),
updated_at: "2024-01-01T00:00:00Z".to_string(),
},
expected_other.clone(),
expected.clone(),
SessionIndexEntry {
id: ThreadId::new(),
thread_name: "another".to_string(),
updated_at: "2024-01-04T00:00:00Z".to_string(),
},
];
write_index(&path, &lines)?;
let found_by_name = scan_index_from_end(&path, |entry| entry.thread_name == "target")?;
assert_eq!(found_by_name, Some(expected.clone()));
let found_by_id = scan_index_from_end_by_id(&path, &id_target)?;
assert_eq!(found_by_id, Some(expected));
let found_other_by_id = scan_index_from_end_by_id(&path, &id_other)?;
assert_eq!(found_other_by_id, Some(expected_other));
Ok(())
}

View File

@@ -0,0 +1,73 @@
use std::sync::Arc;
use std::time::Duration;
use codex_otel::ORIGINATOR_TAG;
use codex_otel::bounded_originator_tag_value;
use codex_state::DbTelemetry;
use codex_state::DbTelemetryHandle;
use codex_state::LOG_WRITE_BYTES_METRIC;
use codex_state::LOG_WRITE_MAX_ENTRY_BYTES_METRIC;
const LOG_WRITE_BYTES_BOUNDARIES: &[f64] = &[
128.0,
256.0,
512.0,
1_024.0,
2_048.0,
4_096.0,
8_192.0,
16_384.0,
32_768.0,
65_536.0,
131_072.0,
262_144.0,
524_288.0,
1_048_576.0,
2_097_152.0,
4_194_304.0,
8_388_608.0,
16_777_216.0,
];
struct OtelDbTelemetry {
metrics: codex_otel::MetricsClient,
originator: &'static str,
}
impl DbTelemetry for OtelDbTelemetry {
fn counter(&self, name: &str, inc: i64, tags: &[(&str, &str)]) {
let tags = with_originator(tags, self.originator);
let _ = self.metrics.counter(name, inc, &tags);
}
fn histogram(&self, name: &str, value: i64, tags: &[(&str, &str)]) {
let tags = with_originator(tags, self.originator);
let _ = match name {
LOG_WRITE_BYTES_METRIC | LOG_WRITE_MAX_ENTRY_BYTES_METRIC => self
.metrics
.histogram_with_boundaries(name, value, LOG_WRITE_BYTES_BOUNDARIES, &tags),
_ => self.metrics.histogram(name, value, &tags),
};
}
fn record_duration(&self, name: &str, duration: Duration, tags: &[(&str, &str)]) {
let tags = with_originator(tags, self.originator);
let _ = self.metrics.record_duration(name, duration, &tags);
}
}
pub(crate) fn recorder(metrics: codex_otel::MetricsClient, originator: &str) -> DbTelemetryHandle {
Arc::new(OtelDbTelemetry {
metrics,
originator: bounded_originator_tag_value(originator),
})
}
fn with_originator<'a>(
tags: &[(&'a str, &'a str)],
originator: &'static str,
) -> Vec<(&'a str, &'a str)> {
let mut tags = tags.to_vec();
tags.push((ORIGINATOR_TAG, originator));
tags
}

View File

@@ -0,0 +1,744 @@
use crate::RolloutItem;
use crate::config::RolloutConfig;
use crate::config::RolloutConfigView;
use crate::list::Cursor;
use crate::list::SortDirection;
use crate::list::ThreadSortKey;
use crate::metadata;
use crate::sqlite_metrics;
use anyhow::Context;
use chrono::DateTime;
use chrono::Utc;
use codex_protocol::ThreadId;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::ThreadHistoryMode;
pub use codex_state::LogEntry;
use codex_state::SqliteConfig;
use codex_state::ThreadMetadataBuilder;
use codex_utils_path::normalize_for_path_comparison;
use serde_json::Value;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use tracing::info;
use tracing::warn;
/// Core-facing handle to the SQLite-backed state runtime.
pub type StateDbHandle = Arc<codex_state::StateRuntime>;
#[cfg(not(test))]
const STARTUP_BACKFILL_POLL_INTERVAL: Duration = Duration::from_secs(1);
#[cfg(test)]
const STARTUP_BACKFILL_POLL_INTERVAL: Duration = Duration::from_millis(10);
#[cfg(not(test))]
const STARTUP_BACKFILL_WAIT_TIMEOUT: Duration = Duration::from_secs(30);
#[cfg(test)]
const STARTUP_BACKFILL_WAIT_TIMEOUT: Duration = Duration::from_secs(2);
/// Initialize the state runtime for thread state persistence.
///
/// This is the process entry point for local state: it opens the SQLite-backed
/// runtime, applies rollout metadata backfills as needed, and returns the
/// initialized handle.
pub async fn init(config: &impl RolloutConfigView) -> Option<StateDbHandle> {
let config = RolloutConfig::from_view(config);
match try_init_with_roots(config.codex_home, config.sqlite, config.model_provider_id).await {
Ok(runtime) => Some(runtime),
Err(err) => {
emit_startup_warning(&format!("failed to initialize state runtime: {err:#}"));
None
}
}
}
/// Initialize the state runtime and return any initialization error to the caller.
///
/// Prefer [`init`] unless the caller needs to surface the exact failure after
/// tracing or UI setup has completed.
pub async fn try_init(config: &impl RolloutConfigView) -> anyhow::Result<StateDbHandle> {
let config = RolloutConfig::from_view(config);
try_init_with_roots(config.codex_home, config.sqlite, config.model_provider_id).await
}
async fn try_init_with_roots(
codex_home: PathBuf,
sqlite: SqliteConfig,
default_model_provider_id: String,
) -> anyhow::Result<StateDbHandle> {
try_init_with_roots_inner(
codex_home,
sqlite,
default_model_provider_id,
/*backfill_lease_seconds*/ None,
)
.await
}
#[cfg(test)]
async fn try_init_with_roots_and_backfill_lease(
codex_home: PathBuf,
sqlite: SqliteConfig,
default_model_provider_id: String,
backfill_lease_seconds: i64,
) -> anyhow::Result<StateDbHandle> {
try_init_with_roots_inner(
codex_home,
sqlite,
default_model_provider_id,
Some(backfill_lease_seconds),
)
.await
}
async fn try_init_with_roots_inner(
codex_home: PathBuf,
sqlite: SqliteConfig,
default_model_provider_id: String,
backfill_lease_seconds: Option<i64>,
) -> anyhow::Result<StateDbHandle> {
let runtime =
codex_state::StateRuntime::init(sqlite.clone(), default_model_provider_id.clone())
.await
.with_context(|| {
format!(
"failed to initialize state runtime at {}",
sqlite.home().display()
)
})?;
let backfill_gate_started = Instant::now();
let backfill_gate_result = wait_for_backfill_gate(
runtime.as_ref(),
codex_home.as_path(),
default_model_provider_id.as_str(),
backfill_lease_seconds,
)
.await;
codex_state::record_backfill_gate(
/*telemetry*/ None,
backfill_gate_started.elapsed(),
&backfill_gate_result,
);
if let Err(err) = backfill_gate_result {
runtime.close().await;
return Err(err);
}
Ok(runtime)
}
async fn wait_for_backfill_gate(
runtime: &codex_state::StateRuntime,
codex_home: &Path,
default_model_provider_id: &str,
backfill_lease_seconds: Option<i64>,
) -> anyhow::Result<()> {
let wait_started = Instant::now();
let mut reported_wait = false;
loop {
let backfill_state = runtime.get_backfill_state().await.map_err(|err| {
anyhow::anyhow!(
"failed to read backfill state at {}: {err}",
codex_home.display()
)
})?;
if backfill_state.status == codex_state::BackfillStatus::Complete {
return Ok(());
}
if let Some(backfill_lease_seconds) = backfill_lease_seconds {
metadata::backfill_sessions_with_lease(
runtime,
codex_home,
default_model_provider_id,
backfill_lease_seconds,
)
.await;
} else {
metadata::backfill_sessions(runtime, codex_home, default_model_provider_id).await;
}
let backfill_state = runtime.get_backfill_state().await.map_err(|err| {
anyhow::anyhow!(
"failed to read backfill state at {} after startup backfill: {err}",
codex_home.display()
)
})?;
if backfill_state.status == codex_state::BackfillStatus::Complete {
return Ok(());
}
if wait_started.elapsed() >= STARTUP_BACKFILL_WAIT_TIMEOUT {
return Err(anyhow::anyhow!(
"timed out waiting for state db backfill at {} after {:?} (status: {})",
codex_home.display(),
STARTUP_BACKFILL_WAIT_TIMEOUT,
backfill_state.status.as_str()
));
}
let message = format!(
"state db backfill is {} at {}; waiting up to {:?} before retrying startup initialization",
backfill_state.status.as_str(),
codex_home.display(),
STARTUP_BACKFILL_WAIT_TIMEOUT,
);
if reported_wait {
info!("{message}");
} else {
emit_startup_warning(&message);
reported_wait = true;
}
tokio::time::sleep(STARTUP_BACKFILL_POLL_INTERVAL).await;
}
}
fn emit_startup_warning(message: &str) {
warn!("{message}");
if !tracing::dispatcher::has_been_set() {
#[allow(clippy::print_stderr)]
{
eprintln!("{message}");
}
}
}
/// Open the DB if it exists and its startup backfill has already completed.
///
/// Unlike [`init`], this helper does not run rollout backfill. It is for
/// optional local reads from non-owning contexts such as remote app-server mode.
pub async fn get_state_db(config: &impl RolloutConfigView) -> Option<StateDbHandle> {
let state_path = config.sqlite_config().state_db_path();
if !tokio::fs::try_exists(&state_path).await.unwrap_or(false) {
codex_state::record_fallback(
"get_state_db",
"db_unavailable",
/*telemetry_override*/ None,
);
return None;
}
let runtime = match codex_state::StateRuntime::init(
config.sqlite_config().clone(),
config.model_provider_id().to_string(),
)
.await
{
Ok(runtime) => runtime,
Err(_) => {
codex_state::record_fallback(
"get_state_db",
"db_error",
/*telemetry_override*/ None,
);
return None;
}
};
require_backfill_complete(runtime, config.sqlite_config().home()).await
}
/// Build a SQLite telemetry recorder backed by an OTEL metrics client.
pub fn sqlite_telemetry_recorder(
metrics: codex_otel::MetricsClient,
originator: &str,
) -> codex_state::DbTelemetryHandle {
sqlite_metrics::recorder(metrics, originator)
}
async fn require_backfill_complete(
runtime: StateDbHandle,
codex_home: &Path,
) -> Option<StateDbHandle> {
match runtime.get_backfill_state().await {
Ok(state) if state.status == codex_state::BackfillStatus::Complete => Some(runtime),
Ok(state) => {
warn!(
"state db backfill not complete at {} (status: {})",
codex_home.display(),
state.status.as_str()
);
codex_state::record_fallback(
"get_state_db",
"backfill_incomplete",
/*telemetry_override*/ None,
);
None
}
Err(err) => {
warn!(
"failed to read backfill state at {}: {err}",
codex_home.display()
);
codex_state::record_fallback(
"get_state_db",
"db_error",
/*telemetry_override*/ None,
);
None
}
}
}
fn cursor_to_anchor(cursor: Option<&Cursor>) -> Option<codex_state::Anchor> {
let cursor = cursor?;
let millis = cursor.timestamp().unix_timestamp_nanos() / 1_000_000;
let millis = i64::try_from(millis).ok()?;
let ts = chrono::DateTime::<Utc>::from_timestamp_millis(millis)?;
Some(codex_state::Anchor {
ts,
id: cursor.thread_id(),
})
}
pub fn normalize_cwd_for_state_db(cwd: &Path) -> PathBuf {
normalize_for_path_comparison(cwd).unwrap_or_else(|_| cwd.to_path_buf())
}
/// List thread ids from SQLite for parity checks without rollout scanning.
#[allow(clippy::too_many_arguments)]
pub async fn list_thread_ids_db(
context: Option<&codex_state::StateRuntime>,
sqlite: &codex_state::SqliteConfig,
page_size: usize,
cursor: Option<&Cursor>,
sort_key: ThreadSortKey,
allowed_sources: &[SessionSource],
model_providers: Option<&[String]>,
archived_only: bool,
stage: &str,
) -> Option<Vec<ThreadId>> {
let ctx = context?;
if ctx.sqlite() != sqlite {
warn!(
"state db SQLite home mismatch: expected {}, got {}",
sqlite.home().display(),
ctx.sqlite().home().display()
);
return None;
}
let anchor = cursor_to_anchor(cursor);
let allowed_sources: Vec<String> = allowed_sources
.iter()
.map(|value| match serde_json::to_value(value) {
Ok(Value::String(s)) => s,
Ok(other) => other.to_string(),
Err(_) => String::new(),
})
.collect();
let model_providers = model_providers.map(<[String]>::to_vec);
match ctx
.list_thread_ids(
page_size,
anchor.as_ref(),
match sort_key {
ThreadSortKey::CreatedAt => codex_state::SortKey::CreatedAt,
ThreadSortKey::UpdatedAt => codex_state::SortKey::UpdatedAt,
ThreadSortKey::RecencyAt => codex_state::SortKey::RecencyAt,
},
allowed_sources.as_slice(),
model_providers.as_deref(),
archived_only,
)
.await
{
Ok(ids) => Some(ids),
Err(err) => {
warn!("state db list_thread_ids failed during {stage}: {err}");
None
}
}
}
/// List thread metadata from SQLite without rollout directory traversal.
#[allow(clippy::too_many_arguments)]
pub async fn list_threads_db(
context: Option<&codex_state::StateRuntime>,
sqlite: &codex_state::SqliteConfig,
page_size: usize,
cursor: Option<&Cursor>,
sort_key: ThreadSortKey,
sort_direction: SortDirection,
allowed_sources: &[SessionSource],
model_providers: Option<&[String]>,
cwd_filters: Option<&[PathBuf]>,
relation_filter: Option<codex_state::ThreadRelationFilter>,
archived: bool,
section: Option<Option<&str>>,
project_id: Option<Option<&str>>,
search_term: Option<&str>,
) -> Option<codex_state::ThreadsPage> {
let ctx = context?;
if ctx.sqlite() != sqlite {
warn!(
"state db SQLite home mismatch: expected {}, got {}",
sqlite.home().display(),
ctx.sqlite().home().display()
);
return None;
}
let mut anchor = cursor_to_anchor(cursor);
let allowed_sources: Vec<String> = allowed_sources
.iter()
.map(|value| match serde_json::to_value(value) {
Ok(Value::String(s)) => s,
Ok(other) => other.to_string(),
Err(_) => String::new(),
})
.collect();
let model_providers = model_providers.map(<[String]>::to_vec);
let normalized_cwd_filters = cwd_filters.map(|filters| {
filters
.iter()
.map(|cwd| normalize_cwd_for_state_db(cwd))
.collect::<Vec<_>>()
});
let state_sort_key = match sort_key {
ThreadSortKey::CreatedAt => codex_state::SortKey::CreatedAt,
ThreadSortKey::UpdatedAt => codex_state::SortKey::UpdatedAt,
ThreadSortKey::RecencyAt => codex_state::SortKey::RecencyAt,
};
let state_sort_direction = match sort_direction {
SortDirection::Asc => codex_state::SortDirection::Asc,
SortDirection::Desc => codex_state::SortDirection::Desc,
};
if let Some(relation_filter) = relation_filter {
let filters = codex_state::ThreadFilterOptions {
archived_only: archived,
section,
allowed_sources: allowed_sources.as_slice(),
model_providers: model_providers.as_deref(),
cwd_filters: normalized_cwd_filters.as_deref(),
project_id,
anchor: anchor.as_ref(),
sort_key: state_sort_key,
sort_direction: state_sort_direction,
search_term,
};
return match ctx
.list_threads_by_relation(page_size, relation_filter, filters)
.await
{
Ok(page) => Some(page),
Err(err) => {
warn!("state db list_threads failed: {err}");
None
}
};
}
let mut items = Vec::with_capacity(page_size);
let mut next_anchor = None;
let mut num_scanned_rows = 0usize;
while items.len() < page_size {
let filters = codex_state::ThreadFilterOptions {
archived_only: archived,
section,
allowed_sources: allowed_sources.as_slice(),
model_providers: model_providers.as_deref(),
cwd_filters: normalized_cwd_filters.as_deref(),
project_id,
anchor: anchor.as_ref(),
sort_key: state_sort_key,
sort_direction: state_sort_direction,
search_term,
};
let page = match ctx.list_threads(page_size - items.len(), filters).await {
Ok(page) => page,
Err(err) => {
warn!("state db list_threads failed: {err}");
return None;
}
};
num_scanned_rows = num_scanned_rows.saturating_add(page.num_scanned_rows);
next_anchor = page.next_anchor;
for item in page.items {
if let Some(existing_path) =
crate::compression::existing_rollout_path(item.rollout_path.as_path()).await
{
let mut item = item;
item.rollout_path = existing_path;
items.push(item);
} else {
warn!(
"state db list_threads returned stale rollout path for thread {}: {}",
item.id,
item.rollout_path.display()
);
warn!("state db discrepancy during list_threads_db: stale_db_path_retained");
}
}
if items.len() == page_size || next_anchor.is_none() {
break;
}
anchor = next_anchor.clone();
}
Some(codex_state::ThreadsPage {
items,
parent_thread_ids: Default::default(),
next_anchor,
num_scanned_rows,
})
}
/// Look up the rollout path for a thread id using SQLite.
pub async fn find_rollout_path_by_id(
context: Option<&codex_state::StateRuntime>,
thread_id: ThreadId,
archived_only: Option<bool>,
stage: &str,
) -> Option<PathBuf> {
let ctx = context?;
ctx.find_rollout_path_by_id(thread_id, archived_only)
.await
.unwrap_or_else(|err| {
warn!("state db find_rollout_path_by_id failed during {stage}: {err}");
None
})
}
pub async fn mark_thread_memory_mode_polluted(
context: Option<&codex_state::StateRuntime>,
thread_id: ThreadId,
stage: &str,
) {
let Some(ctx) = context else {
return;
};
if let Err(err) = ctx
.memories()
.mark_thread_memory_mode_polluted(thread_id)
.await
{
warn!("memories db mark_thread_memory_mode_polluted failed during {stage}: {err}");
}
}
/// Reconcile rollout items into SQLite, falling back to scanning the rollout file.
pub async fn reconcile_rollout(
context: Option<&codex_state::StateRuntime>,
rollout_path: &Path,
default_provider: &str,
builder: Option<&ThreadMetadataBuilder>,
items: &[RolloutItem],
archived_only: Option<bool>,
new_thread_memory_mode: Option<&str>,
) {
let Some(ctx) = context else {
return;
};
if builder.is_some() || !items.is_empty() {
apply_rollout_items(
Some(ctx),
rollout_path,
default_provider,
builder,
items,
"reconcile_rollout",
new_thread_memory_mode,
/*updated_at_override*/ None,
)
.await;
return;
}
let outcome =
match metadata::extract_metadata_from_rollout(rollout_path, default_provider).await {
Ok(outcome) => outcome,
Err(err) => {
warn!(
"state db reconcile_rollout extraction failed {}: {err}",
rollout_path.display()
);
return;
}
};
let mut metadata = outcome.metadata;
let memory_mode = outcome.memory_mode.unwrap_or_else(|| "enabled".to_string());
metadata.cwd = normalize_cwd_for_state_db(&metadata.cwd);
let existing_metadata = ctx.get_thread(metadata.id).await.ok().flatten();
// Filesystem repair may seed a missing row, but it must not change an existing row's
// selected rollout path. After `thread/revert`, a scan can find multiple immutable
// rollouts for one thread and cannot know which one SQLite selected.
if existing_metadata
.as_ref()
.is_some_and(|existing| existing.rollout_path.as_path() != rollout_path)
{
return;
}
// Paginated metadata updates are SQLite-only. Use the rollout mode to seed a
// missing row, then keep the value from SQLite.
let restore_memory_mode_from_rollout =
existing_metadata.is_none() || matches!(metadata.history_mode, ThreadHistoryMode::Legacy);
if let Some(existing_metadata) = existing_metadata.as_ref() {
metadata.prefer_existing_git_info(existing_metadata);
metadata.prefer_existing_explicit_title(existing_metadata);
}
match archived_only {
Some(true) if metadata.archived_at.is_none() => {
metadata.archived_at = Some(metadata.updated_at);
}
Some(false) => {
metadata.archived_at = None;
}
Some(true) | None => {}
}
if let Err(err) = ctx.upsert_thread(&metadata).await {
warn!(
"state db reconcile_rollout upsert failed {}: {err}",
rollout_path.display()
);
return;
}
if restore_memory_mode_from_rollout
&& let Err(err) = ctx
.set_thread_memory_mode(metadata.id, memory_mode.as_str())
.await
{
warn!(
"state db reconcile_rollout memory_mode update failed {}: {err}",
rollout_path.display()
);
}
}
/// Repair a thread's rollout path after filesystem fallback succeeds.
pub async fn read_repair_rollout_path(
context: Option<&codex_state::StateRuntime>,
thread_id: Option<ThreadId>,
archived_only: Option<bool>,
rollout_path: &Path,
) {
let Some(ctx) = context else {
return;
};
// Fast path: update an existing metadata row in place, but avoid writes when
// read-repair computes no effective change.
let mut saw_existing_metadata = false;
if let Some(thread_id) = thread_id
&& let Ok(Some(metadata)) = ctx.get_thread(thread_id).await
{
// Filesystem repair may seed a missing row, but it must not change an existing row's
// selected rollout path. After `thread/revert`, a scan can find multiple immutable
// rollouts for one thread and cannot know which one SQLite selected.
if metadata.rollout_path.as_path() != rollout_path {
return;
}
saw_existing_metadata = true;
let mut repaired = metadata.clone();
repaired.rollout_path = rollout_path.to_path_buf();
repaired.cwd = normalize_cwd_for_state_db(&repaired.cwd);
match archived_only {
Some(true) if repaired.archived_at.is_none() => {
repaired.archived_at = Some(repaired.updated_at);
}
Some(false) => {
repaired.archived_at = None;
}
Some(true) | None => {}
}
if repaired == metadata {
return;
}
warn!("state db discrepancy during read_repair_rollout_path: upsert_needed (fast path)");
if let Err(err) = ctx.upsert_thread(&repaired).await {
warn!(
"state db read-repair upsert failed for {}: {err}",
rollout_path.display()
);
} else {
return;
}
}
// Slow path: when the row is missing/unreadable (or direct upsert failed),
// rebuild metadata from rollout contents and reconcile it into SQLite.
if !saw_existing_metadata {
warn!("state db discrepancy during read_repair_rollout_path: upsert_needed (slow path)");
}
let default_provider = crate::list::read_session_meta_line(rollout_path)
.await
.ok()
.and_then(|meta| meta.meta.model_provider)
.unwrap_or_default();
reconcile_rollout(
Some(ctx),
rollout_path,
default_provider.as_str(),
/*builder*/ None,
&[],
archived_only,
/*new_thread_memory_mode*/ None,
)
.await;
}
/// Apply rollout items incrementally to SQLite.
#[allow(clippy::too_many_arguments)]
pub async fn apply_rollout_items(
context: Option<&codex_state::StateRuntime>,
rollout_path: &Path,
default_provider: &str,
builder: Option<&ThreadMetadataBuilder>,
items: &[RolloutItem],
stage: &str,
new_thread_memory_mode: Option<&str>,
updated_at_override: Option<DateTime<Utc>>,
) {
let Some(ctx) = context else {
return;
};
let mut builder = match builder {
Some(builder) => builder.clone(),
None => match metadata::builder_from_items(items, rollout_path) {
Some(builder) => builder,
None => {
warn!(
"state db apply_rollout_items missing builder during {stage}: {}",
rollout_path.display()
);
warn!("state db discrepancy during apply_rollout_items: {stage}, missing_builder");
return;
}
},
};
if builder.model_provider.is_none() {
builder.model_provider = Some(default_provider.to_string());
}
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)
.await
{
warn!(
"state db apply_rollout_items failed during {stage} for {}: {err}",
rollout_path.display()
);
}
}
pub async fn touch_thread_updated_at(
context: Option<&codex_state::StateRuntime>,
thread_id: Option<ThreadId>,
updated_at: DateTime<Utc>,
stage: &str,
) -> bool {
let Some(ctx) = context else {
return false;
};
let Some(thread_id) = thread_id else {
return false;
};
ctx.touch_thread_updated_at(thread_id, updated_at)
.await
.unwrap_or_else(|err| {
warn!("state db touch_thread_updated_at failed during {stage} for {thread_id}: {err}");
false
})
}
#[cfg(test)]
#[path = "state_db_tests.rs"]
mod tests;

View File

@@ -0,0 +1,377 @@
#![allow(warnings, clippy::all)]
use super::*;
use crate::RolloutLine;
use crate::list::parse_cursor;
use chrono::DateTime;
use chrono::NaiveDateTime;
use chrono::Timelike;
use chrono::Utc;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::SessionMeta;
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::ThreadHistoryMode;
use codex_protocol::protocol::UserMessageEvent;
use codex_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use std::path::Path;
use tempfile::TempDir;
#[test]
fn cursor_to_anchor_normalizes_timestamp_format() {
let ts_str = "2026-01-27T12-34-56";
let cursor = parse_cursor(ts_str).expect("cursor should parse");
let anchor = cursor_to_anchor(Some(&cursor)).expect("anchor should parse");
let naive =
NaiveDateTime::parse_from_str(ts_str, "%Y-%m-%dT%H-%M-%S").expect("ts should parse");
let expected_ts = DateTime::<Utc>::from_naive_utc_and_offset(naive, Utc)
.with_nanosecond(0)
.expect("nanosecond");
assert_eq!(anchor.ts, expected_ts);
assert_eq!(anchor.id, None);
}
#[test]
fn cursor_to_anchor_preserves_recency_tie_breaker() {
let id = ThreadId::from_string("00000000-0000-0000-0000-000000000123")
.expect("thread id should parse");
let token = format!("2026-01-27T12:34:56Z|{id}");
let cursor = parse_cursor(&token).expect("cursor should parse");
let anchor = cursor_to_anchor(Some(&cursor)).expect("anchor should parse");
assert_eq!(anchor.id, Some(id));
assert_eq!(
serde_json::to_string(&cursor).expect("cursor should serialize"),
format!("\"{token}\"")
);
}
/// A runtime for another SQLite home must not be queried or clean up rows when
/// a caller supplies a mismatched configuration.
#[tokio::test]
async fn list_threads_db_rejects_mismatched_sqlite_config_without_cleanup() -> anyhow::Result<()> {
let root = TempDir::new().expect("temp dir");
let runtime_sqlite = codex_state::SqliteConfig::new_for_testing(
root.path().join("runtime-sqlite").as_path().abs(),
);
let requested_sqlite = codex_state::SqliteConfig::new_for_testing(
root.path().join("requested-sqlite").as_path().abs(),
);
let runtime =
codex_state::StateRuntime::init(runtime_sqlite, "test-provider".to_string()).await?;
let thread_id = ThreadId::new();
let metadata = ThreadMetadataBuilder::new(
thread_id,
root.path().join("missing-rollout.jsonl"),
Utc::now(),
SessionSource::Cli,
)
.build("test-provider");
runtime.upsert_thread(&metadata).await?;
let page = list_threads_db(
Some(runtime.as_ref()),
&requested_sqlite,
/*page_size*/ 10,
/*cursor*/ None,
ThreadSortKey::CreatedAt,
SortDirection::Desc,
&[],
/*model_providers*/ None,
/*cwd_filters*/ None,
/*relation_filter*/ None,
/*archived*/ false,
/*section*/ None,
/*project_id*/ None,
/*search_term*/ None,
)
.await;
assert!(page.is_none());
assert_eq!(runtime.get_thread(thread_id).await?, Some(metadata));
Ok(())
}
#[tokio::test]
async fn try_init_waits_for_concurrent_startup_backfill() -> anyhow::Result<()> {
let home = TempDir::new().expect("temp dir");
let runtime = codex_state::StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(home.path().abs()),
"test-provider".to_string(),
)
.await?;
let claimed = runtime.try_claim_backfill(/*lease_seconds*/ 60).await?;
assert!(claimed);
let runtime_for_completion = runtime.clone();
let complete_backfill = tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
runtime_for_completion
.mark_backfill_complete(/*last_watermark*/ None)
.await
});
let initialized = try_init_with_roots_and_backfill_lease(
home.path().to_path_buf(),
codex_state::SqliteConfig::new_for_testing(home.path().abs()),
"test-provider".to_string(),
/*backfill_lease_seconds*/ 60,
)
.await?;
complete_backfill.await??;
assert_eq!(
initialized.get_backfill_state().await?.status,
codex_state::BackfillStatus::Complete
);
Ok(())
}
#[tokio::test]
async fn try_init_times_out_waiting_for_stuck_startup_backfill() -> anyhow::Result<()> {
let home = TempDir::new().expect("temp dir");
let runtime = codex_state::StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(home.path().abs()),
"test-provider".to_string(),
)
.await?;
let claimed = runtime.try_claim_backfill(/*lease_seconds*/ 60).await?;
assert!(claimed);
let result = try_init_with_roots_and_backfill_lease(
home.path().to_path_buf(),
codex_state::SqliteConfig::new_for_testing(home.path().abs()),
"test-provider".to_string(),
/*backfill_lease_seconds*/ 60,
)
.await;
let err = match result {
Ok(_) => panic!("state db init should not wait forever for incomplete backfill"),
Err(err) => err,
};
assert!(
err.to_string()
.contains("timed out waiting for state db backfill"),
"unexpected error: {err}"
);
Ok(())
}
#[tokio::test]
async fn reconcile_rollout_preserves_existing_explicit_title() -> anyhow::Result<()> {
let home = TempDir::new().expect("temp dir");
let thread_id = ThreadId::new();
let rollout_path =
write_rollout_with_user_message(home.path(), thread_id, "Hey", ThreadHistoryMode::Legacy)?;
let runtime = codex_state::StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(home.path().abs()),
"test-provider".to_string(),
)
.await?;
let mut metadata =
metadata::extract_metadata_from_rollout(rollout_path.as_path(), "test-provider")
.await?
.metadata;
assert_eq!(metadata.title, "Hey");
assert_eq!(metadata.first_user_message.as_deref(), Some("Hey"));
metadata.title = "math".to_string();
runtime.upsert_thread(&metadata).await?;
reconcile_rollout(
Some(runtime.as_ref()),
rollout_path.as_path(),
"test-provider",
/*builder*/ None,
&[],
/*archived_only*/ Some(false),
/*new_thread_memory_mode*/ None,
)
.await;
let persisted = runtime
.get_thread(thread_id)
.await?
.expect("thread should exist");
assert_eq!(persisted.title, "math");
assert_eq!(persisted.first_user_message.as_deref(), Some("Hey"));
Ok(())
}
#[tokio::test]
async fn filesystem_repair_preserves_existing_rollout_path() -> anyhow::Result<()> {
let home = TempDir::new().expect("temp dir");
let thread_id = ThreadId::new();
let initial_rollout_path = write_rollout_with_user_message(
home.path(),
thread_id,
"Old",
ThreadHistoryMode::Paginated,
)?;
let old_rollout_path = initial_rollout_path
.with_file_name(format!("rollout-2026-06-01T14-26-25-{thread_id}_old.jsonl"));
std::fs::rename(initial_rollout_path, old_rollout_path.as_path())?;
let active_rollout_path = write_rollout_with_user_message(
home.path(),
thread_id,
"Current",
ThreadHistoryMode::Paginated,
)?;
let runtime = codex_state::StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(home.path().abs()),
"test-provider".to_string(),
)
.await?;
let active_metadata =
metadata::extract_metadata_from_rollout(active_rollout_path.as_path(), "test-provider")
.await?
.metadata;
runtime.upsert_thread(&active_metadata).await?;
let active_metadata = runtime
.get_thread(thread_id)
.await?
.expect("thread should exist");
read_repair_rollout_path(
Some(runtime.as_ref()),
Some(thread_id),
/*archived_only*/ None,
old_rollout_path.as_path(),
)
.await;
assert_eq!(
runtime.get_thread(thread_id).await?,
Some(active_metadata.clone())
);
reconcile_rollout(
Some(runtime.as_ref()),
old_rollout_path.as_path(),
"test-provider",
/*builder*/ None,
&[],
/*archived_only*/ None,
/*new_thread_memory_mode*/ None,
)
.await;
assert_eq!(runtime.get_thread(thread_id).await?, Some(active_metadata));
Ok(())
}
#[tokio::test]
async fn reconcile_rollout_preserves_existing_paginated_memory_mode() -> anyhow::Result<()> {
let home = TempDir::new().expect("temp dir");
let thread_id = ThreadId::new();
let rollout_path = write_rollout_with_user_message(
home.path(),
thread_id,
"Hey",
ThreadHistoryMode::Paginated,
)?;
let runtime = codex_state::StateRuntime::init(
codex_state::SqliteConfig::new_for_testing(home.path().abs()),
"test-provider".to_string(),
)
.await?;
reconcile_rollout(
Some(runtime.as_ref()),
rollout_path.as_path(),
"test-provider",
/*builder*/ None,
&[],
/*archived_only*/ None,
/*new_thread_memory_mode*/ None,
)
.await;
assert!(
runtime
.set_thread_memory_mode(thread_id, "disabled")
.await?
);
reconcile_rollout(
Some(runtime.as_ref()),
rollout_path.as_path(),
"test-provider",
/*builder*/ None,
&[],
/*archived_only*/ None,
/*new_thread_memory_mode*/ None,
)
.await;
assert_eq!(
runtime.get_thread_memory_mode(thread_id).await?.as_deref(),
Some("disabled")
);
Ok(())
}
fn write_rollout_with_user_message(
home: &Path,
thread_id: ThreadId,
message: &str,
history_mode: ThreadHistoryMode,
) -> anyhow::Result<std::path::PathBuf> {
let dir = home.join("sessions/2026/06/01");
std::fs::create_dir_all(dir.as_path())?;
let path = dir.join(format!("rollout-2026-06-01T14-26-25-{thread_id}.jsonl"));
let lines = [
RolloutLine {
timestamp: "2026-06-01T14:26:25Z".to_string(),
ordinal: None,
item: RolloutItem::SessionMeta(Box::new(SessionMetaLine {
meta: SessionMeta {
account_scoped: false,
attached_thread: false,
creator_user_id: None,
creator_account_id: None,
session_id: thread_id.into(),
id: thread_id,
forked_from_id: None,
forked_from_ordinal_exclusive: None,
parent_thread_id: None,
timestamp: "2026-06-01T14:26:25Z".to_string(),
cwd: home.to_path_buf(),
runtime_workspace_roots: None,
originator: "test".to_string(),
cli_version: "test".to_string(),
source: SessionSource::Cli,
thread_source: None,
agent_nickname: None,
agent_role: None,
agent_path: None,
model_provider: Some("test-provider".to_string()),
base_instructions: None,
dynamic_tools: None,
selected_capability_roots: Vec::new(),
memory_mode: None,
history_mode,
history_base: None,
subagent_history_start_ordinal: None,
multi_agent_version: None,
context_window: None,
},
git: None,
})),
},
RolloutLine {
timestamp: "2026-06-01T14:26:26Z".to_string(),
ordinal: None,
item: RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent {
message: message.to_string(),
..Default::default()
})),
},
];
let jsonl = lines
.iter()
.map(serde_json::to_string)
.collect::<Result<Vec<_>, _>>()?
.join("\n");
std::fs::write(path.as_path(), format!("{jsonl}\n"))?;
Ok(path)
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,244 @@
//! Shared cross-process ownership for local thread writers and rollout publication.
//! Opening a thread lock file uses a bounded wait for home coordination. Cleanup
//! removes the file only if it can acquire exclusive coordination immediately.
use std::fs;
use std::fs::File;
use std::fs::OpenOptions;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use codex_protocol::ThreadId;
use tracing::warn;
const WRITER_LOCK_DIR: &str = "thread-writer-locks";
const COORDINATION_LOCK_FILE: &str = ".coordination.lock";
/// Coordinates writer ownership within one Codex home.
pub struct WriterLockCoordinator {
directory: PathBuf,
cleanup_attempted: AtomicBool,
}
/// Keeps a thread owned until all file work has finished.
pub struct WriterLockGuard {
coordinator: Arc<WriterLockCoordinator>,
path: PathBuf,
file: Option<File>,
}
impl WriterLockCoordinator {
/// Uses the same lock namespace as existing local thread-store writers.
pub fn new(codex_home: &Path) -> Self {
Self {
directory: codex_home.join(WRITER_LOCK_DIR),
cleanup_attempted: AtomicBool::new(false),
}
}
/// Acquires exclusive writer ownership, returning `WouldBlock` for an active writer.
pub fn acquire(self: &Arc<Self>, thread_id: ThreadId) -> io::Result<WriterLockGuard> {
let file = self.open_coordination()?;
// Never queue a directory sweep behind another writer. Removal remains exclusive.
let have_exclusive = !self.cleanup_attempted.swap(true, Ordering::Relaxed)
&& match file.try_lock() {
Ok(()) => true,
Err(fs::TryLockError::WouldBlock) => false,
Err(fs::TryLockError::Error(err)) => return Err(err),
};
if have_exclusive {
if let Err(err) = self.remove_stale_thread_locks() {
warn!("failed to clean up stale thread writer locks: {err}");
}
} else {
Self::wait_for_coordination(|| file.try_lock_shared())?;
}
let _coordination_lock = file;
let path = self.directory.join(format!("{thread_id}.lock"));
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&path)
.map_err(|err| {
io::Error::other(format!(
"failed to open thread writer lock {}: {err}",
path.display()
))
})?;
match file.try_lock() {
Ok(()) => {}
Err(std::fs::TryLockError::WouldBlock) => {
return Err(io::Error::new(
io::ErrorKind::WouldBlock,
format!("thread {thread_id} already has an active writer"),
));
}
Err(std::fs::TryLockError::Error(err)) => {
return Err(io::Error::other(format!(
"failed to acquire thread writer lock {}: {err}",
path.display()
)));
}
}
Ok(WriterLockGuard {
coordinator: Arc::clone(self),
path,
file: Some(file),
})
}
/// Holds coordination through publication after probing that the thread is idle.
/// Every writer takes coordination before opening its thread lock, so the probe
/// itself can be released. Encoding and verification must finish before this call.
pub(crate) fn try_acquire_for_publication(
&self,
thread_id: ThreadId,
) -> io::Result<Option<File>> {
let coordination_lock = self.lock_coordination()?;
let path = self.directory.join(format!("{thread_id}.lock"));
match OpenOptions::new().read(true).write(true).open(path) {
Ok(file) => match file.try_lock() {
Ok(()) => Ok(Some(coordination_lock)),
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
Err(std::fs::TryLockError::Error(err)) => Err(err),
},
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Some(coordination_lock)),
Err(err) => Err(err),
}
}
fn open_coordination(&self) -> io::Result<File> {
fs::create_dir_all(&self.directory)?;
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(self.directory.join(COORDINATION_LOCK_FILE))
}
fn lock_coordination(&self) -> io::Result<File> {
let file = self.open_coordination()?;
Self::wait_for_coordination(|| file.try_lock())?;
Ok(file)
}
fn wait_for_coordination(
try_lock: impl Fn() -> Result<(), fs::TryLockError>,
) -> io::Result<()> {
let deadline = Instant::now() + Duration::from_secs(/*secs*/ 30);
loop {
match try_lock() {
Ok(()) => return Ok(()),
Err(fs::TryLockError::WouldBlock) if Instant::now() < deadline => {
std::thread::sleep(Duration::from_millis(/*millis*/ 50));
}
Err(fs::TryLockError::WouldBlock) => {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"timed out waiting for the thread writer coordination lock; another Codex process may be suspended on this or another host",
));
}
Err(fs::TryLockError::Error(err)) => return Err(err),
}
}
}
fn remove_stale_thread_locks(&self) -> io::Result<()> {
for entry in fs::read_dir(&self.directory)? {
let entry = entry?;
let Some(file_name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
let Some(thread_id) = file_name.strip_suffix(".lock") else {
continue;
};
if ThreadId::from_string(thread_id).is_err() {
continue;
}
let path = entry.path();
let file = match OpenOptions::new().read(true).write(true).open(&path) {
Ok(file) => file,
Err(err) if err.kind() == io::ErrorKind::NotFound => continue,
Err(err) => {
warn!(
"failed to inspect thread writer lock {}: {err}",
path.display()
);
continue;
}
};
match file.try_lock() {
Ok(()) => {
drop(file);
if let Err(err) = fs::remove_file(&path)
&& err.kind() != io::ErrorKind::NotFound
{
warn!(
"failed to remove stale thread writer lock {}: {err}",
path.display()
);
}
}
Err(std::fs::TryLockError::WouldBlock) => {}
Err(std::fs::TryLockError::Error(err)) => {
warn!(
"failed to inspect thread writer lock {}: {err}",
path.display()
);
}
}
}
Ok(())
}
}
impl Drop for WriterLockGuard {
fn drop(&mut self) {
let coordination_lock = match self.coordinator.open_coordination() {
Ok(lock) => lock,
Err(err) => {
warn!("failed to coordinate thread writer lock cleanup: {err}");
return;
}
};
match coordination_lock.try_lock() {
Ok(()) => {}
// Leave the file for the next writer. Dropping the guard still closes it.
Err(fs::TryLockError::WouldBlock) => return,
Err(fs::TryLockError::Error(err)) => {
warn!("failed to coordinate thread writer lock cleanup: {err}");
return;
}
}
// Close the writer lock before deleting it so cleanup works on Windows too.
drop(self.file.take());
if let Err(err) = fs::remove_file(&self.path)
&& err.kind() != io::ErrorKind::NotFound
{
warn!(
"failed to remove thread writer lock {}: {err}",
self.path.display()
);
}
drop(coordination_lock);
}
}
#[cfg(test)]
#[path = "writer_lock_tests.rs"]
mod tests;

View File

@@ -0,0 +1,155 @@
use std::fs;
use std::sync::Arc;
use std::sync::mpsc;
use std::time::Duration;
use codex_protocol::ThreadId;
use tempfile::TempDir;
use super::COORDINATION_LOCK_FILE;
use super::WRITER_LOCK_DIR;
use super::WriterLockCoordinator;
use pretty_assertions::assert_eq;
use std::io::ErrorKind;
#[test]
fn writer_locks_reject_competing_owners_and_release_their_files() {
let home = TempDir::new().expect("temp dir");
let primary = Arc::new(WriterLockCoordinator::new(home.path()));
let secondary = Arc::new(WriterLockCoordinator::new(home.path()));
let thread_id = ThreadId::default();
let other_thread_id = ThreadId::default();
let owner = primary.acquire(thread_id).expect("acquire writer lock");
let lock_path = home
.path()
.join(WRITER_LOCK_DIR)
.join(format!("{thread_id}.lock"));
assert!(lock_path.exists());
// Another process is opening a writer. Distinct threads can start together,
// but even during this overlap the same thread must still have one owner.
let opening = fs::OpenOptions::new()
.read(true)
.write(true)
.open(
home.path()
.join(WRITER_LOCK_DIR)
.join(COORDINATION_LOCK_FILE),
)
.expect("open coordination");
opening.lock_shared().expect("another writer is opening");
let err = match secondary.acquire(thread_id) {
Ok(_) => panic!("competing owner should fail"),
Err(err) => err,
};
assert_eq!(err.kind(), ErrorKind::WouldBlock);
let other_owner = secondary
.acquire(other_thread_id)
.expect("other thread should acquire its own lock");
let next_owner = std::thread::scope(|scope| {
let _opening = opening;
let (closed, wait_for_close) = mpsc::channel();
scope.spawn(move || {
drop(owner);
let _ = closed.send(());
});
wait_for_close
.recv_timeout(Duration::from_secs(/*secs*/ 10))
.expect("writer should close while another writer is opening");
assert!(lock_path.exists());
secondary
.acquire(thread_id)
.expect("released thread should accept another owner")
});
drop(next_owner);
drop(other_owner);
let entries = fs::read_dir(home.path().join(WRITER_LOCK_DIR))
.expect("read lock directory")
.map(|entry| entry.expect("lock directory entry").file_name())
.collect::<Vec<_>>();
assert_eq!(entries, vec![COORDINATION_LOCK_FILE]);
}
#[test]
fn first_acquisition_removes_stale_locks_without_removing_active_locks() {
let home = TempDir::new().expect("temp dir");
let primary = Arc::new(WriterLockCoordinator::new(home.path()));
let active_thread_id = ThreadId::default();
let active_owner = primary
.acquire(active_thread_id)
.expect("acquire active writer lock");
let stale_thread_id = ThreadId::default();
let stale_path = home
.path()
.join(WRITER_LOCK_DIR)
.join(format!("{stale_thread_id}.lock"));
fs::File::create(&stale_path).expect("create stale writer lock");
let secondary = Arc::new(WriterLockCoordinator::new(home.path()));
let secondary_owner = secondary
.acquire(ThreadId::default())
.expect("acquire writer lock after cleanup");
assert!(!stale_path.exists());
let err = match secondary.acquire(active_thread_id) {
Ok(_) => panic!("active writer should survive cleanup"),
Err(err) => err,
};
assert_eq!(err.kind(), ErrorKind::WouldBlock);
drop(secondary_owner);
drop(active_owner);
}
#[test]
fn publication_skips_live_writers_and_keeps_coordination_locked() {
let home = TempDir::new().expect("temp dir");
let publisher = Arc::new(WriterLockCoordinator::new(home.path()));
let writer = Arc::new(WriterLockCoordinator::new(home.path()));
let thread_id = ThreadId::default();
let owner = writer.acquire(thread_id).expect("writer owns thread");
assert!(
publisher
.try_acquire_for_publication(thread_id)
.unwrap()
.is_none()
);
drop(owner);
let publication = publisher
.try_acquire_for_publication(thread_id)
.unwrap()
.unwrap();
let coordination = fs::OpenOptions::new()
.read(true)
.write(true)
.open(writer.directory.join(COORDINATION_LOCK_FILE))
.unwrap();
assert!(matches!(
coordination.try_lock(),
Err(fs::TryLockError::WouldBlock)
));
let error = writer
.acquire(ThreadId::default())
.err()
.expect("coordination contention must return an error instead of hanging");
assert_eq!(error.kind(), ErrorKind::TimedOut);
drop(publication);
coordination
.try_lock()
.expect("publication releases coordination");
drop(coordination);
// An existing but unlocked file is also idle; file existence is not ownership.
fs::File::create(writer.directory.join(format!("{thread_id}.lock"))).unwrap();
drop(
publisher
.try_acquire_for_publication(thread_id)
.unwrap()
.expect("stale lock is idle"),
);
assert!(writer.acquire(thread_id).is_ok());
}