Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
6
akode-rs/feedback/BUILD.bazel
Normal file
6
akode-rs/feedback/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "feedback",
|
||||
crate_name = "akode_feedback",
|
||||
)
|
||||
30
akode-rs/feedback/Cargo.toml
Normal file
30
akode-rs/feedback/Cargo.toml
Normal file
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "akode-feedback"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
akode-login = { workspace = true }
|
||||
akode-protocol = { workspace = true }
|
||||
akode-rollout = { workspace = true }
|
||||
akode-state = { workspace = true }
|
||||
mime_guess = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["time"] }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
log = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt"] }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
127
akode-rs/feedback/src/archive.rs
Normal file
127
akode-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
akode-rs/feedback/src/archive_tests.rs
Normal file
175
akode-rs/feedback/src/archive_tests.rs
Normal file
@@ -0,0 +1,175 @@
|
||||
use super::*;
|
||||
use crate::CodexFeedback;
|
||||
use crate::FeedbackSaveOptions;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use zip::ZipArchive;
|
||||
|
||||
fn options() -> FeedbackSaveOptions<'static> {
|
||||
FeedbackSaveOptions {
|
||||
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(
|
||||
FeedbackSaveOptions {
|
||||
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(
|
||||
FeedbackSaveOptions {
|
||||
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
akode-rs/feedback/src/daemon_logs.rs
Normal file
64
akode-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
akode-rs/feedback/src/daemon_logs_tests.rs
Normal file
55
akode-rs/feedback/src/daemon_logs_tests.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
use super::*;
|
||||
use akode_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
akode-rs/feedback/src/feedback_diagnostics.rs
Normal file
179
akode-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()],
|
||||
},],
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
137
akode-rs/feedback/src/feedback_event_tests.rs
Normal file
137
akode-rs/feedback/src/feedback_event_tests.rs
Normal file
@@ -0,0 +1,137 @@
|
||||
//! Local feedback report contracts for titles, tags, and lossless comment bodies.
|
||||
|
||||
use crate::CodexFeedback;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn expected_report(
|
||||
level: &str,
|
||||
title: &str,
|
||||
reason: Option<&str>,
|
||||
tags: BTreeMap<String, String>,
|
||||
) -> serde_json::Value {
|
||||
let mut report = json!({
|
||||
"level": level,
|
||||
"message": title,
|
||||
"tags": tags,
|
||||
});
|
||||
if let Some(reason) = reason {
|
||||
report["exception"] = json!({ "values": [{ "type": title, "value": reason }] });
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_titles_preserve_comments() {
|
||||
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 report =
|
||||
snapshot.feedback_report("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!(
|
||||
report,
|
||||
expected_report("info", title, reason, expected_tags)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_or_blank_titles_preserve_session_titles() {
|
||||
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 report = snapshot.feedback_report(
|
||||
"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!(
|
||||
report,
|
||||
expected_report("error", &title, Some(reason), expected_tags)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[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 report = snapshot.feedback_report(
|
||||
"bug",
|
||||
Some(&reason),
|
||||
/*tags*/ None,
|
||||
/*session_source*/ None,
|
||||
);
|
||||
assert_eq!(
|
||||
report,
|
||||
expected_report(
|
||||
"error",
|
||||
&title,
|
||||
Some(&reason),
|
||||
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),
|
||||
]),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
157
akode-rs/feedback/src/guardian.rs
Normal file
157
akode-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 akode_protocol::ThreadId;
|
||||
pub use akode_state::GuardianReviewRecord;
|
||||
use akode_state::MAX_GUARDIAN_REVIEW_BYTES as MAX_BYTES;
|
||||
use akode_state::MAX_GUARDIAN_REVIEW_RECORDS as MAX_RECORDS;
|
||||
use akode_state::MAX_GUARDIAN_REVIEW_RECORDS_PER_THREAD as MAX_RECORDS_PER_THREAD;
|
||||
use akode_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
akode-rs/feedback/src/guardian_tests.rs
Normal file
90
akode-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 = akode_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(())
|
||||
}
|
||||
784
akode-rs/feedback/src/lib.rs
Normal file
784
akode-rs/feedback/src/lib.rs
Normal file
@@ -0,0 +1,784 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::VecDeque;
|
||||
use std::collections::btree_map::Entry;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::io::{self};
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use anyhow::Result;
|
||||
use akode_login::AuthEnvTelemetry;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::SessionSource;
|
||||
use akode_state::LogWriteFailureReporter;
|
||||
use tracing::Event;
|
||||
use tracing::Level;
|
||||
use tracing::field::Visit;
|
||||
use tracing::level_filters::LevelFilter;
|
||||
use tracing_subscriber::Layer;
|
||||
use tracing_subscriber::filter::Targets;
|
||||
use tracing_subscriber::fmt::writer::MakeWriter;
|
||||
use tracing_subscriber::registry::LookupSpan;
|
||||
|
||||
mod archive;
|
||||
mod daemon_logs;
|
||||
pub use daemon_logs::daemon_log_attachments;
|
||||
pub(crate) mod feedback_diagnostics;
|
||||
mod guardian;
|
||||
pub use feedback_diagnostics::FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME;
|
||||
pub use feedback_diagnostics::FeedbackDiagnostic;
|
||||
pub use feedback_diagnostics::FeedbackDiagnostics;
|
||||
pub use guardian::GuardianReviewFailures;
|
||||
pub use guardian::GuardianReviewRecord;
|
||||
pub use guardian::guardian_review_failures;
|
||||
pub use guardian::record_guardian_review_failure;
|
||||
|
||||
/// Filename used for the redacted `akode doctor --json` feedback attachment.
|
||||
pub const DOCTOR_REPORT_ATTACHMENT_FILENAME: &str = "codex-doctor-report.json";
|
||||
/// Filename used for the raw Codex Apps MCP tools cache feedback attachment.
|
||||
pub const AKODE_APPS_TOOLS_CACHE_ATTACHMENT_FILENAME: &str = "codex-apps-tools-cache.json";
|
||||
/// Filename used for the raw connector directory cache feedback attachment.
|
||||
pub const AKODE_APP_DIRECTORY_CACHE_ATTACHMENT_FILENAME: &str = "codex-app-directory-cache.json";
|
||||
/// Filename used for the Windows sandbox log feedback attachment.
|
||||
pub const WINDOWS_SANDBOX_LOG_ATTACHMENT_FILENAME: &str = "windows-sandbox.log";
|
||||
const DEFAULT_MAX_BYTES: usize = 4 * 1024 * 1024; // 4 MiB
|
||||
// Raw collection budgets for rollout history attachments.
|
||||
pub const MAX_ATTACHMENT_BYTES: usize = 64 * 1024 * 1024;
|
||||
pub const MAX_ATTACHMENTS_BYTES: usize = 126 * 1024 * 1024;
|
||||
const MAX_EVENT_BYTES: usize = 1024 * 1024;
|
||||
const FEEDBACK_TAGS_TARGET: &str = "feedback_tags";
|
||||
// Leave room for every feature, usage settings, and request/auth diagnostics.
|
||||
const MAX_FEEDBACK_TAGS: usize = 512;
|
||||
|
||||
/// Structured request/auth fields that should be attached to saved feedback reports.
|
||||
pub struct FeedbackRequestTags<'a> {
|
||||
pub endpoint: &'a str,
|
||||
pub auth_header_attached: bool,
|
||||
pub auth_header_name: Option<&'a str>,
|
||||
pub auth_mode: Option<&'a str>,
|
||||
pub auth_retry_after_unauthorized: Option<bool>,
|
||||
pub auth_recovery_mode: Option<&'a str>,
|
||||
pub auth_recovery_phase: Option<&'a str>,
|
||||
pub auth_connection_reused: Option<bool>,
|
||||
pub auth_request_id: Option<&'a str>,
|
||||
pub auth_cf_ray: Option<&'a str>,
|
||||
pub auth_error: Option<&'a str>,
|
||||
pub auth_error_code: Option<&'a str>,
|
||||
pub auth_recovery_followup_success: Option<bool>,
|
||||
pub auth_recovery_followup_status: Option<u16>,
|
||||
}
|
||||
|
||||
struct FeedbackRequestSnapshot<'a> {
|
||||
endpoint: &'a str,
|
||||
auth_header_attached: bool,
|
||||
auth_header_name: &'a str,
|
||||
auth_mode: &'a str,
|
||||
auth_retry_after_unauthorized: String,
|
||||
auth_recovery_mode: &'a str,
|
||||
auth_recovery_phase: &'a str,
|
||||
auth_connection_reused: String,
|
||||
auth_request_id: &'a str,
|
||||
auth_cf_ray: &'a str,
|
||||
auth_error: &'a str,
|
||||
auth_error_code: &'a str,
|
||||
auth_recovery_followup_success: String,
|
||||
auth_recovery_followup_status: String,
|
||||
}
|
||||
|
||||
impl<'a> FeedbackRequestSnapshot<'a> {
|
||||
fn from_tags(tags: &'a FeedbackRequestTags<'a>) -> Self {
|
||||
Self {
|
||||
endpoint: tags.endpoint,
|
||||
auth_header_attached: tags.auth_header_attached,
|
||||
auth_header_name: tags.auth_header_name.unwrap_or(""),
|
||||
auth_mode: tags.auth_mode.unwrap_or(""),
|
||||
auth_retry_after_unauthorized: tags
|
||||
.auth_retry_after_unauthorized
|
||||
.map_or_else(String::new, |value| value.to_string()),
|
||||
auth_recovery_mode: tags.auth_recovery_mode.unwrap_or(""),
|
||||
auth_recovery_phase: tags.auth_recovery_phase.unwrap_or(""),
|
||||
auth_connection_reused: tags
|
||||
.auth_connection_reused
|
||||
.map_or_else(String::new, |value| value.to_string()),
|
||||
auth_request_id: tags.auth_request_id.unwrap_or(""),
|
||||
auth_cf_ray: tags.auth_cf_ray.unwrap_or(""),
|
||||
auth_error: tags.auth_error.unwrap_or(""),
|
||||
auth_error_code: tags.auth_error_code.unwrap_or(""),
|
||||
auth_recovery_followup_success: tags
|
||||
.auth_recovery_followup_success
|
||||
.map_or_else(String::new, |value| value.to_string()),
|
||||
auth_recovery_followup_status: tags
|
||||
.auth_recovery_followup_status
|
||||
.map_or_else(String::new, |value| value.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn emit_feedback_request_tags(tags: &FeedbackRequestTags<'_>) {
|
||||
let snapshot = FeedbackRequestSnapshot::from_tags(tags);
|
||||
tracing::info!(
|
||||
target: FEEDBACK_TAGS_TARGET,
|
||||
endpoint = tracing::field::debug(snapshot.endpoint),
|
||||
auth_header_attached = tracing::field::debug(snapshot.auth_header_attached),
|
||||
auth_header_name = tracing::field::debug(snapshot.auth_header_name),
|
||||
auth_mode = tracing::field::debug(snapshot.auth_mode),
|
||||
auth_retry_after_unauthorized = tracing::field::debug(&snapshot.auth_retry_after_unauthorized),
|
||||
auth_recovery_mode = tracing::field::debug(snapshot.auth_recovery_mode),
|
||||
auth_recovery_phase = tracing::field::debug(snapshot.auth_recovery_phase),
|
||||
auth_connection_reused = tracing::field::debug(&snapshot.auth_connection_reused),
|
||||
auth_request_id = tracing::field::debug(snapshot.auth_request_id),
|
||||
auth_cf_ray = tracing::field::debug(snapshot.auth_cf_ray),
|
||||
auth_error = tracing::field::debug(snapshot.auth_error),
|
||||
auth_error_code = tracing::field::debug(snapshot.auth_error_code),
|
||||
auth_recovery_followup_success = tracing::field::debug(&snapshot.auth_recovery_followup_success),
|
||||
auth_recovery_followup_status = tracing::field::debug(&snapshot.auth_recovery_followup_status),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn emit_feedback_request_tags_with_auth_env(
|
||||
tags: &FeedbackRequestTags<'_>,
|
||||
auth_env: &AuthEnvTelemetry,
|
||||
) {
|
||||
let snapshot = FeedbackRequestSnapshot::from_tags(tags);
|
||||
tracing::info!(
|
||||
target: FEEDBACK_TAGS_TARGET,
|
||||
endpoint = tracing::field::debug(snapshot.endpoint),
|
||||
auth_header_attached = tracing::field::debug(snapshot.auth_header_attached),
|
||||
auth_header_name = tracing::field::debug(snapshot.auth_header_name),
|
||||
auth_mode = tracing::field::debug(snapshot.auth_mode),
|
||||
auth_retry_after_unauthorized = tracing::field::debug(&snapshot.auth_retry_after_unauthorized),
|
||||
auth_recovery_mode = tracing::field::debug(snapshot.auth_recovery_mode),
|
||||
auth_recovery_phase = tracing::field::debug(snapshot.auth_recovery_phase),
|
||||
auth_connection_reused = tracing::field::debug(&snapshot.auth_connection_reused),
|
||||
auth_request_id = tracing::field::debug(snapshot.auth_request_id),
|
||||
auth_cf_ray = tracing::field::debug(snapshot.auth_cf_ray),
|
||||
auth_error = tracing::field::debug(snapshot.auth_error),
|
||||
auth_error_code = tracing::field::debug(snapshot.auth_error_code),
|
||||
auth_recovery_followup_success = tracing::field::debug(&snapshot.auth_recovery_followup_success),
|
||||
auth_recovery_followup_status = tracing::field::debug(&snapshot.auth_recovery_followup_status),
|
||||
auth_env_openai_api_key_present = tracing::field::debug(auth_env.openai_api_key_env_present),
|
||||
auth_env_codex_api_key_present = tracing::field::debug(auth_env.codex_api_key_env_present),
|
||||
auth_env_codex_api_key_enabled = tracing::field::debug(auth_env.codex_api_key_env_enabled),
|
||||
// Custom provider `env_key` is arbitrary config text, so emit only a safe bucket.
|
||||
auth_env_provider_key_name = tracing::field::debug(
|
||||
auth_env.provider_env_key_name.as_deref().unwrap_or("")
|
||||
),
|
||||
auth_env_provider_key_present = tracing::field::debug(
|
||||
&auth_env.provider_env_key_present.map_or_else(String::new, |value| value.to_string())
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CodexFeedback {
|
||||
inner: Arc<FeedbackInner>,
|
||||
}
|
||||
|
||||
impl LogWriteFailureReporter for CodexFeedback {
|
||||
fn report_failure(&self, diagnostic: &str) {
|
||||
// Bypass tracing so this diagnostic cannot return to the SQLite writer.
|
||||
self.inner
|
||||
.ring
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.push_bytes(diagnostic.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CodexFeedback {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl CodexFeedback {
|
||||
pub fn new() -> Self {
|
||||
Self::with_capacity(DEFAULT_MAX_BYTES)
|
||||
}
|
||||
|
||||
pub(crate) fn with_capacity(max_bytes: usize) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(FeedbackInner::new(max_bytes)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn make_writer(&self) -> FeedbackMakeWriter {
|
||||
FeedbackMakeWriter {
|
||||
inner: self.inner.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a [`tracing_subscriber`] layer that captures diagnostic logs into this feedback
|
||||
/// ring buffer.
|
||||
///
|
||||
/// This is intended for initialization code so call sites don't have to duplicate the exact
|
||||
/// `fmt::layer()` configuration and filter logic.
|
||||
pub fn logger_layer<S>(&self) -> impl Layer<S> + Send + Sync + 'static
|
||||
where
|
||||
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
|
||||
{
|
||||
tracing_subscriber::fmt::layer()
|
||||
.with_writer(self.make_writer())
|
||||
.with_timer(tracing_subscriber::fmt::time::SystemTime)
|
||||
.with_ansi(false)
|
||||
.with_target(false)
|
||||
// Capture diagnostics independently of `RUST_LOG` without filling the feedback ring
|
||||
// with high-volume request and response payloads.
|
||||
.with_filter(
|
||||
Targets::new()
|
||||
.with_default(Level::TRACE)
|
||||
// Opted-in content is never part of feedback.
|
||||
.with_target("akode_otel.log_only", LevelFilter::OFF)
|
||||
.with_target("akode_http_client::transport", LevelFilter::DEBUG)
|
||||
.with_target("akode_api::sse", LevelFilter::DEBUG)
|
||||
// `tracing-log` checks legacy log records against their original
|
||||
// target before re-emitting them as `log`; tungstenite TRACE
|
||||
// includes full websocket frames and authenticated handshakes.
|
||||
.with_target("tungstenite", LevelFilter::DEBUG)
|
||||
.with_target("akode_api::responses_websocket_timing", LevelFilter::OFF)
|
||||
.with_target("akode_core::post_sampling_token_estimate", LevelFilter::OFF),
|
||||
)
|
||||
}
|
||||
|
||||
/// Returns a [`tracing_subscriber`] layer that collects structured metadata for feedback.
|
||||
///
|
||||
/// Events with `target: "feedback_tags"` are treated as key/value tags to attach to feedback
|
||||
/// saved reports later.
|
||||
pub fn metadata_layer<S>(&self) -> impl Layer<S> + Send + Sync + 'static
|
||||
where
|
||||
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
|
||||
{
|
||||
FeedbackMetadataLayer {
|
||||
inner: self.inner.clone(),
|
||||
}
|
||||
.with_filter(Targets::new().with_target(FEEDBACK_TAGS_TARGET, Level::TRACE))
|
||||
}
|
||||
|
||||
pub fn snapshot(&self, session_id: Option<ThreadId>) -> FeedbackSnapshot {
|
||||
let bytes = {
|
||||
#[allow(clippy::expect_used)]
|
||||
let guard = self.inner.ring.lock().expect("mutex poisoned");
|
||||
guard.snapshot_bytes()
|
||||
};
|
||||
let tags = {
|
||||
#[allow(clippy::expect_used)]
|
||||
let guard = self.inner.tags.lock().expect("mutex poisoned");
|
||||
guard.clone()
|
||||
};
|
||||
FeedbackSnapshot {
|
||||
bytes,
|
||||
tags,
|
||||
feedback_diagnostics: FeedbackDiagnostics::collect_from_env(),
|
||||
thread_id: session_id
|
||||
.map(|id| id.to_string())
|
||||
.unwrap_or("no-active-thread-".to_string() + &ThreadId::new().to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FeedbackInner {
|
||||
ring: Mutex<RingBuffer>,
|
||||
tags: Mutex<BTreeMap<String, String>>,
|
||||
}
|
||||
|
||||
impl FeedbackInner {
|
||||
fn new(max_bytes: usize) -> Self {
|
||||
Self {
|
||||
ring: Mutex::new(RingBuffer::new(max_bytes)),
|
||||
tags: Mutex::new(BTreeMap::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FeedbackMakeWriter {
|
||||
inner: Arc<FeedbackInner>,
|
||||
}
|
||||
|
||||
impl<'a> MakeWriter<'a> for FeedbackMakeWriter {
|
||||
type Writer = FeedbackWriter;
|
||||
|
||||
fn make_writer(&'a self) -> Self::Writer {
|
||||
FeedbackWriter {
|
||||
inner: self.inner.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FeedbackWriter {
|
||||
inner: Arc<FeedbackInner>,
|
||||
}
|
||||
|
||||
impl Write for FeedbackWriter {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
let mut guard = self.inner.ring.lock().map_err(|_| io::ErrorKind::Other)?;
|
||||
guard.push_bytes(buf);
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct RingBuffer {
|
||||
max: usize,
|
||||
buf: VecDeque<u8>,
|
||||
}
|
||||
|
||||
impl RingBuffer {
|
||||
fn new(capacity: usize) -> Self {
|
||||
Self {
|
||||
max: capacity,
|
||||
buf: VecDeque::with_capacity(capacity),
|
||||
}
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.buf.len()
|
||||
}
|
||||
|
||||
fn push_bytes(&mut self, data: &[u8]) {
|
||||
if data.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
// If the incoming chunk is larger than capacity, keep only the trailing bytes.
|
||||
if data.len() >= self.max {
|
||||
self.buf.clear();
|
||||
let start = data.len() - self.max;
|
||||
self.buf.extend(data[start..].iter().copied());
|
||||
return;
|
||||
}
|
||||
|
||||
// Evict from the front if we would exceed capacity.
|
||||
let needed = self.len() + data.len();
|
||||
if needed > self.max {
|
||||
let to_drop = needed - self.max;
|
||||
for _ in 0..to_drop {
|
||||
let _ = self.buf.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
self.buf.extend(data.iter().copied());
|
||||
}
|
||||
|
||||
fn snapshot_bytes(&self) -> Vec<u8> {
|
||||
self.buf.iter().copied().collect()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FeedbackSnapshot {
|
||||
bytes: Vec<u8>,
|
||||
tags: BTreeMap<String, String>,
|
||||
feedback_diagnostics: FeedbackDiagnostics,
|
||||
pub thread_id: String,
|
||||
}
|
||||
|
||||
pub struct FeedbackAttachmentPath {
|
||||
pub path: PathBuf,
|
||||
/// Optional filename to use for the saved attachment instead of `path`'s basename.
|
||||
pub attachment_filename_override: Option<String>,
|
||||
}
|
||||
|
||||
impl FeedbackAttachmentPath {
|
||||
/// Read a whole regular file within the caller's size limit.
|
||||
pub fn read_attachment(&self, max_bytes: usize) -> io::Result<Option<FeedbackAttachment>> {
|
||||
let mut attachment_path = self.path.clone();
|
||||
let mut rollout_path = akode_rollout::rollout_id_from_path(&self.path)
|
||||
.map(|_| akode_rollout::plain_rollout_path(&self.path));
|
||||
let mut raw_rollout = false;
|
||||
let decoded = if let Some(plain_path) = &rollout_path {
|
||||
match akode_rollout::read_rollout_prefix(&self.path, max_bytes.saturating_add(1)) {
|
||||
Ok(Some(buffer)) => Some(buffer),
|
||||
Ok(None) => {
|
||||
tracing::error!(
|
||||
"feedback attachment skipped: rollout is missing or not a regular file"
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
Err(error)
|
||||
if error.raw_os_error().is_none()
|
||||
&& matches!(
|
||||
error.kind(),
|
||||
io::ErrorKind::UnexpectedEof
|
||||
| io::ErrorKind::InvalidData
|
||||
| io::ErrorKind::Other
|
||||
)
|
||||
&& !plain_path.try_exists().unwrap_or(true) =>
|
||||
{
|
||||
// Preserve a selected, undecodable archive for diagnosis. Never replace
|
||||
// a preferred plain rollout with its potentially stale compressed sibling.
|
||||
attachment_path = plain_path.with_extension("jsonl.zst");
|
||||
rollout_path = None;
|
||||
raw_rollout = true;
|
||||
None
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let buffer = if let Some(buffer) = decoded {
|
||||
buffer
|
||||
} else {
|
||||
let metadata = fs::metadata(&attachment_path)?;
|
||||
if !metadata.is_file() {
|
||||
tracing::error!("feedback attachment skipped: not a regular file");
|
||||
return Ok(None);
|
||||
}
|
||||
if metadata.len() > max_bytes as u64 {
|
||||
tracing::error!(
|
||||
bytes = metadata.len(),
|
||||
max_bytes,
|
||||
"feedback attachment skipped: size limit exceeded"
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
let mut buffer = Vec::new();
|
||||
// Detect files that grow past the limit after the metadata check.
|
||||
fs::File::open(&attachment_path)?
|
||||
.take(max_bytes as u64 + 1)
|
||||
.read_to_end(&mut buffer)?;
|
||||
buffer
|
||||
};
|
||||
if buffer.len() > max_bytes {
|
||||
tracing::error!(
|
||||
bytes_read = buffer.len(),
|
||||
max_bytes,
|
||||
"feedback attachment skipped: decoded size limit exceeded"
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
let mut filename = self
|
||||
.attachment_filename_override
|
||||
.clone()
|
||||
.unwrap_or_else(|| {
|
||||
rollout_path
|
||||
.as_ref()
|
||||
.unwrap_or(&attachment_path)
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "extra-log.log".to_string())
|
||||
});
|
||||
if raw_rollout && !filename.ends_with(".zst") {
|
||||
filename.push_str(".zst");
|
||||
}
|
||||
let content_type = match Path::new(&filename)
|
||||
.extension()
|
||||
.and_then(|extension| extension.to_str())
|
||||
{
|
||||
Some(extension) if extension.eq_ignore_ascii_case("jsonl") => "text/plain".to_string(),
|
||||
_ => mime_guess::from_path(&filename)
|
||||
.first_or_octet_stream()
|
||||
.essence_str()
|
||||
.to_string(),
|
||||
};
|
||||
Ok(Some(FeedbackAttachment {
|
||||
filename,
|
||||
content_type: Some(content_type),
|
||||
buffer,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// In-memory attachment to include in a saved feedback report.
|
||||
///
|
||||
/// Use this for generated diagnostics that should not be materialized on disk,
|
||||
/// such as the redacted doctor report. File-backed artifacts should use
|
||||
/// `FeedbackAttachmentPath` so save-time read failures can be logged and
|
||||
/// skipped independently.
|
||||
pub struct FeedbackAttachment {
|
||||
/// Attachment filename shown in the saved archive and in the feedback consent UI.
|
||||
pub filename: String,
|
||||
/// Optional MIME type for consumers that render or classify attachments.
|
||||
pub content_type: Option<String>,
|
||||
/// Attachment bytes captured before the report is saved.
|
||||
pub buffer: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Inputs that control one locally saved feedback report.
|
||||
///
|
||||
/// The caller is responsible for applying any user-consent gate before setting
|
||||
/// `include_logs` or passing diagnostic attachments. This type only describes
|
||||
/// what to save once that decision has been made.
|
||||
pub struct FeedbackSaveOptions<'a> {
|
||||
pub classification: &'a str,
|
||||
pub reason: Option<&'a str>,
|
||||
pub tags: Option<&'a BTreeMap<String, String>>,
|
||||
pub include_logs: bool,
|
||||
/// Owned diagnostics and frozen rollout prefixes that are safe to save.
|
||||
///
|
||||
/// Diagnostics follow `codex-logs.log`; rollout prefixes join the archive with
|
||||
/// path-backed rollouts. Callers must apply any user consent gate first.
|
||||
pub extra_attachments: Vec<FeedbackAttachment>,
|
||||
pub extra_attachment_paths: &'a [FeedbackAttachmentPath],
|
||||
pub session_source: Option<SessionSource>,
|
||||
pub logs_override: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl FeedbackSnapshot {
|
||||
/// Refreshes log bytes while preserving the captured metadata and thread identity.
|
||||
pub fn refresh_logs(&mut self, feedback: &CodexFeedback) {
|
||||
self.bytes = feedback
|
||||
.inner
|
||||
.ring
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.snapshot_bytes();
|
||||
}
|
||||
|
||||
/// Builds the local JSON report saved next to the feedback attachments.
|
||||
fn feedback_report(
|
||||
&self,
|
||||
classification: &str,
|
||||
reason: Option<&str>,
|
||||
tags: Option<&BTreeMap<String, String>>,
|
||||
session_source: Option<&SessionSource>,
|
||||
) -> serde_json::Value {
|
||||
let level = match classification {
|
||||
"bug" | "bad_result" | "safety_check" => "error",
|
||||
_ => "info",
|
||||
};
|
||||
let custom_title = tags
|
||||
.and_then(|tags| tags.get("feedback_title"))
|
||||
.map(|title| title.trim())
|
||||
.filter(|title| !title.is_empty());
|
||||
let title = custom_title.map_or_else(
|
||||
|| {
|
||||
format!(
|
||||
"[{}]: Codex session {}",
|
||||
display_classification(classification),
|
||||
self.thread_id
|
||||
)
|
||||
},
|
||||
str::to_owned,
|
||||
);
|
||||
let mut report = serde_json::json!({
|
||||
"level": level,
|
||||
"message": title,
|
||||
"tags": self.report_tags(classification, reason, tags, session_source),
|
||||
});
|
||||
if let Some(reason) = reason {
|
||||
report["exception"] = serde_json::json!({
|
||||
"values": [{ "type": title, "value": reason }],
|
||||
});
|
||||
}
|
||||
report
|
||||
}
|
||||
|
||||
pub fn log_attachment(&self, logs_override: Option<Vec<u8>>) -> FeedbackAttachment {
|
||||
FeedbackAttachment {
|
||||
filename: "codex-logs.log".to_string(),
|
||||
content_type: Some("text/plain".to_string()),
|
||||
buffer: logs_override.unwrap_or_else(|| self.bytes.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn feedback_diagnostics(&self) -> &FeedbackDiagnostics {
|
||||
&self.feedback_diagnostics
|
||||
}
|
||||
|
||||
pub fn with_feedback_diagnostics(mut self, feedback_diagnostics: FeedbackDiagnostics) -> Self {
|
||||
self.feedback_diagnostics = feedback_diagnostics;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn feedback_diagnostics_attachment_text(&self, include_logs: bool) -> Option<String> {
|
||||
if !include_logs {
|
||||
return None;
|
||||
}
|
||||
|
||||
self.feedback_diagnostics.attachment_text()
|
||||
}
|
||||
|
||||
/// Atomically saves the consent-selected report and attachments to a local file.
|
||||
/// Existing paths are rejected and failures never publish a partial archive.
|
||||
pub fn save_feedback(&self, options: FeedbackSaveOptions<'_>, path: &Path) -> Result<()> {
|
||||
let report = serde_json::to_vec(&self.feedback_report(
|
||||
options.classification,
|
||||
options.reason,
|
||||
options.tags,
|
||||
options.session_source.as_ref(),
|
||||
))?;
|
||||
anyhow::ensure!(
|
||||
report.len() <= MAX_EVENT_BYTES,
|
||||
"feedback event exceeds the size limit"
|
||||
);
|
||||
let logs = options
|
||||
.include_logs
|
||||
.then(|| self.log_attachment(options.logs_override));
|
||||
let diagnostics = self
|
||||
.feedback_diagnostics_attachment_text(options.include_logs)
|
||||
.map(|text| FeedbackAttachment {
|
||||
buffer: text.into_bytes(),
|
||||
filename: FEEDBACK_DIAGNOSTICS_ATTACHMENT_FILENAME.to_string(),
|
||||
content_type: Some("text/plain".to_string()),
|
||||
});
|
||||
archive::save(
|
||||
path,
|
||||
&report,
|
||||
logs.into_iter()
|
||||
.chain(options.extra_attachments)
|
||||
.chain(diagnostics)
|
||||
.map(archive::Input::Owned)
|
||||
.chain(
|
||||
options
|
||||
.extra_attachment_paths
|
||||
.iter()
|
||||
.map(archive::Input::Path),
|
||||
),
|
||||
archive::Limits::default(),
|
||||
)
|
||||
}
|
||||
|
||||
fn report_tags(
|
||||
&self,
|
||||
classification: &str,
|
||||
reason: Option<&str>,
|
||||
client_tags: Option<&BTreeMap<String, String>>,
|
||||
session_source: Option<&SessionSource>,
|
||||
) -> BTreeMap<String, String> {
|
||||
let cli_version = env!("CARGO_PKG_VERSION");
|
||||
let mut tags = BTreeMap::from([
|
||||
(String::from("thread_id"), self.thread_id.to_string()),
|
||||
(String::from("classification"), classification.to_string()),
|
||||
(String::from("cli_version"), cli_version.to_string()),
|
||||
]);
|
||||
if let Some(source) = session_source {
|
||||
tags.insert(String::from("session_source"), source.to_string());
|
||||
}
|
||||
if let Some(reason) = reason {
|
||||
// Keep the full comment in the exception body and a single-line,
|
||||
// 200-character preview for tag consumers.
|
||||
let preview = reason
|
||||
.chars()
|
||||
.take(200)
|
||||
.map(|ch| if matches!(ch, '\r' | '\n') { ' ' } else { ch })
|
||||
.collect();
|
||||
tags.insert(String::from("reason"), preview);
|
||||
}
|
||||
|
||||
let reserved = [
|
||||
"thread_id",
|
||||
"classification",
|
||||
"cli_version",
|
||||
"session_source",
|
||||
"reason",
|
||||
];
|
||||
if let Some(client_tags) = client_tags {
|
||||
for (key, value) in client_tags {
|
||||
if reserved.contains(&key.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if let Entry::Vacant(entry) = tags.entry(key.clone()) {
|
||||
entry.insert(value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (key, value) in &self.tags {
|
||||
if reserved.contains(&key.as_str()) {
|
||||
continue;
|
||||
}
|
||||
if let Entry::Vacant(entry) = tags.entry(key.clone()) {
|
||||
entry.insert(value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
tags
|
||||
}
|
||||
}
|
||||
|
||||
fn display_classification(classification: &str) -> String {
|
||||
match classification {
|
||||
"bug" => "Bug".to_string(),
|
||||
"bad_result" => "Bad result".to_string(),
|
||||
"good_result" => "Good result".to_string(),
|
||||
"safety_check" => "Safety check".to_string(),
|
||||
_ => "Other".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct FeedbackMetadataLayer {
|
||||
inner: Arc<FeedbackInner>,
|
||||
}
|
||||
|
||||
impl<S> Layer<S> for FeedbackMetadataLayer
|
||||
where
|
||||
S: tracing::Subscriber + for<'a> LookupSpan<'a>,
|
||||
{
|
||||
fn on_event(&self, event: &Event<'_>, _ctx: tracing_subscriber::layer::Context<'_, S>) {
|
||||
// This layer is filtered by `Targets`, but keep the guard anyway in case it is used without
|
||||
// the filter.
|
||||
if event.metadata().target() != FEEDBACK_TAGS_TARGET {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut visitor = FeedbackTagsVisitor::default();
|
||||
event.record(&mut visitor);
|
||||
// Expand runtime-selected keys alongside ordinary tracing fields.
|
||||
if let Some(json) = visitor.tags.remove("tags_json")
|
||||
&& let Ok(tags) = serde_json::from_str::<BTreeMap<String, String>>(&json)
|
||||
{
|
||||
visitor.tags.extend(tags);
|
||||
}
|
||||
if visitor.tags.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
#[allow(clippy::expect_used)]
|
||||
let mut guard = self.inner.tags.lock().expect("mutex poisoned");
|
||||
for (key, value) in visitor.tags {
|
||||
if guard.len() >= MAX_FEEDBACK_TAGS && !guard.contains_key(&key) {
|
||||
continue;
|
||||
}
|
||||
guard.insert(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct FeedbackTagsVisitor {
|
||||
tags: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
impl Visit for FeedbackTagsVisitor {
|
||||
fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
|
||||
self.tags
|
||||
.insert(field.name().to_string(), value.to_string());
|
||||
}
|
||||
|
||||
fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
|
||||
self.tags
|
||||
.insert(field.name().to_string(), value.to_string());
|
||||
}
|
||||
|
||||
fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
|
||||
self.tags
|
||||
.insert(field.name().to_string(), value.to_string());
|
||||
}
|
||||
|
||||
fn record_f64(&mut self, field: &tracing::field::Field, value: f64) {
|
||||
self.tags
|
||||
.insert(field.name().to_string(), value.to_string());
|
||||
}
|
||||
|
||||
fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
|
||||
self.tags
|
||||
.insert(field.name().to_string(), value.to_string());
|
||||
}
|
||||
|
||||
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
|
||||
self.tags
|
||||
.insert(field.name().to_string(), format!("{value:?}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lib_tests.rs"]
|
||||
mod tests;
|
||||
237
akode-rs/feedback/src/lib_tests.rs
Normal file
237
akode-rs/feedback/src/lib_tests.rs
Normal file
@@ -0,0 +1,237 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! Unit tests for the crate and its related test suites.
|
||||
|
||||
use std::fs;
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use tracing_subscriber::util::SubscriberInitExt;
|
||||
|
||||
#[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: "akode_api::responses_websocket_timing", payload = "secret");
|
||||
tracing::event!(
|
||||
target: "akode_otel.log_only", tracing::Level::INFO,
|
||||
event.name = "codex.agent_response", response = "private-agent-response"
|
||||
);
|
||||
tracing::info!(target: "akode_otel.log_only", rationale = "private-guardian-rationale");
|
||||
tracing::trace!(target: "akode_http_client::transport", "transport-trace");
|
||||
tracing::trace!(target: "akode_api::sse", "sse-trace");
|
||||
tracing::trace!(target: "akode_api::sse::responses", "nested-sse-trace");
|
||||
tracing::debug!(target: "akode_http_client::transport", "transport-debug");
|
||||
tracing::debug!(target: "akode_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"));
|
||||
}
|
||||
|
||||
#[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 = [&gzip_path, &unknown_path]
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
FeedbackAttachmentPath {
|
||||
path: path.clone(),
|
||||
attachment_filename_override: None,
|
||||
}
|
||||
.read_attachment(DEFAULT_MAX_BYTES)
|
||||
.unwrap()
|
||||
.expect("attachment should be readable")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
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 report_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 report_tags = snapshot.report_tags(
|
||||
"bug",
|
||||
Some("actual reason"),
|
||||
Some(&client_tags),
|
||||
Some(&SessionSource::Cli),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
report_tags.get("thread_id").map(String::as_str),
|
||||
Some("thread-123")
|
||||
);
|
||||
assert_eq!(
|
||||
report_tags.get("turn_id").map(String::as_str),
|
||||
Some("turn-456")
|
||||
);
|
||||
assert_eq!(
|
||||
report_tags.get("classification").map(String::as_str),
|
||||
Some("bug")
|
||||
);
|
||||
assert_eq!(
|
||||
report_tags.get("session_source").map(String::as_str),
|
||||
Some("cli")
|
||||
);
|
||||
assert_eq!(
|
||||
report_tags.get("reason").map(String::as_str),
|
||||
Some("actual reason")
|
||||
);
|
||||
assert_eq!(
|
||||
report_tags.get("account_id").map(String::as_str),
|
||||
Some("actual-account")
|
||||
);
|
||||
assert_eq!(
|
||||
report_tags.get("model").map(String::as_str),
|
||||
Some("mewthree")
|
||||
);
|
||||
assert_eq!(
|
||||
report_tags.get("effort").map(String::as_str),
|
||||
Some("Some(Ultra)")
|
||||
);
|
||||
assert_eq!(
|
||||
report_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;
|
||||
99
akode-rs/feedback/src/metadata_tests.rs
Normal file
99
akode-rs/feedback/src/metadata_tests.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
//! Exercise dynamic tag collection, report serialization, and bounded updates.
|
||||
|
||||
use crate::CodexFeedback;
|
||||
use crate::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
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_in_report_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 report = snapshot.feedback_report(
|
||||
"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!(report["tags"], serde_json::json!(expected));
|
||||
let size = serde_json::to_vec(&report).unwrap().len();
|
||||
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);
|
||||
}
|
||||
205
akode-rs/feedback/src/rollout_attachment_tests.rs
Normal file
205
akode-rs/feedback/src/rollout_attachment_tests.rs
Normal file
@@ -0,0 +1,205 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
|
||||
#[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)
|
||||
);
|
||||
}
|
||||
94
akode-rs/feedback/src/save_rollout_tests.rs
Normal file
94
akode-rs/feedback/src/save_rollout_tests.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
//! 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);
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user