use crate::error::{OmegaError, Result};
use alloc::collections::BTreeMap;
use serde::Serialize;
use std::io::Write;
use std::path::{Path, PathBuf};
pub const DEFAULT_MAX_TRAJECTORY_BYTES: u64 = 64 * 1024 * 1024;
struct TrajectoryAppendLock {
#[cfg(any(unix, windows))]
_file: std::fs::File,
}
impl TrajectoryAppendLock {
fn acquire(path: &Path) -> Result<Self> {
#[cfg(any(unix, windows))]
{
use fs2::FileExt;
let file = crate::private_fs::open_options()
.read(true)
.write(true)
.create(true)
.open(path)
.map_err(|error| {
OmegaError::Persist(format!("trajectory lock open {}: {error}", path.display()))
})?;
file.lock_exclusive().map_err(|error| {
OmegaError::Persist(format!(
"trajectory lock acquire {}: {error}",
path.display()
))
})?;
Ok(Self { _file: file })
}
#[cfg(not(any(unix, windows)))]
{
let _ = path;
Ok(Self {})
}
}
}
pub(super) fn trajectory_lock_path(path: &Path) -> PathBuf {
let mut lock_path = path.as_os_str().to_os_string();
lock_path.push(".lock");
PathBuf::from(lock_path)
}
pub(super) fn append_trajectory_record(
path: &Path,
record: &serde_json::Value,
max_bytes: u64,
) -> Result<()> {
let mut line = serde_json::to_vec(record)
.map_err(|error| OmegaError::Persist(format!("trajectory serialize: {error}")))?;
line.push(b'\n');
if let Some(parent) = path.parent() {
crate::private_fs::create_dir_all(parent)
.map_err(|error| OmegaError::Persist(format!("trajectory directory: {error}")))?;
}
let _lock = TrajectoryAppendLock::acquire(&trajectory_lock_path(path))?;
let current_len = match std::fs::metadata(path) {
Ok(metadata) => metadata.len(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => 0,
Err(error) => {
return Err(OmegaError::Persist(format!(
"trajectory metadata {}: {error}",
path.display()
)))
}
};
let record_len = u64::try_from(line.len())
.map_err(|error| OmegaError::Persist(format!("trajectory record size: {error}")))?;
if !matches!(current_len.checked_add(record_len), Some(size) if size <= max_bytes) {
return Err(OmegaError::Persist(format!(
"trajectory size limit exceeded for {}: current {current_len} bytes, record {record_len} bytes, maximum {max_bytes} bytes",
path.display()
)));
}
let mut file = crate::private_fs::open_options()
.create(true)
.append(true)
.open(path)
.map_err(|error| {
OmegaError::Persist(format!("trajectory open {}: {error}", path.display()))
})?;
file.write_all(&line).map_err(|error| {
OmegaError::Persist(format!("trajectory write {}: {error}", path.display()))
})
}
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct TrajectoryReplaySummary {
pub path: String,
pub rows: usize,
pub patches: usize,
pub first_avg_err: Option<f64>,
pub last_avg_err: Option<f64>,
pub action_counts: Vec<(String, usize)>,
pub tail: Vec<TrajectoryReplayRow>,
}
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct TrajectoryReplayRow {
pub step: u64,
pub action: String,
pub patched: bool,
pub avg_err: Option<f64>,
pub goal: Option<String>,
pub l2_decision: Option<crate::types::L2DecisionRecord>,
pub l2_gate_state: crate::l2::control::L2GateState,
pub l2_alpha: f64,
pub l2_expert_weights: BTreeMap<String, f64>,
pub l2_beta: f64,
pub l2_lyapunov_potential: f64,
pub l2_lyapunov_veto: bool,
pub l2_meta_cache_hit: bool,
pub l2_dayan_residual: f64,
pub l2_applied_policy: crate::types::L2Policy,
pub l2_pending_policy: crate::types::L2Policy,
}
pub fn replay_trajectory_file(path: &Path, tail_n: usize) -> Result<TrajectoryReplaySummary> {
use std::fs;
if !path.exists() {
return Err(OmegaError::Persist(format!(
"trajectory not found: {}",
path.display()
)));
}
const MAX_TRACE_BYTES: u64 = 64 * 1024 * 1024;
const MAX_TRACE_LINE_BYTES: usize = 1024 * 1024;
const MAX_TRACE_ROWS: usize = 1_000_000;
let mut file = fs::File::open(path).map_err(|e| OmegaError::Persist(e.to_string()))?;
let mut data = String::new();
std::io::Read::read_to_string(
&mut std::io::Read::take(std::io::Read::by_ref(&mut file), MAX_TRACE_BYTES + 1),
&mut data,
)
.map_err(|e| OmegaError::Persist(e.to_string()))?;
if data.len() as u64 > MAX_TRACE_BYTES {
return Err(OmegaError::Persist(format!(
"trajectory replay byte limit exceeded: maximum {MAX_TRACE_BYTES} bytes"
)));
}
let mut rows = 0usize;
let mut patches = 0usize;
let mut first_avg_err = None;
let mut last_avg_err = None;
let mut actions: BTreeMap<String, usize> = BTreeMap::new();
let mut tail_buf: Vec<TrajectoryReplayRow> = Vec::new();
for line in data.lines().filter(|l| !l.trim().is_empty()) {
if line.len() > MAX_TRACE_LINE_BYTES {
return Err(OmegaError::Persist(format!(
"trajectory replay line exceeds {MAX_TRACE_LINE_BYTES} byte limit"
)));
}
if rows >= MAX_TRACE_ROWS {
return Err(OmegaError::Persist(format!(
"trajectory replay row count exceeds {MAX_TRACE_ROWS} limit"
)));
}
let v: serde_json::Value =
serde_json::from_str(line).map_err(|e| OmegaError::Persist(e.to_string()))?;
rows += 1;
let step = v.get("step").and_then(|x| x.as_u64()).unwrap_or(0);
let action = v
.get("action")
.and_then(|x| x.as_str())
.unwrap_or("-")
.to_string();
let patched = v.get("patched").and_then(|x| x.as_bool()).unwrap_or(false);
if patched {
patches += 1;
}
let avg_err = v.get("avg_err").and_then(|x| x.as_f64());
if first_avg_err.is_none() {
first_avg_err = avg_err;
}
if avg_err.is_some() {
last_avg_err = avg_err;
}
*actions.entry(action.clone()).or_insert(0) += 1;
let goal = v
.get("goal")
.and_then(|x| x.as_str())
.map(|s| s.to_string());
tail_buf.push(TrajectoryReplayRow {
step,
action,
patched,
avg_err,
goal,
l2_decision: v
.get("l2_decision")
.cloned()
.and_then(|value| serde_json::from_value(value).ok()),
l2_gate_state: v
.get("l2_gate_state")
.cloned()
.and_then(|value| serde_json::from_value(value).ok())
.unwrap_or_default(),
l2_alpha: v
.get("l2_alpha")
.and_then(|value| value.as_f64())
.unwrap_or(0.0),
l2_expert_weights: v
.get("l2_expert_weights")
.cloned()
.and_then(|value| serde_json::from_value(value).ok())
.unwrap_or_default(),
l2_beta: v
.get("l2_beta")
.and_then(|value| value.as_f64())
.unwrap_or(0.0),
l2_lyapunov_potential: v
.get("l2_lyapunov_potential")
.and_then(|value| value.as_f64())
.unwrap_or(1.0),
l2_lyapunov_veto: v
.get("l2_lyapunov_veto")
.and_then(|value| value.as_bool())
.unwrap_or(false),
l2_meta_cache_hit: v
.get("l2_meta_cache_hit")
.and_then(|value| value.as_bool())
.unwrap_or(false),
l2_dayan_residual: v
.get("l2_dayan_residual")
.and_then(|value| value.as_f64())
.unwrap_or(0.0),
l2_applied_policy: v
.get("l2_applied_policy")
.cloned()
.and_then(|value| serde_json::from_value(value).ok())
.unwrap_or_default(),
l2_pending_policy: v
.get("l2_pending_policy")
.cloned()
.and_then(|value| serde_json::from_value(value).ok())
.unwrap_or_default(),
});
}
let mut action_counts: Vec<_> = actions.into_iter().collect();
action_counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
let tail = if tail_buf.len() > tail_n {
tail_buf.split_off(tail_buf.len() - tail_n)
} else {
tail_buf
};
Ok(TrajectoryReplaySummary {
path: path.display().to_string(),
rows,
patches,
first_avg_err,
last_avg_err,
action_counts,
tail,
})
}