Base: codex-main originale (prima del fork aKode)
This commit is contained in:
127
codex-rs/feedback/src/archive.rs
Normal file
127
codex-rs/feedback/src/archive.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
//! Atomic local feedback export with bounded contents and no file replacement.
|
||||
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::FeedbackAttachment;
|
||||
use crate::FeedbackAttachmentPath;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
|
||||
pub(crate) enum Input<'a> {
|
||||
Owned(FeedbackAttachment),
|
||||
Path(&'a FeedbackAttachmentPath),
|
||||
}
|
||||
use zip::ZipWriter;
|
||||
use zip::write::SimpleFileOptions;
|
||||
|
||||
pub(crate) struct Limits {
|
||||
pub max_bytes: usize,
|
||||
pub max_attachments: usize,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_bytes: 200 * 1024 * 1024,
|
||||
max_attachments: 128,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Count uncompressed entry contents, including report and manifest serialization.
|
||||
struct BudgetWriter<'a, W> {
|
||||
inner: &'a mut W,
|
||||
remaining: &'a mut usize,
|
||||
}
|
||||
|
||||
impl<W: Write> Write for BudgetWriter<'_, W> {
|
||||
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
|
||||
let remaining = self.remaining.checked_sub(buffer.len()).ok_or_else(|| {
|
||||
io::Error::other("feedback archive exceeds the uncompressed size limit")
|
||||
})?;
|
||||
self.inner.write_all(buffer)?;
|
||||
*self.remaining = remaining;
|
||||
Ok(buffer.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.inner.flush()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn save<'a>(
|
||||
path: &Path,
|
||||
report: &[u8],
|
||||
attachments: impl Iterator<Item = Input<'a>>,
|
||||
limits: Limits,
|
||||
) -> Result<()> {
|
||||
anyhow::ensure!(path.is_absolute(), "feedback save path must be absolute");
|
||||
anyhow::ensure!(!path.exists(), "feedback save path already exists");
|
||||
let parent = path.parent().context("feedback save path has no parent")?;
|
||||
let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
|
||||
let mut writer = ZipWriter::new(temporary.as_file_mut());
|
||||
let options = SimpleFileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated)
|
||||
.large_file(true);
|
||||
let mut remaining = limits.max_bytes;
|
||||
writer.start_file("report.json", options)?;
|
||||
BudgetWriter {
|
||||
inner: &mut writer,
|
||||
remaining: &mut remaining,
|
||||
}
|
||||
.write_all(report)?;
|
||||
let mut manifest = Vec::new();
|
||||
for (index, attachment) in attachments.enumerate() {
|
||||
// Inspect metadata before reading the next file or compressing its contents.
|
||||
anyhow::ensure!(
|
||||
index < limits.max_attachments,
|
||||
"feedback archive exceeds the attachment count limit"
|
||||
);
|
||||
let attachment = match attachment {
|
||||
Input::Owned(attachment) => attachment,
|
||||
Input::Path(path) => path.read_attachment(remaining)
|
||||
.with_context(|| format!("failed to read selected attachment {}", path.path.display()))?
|
||||
.with_context(|| format!("selected attachment {} is missing, nonregular, or exceeds the remaining decoded size limit", path.path.display()))?,
|
||||
};
|
||||
let basename = attachment
|
||||
.filename
|
||||
.rsplit(['/', '\\'])
|
||||
.next()
|
||||
.filter(|name| !name.is_empty() && *name != "." && *name != "..")
|
||||
.unwrap_or("attachment");
|
||||
// Numbered directories retain duplicate names without unsafe ZIP paths.
|
||||
let entry = format!("attachments/{index:04}/{basename}");
|
||||
writer.start_file(&entry, options)?;
|
||||
BudgetWriter {
|
||||
inner: &mut writer,
|
||||
remaining: &mut remaining,
|
||||
}
|
||||
.write_all(&attachment.buffer)?;
|
||||
manifest.push(serde_json::json!({
|
||||
"entry": entry,
|
||||
"filename": attachment.filename,
|
||||
"contentType": attachment.content_type,
|
||||
}));
|
||||
}
|
||||
writer.start_file("manifest.json", options)?;
|
||||
serde_json::to_writer(
|
||||
BudgetWriter {
|
||||
inner: &mut writer,
|
||||
remaining: &mut remaining,
|
||||
},
|
||||
&manifest,
|
||||
)?;
|
||||
writer.finish()?;
|
||||
temporary.as_file().sync_all()?;
|
||||
// Same-directory publication is atomic and must not replace an existing file.
|
||||
temporary
|
||||
.persist_noclobber(path)
|
||||
.map_err(|error| error.error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "archive_tests.rs"]
|
||||
mod tests;
|
||||
175
codex-rs/feedback/src/archive_tests.rs
Normal file
175
codex-rs/feedback/src/archive_tests.rs
Normal file
@@ -0,0 +1,175 @@
|
||||
use super::*;
|
||||
use crate::CodexFeedback;
|
||||
use crate::FeedbackUploadOptions;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use zip::ZipArchive;
|
||||
|
||||
fn options() -> FeedbackUploadOptions<'static> {
|
||||
FeedbackUploadOptions {
|
||||
classification: "bug",
|
||||
reason: Some("synthetic feedback"),
|
||||
tags: None,
|
||||
include_logs: false,
|
||||
extra_attachments: Vec::new(),
|
||||
extra_attachment_paths: &[],
|
||||
session_source: None,
|
||||
logs_override: Some(b"consented log bytes".to_vec()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Exports preserve attachment bytes and duplicate names without unsafe ZIP paths.
|
||||
#[test]
|
||||
fn archive_preserves_selected_bytes_and_safe_names() -> Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let path = directory.path().join("feedback.zip");
|
||||
let expected = [
|
||||
("../../same.log", b"first".as_slice()),
|
||||
("../../same.log", b"second"),
|
||||
("rollouts.tar.gz", b"compressed rollout bytes"),
|
||||
];
|
||||
super::save(
|
||||
&path,
|
||||
b"{}",
|
||||
expected.iter().map(|(filename, buffer)| {
|
||||
Input::Owned(FeedbackAttachment {
|
||||
filename: filename.to_string(),
|
||||
buffer: buffer.to_vec(),
|
||||
content_type: None,
|
||||
})
|
||||
}),
|
||||
Limits::default(),
|
||||
)?;
|
||||
let mut archive = ZipArchive::new(File::open(&path)?)?;
|
||||
assert_eq!(archive.len(), 5);
|
||||
let manifest: serde_json::Value = serde_json::from_reader(archive.by_name("manifest.json")?)?;
|
||||
for (index, (filename, bytes)) in expected.iter().enumerate() {
|
||||
let basename = filename.rsplit('/').next().unwrap();
|
||||
let mut entry = archive.by_name(&format!("attachments/{index:04}/{basename}"))?;
|
||||
let mut actual = Vec::new();
|
||||
entry.read_to_end(&mut actual)?;
|
||||
assert_eq!(actual, *bytes);
|
||||
assert_eq!(manifest[index]["filename"], *filename);
|
||||
assert_eq!(entry.compression(), zip::CompressionMethod::Deflated);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Byte and count budgets include metadata and reject excess input without leaving a partial ZIP.
|
||||
#[test]
|
||||
fn archive_bounds_all_contents_and_cleans_failed_exports() -> Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let path = directory.path().join("feedback.zip");
|
||||
// Filtering removes the exact size hint, exercising streaming attachment limits.
|
||||
let attachments = |count| {
|
||||
(0..count).filter(|_| true).map(|_| {
|
||||
Input::Owned(FeedbackAttachment {
|
||||
filename: "test.log".to_string(),
|
||||
buffer: b"synthetic".to_vec(),
|
||||
content_type: None,
|
||||
})
|
||||
})
|
||||
};
|
||||
super::save(
|
||||
&path,
|
||||
b"{}",
|
||||
attachments(2),
|
||||
Limits {
|
||||
max_bytes: 1024,
|
||||
max_attachments: 2,
|
||||
},
|
||||
)?;
|
||||
let mut archive = ZipArchive::new(File::open(&path)?)?;
|
||||
let bytes = (0..archive.len()).try_fold(0, |sum, index| {
|
||||
Ok::<_, zip::result::ZipError>(sum + archive.by_index(index)?.size() as usize)
|
||||
})?;
|
||||
drop(archive);
|
||||
std::fs::remove_file(&path)?;
|
||||
super::save(
|
||||
&path,
|
||||
b"{}",
|
||||
attachments(2),
|
||||
Limits {
|
||||
max_bytes: bytes,
|
||||
max_attachments: 2,
|
||||
},
|
||||
)?;
|
||||
std::fs::remove_file(&path)?;
|
||||
for (count, max_bytes, error) in [
|
||||
(2, bytes - 1, "uncompressed size limit"),
|
||||
(0, 1, "uncompressed size limit"),
|
||||
(3, 1024, "attachment count limit"),
|
||||
] {
|
||||
let failure = super::save(
|
||||
&path,
|
||||
b"{}",
|
||||
attachments(count),
|
||||
Limits {
|
||||
max_bytes,
|
||||
max_attachments: 2,
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(failure.to_string().contains(error), "{failure:#}");
|
||||
assert_eq!(std::fs::read_dir(directory.path())?.count(), 0);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A local report keeps its description and includes log bytes only with consent.
|
||||
#[test]
|
||||
fn save_preserves_report_and_log_consent() -> Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
for include_logs in [false, true] {
|
||||
let path = directory.path().join(format!("{include_logs}.zip"));
|
||||
CodexFeedback::new()
|
||||
.snapshot(/*session_id*/ None)
|
||||
.save_feedback(
|
||||
FeedbackUploadOptions {
|
||||
include_logs,
|
||||
..options()
|
||||
},
|
||||
&path,
|
||||
)?;
|
||||
let mut archive = ZipArchive::new(File::open(path)?)?;
|
||||
let report: serde_json::Value = serde_json::from_reader(archive.by_name("report.json")?)?;
|
||||
assert_eq!(
|
||||
report["exception"]["values"][0]["value"],
|
||||
"synthetic feedback"
|
||||
);
|
||||
let logs = archive
|
||||
.file_names()
|
||||
.collect::<zip::result::ZipResult<Vec<_>>>()?
|
||||
.into_iter()
|
||||
.find(|name| name.ends_with("/codex-logs.log"))
|
||||
.map(std::borrow::Cow::into_owned);
|
||||
assert_eq!(logs.is_some(), include_logs);
|
||||
if let Some(logs) = logs {
|
||||
let mut bytes = Vec::new();
|
||||
archive.by_name(&logs)?.read_to_end(&mut bytes)?;
|
||||
assert_eq!(bytes, b"consented log bytes");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Oversized reports fail before publishing, using the serialized report size.
|
||||
#[test]
|
||||
fn save_rejects_oversized_events_without_publishing() -> Result<()> {
|
||||
let directory = tempfile::tempdir()?;
|
||||
let reason = "x".repeat(crate::MAX_EVENT_BYTES);
|
||||
let error = CodexFeedback::new()
|
||||
.snapshot(/*session_id*/ None)
|
||||
.save_feedback(
|
||||
FeedbackUploadOptions {
|
||||
reason: Some(&reason),
|
||||
..options()
|
||||
},
|
||||
&directory.path().join("oversized.zip"),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.to_string(), "feedback event exceeds the size limit");
|
||||
assert_eq!(std::fs::read_dir(directory.path())?.count(), 0);
|
||||
Ok(())
|
||||
}
|
||||
64
codex-rs/feedback/src/daemon_logs.rs
Normal file
64
codex-rs/feedback/src/daemon_logs.rs
Normal file
@@ -0,0 +1,64 @@
|
||||
//! Collects bounded current and previous updater log tails after feedback log consent.
|
||||
//! Read failures omit individual files; only fixed regular-file names are considered.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::io::Seek;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::FeedbackAttachment;
|
||||
|
||||
const MAX_LOG_BYTES: u64 = 256 * 1024;
|
||||
const LOG_NAMES: [&str; 2] = ["daemon-updater.stderr.log", "app-server-updater.stderr.log"];
|
||||
|
||||
/// Collect at most two 256 KiB updater tails (512 KiB total) from the app-server host.
|
||||
/// Call only after feedback consent includes logs, on a blocking worker.
|
||||
pub fn daemon_log_attachments(codex_home: &Path) -> Vec<FeedbackAttachment> {
|
||||
let directory = codex_home.join("app-server-daemon");
|
||||
let mut attachments = Vec::new();
|
||||
for suffix in ["", ".previous"] {
|
||||
for name in LOG_NAMES {
|
||||
let filename = format!("{name}{suffix}");
|
||||
let path = directory.join(&filename);
|
||||
let result = (|| -> io::Result<Vec<u8>> {
|
||||
// Reject symlinks and nonregular files before opening (e.g. FIFOs).
|
||||
if !fs::symlink_metadata(&path)?.is_file() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut file = fs::File::open(&path)?;
|
||||
let metadata = file.metadata()?;
|
||||
if !metadata.is_file() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
file.seek(io::SeekFrom::Start(
|
||||
metadata.len().saturating_sub(MAX_LOG_BYTES),
|
||||
))?;
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_LOG_BYTES).read_to_end(&mut bytes)?;
|
||||
Ok(bytes)
|
||||
})();
|
||||
match result {
|
||||
Ok(buffer) if !buffer.is_empty() => {
|
||||
attachments.push(FeedbackAttachment {
|
||||
filename,
|
||||
content_type: Some("text/plain".to_string()),
|
||||
buffer,
|
||||
});
|
||||
// Legacy filenames are a fallback, not additional attachments.
|
||||
break;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => {
|
||||
tracing::warn!(filename, error_kind = ?error.kind(), "failed to read daemon feedback log; skipping attachment")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
attachments
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "daemon_logs_tests.rs"]
|
||||
mod tests;
|
||||
55
codex-rs/feedback/src/daemon_logs_tests.rs
Normal file
55
codex-rs/feedback/src/daemon_logs_tests.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use super::*;
|
||||
use codex_protocol::ThreadId;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn collects_bounded_tails_and_skips_missing_empty_and_nonregular_files() -> io::Result<()> {
|
||||
let home = std::env::temp_dir().join(format!("codex-feedback-daemon-{}", ThreadId::new()));
|
||||
let directory = home.join("app-server-daemon");
|
||||
assert!(daemon_log_attachments(&home).is_empty());
|
||||
fs::create_dir_all(&directory)?;
|
||||
let bytes = vec![b'x'; MAX_LOG_BYTES as usize + 100];
|
||||
fs::write(directory.join("daemon.stderr.log"), b"already included")?;
|
||||
fs::write(directory.join("daemon-updater.stderr.log"), &bytes)?;
|
||||
fs::write(
|
||||
directory.join("daemon.stderr.log.previous"),
|
||||
b"failed restart",
|
||||
)?;
|
||||
fs::write(
|
||||
directory.join("app-server-updater.stderr.log"),
|
||||
b"legacy updater",
|
||||
)?;
|
||||
fs::write(
|
||||
directory.join("app-server-updater.stderr.log.previous"),
|
||||
b"previous updater",
|
||||
)?;
|
||||
fs::create_dir(directory.join("app-server.stderr.log.previous"))?;
|
||||
let attachments = daemon_log_attachments(&home);
|
||||
let actual: Vec<_> = attachments
|
||||
.into_iter()
|
||||
.map(|attachment| {
|
||||
(
|
||||
attachment.filename,
|
||||
attachment.content_type,
|
||||
attachment.buffer,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
actual,
|
||||
vec![
|
||||
(
|
||||
"daemon-updater.stderr.log".to_string(),
|
||||
Some("text/plain".to_string()),
|
||||
bytes[100..].to_vec()
|
||||
),
|
||||
(
|
||||
"app-server-updater.stderr.log.previous".to_string(),
|
||||
Some("text/plain".to_string()),
|
||||
b"previous updater".to_vec()
|
||||
),
|
||||
]
|
||||
);
|
||||
fs::remove_dir_all(home)?;
|
||||
Ok(())
|
||||
}
|
||||
179
codex-rs/feedback/src/feedback_diagnostics.rs
Normal file
179
codex-rs/feedback/src/feedback_diagnostics.rs
Normal file
@@ -0,0 +1,179 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub const FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME: &str = "codex-connectivity-diagnostics.txt";
|
||||
const PROXY_ENV_VARS: &[&str] = &[
|
||||
"HTTP_PROXY",
|
||||
"http_proxy",
|
||||
"HTTPS_PROXY",
|
||||
"https_proxy",
|
||||
"ALL_PROXY",
|
||||
"all_proxy",
|
||||
];
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct FeedbackDiagnostics {
|
||||
diagnostics: Vec<FeedbackDiagnostic>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FeedbackDiagnostic {
|
||||
pub headline: String,
|
||||
pub details: Vec<String>,
|
||||
}
|
||||
|
||||
impl FeedbackDiagnostics {
|
||||
pub fn new(diagnostics: Vec<FeedbackDiagnostic>) -> Self {
|
||||
Self { diagnostics }
|
||||
}
|
||||
|
||||
pub fn collect_from_env() -> Self {
|
||||
Self::collect_from_pairs(std::env::vars())
|
||||
}
|
||||
|
||||
fn collect_from_pairs<I, K, V>(pairs: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = (K, V)>,
|
||||
K: Into<String>,
|
||||
V: Into<String>,
|
||||
{
|
||||
let env = pairs
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into()))
|
||||
.collect::<HashMap<_, _>>();
|
||||
let mut diagnostics = Vec::new();
|
||||
|
||||
let proxy_details = PROXY_ENV_VARS
|
||||
.iter()
|
||||
.filter_map(|key| {
|
||||
let value = env.get(*key)?;
|
||||
Some(format!("{key} = {value}"))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if !proxy_details.is_empty() {
|
||||
diagnostics.push(FeedbackDiagnostic {
|
||||
headline: "Proxy environment variables are set and may affect connectivity."
|
||||
.to_string(),
|
||||
details: proxy_details,
|
||||
});
|
||||
}
|
||||
|
||||
Self { diagnostics }
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.diagnostics.is_empty()
|
||||
}
|
||||
|
||||
pub fn diagnostics(&self) -> &[FeedbackDiagnostic] {
|
||||
&self.diagnostics
|
||||
}
|
||||
|
||||
pub fn attachment_text(&self) -> Option<String> {
|
||||
if self.diagnostics.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut lines = vec!["Connectivity diagnostics".to_string(), String::new()];
|
||||
for diagnostic in &self.diagnostics {
|
||||
lines.push(format!("- {}", diagnostic.headline));
|
||||
lines.extend(
|
||||
diagnostic
|
||||
.details
|
||||
.iter()
|
||||
.map(|detail| format!(" - {detail}")),
|
||||
);
|
||||
}
|
||||
|
||||
Some(lines.join("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::FeedbackDiagnostic;
|
||||
use super::FeedbackDiagnostics;
|
||||
|
||||
#[test]
|
||||
fn collect_from_pairs_reports_raw_values_and_attachment() {
|
||||
let diagnostics = FeedbackDiagnostics::collect_from_pairs([
|
||||
(
|
||||
"HTTPS_PROXY",
|
||||
"https://user:password@secure-proxy.example.com:443?secret=1",
|
||||
),
|
||||
("http_proxy", "proxy.example.com:8080"),
|
||||
("all_proxy", "socks5h://all-proxy.example.com:1080"),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
diagnostics,
|
||||
FeedbackDiagnostics {
|
||||
diagnostics: vec![FeedbackDiagnostic {
|
||||
headline: "Proxy environment variables are set and may affect connectivity."
|
||||
.to_string(),
|
||||
details: vec![
|
||||
"http_proxy = proxy.example.com:8080".to_string(),
|
||||
"HTTPS_PROXY = https://user:password@secure-proxy.example.com:443?secret=1"
|
||||
.to_string(),
|
||||
"all_proxy = socks5h://all-proxy.example.com:1080".to_string(),
|
||||
],
|
||||
},],
|
||||
}
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
diagnostics.attachment_text(),
|
||||
Some(
|
||||
r#"Connectivity diagnostics
|
||||
|
||||
- Proxy environment variables are set and may affect connectivity.
|
||||
- http_proxy = proxy.example.com:8080
|
||||
- HTTPS_PROXY = https://user:password@secure-proxy.example.com:443?secret=1
|
||||
- all_proxy = socks5h://all-proxy.example.com:1080"#
|
||||
.to_string()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_from_pairs_ignores_absent_values() {
|
||||
let diagnostics = FeedbackDiagnostics::collect_from_pairs(Vec::<(String, String)>::new());
|
||||
assert_eq!(diagnostics, FeedbackDiagnostics::default());
|
||||
assert_eq!(diagnostics.attachment_text(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_from_pairs_preserves_whitespace_and_empty_values() {
|
||||
let diagnostics =
|
||||
FeedbackDiagnostics::collect_from_pairs([("HTTP_PROXY", " proxy with spaces ")]);
|
||||
|
||||
assert_eq!(
|
||||
diagnostics,
|
||||
FeedbackDiagnostics {
|
||||
diagnostics: vec![FeedbackDiagnostic {
|
||||
headline: "Proxy environment variables are set and may affect connectivity."
|
||||
.to_string(),
|
||||
details: vec!["HTTP_PROXY = proxy with spaces ".to_string()],
|
||||
},],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collect_from_pairs_reports_values_verbatim() {
|
||||
let proxy_value = "not a valid proxy";
|
||||
let diagnostics = FeedbackDiagnostics::collect_from_pairs([("HTTP_PROXY", proxy_value)]);
|
||||
|
||||
assert_eq!(
|
||||
diagnostics,
|
||||
FeedbackDiagnostics {
|
||||
diagnostics: vec![FeedbackDiagnostic {
|
||||
headline: "Proxy environment variables are set and may affect connectivity."
|
||||
.to_string(),
|
||||
details: vec!["HTTP_PROXY = not a valid proxy".to_string()],
|
||||
},],
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
256
codex-rs/feedback/src/feedback_event_tests.rs
Normal file
256
codex-rs/feedback/src/feedback_event_tests.rs
Normal file
@@ -0,0 +1,256 @@
|
||||
//! Feedback event contracts for titles, report grouping, and lossless comment bodies.
|
||||
|
||||
use crate::CodexFeedback;
|
||||
use crate::FeedbackUploadOptions;
|
||||
use crate::UPLOAD_TIMEOUT;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use flate2::read::GzDecoder;
|
||||
use http::StatusCode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use sentry::protocol::Event;
|
||||
use sentry::protocol::Exception;
|
||||
use sentry::protocol::Level;
|
||||
use sentry::protocol::Value;
|
||||
use sentry::protocol::Values;
|
||||
use sentry::protocol::value::to_value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::Read;
|
||||
use std::time::Instant;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[test]
|
||||
fn custom_titles_preserve_comments_and_keep_submissions_separate() {
|
||||
let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None);
|
||||
let tags = BTreeMap::from([
|
||||
(
|
||||
"feedback_title".to_string(),
|
||||
" \t\u{2003}Workflow feedback\nwith 🌍 context\r\n ".to_string(),
|
||||
),
|
||||
("entrypoint".to_string(), "task-picker".to_string()),
|
||||
]);
|
||||
let title = "Workflow feedback\nwith 🌍 context";
|
||||
for (reason, reason_tag) in [
|
||||
(
|
||||
Some(" The\n\nworkflow\twas\u{2003}useful 🌍. "),
|
||||
Some(" The workflow\twas\u{2003}useful 🌍. "),
|
||||
),
|
||||
(Some(""), Some("")),
|
||||
(None, None),
|
||||
] {
|
||||
let event =
|
||||
snapshot.feedback_event("other", reason, Some(&tags), /*session_source*/ None);
|
||||
let mut expected_tags = tags.clone();
|
||||
expected_tags.extend([
|
||||
("thread_id".to_string(), snapshot.thread_id.clone()),
|
||||
("classification".to_string(), "other".to_string()),
|
||||
(
|
||||
"cli_version".to_string(),
|
||||
env!("CARGO_PKG_VERSION").to_string(),
|
||||
),
|
||||
]);
|
||||
if let Some(reason_tag) = reason_tag {
|
||||
expected_tags.insert("reason".to_string(), reason_tag.to_string());
|
||||
}
|
||||
assert_eq!(
|
||||
event,
|
||||
Event {
|
||||
event_id: event.event_id,
|
||||
timestamp: event.timestamp,
|
||||
level: Level::Info,
|
||||
message: Some(title.to_string()),
|
||||
exception: reason
|
||||
.map(|reason| Exception {
|
||||
ty: title.to_string(),
|
||||
value: Some(reason.to_string()),
|
||||
..Default::default()
|
||||
})
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>()
|
||||
.into(),
|
||||
tags: expected_tags,
|
||||
fingerprint: vec![event.event_id.to_string().into()].into(),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
let next_event =
|
||||
snapshot.feedback_event("other", reason, Some(&tags), /*session_source*/ None);
|
||||
assert_ne!(event.fingerprint, next_event.fingerprint);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_blank_titles_preserve_session_titles_and_default_grouping() {
|
||||
let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None);
|
||||
let reason = " Feedback\nwith 🌍 context. ";
|
||||
for custom_title in [None, Some(""), Some(" \t\n\u{2003} ")] {
|
||||
let tags = custom_title
|
||||
.map(|title| BTreeMap::from([("feedback_title".to_string(), title.to_string())]));
|
||||
let event = snapshot.feedback_event(
|
||||
"bug",
|
||||
Some(reason),
|
||||
tags.as_ref(),
|
||||
/*session_source*/ None,
|
||||
);
|
||||
let title = format!("[Bug]: Codex session {}", snapshot.thread_id);
|
||||
let mut expected_tags = tags.unwrap_or_default();
|
||||
expected_tags.extend([
|
||||
("thread_id".to_string(), snapshot.thread_id.clone()),
|
||||
("classification".to_string(), "bug".to_string()),
|
||||
(
|
||||
"cli_version".to_string(),
|
||||
env!("CARGO_PKG_VERSION").to_string(),
|
||||
),
|
||||
(
|
||||
"reason".to_string(),
|
||||
" Feedback with 🌍 context. ".to_string(),
|
||||
),
|
||||
]);
|
||||
assert_eq!(
|
||||
event,
|
||||
Event {
|
||||
event_id: event.event_id,
|
||||
timestamp: event.timestamp,
|
||||
level: Level::Error,
|
||||
message: Some(title.clone()),
|
||||
exception: vec![Exception {
|
||||
ty: title,
|
||||
value: Some(reason.to_string()),
|
||||
..Default::default()
|
||||
}]
|
||||
.into(),
|
||||
tags: expected_tags,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reason_tag_previews_preserve_full_comments_in_the_exception() {
|
||||
let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None);
|
||||
let title = format!("[Bug]: Codex session {}", snapshot.thread_id);
|
||||
for (reason, preview) in [
|
||||
("A short comment".to_string(), "A short comment".to_string()),
|
||||
(
|
||||
"First\r\n\r\nSecond\rThird\n".to_string(),
|
||||
"First Second Third ".to_string(),
|
||||
),
|
||||
("a".repeat(200), "a".repeat(200)),
|
||||
("a".repeat(201), "a".repeat(200)),
|
||||
(format!("{}extra", "界🌍".repeat(100)), "界🌍".repeat(100)),
|
||||
] {
|
||||
let event = snapshot.feedback_event(
|
||||
"bug",
|
||||
Some(&reason),
|
||||
/*tags*/ None,
|
||||
/*session_source*/ None,
|
||||
);
|
||||
assert_eq!(
|
||||
event,
|
||||
Event {
|
||||
event_id: event.event_id,
|
||||
timestamp: event.timestamp,
|
||||
level: Level::Error,
|
||||
message: Some(title.clone()),
|
||||
exception: vec![Exception {
|
||||
ty: title.clone(),
|
||||
value: Some(reason),
|
||||
..Default::default()
|
||||
}]
|
||||
.into(),
|
||||
tags: BTreeMap::from([
|
||||
("thread_id".to_string(), snapshot.thread_id.clone()),
|
||||
("classification".to_string(), "bug".to_string()),
|
||||
(
|
||||
"cli_version".to_string(),
|
||||
env!("CARGO_PKG_VERSION").to_string()
|
||||
),
|
||||
("reason".to_string(), preview),
|
||||
]),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_upload_sends_safe_reason_tag_and_full_comment() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/42/envelope/"))
|
||||
.and(header("Content-Encoding", "gzip"))
|
||||
.respond_with(ResponseTemplate::new(StatusCode::OK))
|
||||
.expect(/*r*/ 1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None);
|
||||
let reason = format!("first\r\nsecond\n{}tail", "界🌍".repeat(120));
|
||||
let tags = BTreeMap::from([("reason".to_string(), "caller override\n".to_string())]);
|
||||
snapshot
|
||||
.upload_feedback_with_dsn(
|
||||
FeedbackUploadOptions {
|
||||
classification: "bug",
|
||||
reason: Some(&reason),
|
||||
tags: Some(&tags),
|
||||
include_logs: false,
|
||||
extra_attachments: Vec::new(),
|
||||
extra_attachment_paths: &[],
|
||||
session_source: None,
|
||||
logs_override: None,
|
||||
},
|
||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
&format!("http://public@{}/42", server.address()),
|
||||
Instant::now() + UPLOAD_TIMEOUT,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
let mut decoded = Vec::new();
|
||||
GzDecoder::new(requests[0].body.as_slice())
|
||||
.read_to_end(&mut decoded)
|
||||
.unwrap();
|
||||
// The first two envelope lines are its header and the event item header.
|
||||
let payload = std::str::from_utf8(&decoded)
|
||||
.unwrap()
|
||||
.splitn(/*n*/ 3, '\n')
|
||||
.nth(/*n*/ 2)
|
||||
.unwrap();
|
||||
let event: Value = payload.parse().unwrap();
|
||||
assert_eq!(
|
||||
event["tags"]["reason"].as_str().unwrap().chars().count(),
|
||||
200
|
||||
);
|
||||
let title = format!("[Bug]: Codex session {}", snapshot.thread_id);
|
||||
let expected_tags = to_value(BTreeMap::from([
|
||||
("thread_id".to_string(), snapshot.thread_id),
|
||||
("classification".to_string(), "bug".to_string()),
|
||||
(
|
||||
"cli_version".to_string(),
|
||||
env!("CARGO_PKG_VERSION").to_string(),
|
||||
),
|
||||
(
|
||||
"reason".to_string(),
|
||||
format!("first second {}", "界🌍".repeat(93)),
|
||||
),
|
||||
]))
|
||||
.unwrap();
|
||||
let expected_exception = to_value(Values::from(vec![Exception {
|
||||
ty: title,
|
||||
value: Some(reason),
|
||||
..Default::default()
|
||||
}]))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(&event["tags"], &event["exception"]),
|
||||
(&expected_tags, &expected_exception)
|
||||
);
|
||||
}
|
||||
157
codex-rs/feedback/src/guardian.rs
Normal file
157
codex-rs/feedback/src/guardian.rs
Normal file
@@ -0,0 +1,157 @@
|
||||
//! Bounded durable failed-review evidence, with an in-memory fallback for storage failures.
|
||||
//! Captures are exported only by a feedback request that includes logs.
|
||||
|
||||
use crate::FeedbackAttachment;
|
||||
use codex_protocol::ThreadId;
|
||||
pub use codex_state::GuardianReviewRecord;
|
||||
use codex_state::MAX_GUARDIAN_REVIEW_BYTES as MAX_BYTES;
|
||||
use codex_state::MAX_GUARDIAN_REVIEW_RECORDS as MAX_RECORDS;
|
||||
use codex_state::MAX_GUARDIAN_REVIEW_RECORDS_PER_THREAD as MAX_RECORDS_PER_THREAD;
|
||||
use codex_state::StateRuntime;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
const PERSIST_TIMEOUT: Duration = Duration::from_millis(250);
|
||||
|
||||
static RECORDS: Mutex<ReviewRecords> = Mutex::new(ReviewRecords {
|
||||
records: VecDeque::new(),
|
||||
bytes: 0,
|
||||
discarded_records: 0,
|
||||
});
|
||||
|
||||
/// A consistent snapshot of retained failures and their owning threads.
|
||||
pub struct GuardianReviewFailures {
|
||||
pub attachment: Option<FeedbackAttachment>,
|
||||
/// Unique threads, ordered by most recently retained failure first.
|
||||
pub thread_ids: Vec<ThreadId>,
|
||||
/// Process-wide evictions or oversized records, not a count for this task tree.
|
||||
pub process_discarded_records: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct ReviewRecords {
|
||||
records: VecDeque<GuardianReviewRecord>,
|
||||
bytes: usize,
|
||||
discarded_records: usize,
|
||||
}
|
||||
|
||||
impl ReviewRecords {
|
||||
fn push(&mut self, record: GuardianReviewRecord) {
|
||||
if record.record.len() + 1 > MAX_BYTES {
|
||||
self.discarded_records = self.discarded_records.saturating_add(1);
|
||||
return;
|
||||
}
|
||||
if self
|
||||
.records
|
||||
.iter()
|
||||
.filter(|entry| entry.thread_id == record.thread_id)
|
||||
.count()
|
||||
>= MAX_RECORDS_PER_THREAD
|
||||
&& let Some(index) = self
|
||||
.records
|
||||
.iter()
|
||||
.position(|entry| entry.thread_id == record.thread_id)
|
||||
&& let Some(removed) = self.records.remove(index)
|
||||
{
|
||||
self.bytes -= removed.record.len() + 1;
|
||||
self.discarded_records = self.discarded_records.saturating_add(1);
|
||||
}
|
||||
while self.records.len() >= MAX_RECORDS || self.bytes + record.record.len() + 1 > MAX_BYTES
|
||||
{
|
||||
if let Some(removed) = self.records.pop_front() {
|
||||
self.bytes -= removed.record.len() + 1;
|
||||
self.discarded_records = self.discarded_records.saturating_add(1);
|
||||
}
|
||||
}
|
||||
self.bytes += record.record.len() + 1;
|
||||
self.records.push_back(record);
|
||||
}
|
||||
|
||||
fn snapshot(&self, thread_ids: &[ThreadId]) -> GuardianReviewFailures {
|
||||
let thread_ids = thread_ids.iter().copied().collect::<HashSet<_>>();
|
||||
let mut buffer = Vec::new();
|
||||
for record in &self.records {
|
||||
if thread_ids.contains(&record.thread_id) {
|
||||
buffer.extend_from_slice(&record.record);
|
||||
buffer.push(b'\n');
|
||||
}
|
||||
}
|
||||
let attachment = (!buffer.is_empty()).then_some(FeedbackAttachment {
|
||||
filename: "auto-review-failures.jsonl".to_string(),
|
||||
buffer,
|
||||
content_type: Some("application/x-ndjson".to_string()),
|
||||
});
|
||||
let mut seen = HashSet::new();
|
||||
let thread_ids = self
|
||||
.records
|
||||
.iter()
|
||||
.rev()
|
||||
.filter(|record| {
|
||||
thread_ids.contains(&record.thread_id) && seen.insert(record.thread_id)
|
||||
})
|
||||
.map(|record| record.thread_id)
|
||||
.collect();
|
||||
GuardianReviewFailures {
|
||||
attachment,
|
||||
thread_ids,
|
||||
process_discarded_records: self.discarded_records,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Retain a failed review in memory and persist it before its session is cleaned up.
|
||||
pub async fn record_guardian_review_failure(
|
||||
state_db: Option<&StateRuntime>,
|
||||
record: GuardianReviewRecord,
|
||||
) {
|
||||
RECORDS
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push(record.clone());
|
||||
if let Some(state_db) = state_db
|
||||
&& !matches!(
|
||||
tokio::time::timeout(
|
||||
PERSIST_TIMEOUT,
|
||||
state_db.record_guardian_review_failure(&record)
|
||||
)
|
||||
.await,
|
||||
Ok(Ok(()))
|
||||
)
|
||||
{
|
||||
tracing::warn!("failed to persist Guardian feedback; retaining an in-memory fallback");
|
||||
}
|
||||
}
|
||||
|
||||
/// Recover retained failures before selecting rollout attachments, scoped to the reported task tree.
|
||||
pub async fn guardian_review_failures(
|
||||
state_db: Option<&StateRuntime>,
|
||||
thread_ids: &[ThreadId],
|
||||
) -> GuardianReviewFailures {
|
||||
let fallback = RECORDS
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone();
|
||||
let Some(state_db) = state_db else {
|
||||
return fallback.snapshot(thread_ids);
|
||||
};
|
||||
let Ok(mut records) = state_db.list_guardian_review_records().await else {
|
||||
tracing::warn!("failed to load persisted Guardian feedback");
|
||||
return fallback.snapshot(thread_ids);
|
||||
};
|
||||
records.extend(fallback.records);
|
||||
records.sort_unstable_by(|left, right| left.id.cmp(&right.id));
|
||||
records.dedup_by(|left, right| left.id == right.id);
|
||||
let mut retained = ReviewRecords::default();
|
||||
for record in records {
|
||||
retained.push(record);
|
||||
}
|
||||
// This legacy diagnostic describes only the in-memory fallback, not durable evictions.
|
||||
retained.discarded_records = fallback.discarded_records;
|
||||
retained.snapshot(thread_ids)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "guardian_tests.rs"]
|
||||
mod tests;
|
||||
90
codex-rs/feedback/src/guardian_tests.rs
Normal file
90
codex-rs/feedback/src/guardian_tests.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn records_keep_recent_failures_and_select_the_requested_tree() {
|
||||
let mut records = ReviewRecords::default();
|
||||
let root = ThreadId::new();
|
||||
let child = ThreadId::new();
|
||||
let unrelated = ThreadId::new();
|
||||
records.push(GuardianReviewRecord::new(
|
||||
child,
|
||||
br#"{"child":"denied"}"#.to_vec(),
|
||||
));
|
||||
records.push(GuardianReviewRecord::new(
|
||||
unrelated,
|
||||
br#"{"unrelated":"denied"}"#.to_vec(),
|
||||
));
|
||||
for index in 0..12 {
|
||||
records.push(GuardianReviewRecord::new(
|
||||
root,
|
||||
format!(r#"{{"root":{index}}}"#).into_bytes(),
|
||||
));
|
||||
}
|
||||
let snapshot = records.snapshot(&[root, child]);
|
||||
let attachment = snapshot.attachment.expect("task-tree records");
|
||||
let expected = std::iter::once("{\"child\":\"denied\"}\n".to_string())
|
||||
.chain((4..12).map(|index| format!("{{\"root\":{index}}}\n")))
|
||||
.collect::<String>();
|
||||
assert_eq!(attachment.buffer, expected.into_bytes());
|
||||
assert_eq!(snapshot.thread_ids, vec![root, child]);
|
||||
assert_eq!(snapshot.process_discarded_records, 4);
|
||||
let unrelated_snapshot = records.snapshot(&[unrelated]);
|
||||
assert_eq!(unrelated_snapshot.thread_ids, vec![unrelated]);
|
||||
// The diagnostic counter must not be mistaken for tree-specific omissions.
|
||||
assert_eq!(unrelated_snapshot.process_discarded_records, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_count_and_bytes_are_bounded_across_threads() {
|
||||
let mut records = ReviewRecords::default();
|
||||
for _ in 0..MAX_RECORDS + 1 {
|
||||
records.push(GuardianReviewRecord::new(ThreadId::new(), b"{}".to_vec()));
|
||||
}
|
||||
assert_eq!(records.records.len(), MAX_RECORDS);
|
||||
let payload = vec![b' '; MAX_BYTES / 3];
|
||||
let thread_id = ThreadId::new();
|
||||
for _ in 0..4 {
|
||||
records.push(GuardianReviewRecord::new(thread_id, payload.clone()));
|
||||
}
|
||||
assert!(records.bytes <= MAX_BYTES);
|
||||
assert_eq!(records.records.len(), 2);
|
||||
assert_eq!(
|
||||
records
|
||||
.snapshot(&[thread_id])
|
||||
.attachment
|
||||
.expect("bounded records")
|
||||
.buffer
|
||||
.len(),
|
||||
2 * (payload.len() + 1)
|
||||
);
|
||||
assert_eq!(records.discarded_records, MAX_RECORDS + 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn busy_storage_retains_feedback_without_delaying_review_completion() -> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let sqlite = codex_state::SqliteConfig::new_for_testing(home.path().try_into()?);
|
||||
let state = StateRuntime::init(sqlite.clone(), "test".to_string()).await?;
|
||||
let thread_id = ThreadId::new();
|
||||
let pool = sqlite.open_read_write_pool(&sqlite.state_db_path()).await?;
|
||||
let transaction = pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 1),
|
||||
record_guardian_review_failure(
|
||||
Some(&state),
|
||||
GuardianReviewRecord::new(thread_id, br#"{"fallback":true}"#.to_vec()),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
transaction.rollback().await?;
|
||||
let snapshot = guardian_review_failures(Some(&state), &[thread_id]).await;
|
||||
assert_eq!(snapshot.thread_ids, vec![thread_id]);
|
||||
assert_eq!(
|
||||
snapshot.attachment.unwrap().buffer,
|
||||
b"{\"fallback\":true}\n"
|
||||
);
|
||||
pool.close().await;
|
||||
state.close().await;
|
||||
Ok(())
|
||||
}
|
||||
1073
codex-rs/feedback/src/lib.rs
Normal file
1073
codex-rs/feedback/src/lib.rs
Normal file
File diff suppressed because it is too large
Load Diff
833
codex-rs/feedback/src/lib_tests.rs
Normal file
833
codex-rs/feedback/src/lib_tests.rs
Normal file
@@ -0,0 +1,833 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! Unit tests for the crate and its related test suites.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
use crate::FeedbackDiagnostic;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use flate2::Compression;
|
||||
use flate2::read::GzDecoder;
|
||||
use flate2::write::GzEncoder;
|
||||
use http::StatusCode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::header_exists;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[test]
|
||||
fn ring_buffer_drops_front_when_full() {
|
||||
let fb = CodexFeedback::with_capacity(/*max_bytes*/ 8);
|
||||
{
|
||||
let mut w = fb.make_writer().make_writer();
|
||||
w.write_all(b"abcdefgh").unwrap();
|
||||
w.write_all(b"ij").unwrap();
|
||||
}
|
||||
let snap = fb.snapshot(/*session_id*/ None);
|
||||
// Capacity 8: after writing 10 bytes, we should keep the last 8.
|
||||
pretty_assertions::assert_eq!(std::str::from_utf8(&snap.bytes).unwrap(), "cdefghij");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logger_layer_filters_noisy_trace_payloads() {
|
||||
let fb = CodexFeedback::new();
|
||||
let _guard = tracing_subscriber::registry()
|
||||
// Keep another TRACE subscriber interested so bridged records are
|
||||
// emitted; feedback must still reject them with its own filter.
|
||||
.with(tracing_subscriber::fmt::layer().with_writer(std::io::sink))
|
||||
.with(fb.logger_layer())
|
||||
.set_default();
|
||||
|
||||
tracing::trace!(target: "codex_api::responses_websocket_timing", payload = "secret");
|
||||
tracing::event!(
|
||||
target: "codex_otel.log_only", tracing::Level::INFO,
|
||||
event.name = "codex.agent_response", response = "private-agent-response"
|
||||
);
|
||||
tracing::info!(target: "codex_otel.log_only", rationale = "private-guardian-rationale");
|
||||
tracing::trace!(target: "codex_http_client::transport", "transport-trace");
|
||||
tracing::trace!(target: "codex_api::sse", "sse-trace");
|
||||
tracing::trace!(target: "codex_api::sse::responses", "nested-sse-trace");
|
||||
tracing::debug!(target: "codex_http_client::transport", "transport-debug");
|
||||
tracing::debug!(target: "codex_api::sse::responses", "sse-debug");
|
||||
tracing::trace!(target: "codex_feedback_test", "unrelated-trace");
|
||||
log::trace!(target: "codex_feedback_test", "unrelated-log-trace");
|
||||
log::trace!(
|
||||
target: "tungstenite::handshake::client",
|
||||
"websocket-handshake-payload"
|
||||
);
|
||||
log::trace!(target: "tungstenite::protocol", "websocket-frame-payload");
|
||||
log::debug!(target: "tungstenite::protocol", "websocket-debug");
|
||||
|
||||
let logs = String::from_utf8(fb.snapshot(/*session_id*/ None).bytes).unwrap();
|
||||
for excluded in [
|
||||
"secret",
|
||||
"private-agent-response",
|
||||
"private-guardian-rationale",
|
||||
"transport-trace",
|
||||
"sse-trace",
|
||||
"nested-sse-trace",
|
||||
"websocket-handshake-payload",
|
||||
"websocket-frame-payload",
|
||||
] {
|
||||
assert!(!logs.contains(excluded));
|
||||
}
|
||||
for retained in [
|
||||
"transport-debug",
|
||||
"sse-debug",
|
||||
"unrelated-trace",
|
||||
"unrelated-log-trace",
|
||||
"websocket-debug",
|
||||
] {
|
||||
assert!(logs.contains(retained));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_layer_records_tags_from_feedback_target() {
|
||||
let fb = CodexFeedback::new();
|
||||
let _guard = tracing_subscriber::registry()
|
||||
.with(fb.metadata_layer())
|
||||
.set_default();
|
||||
|
||||
tracing::info!(target: FEEDBACK_TAGS_TARGET, model = "gpt-5", cached = true, "tags");
|
||||
|
||||
let snap = fb.snapshot(/*session_id*/ None);
|
||||
pretty_assertions::assert_eq!(snap.tags.get("model").map(String::as_str), Some("gpt-5"));
|
||||
pretty_assertions::assert_eq!(snap.tags.get("cached").map(String::as_str), Some("true"));
|
||||
}
|
||||
|
||||
async fn upload_test_feedback(
|
||||
feedback: &CodexFeedback,
|
||||
dsn: &str,
|
||||
extra_attachments: Vec<FeedbackAttachment>,
|
||||
) -> Result<()> {
|
||||
feedback
|
||||
.snapshot(/*session_id*/ None)
|
||||
.with_feedback_diagnostics(FeedbackDiagnostics::default())
|
||||
.upload_feedback_with_dsn(
|
||||
FeedbackUploadOptions {
|
||||
classification: "bug",
|
||||
reason: Some("private feedback"),
|
||||
tags: None,
|
||||
include_logs: true,
|
||||
extra_attachments,
|
||||
extra_attachment_paths: &[],
|
||||
session_source: Some(SessionSource::Cli),
|
||||
logs_override: Some(b"private log contents".to_vec()),
|
||||
},
|
||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
dsn,
|
||||
Instant::now() + UPLOAD_TIMEOUT,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_upload_allows_slow_reports() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/42/envelope/"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(StatusCode::OK).set_delay(Duration::from_secs(/*secs*/ 4)),
|
||||
)
|
||||
.expect(/*r*/ 3)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let dsn = format!("http://public@{}/42", server.address());
|
||||
let attachment = FeedbackAttachment {
|
||||
filename: "later.txt".to_string(),
|
||||
content_type: None,
|
||||
buffer: b"later diagnostic".to_vec(),
|
||||
};
|
||||
upload_test_feedback(&CodexFeedback::new(), &dsn, vec![attachment])
|
||||
.await
|
||||
.expect("all three envelopes should finish across twelve seconds of network waits");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_upload_deadline_stops_retries_and_later_attachments() {
|
||||
let server = MockServer::start().await;
|
||||
let attempt = AtomicUsize::default();
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/42/envelope/"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
match attempt.fetch_add(/*val*/ 1, Ordering::SeqCst) {
|
||||
0 | 2 => ResponseTemplate::new(StatusCode::OK)
|
||||
.set_delay(Duration::from_secs(/*secs*/ 1)),
|
||||
1 => ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE)
|
||||
.set_delay(Duration::from_secs(/*secs*/ 1)),
|
||||
_ => ResponseTemplate::new(StatusCode::OK)
|
||||
.set_delay(Duration::from_secs(/*secs*/ 20)),
|
||||
}
|
||||
})
|
||||
.expect(/*r*/ 4)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let dsn = format!("http://public@{}/42", server.address());
|
||||
let attachments = ["stalled.txt", "later.txt"].map(|filename| FeedbackAttachment {
|
||||
filename: filename.to_string(),
|
||||
content_type: None,
|
||||
buffer: filename.as_bytes().to_vec(),
|
||||
});
|
||||
let snapshot = CodexFeedback::new()
|
||||
.snapshot(/*session_id*/ None)
|
||||
.with_feedback_diagnostics(FeedbackDiagnostics::default());
|
||||
let error = tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 10),
|
||||
snapshot.upload_feedback_with_dsn(
|
||||
FeedbackUploadOptions {
|
||||
classification: "bug",
|
||||
reason: None,
|
||||
tags: None,
|
||||
include_logs: true,
|
||||
extra_attachments: attachments.into(),
|
||||
extra_attachment_paths: &[],
|
||||
session_source: Some(SessionSource::Cli),
|
||||
logs_override: Some(b"log contents".to_vec()),
|
||||
},
|
||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
&dsn,
|
||||
Instant::now() + Duration::from_secs(/*secs*/ 8),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("each request must use only the time left in the report deadline")
|
||||
.expect_err("the accepted report must report incomplete attachments");
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"feedback report was accepted, but some attachments failed to upload"
|
||||
);
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 4);
|
||||
assert_eq!(requests[1].body, requests[2].body);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_upload_retries_diagnostics_without_replaying_core() {
|
||||
let server = MockServer::start().await;
|
||||
let attempt = AtomicUsize::default();
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/42/envelope/"))
|
||||
.and(header_exists("X-Sentry-Auth"))
|
||||
.and(header("Content-Encoding", "gzip"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
match attempt.fetch_add(/*val*/ 1, Ordering::SeqCst) {
|
||||
// Accept the core once; accept logs only on their second attempt.
|
||||
0 => ResponseTemplate::new(StatusCode::OK).insert_header(
|
||||
"X-Sentry-Rate-Limits",
|
||||
"0:attachment:project,60:transaction:project",
|
||||
),
|
||||
2 => ResponseTemplate::new(StatusCode::OK).insert_header("Retry-After", "0"),
|
||||
6 => ResponseTemplate::new(StatusCode::OK)
|
||||
.insert_header("X-Sentry-Rate-Limits", "60:transaction:project"),
|
||||
1 => ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE)
|
||||
.insert_header("Retry-After", "2"),
|
||||
5 => ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE)
|
||||
.insert_header("Retry-After", "8"),
|
||||
_ => ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE)
|
||||
.insert_header("Retry-After", "0"),
|
||||
}
|
||||
})
|
||||
.expect(/*r*/ 7)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let dsn = format!("http://public@{}/42", server.address());
|
||||
let attachments = ["retry-exhausted.txt", "later.txt"].map(|filename| FeedbackAttachment {
|
||||
filename: filename.to_string(),
|
||||
content_type: Some("text/plain".to_string()),
|
||||
buffer: filename.as_bytes().to_vec(),
|
||||
});
|
||||
let started = Instant::now();
|
||||
upload_test_feedback(&CodexFeedback::new(), &dsn, attachments.into())
|
||||
.await
|
||||
.expect_err("legacy uploads report incomplete diagnostics");
|
||||
assert!(started.elapsed() >= Duration::from_secs(2));
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(
|
||||
requests[1].body, requests[2].body,
|
||||
"retry exact request bytes"
|
||||
);
|
||||
// Exhausting one diagnostic must not delay later.txt or replay earlier files.
|
||||
assert!(
|
||||
requests[3..6]
|
||||
.iter()
|
||||
.all(|request| request.body == requests[3].body)
|
||||
);
|
||||
let mut decoded = String::new();
|
||||
GzDecoder::new(requests[1].body.as_slice())
|
||||
.read_to_string(&mut decoded)
|
||||
.unwrap();
|
||||
assert!(decoded.ends_with("private log contents\n"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_upload_delivers_large_files_intact() {
|
||||
let suffix = ThreadId::new();
|
||||
let first_path = std::env::temp_dir().join(format!("feedback-first-{suffix}.jsonl"));
|
||||
let second_path = std::env::temp_dir().join(format!("feedback-second-{suffix}.jsonl"));
|
||||
let binary_path = std::env::temp_dir().join(format!("feedback-archive-{suffix}.jsonl.gz"));
|
||||
let pending_path = second_path.with_extension("pending");
|
||||
let block = "{\"type\":\"event_msg\",\"payload\":{\"type\":\"agent_message\",\"message\":\"diagnostic fixture 🍵\"}}\n"
|
||||
.repeat(1024);
|
||||
let block_counts = [65, 80].map(|mib| mib * 1024 * 1024 / block.len() + 1);
|
||||
for (path, blocks) in [&first_path, &pending_path].into_iter().zip(block_counts) {
|
||||
let mut file = fs::File::create(path).unwrap();
|
||||
for _ in 0..blocks {
|
||||
file.write_all(block.as_bytes()).unwrap();
|
||||
}
|
||||
}
|
||||
// Repeats beyond gzip's window keep the archive above the former 38.1 MiB cap.
|
||||
let record_block = (0..4096)
|
||||
.flat_map(|_| sentry::types::Uuid::new_v4().into_bytes())
|
||||
.map(|byte| {
|
||||
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
||||
[usize::from(byte % 64)]
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut file = GzEncoder::new(fs::File::create(&binary_path).unwrap(), Compression::fast());
|
||||
for mib in [32, 30] {
|
||||
file.write_all(b"{\"message\":\"").unwrap();
|
||||
for _ in 0..mib * 1024 * 1024 / record_block.len() {
|
||||
file.write_all(&record_block).unwrap();
|
||||
}
|
||||
file.write_all(b"\"}\n").unwrap();
|
||||
}
|
||||
file.finish().unwrap();
|
||||
assert!(fs::metadata(&binary_path).unwrap().len() > 40_000_000);
|
||||
|
||||
let server = MockServer::start().await;
|
||||
let attempt = AtomicUsize::default();
|
||||
let ready_path = second_path.clone();
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/42/envelope/"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
if attempt.fetch_add(/*val*/ 1, Ordering::SeqCst) == 1 {
|
||||
// The next file becomes readable only after the first file arrives.
|
||||
fs::rename(&pending_path, &ready_path).unwrap();
|
||||
}
|
||||
ResponseTemplate::new(StatusCode::OK)
|
||||
})
|
||||
.expect(/*r*/ 4)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
CodexFeedback::new()
|
||||
.snapshot(/*session_id*/ None)
|
||||
.upload_feedback_with_dsn(
|
||||
FeedbackUploadOptions {
|
||||
classification: "bug",
|
||||
reason: Some("large diagnostic upload"),
|
||||
tags: None,
|
||||
include_logs: false,
|
||||
extra_attachments: Vec::new(),
|
||||
extra_attachment_paths: &[
|
||||
FeedbackAttachmentPath {
|
||||
path: first_path.clone(),
|
||||
attachment_filename_override: None,
|
||||
},
|
||||
FeedbackAttachmentPath {
|
||||
path: second_path.clone(),
|
||||
attachment_filename_override: None,
|
||||
},
|
||||
FeedbackAttachmentPath {
|
||||
path: binary_path.clone(),
|
||||
attachment_filename_override: None,
|
||||
},
|
||||
],
|
||||
session_source: Some(SessionSource::Cli),
|
||||
logs_override: None,
|
||||
},
|
||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
&format!("http://public@{}/42", server.address()),
|
||||
Instant::now() + UPLOAD_TIMEOUT,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 4);
|
||||
let mut event = String::new();
|
||||
GzDecoder::new(requests[0].body.as_slice())
|
||||
.read_to_string(&mut event)
|
||||
.unwrap();
|
||||
for (request, (filename, source_path)) in requests[1..].iter().zip([
|
||||
(format!("feedback-first-{suffix}.jsonl"), &first_path),
|
||||
(format!("feedback-second-{suffix}.jsonl"), &second_path),
|
||||
(format!("feedback-archive-{suffix}.jsonl.gz"), &binary_path),
|
||||
]) {
|
||||
let mut decoded = Vec::new();
|
||||
if request.headers.contains_key("Content-Encoding") {
|
||||
GzDecoder::new(request.body.as_slice())
|
||||
.read_to_end(&mut decoded)
|
||||
.unwrap();
|
||||
} else {
|
||||
decoded.extend_from_slice(&request.body);
|
||||
}
|
||||
assert!(decoded.len() <= MAX_DECODED_UPLOAD_BYTES);
|
||||
let mut parts = decoded.splitn(3, |byte| *byte == b'\n');
|
||||
assert_eq!(
|
||||
parts.next().unwrap(),
|
||||
event.lines().next().unwrap().as_bytes()
|
||||
);
|
||||
let header = std::str::from_utf8(parts.next().unwrap()).unwrap();
|
||||
assert!(header.contains(&format!("\"filename\":\"{filename}\"")));
|
||||
let payload = parts.next().unwrap().strip_suffix(b"\n").unwrap();
|
||||
let mut source = fs::File::open(source_path).unwrap();
|
||||
let original_bytes = source.metadata().unwrap().len() as usize;
|
||||
assert_eq!(payload.len(), original_bytes);
|
||||
if filename.ends_with(".jsonl") {
|
||||
let text = std::str::from_utf8(payload).unwrap();
|
||||
assert!(text.ends_with('\n'));
|
||||
} else {
|
||||
let mut archive = GzDecoder::new(payload);
|
||||
io::copy(&mut archive, &mut io::sink()).expect("received archive must be intact");
|
||||
}
|
||||
let mut expected = [0; 64 * 1024];
|
||||
for chunk in payload.chunks(expected.len()) {
|
||||
source.read_exact(&mut expected[..chunk.len()]).unwrap();
|
||||
assert_eq!(chunk, &expected[..chunk.len()]);
|
||||
}
|
||||
}
|
||||
fs::remove_file(first_path).unwrap();
|
||||
fs::remove_file(second_path).unwrap();
|
||||
fs::remove_file(binary_path).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_upload_reports_unreadable_or_oversized_attachments() {
|
||||
let oversized_path =
|
||||
std::env::temp_dir().join(format!("feedback-oversized-{}", ThreadId::new()));
|
||||
fs::File::create(&oversized_path)
|
||||
.unwrap()
|
||||
.set_len(MAX_DECODED_UPLOAD_BYTES as u64 + 1)
|
||||
.unwrap();
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.respond_with(ResponseTemplate::new(StatusCode::OK))
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
for path in [
|
||||
oversized_path.clone(),
|
||||
oversized_path.with_extension("missing"),
|
||||
] {
|
||||
let result = CodexFeedback::new()
|
||||
.snapshot(/*session_id*/ None)
|
||||
.upload_feedback_with_dsn(
|
||||
FeedbackUploadOptions {
|
||||
classification: "bug",
|
||||
reason: None,
|
||||
tags: None,
|
||||
include_logs: false,
|
||||
extra_attachments: Vec::new(),
|
||||
extra_attachment_paths: &[FeedbackAttachmentPath {
|
||||
path,
|
||||
attachment_filename_override: None,
|
||||
}],
|
||||
session_source: Some(SessionSource::Cli),
|
||||
logs_override: None,
|
||||
},
|
||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
&format!("http://public@{}/42", server.address()),
|
||||
Instant::now() + UPLOAD_TIMEOUT,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
result.unwrap_err().to_string(),
|
||||
"feedback report was accepted, but some attachments failed to upload"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
fs::metadata(&oversized_path).unwrap().len(),
|
||||
MAX_DECODED_UPLOAD_BYTES as u64 + 1
|
||||
);
|
||||
fs::remove_file(oversized_path).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_upload_stops_diagnostics_for_sentry_rate_limits() {
|
||||
for (accepted_before_limit, rate_limit) in [
|
||||
(1, ResponseTemplate::new(StatusCode::TOO_MANY_REQUESTS)),
|
||||
(
|
||||
1,
|
||||
ResponseTemplate::new(StatusCode::TOO_MANY_REQUESTS)
|
||||
.insert_header("X-Sentry-Rate-Limits", "60:attachment:project")
|
||||
.insert_header("Retry-After", "0"),
|
||||
),
|
||||
(
|
||||
0,
|
||||
ResponseTemplate::new(StatusCode::OK)
|
||||
.insert_header("X-Sentry-Rate-Limits", "60:attachment:project"),
|
||||
),
|
||||
(
|
||||
1,
|
||||
ResponseTemplate::new(StatusCode::OK)
|
||||
.insert_header("X-Sentry-Rate-Limits", "60::project"),
|
||||
),
|
||||
(
|
||||
0,
|
||||
ResponseTemplate::new(StatusCode::OK).insert_header("Retry-After", "60"),
|
||||
),
|
||||
(
|
||||
1,
|
||||
ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE)
|
||||
.insert_header("Retry-After", "300"),
|
||||
),
|
||||
(
|
||||
1,
|
||||
ResponseTemplate::new(StatusCode::SERVICE_UNAVAILABLE)
|
||||
.insert_header("Retry-After", "invalid"),
|
||||
),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
let attempt = AtomicUsize::default();
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/42/envelope/"))
|
||||
.respond_with(move |_: &wiremock::Request| {
|
||||
if attempt.fetch_add(/*val*/ 1, Ordering::SeqCst) < accepted_before_limit {
|
||||
ResponseTemplate::new(StatusCode::OK)
|
||||
} else {
|
||||
rate_limit.clone()
|
||||
}
|
||||
})
|
||||
.expect((accepted_before_limit + 1) as u64)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let dsn = format!("http://public@{}/42", server.address());
|
||||
let later = FeedbackAttachment {
|
||||
filename: "later.txt".to_string(),
|
||||
content_type: None,
|
||||
buffer: b"later diagnostic".to_vec(),
|
||||
};
|
||||
upload_test_feedback(&CodexFeedback::new(), &dsn, vec![later])
|
||||
.await
|
||||
.expect_err("legacy uploads report rate-limited diagnostics");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_upload_reports_rejected_sentry_response_without_exposing_feedback() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/42/envelope/"))
|
||||
.respond_with(ResponseTemplate::new(503))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let feedback = CodexFeedback::new();
|
||||
let dsn = format!("http://public@{}/42", server.address());
|
||||
|
||||
let error = upload_test_feedback(&feedback, &dsn, Vec::new())
|
||||
.await
|
||||
.expect_err("rejected Sentry responses must fail feedback uploads");
|
||||
|
||||
let error = format!("{error:#}");
|
||||
assert!(error.contains("503"));
|
||||
assert!(!error.contains("private feedback"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_upload_does_not_forward_private_data_to_redirect_target() {
|
||||
let sentry_server = MockServer::start().await;
|
||||
let redirect_target = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/42/envelope/"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(307)
|
||||
.insert_header("Location", format!("{}/capture", redirect_target.uri())),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&sentry_server)
|
||||
.await;
|
||||
let dsn = format!("http://public@{}/42", sentry_server.address());
|
||||
let error = upload_test_feedback(&CodexFeedback::new(), &dsn, Vec::new())
|
||||
.await
|
||||
.expect_err("redirected feedback uploads must be rejected");
|
||||
|
||||
assert!(error.to_string().contains("307"));
|
||||
assert!(
|
||||
redirect_target
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("redirect target should record requests")
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_upload_reports_transport_failures() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0")
|
||||
.expect("unused local address should be available");
|
||||
let address = listener
|
||||
.local_addr()
|
||||
.expect("listener should have an address");
|
||||
drop(listener);
|
||||
|
||||
let dsn = format!("http://public@{address}/42");
|
||||
let error = upload_test_feedback(&CodexFeedback::new(), &dsn, Vec::new())
|
||||
.await
|
||||
.expect_err("transport failures must fail feedback uploads");
|
||||
|
||||
assert!(
|
||||
error
|
||||
.downcast_ref::<codex_http_client::RouteAwareRequestError>()
|
||||
.is_some_and(codex_http_client::RouteAwareRequestError::is_connect)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_attachments_gate_connectivity_diagnostics() {
|
||||
let extra_filename = format!("codex-feedback-extra-{}.jsonl", ThreadId::new());
|
||||
let extra_path = std::env::temp_dir().join(&extra_filename);
|
||||
let extra_attachment_path = FeedbackAttachmentPath {
|
||||
path: extra_path.clone(),
|
||||
attachment_filename_override: None,
|
||||
};
|
||||
fs::write(&extra_path, "rollout").expect("extra attachment should be written");
|
||||
|
||||
let snapshot_with_diagnostics = CodexFeedback::new()
|
||||
.snapshot(/*session_id*/ None)
|
||||
.with_feedback_diagnostics(FeedbackDiagnostics::new(vec![FeedbackDiagnostic {
|
||||
headline: "Proxy environment variables are set and may affect connectivity."
|
||||
.to_string(),
|
||||
details: vec!["HTTPS_PROXY = https://example.com:443".to_string()],
|
||||
}]));
|
||||
|
||||
let attachments_with_diagnostics = snapshot_with_diagnostics
|
||||
.feedback_attachments(
|
||||
&sentry::protocol::EnvelopeHeaders::default(),
|
||||
/*include_logs*/ true,
|
||||
vec![FeedbackAttachment {
|
||||
filename: DOCTOR_REPORT_ATTACHMENT_FILENAME.to_string(),
|
||||
content_type: Some("application/json".to_string()),
|
||||
buffer: b"{\"overallStatus\":\"ok\"}".to_vec(),
|
||||
}],
|
||||
&[extra_attachment_path],
|
||||
Some(vec![1]),
|
||||
)
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
attachments_with_diagnostics
|
||||
.iter()
|
||||
.map(|attachment| attachment.filename.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
"codex-logs.log",
|
||||
DOCTOR_REPORT_ATTACHMENT_FILENAME,
|
||||
FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME,
|
||||
extra_filename.as_str()
|
||||
]
|
||||
);
|
||||
assert_eq!(attachments_with_diagnostics[0].buffer, vec![1]);
|
||||
assert_eq!(
|
||||
attachments_with_diagnostics[1].buffer,
|
||||
b"{\"overallStatus\":\"ok\"}".to_vec()
|
||||
);
|
||||
assert_eq!(
|
||||
attachments_with_diagnostics[2].buffer,
|
||||
b"Connectivity diagnostics\n\n- Proxy environment variables are set and may affect connectivity.\n - HTTPS_PROXY = https://example.com:443".to_vec()
|
||||
);
|
||||
assert_eq!(attachments_with_diagnostics[3].buffer, b"rollout".to_vec());
|
||||
assert_eq!(
|
||||
attachments_with_diagnostics[3].content_type.as_deref(),
|
||||
Some("text/plain")
|
||||
);
|
||||
assert_eq!(
|
||||
OsStr::new(attachments_with_diagnostics[3].filename.as_str()),
|
||||
OsStr::new(extra_filename.as_str())
|
||||
);
|
||||
let attachments_without_diagnostics = CodexFeedback::new()
|
||||
.snapshot(/*session_id*/ None)
|
||||
.with_feedback_diagnostics(FeedbackDiagnostics::default())
|
||||
.feedback_attachments(
|
||||
&sentry::protocol::EnvelopeHeaders::default(),
|
||||
/*include_logs*/ true,
|
||||
Vec::new(),
|
||||
&[],
|
||||
Some(vec![1]),
|
||||
)
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
attachments_without_diagnostics
|
||||
.iter()
|
||||
.map(|attachment| attachment.filename.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["codex-logs.log"]
|
||||
);
|
||||
assert_eq!(attachments_without_diagnostics[0].buffer, vec![1]);
|
||||
fs::remove_file(extra_path).expect("extra attachment should be removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_backed_attachments_use_binary_content_types() {
|
||||
let suffix = ThreadId::new();
|
||||
let gzip_filename = format!("codex-desktop-app-logs-{suffix}.tar.gz");
|
||||
let unknown_filename = format!("codex-feedback-extra-{suffix}.binunknown");
|
||||
let gzip_path = std::env::temp_dir().join(&gzip_filename);
|
||||
let unknown_path = std::env::temp_dir().join(&unknown_filename);
|
||||
let gzip_bytes = b"\x1f\x8b\x08\x00\xff";
|
||||
let unknown_bytes = b"\x00\x9f\x92\x96";
|
||||
fs::write(&gzip_path, gzip_bytes).expect("gzip attachment should be written");
|
||||
fs::write(&unknown_path, unknown_bytes).expect("unknown attachment should be written");
|
||||
|
||||
let attachments = CodexFeedback::new()
|
||||
.snapshot(/*session_id*/ None)
|
||||
.feedback_attachments(
|
||||
&sentry::protocol::EnvelopeHeaders::default(),
|
||||
/*include_logs*/ false,
|
||||
Vec::new(),
|
||||
&[
|
||||
FeedbackAttachmentPath {
|
||||
path: gzip_path.clone(),
|
||||
attachment_filename_override: None,
|
||||
},
|
||||
FeedbackAttachmentPath {
|
||||
path: unknown_path.clone(),
|
||||
attachment_filename_override: None,
|
||||
},
|
||||
],
|
||||
/*logs_override*/ None,
|
||||
)
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.unwrap();
|
||||
|
||||
fs::remove_file(gzip_path).expect("gzip attachment should be removed");
|
||||
fs::remove_file(unknown_path).expect("unknown attachment should be removed");
|
||||
assert_eq!(
|
||||
attachments
|
||||
.iter()
|
||||
.map(|attachment| (
|
||||
attachment.filename.as_str(),
|
||||
attachment.content_type.as_deref(),
|
||||
attachment.buffer.as_slice(),
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
(
|
||||
gzip_filename.as_str(),
|
||||
Some("application/gzip"),
|
||||
gzip_bytes.as_slice(),
|
||||
),
|
||||
(
|
||||
unknown_filename.as_str(),
|
||||
Some("application/octet-stream"),
|
||||
unknown_bytes.as_slice(),
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upload_tags_include_client_tags_and_preserve_reserved_fields() {
|
||||
let mut tags = BTreeMap::new();
|
||||
tags.insert("thread_id".to_string(), "wrong-thread".to_string());
|
||||
tags.insert("turn_id".to_string(), "wrong-turn".to_string());
|
||||
tags.insert(
|
||||
"classification".to_string(),
|
||||
"wrong-classification".to_string(),
|
||||
);
|
||||
tags.insert("cli_version".to_string(), "wrong-version".to_string());
|
||||
tags.insert("session_source".to_string(), "wrong-source".to_string());
|
||||
tags.insert("reason".to_string(), "wrong-reason".to_string());
|
||||
tags.insert("account_id".to_string(), "actual-account".to_string());
|
||||
tags.insert("model".to_string(), "gpt-5".to_string());
|
||||
tags.insert("effort".to_string(), "Some(High)".to_string());
|
||||
let snapshot = FeedbackSnapshot {
|
||||
bytes: Vec::new(),
|
||||
tags,
|
||||
feedback_diagnostics: FeedbackDiagnostics::default(),
|
||||
thread_id: "thread-123".to_string(),
|
||||
};
|
||||
let mut client_tags = BTreeMap::new();
|
||||
client_tags.insert("thread_id".to_string(), "wrong-client-thread".to_string());
|
||||
client_tags.insert("turn_id".to_string(), "turn-456".to_string());
|
||||
client_tags.insert(
|
||||
"classification".to_string(),
|
||||
"wrong-client-classification".to_string(),
|
||||
);
|
||||
client_tags.insert(
|
||||
"cli_version".to_string(),
|
||||
"wrong-client-version".to_string(),
|
||||
);
|
||||
client_tags.insert(
|
||||
"session_source".to_string(),
|
||||
"wrong-client-source".to_string(),
|
||||
);
|
||||
client_tags.insert("reason".to_string(), "wrong-client-reason".to_string());
|
||||
client_tags.insert("client_tag".to_string(), "from-client".to_string());
|
||||
client_tags.insert("model".to_string(), "mewthree".to_string());
|
||||
client_tags.insert("effort".to_string(), "Some(Ultra)".to_string());
|
||||
|
||||
let upload_tags = snapshot.upload_tags(
|
||||
"bug",
|
||||
Some("actual reason"),
|
||||
Some(&client_tags),
|
||||
Some(&SessionSource::Cli),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
upload_tags.get("thread_id").map(String::as_str),
|
||||
Some("thread-123")
|
||||
);
|
||||
assert_eq!(
|
||||
upload_tags.get("turn_id").map(String::as_str),
|
||||
Some("turn-456")
|
||||
);
|
||||
assert_eq!(
|
||||
upload_tags.get("classification").map(String::as_str),
|
||||
Some("bug")
|
||||
);
|
||||
assert_eq!(
|
||||
upload_tags.get("session_source").map(String::as_str),
|
||||
Some("cli")
|
||||
);
|
||||
assert_eq!(
|
||||
upload_tags.get("reason").map(String::as_str),
|
||||
Some("actual reason")
|
||||
);
|
||||
assert_eq!(
|
||||
upload_tags.get("account_id").map(String::as_str),
|
||||
Some("actual-account")
|
||||
);
|
||||
assert_eq!(
|
||||
upload_tags.get("model").map(String::as_str),
|
||||
Some("mewthree")
|
||||
);
|
||||
assert_eq!(
|
||||
upload_tags.get("effort").map(String::as_str),
|
||||
Some("Some(Ultra)")
|
||||
);
|
||||
assert_eq!(
|
||||
upload_tags.get("client_tag").map(String::as_str),
|
||||
Some("from-client")
|
||||
);
|
||||
}
|
||||
|
||||
#[path = "feedback_event_tests.rs"]
|
||||
mod feedback_event_tests;
|
||||
#[path = "metadata_tests.rs"]
|
||||
mod metadata_tests;
|
||||
#[path = "rollout_attachment_tests.rs"]
|
||||
mod rollout_attachment_tests;
|
||||
#[path = "save_rollout_tests.rs"]
|
||||
mod save_rollout_tests;
|
||||
103
codex-rs/feedback/src/metadata_tests.rs
Normal file
103
codex-rs/feedback/src/metadata_tests.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
//! Exercise dynamic tag collection, upload serialization, and bounded updates.
|
||||
|
||||
use crate::CodexFeedback;
|
||||
use crate::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use sentry::protocol::Envelope;
|
||||
use sentry::protocol::EnvelopeItem;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
|
||||
#[test]
|
||||
fn refreshing_logs_preserves_captured_metadata() {
|
||||
let feedback = CodexFeedback::new();
|
||||
let _guard = tracing_subscriber::registry()
|
||||
.with(feedback.metadata_layer())
|
||||
.set_default();
|
||||
let thread_id = ThreadId::new();
|
||||
tracing::info!(target: FEEDBACK_TAGS_TARGET, approval_policy = "on-request");
|
||||
feedback.report_failure("initial log\n");
|
||||
let mut snapshot = feedback.snapshot(Some(thread_id));
|
||||
|
||||
// Another conversation changes the process-wide tags while log collection runs.
|
||||
tracing::info!(target: FEEDBACK_TAGS_TARGET, approval_policy = "never");
|
||||
feedback.report_failure("flush failed\n");
|
||||
snapshot.refresh_logs(&feedback);
|
||||
|
||||
assert_eq!(
|
||||
(snapshot.tags, snapshot.thread_id, snapshot.bytes),
|
||||
(
|
||||
BTreeMap::from([("approval_policy".to_string(), "on-request".to_string())]),
|
||||
thread_id.to_string(),
|
||||
b"initial log\nflush failed\n".to_vec(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_tags_survive_upload_alongside_static_fields() {
|
||||
let feedback = CodexFeedback::new();
|
||||
let _guard = tracing_subscriber::registry()
|
||||
.with(feedback.metadata_layer())
|
||||
.set_default();
|
||||
let mut expected: BTreeMap<_, _> = (0..200)
|
||||
.map(|index| {
|
||||
(
|
||||
format!("feature.test_{index}"),
|
||||
(index % 2 == 0).to_string(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
expected.insert("model_context_window".to_string(), "872000".to_string());
|
||||
tracing::info!(
|
||||
target: FEEDBACK_TAGS_TARGET,
|
||||
model = "test-model",
|
||||
tags_json = ?tracing::field::display(serde_json::json!(expected)),
|
||||
);
|
||||
expected.insert("model".to_string(), "test-model".to_string());
|
||||
let snapshot = feedback.snapshot(/*session_id*/ None);
|
||||
assert_eq!(snapshot.tags, expected);
|
||||
let event = snapshot.feedback_event(
|
||||
"bug", /*reason*/ None, /*tags*/ None, /*session_source*/ None,
|
||||
);
|
||||
expected.extend([
|
||||
("thread_id".to_string(), snapshot.thread_id),
|
||||
("classification".to_string(), "bug".to_string()),
|
||||
(
|
||||
"cli_version".to_string(),
|
||||
env!("CARGO_PKG_VERSION").to_string(),
|
||||
),
|
||||
]);
|
||||
assert_eq!(event.tags, expected);
|
||||
let mut envelope = Envelope::new();
|
||||
envelope.add_item(EnvelopeItem::Event(event));
|
||||
let (_, size) = crate::upload::encode_envelope(&envelope).unwrap();
|
||||
assert!(size < crate::MAX_EVENT_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_dynamic_tags_still_update_existing_values() {
|
||||
let feedback = CodexFeedback::new();
|
||||
let _guard = tracing_subscriber::registry()
|
||||
.with(feedback.metadata_layer())
|
||||
.set_default();
|
||||
let mut expected: BTreeMap<_, _> = (0..MAX_FEEDBACK_TAGS)
|
||||
.map(|index| (format!("feature.test_{index}"), "false".to_string()))
|
||||
.collect();
|
||||
tracing::info!(target: FEEDBACK_TAGS_TARGET, tags_json = %serde_json::json!(expected));
|
||||
tracing::info!(
|
||||
target: FEEDBACK_TAGS_TARGET,
|
||||
tags_json = %serde_json::json!({
|
||||
"feature.overflow": "true",
|
||||
"feature.test_0": "true",
|
||||
}),
|
||||
);
|
||||
expected.insert("feature.test_0".to_string(), "true".to_string());
|
||||
assert_eq!(feedback.snapshot(/*session_id*/ None).tags, expected);
|
||||
tracing::info!(
|
||||
target: FEEDBACK_TAGS_TARGET,
|
||||
tags_json = %serde_json::json!({"feature.test_0": "false"}),
|
||||
);
|
||||
expected.insert("feature.test_0".to_string(), "false".to_string());
|
||||
assert_eq!(feedback.snapshot(/*session_id*/ None).tags, expected);
|
||||
}
|
||||
154
codex-rs/feedback/src/report_upload.rs
Normal file
154
codex-rs/feedback/src/report_upload.rs
Normal file
@@ -0,0 +1,154 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use http::StatusCode;
|
||||
use sentry::protocol::Attachment;
|
||||
use sentry::protocol::Envelope;
|
||||
use sentry::protocol::EnvelopeHeaders;
|
||||
use sentry::protocol::EnvelopeItem;
|
||||
use sentry::types::Dsn;
|
||||
use sentry::types::Uuid;
|
||||
|
||||
use crate::FeedbackAttachment;
|
||||
use crate::FeedbackSnapshot;
|
||||
use crate::MAX_DECODED_UPLOAD_BYTES;
|
||||
use crate::MAX_EVENT_BYTES;
|
||||
use crate::SENTRY_DSN;
|
||||
use crate::upload;
|
||||
|
||||
// Background parts must tolerate slow links without inheriting the interactive
|
||||
// upload's ten-second budget. The report API can cancel the request at any time.
|
||||
const REPORT_PART_UPLOAD_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 300);
|
||||
|
||||
/// The upstream HTTP result, not proof of durable storage in Sentry.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum FeedbackDelivery {
|
||||
Accepted {
|
||||
retry_after: Option<Duration>,
|
||||
},
|
||||
Rejected {
|
||||
status: u16,
|
||||
retry_after: Option<Duration>,
|
||||
},
|
||||
/// No response was received. The upstream may still have accepted the envelope.
|
||||
Unconfirmed,
|
||||
}
|
||||
|
||||
/// Sends persisted report parts without retries or request diagnostics.
|
||||
pub struct FeedbackTransport {
|
||||
client_pool: RouteAwareClientPool,
|
||||
dsn: Dsn,
|
||||
}
|
||||
|
||||
impl FeedbackTransport {
|
||||
pub fn new(http_client_factory: HttpClientFactory) -> Result<Self> {
|
||||
Ok(Self {
|
||||
client_pool: RouteAwareClientPool::new_without_redirects_or_request_logging(
|
||||
http_client_factory,
|
||||
ClientRouteClass::Other,
|
||||
),
|
||||
dsn: SENTRY_DSN
|
||||
.parse()
|
||||
.map_err(|_| anyhow!("invalid feedback DSN"))?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Make one attempt. Callers own retry decisions and must retain the same bytes.
|
||||
pub async fn send(&self, envelope: Vec<u8>) -> FeedbackDelivery {
|
||||
let response = upload::envelope_request(
|
||||
&self.client_pool,
|
||||
&self.dsn,
|
||||
envelope.into(),
|
||||
REPORT_PART_UPLOAD_TIMEOUT,
|
||||
)
|
||||
.send()
|
||||
.await;
|
||||
let Ok(response) = response else {
|
||||
return FeedbackDelivery::Unconfirmed;
|
||||
};
|
||||
let status = response.status();
|
||||
let headers = response.headers();
|
||||
let mut retry_after = headers
|
||||
.get_all("Retry-After")
|
||||
.iter()
|
||||
.map(|value| {
|
||||
upload::parse_retry_after(value.to_str().unwrap_or_default())
|
||||
.unwrap_or(upload::DEFAULT_RATE_LIMIT)
|
||||
})
|
||||
.max();
|
||||
// Report events and attachments share one conservative cooldown. Honor quotas on
|
||||
// successful responses too; ignore quotas for unrelated Sentry categories.
|
||||
// https://develop.sentry.dev/sdk/foundations/transport/rate-limiting/
|
||||
retry_after = retry_after.max(upload::sentry_rate_limit_delay(headers));
|
||||
if status == StatusCode::TOO_MANY_REQUESTS && retry_after.is_none() {
|
||||
retry_after = Some(upload::DEFAULT_RATE_LIMIT);
|
||||
}
|
||||
if status.is_success() {
|
||||
FeedbackDelivery::Accepted { retry_after }
|
||||
} else {
|
||||
FeedbackDelivery::Rejected {
|
||||
status: status.as_u16(),
|
||||
retry_after,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FeedbackSnapshot {
|
||||
/// Prepare only the core report, using the caller's stable UUID as its Sentry event ID.
|
||||
pub fn prepare_report_event(
|
||||
&self,
|
||||
report_id: &str,
|
||||
classification: &str,
|
||||
reason: Option<&str>,
|
||||
tags: Option<&BTreeMap<String, String>>,
|
||||
session_source: Option<&SessionSource>,
|
||||
) -> Result<Vec<u8>> {
|
||||
let mut event = self.feedback_event(classification, reason, tags, session_source);
|
||||
// Auth tags must come from this report's caller, not metadata retained
|
||||
// from an earlier account in the process-wide tracing layer.
|
||||
event.tags.retain(|key, _| {
|
||||
!matches!(key.as_str(), "account_id" | "chatgpt_user_id")
|
||||
|| tags.is_some_and(|tags| tags.contains_key(key))
|
||||
});
|
||||
event.event_id =
|
||||
Uuid::parse_str(report_id).map_err(|_| anyhow!("invalid feedback report ID"))?;
|
||||
let mut envelope = Envelope::new();
|
||||
envelope.add_item(EnvelopeItem::Event(event));
|
||||
prepare_envelope(envelope, MAX_EVENT_BYTES)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prepare one whole attachment linked to an existing report, without replaying its event.
|
||||
/// The caller must apply consent and the report's cumulative attachment budget first.
|
||||
pub fn prepare_report_attachment(
|
||||
report_id: &str,
|
||||
attachment: FeedbackAttachment,
|
||||
) -> Result<Vec<u8>> {
|
||||
let event_id = Uuid::parse_str(report_id).map_err(|_| anyhow!("invalid feedback report ID"))?;
|
||||
let mut envelope = Envelope::new().with_headers(EnvelopeHeaders::new().with_event_id(event_id));
|
||||
envelope.add_item(EnvelopeItem::Attachment(Attachment {
|
||||
buffer: attachment.buffer,
|
||||
filename: attachment.filename,
|
||||
content_type: attachment.content_type,
|
||||
ty: None,
|
||||
}));
|
||||
prepare_envelope(envelope, MAX_DECODED_UPLOAD_BYTES)
|
||||
}
|
||||
|
||||
fn prepare_envelope(envelope: Envelope, max_decoded_bytes: usize) -> Result<Vec<u8>> {
|
||||
let (bytes, decoded_bytes) =
|
||||
upload::encode_envelope(&envelope).context("failed to serialize feedback envelope")?;
|
||||
anyhow::ensure!(
|
||||
decoded_bytes <= max_decoded_bytes,
|
||||
"feedback envelope exceeds the size limit"
|
||||
);
|
||||
Ok(bytes)
|
||||
}
|
||||
148
codex-rs/feedback/src/rollout_archive.rs
Normal file
148
codex-rs/feedback/src/rollout_archive.rs
Normal file
@@ -0,0 +1,148 @@
|
||||
//! Writes selected rollouts to a bounded gzip tar at a caller-provided local path.
|
||||
//! Invalid inputs are logged and skipped; only a complete archive is published.
|
||||
//! Archive failures fall back to lazy individual attachments using the original sources.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::BufWriter;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use flate2::Compression;
|
||||
use flate2::write::GzEncoder;
|
||||
|
||||
use crate::FeedbackAttachment;
|
||||
use crate::FeedbackAttachmentPath;
|
||||
|
||||
pub(super) fn archive_rollouts<'a>(
|
||||
output_path: &Path,
|
||||
rollout_paths: impl IntoIterator<Item = &'a FeedbackAttachmentPath>,
|
||||
rollouts: impl IntoIterator<Item = &'a FeedbackAttachment>,
|
||||
max_bytes: usize,
|
||||
) -> Result<Option<FeedbackAttachmentPath>> {
|
||||
let parent = output_path
|
||||
.parent()
|
||||
.filter(|path| !path.as_os_str().is_empty())
|
||||
.unwrap_or_else(|| Path::new("."));
|
||||
fs::create_dir_all(parent).context("failed to create rollout archive directory")?;
|
||||
let file = tempfile::NamedTempFile::new_in(parent)?;
|
||||
let writer = BoundedWriter {
|
||||
inner: BufWriter::new(file),
|
||||
written: 0,
|
||||
max_bytes,
|
||||
};
|
||||
let mut archive = tar::Builder::new(GzEncoder::new(writer, Compression::default()));
|
||||
let mut filenames = HashSet::new();
|
||||
for path in rollout_paths {
|
||||
match path.read_attachment(max_bytes) {
|
||||
Ok(Some(rollout)) => append_rollout(&mut archive, &mut filenames, &rollout, max_bytes)?,
|
||||
Ok(None) => {} // The attachment reader already logs oversized or nonregular files.
|
||||
Err(error) => tracing::error!(%error, "failed to read rollout; skipping attachment"),
|
||||
}
|
||||
}
|
||||
for rollout in rollouts {
|
||||
append_rollout(&mut archive, &mut filenames, rollout, max_bytes)?;
|
||||
}
|
||||
if filenames.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let writer = archive
|
||||
.into_inner()?
|
||||
.finish()
|
||||
.context("failed to finish rollout archive")?;
|
||||
let file = writer.inner.into_inner()?;
|
||||
// Keep failed writes and incomplete gzip streams out of the destination path.
|
||||
file.persist_noclobber(output_path)?;
|
||||
Ok(Some(FeedbackAttachmentPath {
|
||||
path: output_path.to_path_buf(),
|
||||
attachment_filename_override: None,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn with_individual_fallback<'a>(
|
||||
archive: Result<Option<FeedbackAttachment>>,
|
||||
rollout_paths: Vec<&'a FeedbackAttachmentPath>,
|
||||
rollouts: Vec<FeedbackAttachment>,
|
||||
max_bytes: usize,
|
||||
) -> impl Iterator<Item = Result<FeedbackAttachment>> + 'a {
|
||||
let (archive, fallback) = match archive {
|
||||
Ok(archive) => (archive, false),
|
||||
Err(error) => {
|
||||
tracing::error!(%error, "rollout archiving failed; uploading individual attachments");
|
||||
(None, true)
|
||||
}
|
||||
};
|
||||
archive
|
||||
.into_iter()
|
||||
.map(Ok)
|
||||
.chain(fallback.then_some(rollouts).into_iter().flatten().map(Ok))
|
||||
.chain(
|
||||
fallback
|
||||
.then_some(rollout_paths)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(move |path| {
|
||||
path.read_attachment(max_bytes)?.context(
|
||||
"feedback attachment is not a regular file or exceeds the size limit",
|
||||
)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn append_rollout<W: Write>(
|
||||
archive: &mut tar::Builder<W>,
|
||||
filenames: &mut HashSet<String>,
|
||||
rollout: &FeedbackAttachment,
|
||||
max_bytes: usize,
|
||||
) -> Result<()> {
|
||||
if rollout.buffer.len() > max_bytes {
|
||||
tracing::error!(
|
||||
bytes = rollout.buffer.len(),
|
||||
max_bytes,
|
||||
"rollout skipped: size limit exceeded"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if rollout.filename.is_empty()
|
||||
|| matches!(rollout.filename.as_str(), "." | "..")
|
||||
|| rollout.filename.contains(['/', '\\', ':'])
|
||||
|| filenames.contains(&rollout.filename)
|
||||
{
|
||||
tracing::error!("rollout skipped: invalid or duplicate archive filename");
|
||||
return Ok(());
|
||||
}
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_size(rollout.buffer.len() as u64);
|
||||
header.set_mode(0o600);
|
||||
header.set_mtime(0);
|
||||
header.set_entry_type(tar::EntryType::Regular);
|
||||
archive
|
||||
.append_data(&mut header, &rollout.filename, rollout.buffer.as_slice())
|
||||
.context("failed to write rollout archive")?;
|
||||
filenames.insert(rollout.filename.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct BoundedWriter<W> {
|
||||
inner: W,
|
||||
written: usize,
|
||||
max_bytes: usize,
|
||||
}
|
||||
|
||||
impl<W: Write> Write for BoundedWriter<W> {
|
||||
fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
|
||||
if buffer.len() > self.max_bytes.saturating_sub(self.written) {
|
||||
return Err(io::Error::other("rollout archive exceeds the size limit"));
|
||||
}
|
||||
let written = self.inner.write(buffer)?;
|
||||
self.written += written;
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.inner.flush()
|
||||
}
|
||||
}
|
||||
296
codex-rs/feedback/src/rollout_attachment_tests.rs
Normal file
296
codex-rs/feedback/src/rollout_attachment_tests.rs
Normal file
@@ -0,0 +1,296 @@
|
||||
//! Exercises lazy feedback attachment reads across rollout representations.
|
||||
|
||||
use crate::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
const JSONL: &[u8] = b"{\"message\":\"old diagnostic\"}\n{\"message\":\"more details\"}\n";
|
||||
// A fixed zstd frame for JSONL; the attachment reader does not need an encoder dependency.
|
||||
const COMPRESSED: &[u8] = &[
|
||||
40, 181, 47, 253, 0, 88, 165, 1, 0, 196, 2, 123, 34, 109, 101, 115, 115, 97, 103, 101, 34, 58,
|
||||
34, 111, 108, 100, 32, 100, 105, 97, 103, 110, 111, 115, 116, 105, 99, 34, 125, 10, 109, 111,
|
||||
114, 101, 32, 100, 101, 116, 97, 105, 108, 115, 34, 125, 10, 1, 0, 1, 78, 57, 1,
|
||||
];
|
||||
|
||||
struct Fixture {
|
||||
directory: PathBuf,
|
||||
plain: PathBuf,
|
||||
compressed: PathBuf,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let thread_id = ThreadId::new();
|
||||
let directory = std::env::temp_dir().join(format!("codex-feedback-rollout-{thread_id}"));
|
||||
fs::create_dir(&directory).expect("create fixture directory");
|
||||
let plain = directory.join(format!("rollout-2026-09-09T12-00-00-{thread_id}.jsonl"));
|
||||
let compressed = plain.with_extension("jsonl.zst");
|
||||
fs::write(&compressed, COMPRESSED).expect("write compressed rollout");
|
||||
Self {
|
||||
directory,
|
||||
plain,
|
||||
compressed,
|
||||
}
|
||||
}
|
||||
|
||||
fn attachment(&self) -> FeedbackAttachmentPath {
|
||||
FeedbackAttachmentPath {
|
||||
path: self.plain.clone(),
|
||||
attachment_filename_override: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.directory);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn feedback_upload_archives_readable_rollouts_and_undecodable_sources() -> Result<()> {
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use flate2::read::GzDecoder;
|
||||
use sentry::protocol::Envelope;
|
||||
use sentry::protocol::EnvelopeItem;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
let fixture = Fixture::new();
|
||||
let damaged = Fixture::new();
|
||||
let damaged_bytes = &COMPRESSED[..10];
|
||||
fs::write(&damaged.compressed, damaged_bytes)?;
|
||||
let second_filename = format!("rollout-2026-09-09T12-00-00-{}.jsonl", ThreadId::new());
|
||||
let second_bytes = b"{\"message\":\"second rollout\"}\n";
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/42/envelope/"))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.expect(/*r*/ 2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let dsn = format!("http://public@{}/42", server.address());
|
||||
CodexFeedback::new()
|
||||
.snapshot(/*session_id*/ None)
|
||||
.with_feedback_diagnostics(FeedbackDiagnostics::default())
|
||||
.upload_feedback_with_dsn(
|
||||
FeedbackUploadOptions {
|
||||
classification: "bug",
|
||||
reason: None,
|
||||
tags: None,
|
||||
include_logs: false,
|
||||
extra_attachments: vec![FeedbackAttachment {
|
||||
filename: second_filename.clone(),
|
||||
content_type: Some("text/plain".to_string()),
|
||||
buffer: second_bytes.to_vec(),
|
||||
}],
|
||||
extra_attachment_paths: &[fixture.attachment(), damaged.attachment()],
|
||||
session_source: None,
|
||||
logs_override: None,
|
||||
},
|
||||
&HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
&dsn,
|
||||
Instant::now() + UPLOAD_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 2);
|
||||
let mut body = requests[1].body.clone();
|
||||
if body.starts_with(&[0x1f, 0x8b]) {
|
||||
let mut decoded = Vec::new();
|
||||
GzDecoder::new(body.as_slice()).read_to_end(&mut decoded)?;
|
||||
body = decoded;
|
||||
}
|
||||
let envelope = Envelope::from_slice(&body)?;
|
||||
let mut items = envelope.items();
|
||||
let Some(EnvelopeItem::Attachment(attachment)) = items.next() else {
|
||||
anyhow::bail!("expected a rollout archive attachment");
|
||||
};
|
||||
assert_eq!(attachment.filename, "rollouts.tar.gz");
|
||||
assert!(items.next().is_none());
|
||||
|
||||
let extracted = tempfile::tempdir()?;
|
||||
tar::Archive::new(GzDecoder::new(attachment.buffer.as_slice())).unpack(extracted.path())?;
|
||||
let files = fs::read_dir(extracted.path())?
|
||||
.map(|entry| {
|
||||
let entry = entry?;
|
||||
Ok((entry.file_name(), fs::read(entry.path())?))
|
||||
})
|
||||
.collect::<io::Result<BTreeMap<_, _>>>()?;
|
||||
assert_eq!(
|
||||
files,
|
||||
BTreeMap::from([
|
||||
(
|
||||
fixture.plain.file_name().unwrap().to_owned(),
|
||||
JSONL.to_vec()
|
||||
),
|
||||
(second_filename.into(), second_bytes.to_vec()),
|
||||
(
|
||||
damaged.compressed.file_name().unwrap().to_owned(),
|
||||
damaged_bytes.to_vec(),
|
||||
),
|
||||
])
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_paths_keep_canonical_names_and_filename_overrides() {
|
||||
let mut fixture = Fixture::new();
|
||||
// Reverted rollouts carry a stable thread ID and a separate immutable rollout ID.
|
||||
let plain = fixture.directory.join(format!(
|
||||
"rollout-2026-09-09T12-00-00-{}_{}.jsonl",
|
||||
ThreadId::new(),
|
||||
ThreadId::new()
|
||||
));
|
||||
let compressed = plain.with_extension("jsonl.zst");
|
||||
fs::rename(&fixture.compressed, &compressed).unwrap();
|
||||
fixture.plain = plain;
|
||||
fixture.compressed = compressed;
|
||||
|
||||
for filename_override in [None, Some("reviewer-rollout.jsonl".to_string())] {
|
||||
let path = FeedbackAttachmentPath {
|
||||
path: fixture.compressed.clone(),
|
||||
attachment_filename_override: filename_override.clone(),
|
||||
};
|
||||
let attachment = path.read_attachment(JSONL.len()).unwrap().unwrap();
|
||||
let expected_filename = filename_override.unwrap_or_else(|| {
|
||||
fixture
|
||||
.plain
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
});
|
||||
assert_eq!(
|
||||
(
|
||||
attachment.filename,
|
||||
attachment.content_type,
|
||||
attachment.buffer
|
||||
),
|
||||
(
|
||||
expected_filename,
|
||||
Some("text/plain".to_string()),
|
||||
JSONL.to_vec()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_attachment_prefers_newer_plain_sibling() {
|
||||
let fixture = Fixture::new();
|
||||
let current = b"{\"message\":\"new diagnostic\"}\n";
|
||||
fs::write(&fixture.plain, current).unwrap();
|
||||
let attachment = FeedbackAttachmentPath {
|
||||
path: fixture.compressed.clone(),
|
||||
attachment_filename_override: None,
|
||||
}
|
||||
.read_attachment(/*max_bytes*/ 1024)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(attachment.buffer, current);
|
||||
assert_eq!(fs::read(&fixture.compressed).unwrap(), COMPRESSED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_attachments_follow_both_representation_transitions() {
|
||||
let fixture = Fixture::new();
|
||||
let compressed_path = FeedbackAttachmentPath {
|
||||
path: fixture.compressed.clone(),
|
||||
attachment_filename_override: None,
|
||||
};
|
||||
// The compressed file is materialized after the attachment path was queued.
|
||||
fs::write(&fixture.plain, JSONL).unwrap();
|
||||
fs::remove_file(&fixture.compressed).unwrap();
|
||||
assert_eq!(
|
||||
compressed_path
|
||||
.read_attachment(/*max_bytes*/ 1024)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.buffer,
|
||||
JSONL
|
||||
);
|
||||
let plain_path = fixture.attachment();
|
||||
// The plain file is compressed after the attachment path was queued.
|
||||
fs::write(&fixture.compressed, COMPRESSED).unwrap();
|
||||
fs::remove_file(&fixture.plain).unwrap();
|
||||
assert_eq!(
|
||||
plain_path
|
||||
.read_attachment(/*max_bytes*/ 1024)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.buffer,
|
||||
JSONL
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compressed_attachment_bounds_decoded_bytes() {
|
||||
let fixture = Fixture::new();
|
||||
let path = fixture.attachment();
|
||||
assert!(path.read_attachment(/*max_bytes*/ 35).unwrap().is_none());
|
||||
assert_eq!(
|
||||
path.read_attachment(JSONL.len()).unwrap().unwrap().buffer,
|
||||
JSONL
|
||||
);
|
||||
assert!(!fixture.plain.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undecodable_attachment_preserves_raw_bytes_with_bounds_and_filename_override() {
|
||||
let fixture = Fixture::new();
|
||||
let damaged_bytes = &COMPRESSED[..10];
|
||||
fs::write(&fixture.compressed, damaged_bytes).unwrap();
|
||||
for path in [&fixture.plain, &fixture.compressed] {
|
||||
let attachment = FeedbackAttachmentPath {
|
||||
path: path.clone(),
|
||||
attachment_filename_override: Some("diagnostic.jsonl".to_string()),
|
||||
};
|
||||
assert!(
|
||||
attachment
|
||||
.read_attachment(damaged_bytes.len() - 1)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
let uploaded = attachment
|
||||
.read_attachment(damaged_bytes.len())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(uploaded.filename, uploaded.buffer),
|
||||
("diagnostic.jsonl.zst".to_string(), damaged_bytes.to_vec())
|
||||
);
|
||||
}
|
||||
assert_eq!(fs::read(&fixture.compressed).unwrap(), damaged_bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonregular_rollout_is_omitted_and_unrelated_zstd_attachment_stays_opaque() {
|
||||
let fixture = Fixture::new();
|
||||
fs::create_dir(&fixture.plain).unwrap();
|
||||
assert!(
|
||||
fixture
|
||||
.attachment()
|
||||
.read_attachment(/*max_bytes*/ 1024)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
let opaque_path = fixture.directory.join("diagnostics.zst");
|
||||
fs::rename(&fixture.compressed, &opaque_path).unwrap();
|
||||
let attachment = FeedbackAttachmentPath {
|
||||
path: opaque_path,
|
||||
attachment_filename_override: None,
|
||||
}
|
||||
.read_attachment(/*max_bytes*/ 1024)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(attachment.filename.as_str(), attachment.buffer.as_slice()),
|
||||
("diagnostics.zst", COMPRESSED)
|
||||
);
|
||||
}
|
||||
107
codex-rs/feedback/src/save_rollout_tests.rs
Normal file
107
codex-rs/feedback/src/save_rollout_tests.rs
Normal file
@@ -0,0 +1,107 @@
|
||||
//! Regression coverage for complete, bounded file selection during local saving.
|
||||
use crate::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn rollout_name() -> String {
|
||||
format!("rollout-2026-10-19T12-00-00-{}.jsonl", ThreadId::new())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_bounds_files_before_reading_or_compression() -> Result<()> {
|
||||
let inputs = tempfile::tempdir()?;
|
||||
let output = tempfile::tempdir()?;
|
||||
let path = inputs.path().join(rollout_name());
|
||||
fs::write(&path, vec![b' '; 1024])?;
|
||||
let path = FeedbackAttachmentPath {
|
||||
path,
|
||||
attachment_filename_override: None,
|
||||
};
|
||||
let missing = FeedbackAttachmentPath {
|
||||
path: inputs.path().join("missing"),
|
||||
attachment_filename_override: None,
|
||||
};
|
||||
for (max_bytes, max_attachments, second, expected_error) in [
|
||||
(1500, 2, &path, "decoded size limit"),
|
||||
(4096, 1, &missing, "count limit"),
|
||||
] {
|
||||
let error = archive::save(
|
||||
&output.path().join("feedback.zip"),
|
||||
b"{}",
|
||||
[
|
||||
archive::Input::Owned(FeedbackAttachment {
|
||||
filename: rollout_name(),
|
||||
content_type: None,
|
||||
buffer: vec![b' '; 1024],
|
||||
}),
|
||||
archive::Input::Path(second),
|
||||
]
|
||||
.into_iter(),
|
||||
archive::Limits {
|
||||
max_bytes,
|
||||
max_attachments,
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(format!("{error:#}").contains(expected_error), "{error:#}");
|
||||
assert_eq!(fs::read_dir(output.path())?.count(), 0);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_preserves_duplicate_names_and_rejects_missing_selected_files() -> Result<()> {
|
||||
let inputs = tempfile::tempdir()?;
|
||||
let output = tempfile::tempdir()?;
|
||||
let name = rollout_name();
|
||||
let paths = [
|
||||
inputs.path().join(&name),
|
||||
inputs.path().join("nested").join(&name),
|
||||
];
|
||||
fs::create_dir(paths[1].parent().unwrap())?;
|
||||
fs::write(&paths[0], b"first\n")?;
|
||||
fs::write(&paths[1], b"second\n")?;
|
||||
let paths = paths.map(|path| FeedbackAttachmentPath {
|
||||
path,
|
||||
attachment_filename_override: None,
|
||||
});
|
||||
let destination = output.path().join("feedback.zip");
|
||||
archive::save(
|
||||
&destination,
|
||||
b"{}",
|
||||
paths.iter().map(archive::Input::Path),
|
||||
archive::Limits::default(),
|
||||
)?;
|
||||
let mut zip = zip::ZipArchive::new(fs::File::open(&destination)?)?;
|
||||
for (index, expected) in [b"first\n".as_slice(), b"second\n"].iter().enumerate() {
|
||||
let mut actual = Vec::new();
|
||||
zip.by_name(&format!("attachments/{index:04}/{name}"))?
|
||||
.read_to_end(&mut actual)?;
|
||||
assert_eq!(&actual, expected);
|
||||
}
|
||||
drop(zip);
|
||||
fs::remove_file(&destination)?;
|
||||
fs::remove_file(&paths[1].path)?;
|
||||
let error = archive::save(
|
||||
&destination,
|
||||
b"{}",
|
||||
paths.iter().map(archive::Input::Path),
|
||||
archive::Limits::default(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(format!("{error:#}").contains("selected attachment"));
|
||||
assert_eq!(fs::read_dir(output.path())?.count(), 0);
|
||||
// Upload still uses its existing best-effort aggregation and skips the missing rollout.
|
||||
let snapshot = CodexFeedback::new().snapshot(/*session_id*/ None);
|
||||
let uploaded = snapshot
|
||||
.feedback_attachments(
|
||||
&sentry::protocol::EnvelopeHeaders::default(),
|
||||
/*include_logs*/ false,
|
||||
Vec::new(),
|
||||
&paths,
|
||||
/*logs_override*/ None,
|
||||
)
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
assert_eq!(uploaded.len(), 1);
|
||||
assert_eq!(uploaded[0].filename, "rollouts.tar.gz");
|
||||
Ok(())
|
||||
}
|
||||
215
codex-rs/feedback/src/upload.rs
Normal file
215
codex-rs/feedback/src/upload.rs
Normal file
@@ -0,0 +1,215 @@
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use bytes::Bytes;
|
||||
use codex_http_client::RequestBuilder;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use flate2::Compression;
|
||||
use flate2::write::GzEncoder;
|
||||
use http::HeaderMap;
|
||||
use http::StatusCode;
|
||||
use sentry::ClientOptions;
|
||||
use sentry::protocol::Attachment;
|
||||
use sentry::protocol::Envelope;
|
||||
use sentry::protocol::EnvelopeHeaders;
|
||||
use sentry::protocol::EnvelopeItem;
|
||||
use sentry::types::Dsn;
|
||||
|
||||
use crate::MAX_DECODED_UPLOAD_BYTES;
|
||||
|
||||
pub(super) const DEFAULT_RATE_LIMIT: Duration = Duration::from_secs(/*secs*/ 60);
|
||||
|
||||
pub(super) enum EnvelopeKind {
|
||||
Event,
|
||||
Attachment,
|
||||
}
|
||||
|
||||
pub(super) fn envelope_request(
|
||||
client_pool: &RouteAwareClientPool,
|
||||
dsn: &Dsn,
|
||||
body: Bytes,
|
||||
timeout: Duration,
|
||||
) -> RequestBuilder {
|
||||
let sentry_options = ClientOptions::default();
|
||||
let sentry_auth = dsn.to_auth(Some(sentry_options.user_agent.as_ref()));
|
||||
let request = client_pool
|
||||
.post(dsn.envelope_api_url().as_str())
|
||||
.header("X-Sentry-Auth", sentry_auth.to_string());
|
||||
// Persisted parts retain their encoding. Gzip's magic bytes cannot begin
|
||||
// an uncompressed envelope, which starts with a JSON header.
|
||||
let request = if body.starts_with(&[0x1f, 0x8b]) {
|
||||
request.header("Content-Encoding", "gzip")
|
||||
} else {
|
||||
request
|
||||
};
|
||||
request.body(body).timeout(timeout)
|
||||
}
|
||||
|
||||
/// Send an already-serialized envelope within the report's shared deadline.
|
||||
pub(super) async fn send_envelope(
|
||||
client_pool: &RouteAwareClientPool,
|
||||
dsn: &Dsn,
|
||||
body: Vec<u8>,
|
||||
kind: EnvelopeKind,
|
||||
deadline: Instant,
|
||||
rate_limited: &mut bool,
|
||||
) -> Result<StatusCode> {
|
||||
let body = Bytes::from(body);
|
||||
// Retain the exact request bytes for at most two diagnostic retries. Never replay the core.
|
||||
let mut retry_delays = [250, 500].map(Duration::from_millis).into_iter();
|
||||
let response = loop {
|
||||
let timeout = deadline.saturating_duration_since(Instant::now());
|
||||
anyhow::ensure!(!timeout.is_zero(), "feedback upload deadline exceeded");
|
||||
let response = envelope_request(client_pool, dsn, body.clone(), timeout)
|
||||
.send()
|
||||
.await;
|
||||
if response.as_ref().is_ok_and(|response| {
|
||||
sentry_rate_limit_delay(response.headers()).is_some_and(|delay| !delay.is_zero())
|
||||
|| (response.status().is_success()
|
||||
&& response.headers().get("Retry-After").is_some_and(|value| {
|
||||
parse_retry_after(value.to_str().unwrap_or_default())
|
||||
.is_none_or(|delay| !delay.is_zero())
|
||||
}))
|
||||
}) {
|
||||
// Even accepted requests can impose a quota on events or attachments.
|
||||
// https://develop.sentry.dev/sdk/foundations/transport/rate-limiting/
|
||||
*rate_limited = true;
|
||||
break response;
|
||||
}
|
||||
let retryable = match &response {
|
||||
Ok(response) => matches!(response.status().as_u16(), 408 | 429 | 500..=599),
|
||||
Err(error) => {
|
||||
error.is_timeout()
|
||||
|| (error.failure_class().is_none()
|
||||
&& (error.is_connect() || error.is_request() || error.is_body()))
|
||||
}
|
||||
};
|
||||
if matches!(kind, EnvelopeKind::Event) || !retryable {
|
||||
break response;
|
||||
}
|
||||
let retry_delay = retry_delays.next();
|
||||
if response.as_ref().is_ok_and(|response| {
|
||||
response.status() == StatusCode::TOO_MANY_REQUESTS
|
||||
&& (retry_delay.is_none() || !response.headers().contains_key("Retry-After"))
|
||||
}) {
|
||||
// Never let later files bypass an exhausted rate limit.
|
||||
*rate_limited = true;
|
||||
break response;
|
||||
}
|
||||
let Some(retry_delay) = retry_delay else {
|
||||
break response;
|
||||
};
|
||||
let retry_after = response
|
||||
.as_ref()
|
||||
.ok()
|
||||
.and_then(|response| response.headers().get("Retry-After"))
|
||||
.map(|value| {
|
||||
// An invalid cooldown is not permission to send immediately.
|
||||
parse_retry_after(value.to_str().unwrap_or_default())
|
||||
.unwrap_or_else(|| deadline.saturating_duration_since(Instant::now()))
|
||||
});
|
||||
let delay = retry_delay.max(retry_after.unwrap_or_default());
|
||||
if delay >= deadline.saturating_duration_since(Instant::now()) {
|
||||
// Leave long cooldowns for a later submission, including its remaining files.
|
||||
*rate_limited = true;
|
||||
break response;
|
||||
}
|
||||
tokio::time::sleep(delay).await;
|
||||
};
|
||||
response
|
||||
.map(|response| response.status())
|
||||
.context("failed to upload feedback to Sentry")
|
||||
}
|
||||
|
||||
pub(super) fn sentry_rate_limit_delay(headers: &HeaderMap) -> Option<Duration> {
|
||||
let mut retry_after = None;
|
||||
for value in headers.get_all("X-Sentry-Rate-Limits") {
|
||||
for quota in value.to_str().unwrap_or_default().split(',') {
|
||||
let mut fields = quota.trim().split(':');
|
||||
let seconds = fields.next().unwrap_or_default();
|
||||
let categories = fields.next().unwrap_or_default();
|
||||
if !categories.is_empty()
|
||||
&& !categories
|
||||
.split(';')
|
||||
.any(|category| matches!(category, "error" | "attachment"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let delay = seconds
|
||||
.parse::<f64>()
|
||||
.ok()
|
||||
.and_then(|seconds| Duration::try_from_secs_f64(seconds.ceil()).ok())
|
||||
.unwrap_or(DEFAULT_RATE_LIMIT);
|
||||
retry_after = retry_after.max(Some(delay));
|
||||
}
|
||||
}
|
||||
retry_after
|
||||
}
|
||||
|
||||
pub(super) fn parse_retry_after(value: &str) -> Option<Duration> {
|
||||
value
|
||||
.parse::<u64>()
|
||||
.map(Duration::from_secs)
|
||||
.or_else(|_| {
|
||||
httpdate::parse_http_date(value)
|
||||
.map(|date| date.duration_since(SystemTime::now()).unwrap_or_default())
|
||||
})
|
||||
.ok()
|
||||
}
|
||||
|
||||
pub(super) fn encode_envelope(envelope: &Envelope) -> io::Result<(Vec<u8>, usize)> {
|
||||
let mut writer = CountingWriter {
|
||||
inner: GzEncoder::new(Vec::new(), Compression::fast()),
|
||||
bytes: 0,
|
||||
};
|
||||
envelope.to_writer(&mut writer)?;
|
||||
let decoded_bytes = writer.bytes;
|
||||
let mut body = writer.inner.finish()?;
|
||||
// Already-compressed attachments can grow beyond Sentry's 200 MiB wire limit.
|
||||
// Reuse the buffer for the raw envelope when gzip does not make it smaller.
|
||||
if body.len() >= decoded_bytes {
|
||||
body.clear();
|
||||
envelope.to_writer(&mut body)?;
|
||||
}
|
||||
Ok((body, decoded_bytes))
|
||||
}
|
||||
|
||||
pub(super) fn encode_attachment_envelope(
|
||||
headers: &EnvelopeHeaders,
|
||||
attachment: Attachment,
|
||||
) -> Result<Vec<u8>> {
|
||||
anyhow::ensure!(
|
||||
attachment.buffer.len() <= MAX_DECODED_UPLOAD_BYTES,
|
||||
"feedback attachment exceeds the size limit"
|
||||
);
|
||||
let mut envelope = Envelope::new().with_headers(headers.clone());
|
||||
envelope.add_item(EnvelopeItem::Attachment(attachment));
|
||||
let (body, decoded_bytes) = encode_envelope(&envelope)?;
|
||||
anyhow::ensure!(
|
||||
decoded_bytes <= MAX_DECODED_UPLOAD_BYTES,
|
||||
"feedback attachment envelope exceeds the size limit"
|
||||
);
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
struct CountingWriter<W> {
|
||||
inner: W,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl<W: Write> Write for CountingWriter<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
let written = self.inner.write(buf)?;
|
||||
self.bytes += written;
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
self.inner.flush()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user