Skip to main content

omega_cognitive_kernel/api/
trajectory.rs

1//! Append-only trajectory JSONL writer with file locking and offline replay.
2
3use crate::error::{OmegaError, Result};
4use alloc::collections::BTreeMap;
5use serde::Serialize;
6use std::io::Write;
7use std::path::{Path, PathBuf};
8
9/// Default maximum size for a trajectory JSONL file (64 MiB).
10///
11/// Existing files larger than this remain readable; only new appends are limited.
12pub const DEFAULT_MAX_TRAJECTORY_BYTES: u64 = 64 * 1024 * 1024;
13
14struct TrajectoryAppendLock {
15    #[cfg(any(unix, windows))]
16    _file: std::fs::File,
17}
18
19impl TrajectoryAppendLock {
20    fn acquire(path: &Path) -> Result<Self> {
21        #[cfg(any(unix, windows))]
22        {
23            use fs2::FileExt;
24
25            let file = crate::private_fs::open_options()
26                .read(true)
27                .write(true)
28                .create(true)
29                .open(path)
30                .map_err(|error| {
31                    OmegaError::Persist(format!("trajectory lock open {}: {error}", path.display()))
32                })?;
33            file.lock_exclusive().map_err(|error| {
34                OmegaError::Persist(format!(
35                    "trajectory lock acquire {}: {error}",
36                    path.display()
37                ))
38            })?;
39            Ok(Self { _file: file })
40        }
41        #[cfg(not(any(unix, windows)))]
42        {
43            // These targets do not support the crate's advisory file locks;
44            // single-writer trajectory usage remains supported there.
45            let _ = path;
46            Ok(Self {})
47        }
48    }
49}
50
51pub(super) fn trajectory_lock_path(path: &Path) -> PathBuf {
52    let mut lock_path = path.as_os_str().to_os_string();
53    lock_path.push(".lock");
54    PathBuf::from(lock_path)
55}
56
57pub(super) fn append_trajectory_record(
58    path: &Path,
59    record: &serde_json::Value,
60    max_bytes: u64,
61) -> Result<()> {
62    let mut line = serde_json::to_vec(record)
63        .map_err(|error| OmegaError::Persist(format!("trajectory serialize: {error}")))?;
64    line.push(b'\n');
65
66    if let Some(parent) = path.parent() {
67        crate::private_fs::create_dir_all(parent)
68            .map_err(|error| OmegaError::Persist(format!("trajectory directory: {error}")))?;
69    }
70    let _lock = TrajectoryAppendLock::acquire(&trajectory_lock_path(path))?;
71
72    let current_len = match std::fs::metadata(path) {
73        Ok(metadata) => metadata.len(),
74        Err(error) if error.kind() == std::io::ErrorKind::NotFound => 0,
75        Err(error) => {
76            return Err(OmegaError::Persist(format!(
77                "trajectory metadata {}: {error}",
78                path.display()
79            )))
80        }
81    };
82    let record_len = u64::try_from(line.len())
83        .map_err(|error| OmegaError::Persist(format!("trajectory record size: {error}")))?;
84    if !matches!(current_len.checked_add(record_len), Some(size) if size <= max_bytes) {
85        return Err(OmegaError::Persist(format!(
86            "trajectory size limit exceeded for {}: current {current_len} bytes, record {record_len} bytes, maximum {max_bytes} bytes",
87            path.display()
88        )));
89    }
90
91    let mut file = crate::private_fs::open_options()
92        .create(true)
93        .append(true)
94        .open(path)
95        .map_err(|error| {
96            OmegaError::Persist(format!("trajectory open {}: {error}", path.display()))
97        })?;
98    file.write_all(&line).map_err(|error| {
99        OmegaError::Persist(format!("trajectory write {}: {error}", path.display()))
100    })
101}
102
103/// Offline summary of a `trajectory.jsonl` file (no world re-execution).
104#[derive(Debug, Clone, Serialize)]
105#[non_exhaustive]
106pub struct TrajectoryReplaySummary {
107    /// Path of the trajectory file that was read.
108    pub path: String,
109    /// Number of valid trajectory rows parsed.
110    pub rows: usize,
111    /// Number of rows that record an accepted patch.
112    pub patches: usize,
113    /// First average error.
114    pub first_avg_err: Option<f64>,
115    /// Most recent average error.
116    pub last_avg_err: Option<f64>,
117    /// Action names paired with their occurrence counts.
118    pub action_counts: Vec<(String, usize)>,
119    /// Last N step lines (step, action, patched, avg_err) for operator view.
120    pub tail: Vec<TrajectoryReplayRow>,
121}
122
123#[derive(Debug, Clone, Serialize)]
124#[non_exhaustive]
125/// One parsed trajectory row with the fields shown in replay summaries.
126pub struct TrajectoryReplayRow {
127    /// Kernel step number recorded in the row.
128    pub step: u64,
129    /// Action recorded for the step.
130    pub action: String,
131    /// Whether the step recorded an accepted patch.
132    pub patched: bool,
133    /// Average prediction error reported for the step.
134    pub avg_err: Option<f64>,
135    /// Goal associated with the step, when present in the file.
136    pub goal: Option<String>,
137    /// L2 arm-selection record, when present in the file.
138    pub l2_decision: Option<crate::types::L2DecisionRecord>,
139    /// Current L2 gate state.
140    pub l2_gate_state: crate::l2::control::L2GateState,
141    /// L2 policy learning-rate parameter.
142    pub l2_alpha: f64,
143    /// Current weights assigned to L2 experts.
144    pub l2_expert_weights: BTreeMap<String, f64>,
145    /// L2 policy regularization parameter.
146    pub l2_beta: f64,
147    /// Current Lyapunov stability potential.
148    pub l2_lyapunov_potential: f64,
149    /// Whether the stability monitor vetoed an L2 change.
150    pub l2_lyapunov_veto: bool,
151    /// Whether the most recent L2 lookup hit the meta-cache.
152    pub l2_meta_cache_hit: bool,
153    /// Residual used by the L2 Dayan stability calculation.
154    pub l2_dayan_residual: f64,
155    /// L2 policy currently applied at the control boundary.
156    pub l2_applied_policy: crate::types::L2Policy,
157    /// L2 policy proposed but not yet applied.
158    pub l2_pending_policy: crate::types::L2Policy,
159}
160
161/// Read and summarize a trajectory.jsonl without running the kernel loop.
162pub fn replay_trajectory_file(path: &Path, tail_n: usize) -> Result<TrajectoryReplaySummary> {
163    use std::fs;
164    if !path.exists() {
165        return Err(OmegaError::Persist(format!(
166            "trajectory not found: {}",
167            path.display()
168        )));
169    }
170    const MAX_TRACE_BYTES: u64 = 64 * 1024 * 1024;
171    const MAX_TRACE_LINE_BYTES: usize = 1024 * 1024;
172    const MAX_TRACE_ROWS: usize = 1_000_000;
173    let mut file = fs::File::open(path).map_err(|e| OmegaError::Persist(e.to_string()))?;
174    let mut data = String::new();
175    std::io::Read::read_to_string(
176        &mut std::io::Read::take(std::io::Read::by_ref(&mut file), MAX_TRACE_BYTES + 1),
177        &mut data,
178    )
179    .map_err(|e| OmegaError::Persist(e.to_string()))?;
180    if data.len() as u64 > MAX_TRACE_BYTES {
181        return Err(OmegaError::Persist(format!(
182            "trajectory replay byte limit exceeded: maximum {MAX_TRACE_BYTES} bytes"
183        )));
184    }
185    let mut rows = 0usize;
186    let mut patches = 0usize;
187    let mut first_avg_err = None;
188    let mut last_avg_err = None;
189    let mut actions: BTreeMap<String, usize> = BTreeMap::new();
190    let mut tail_buf: Vec<TrajectoryReplayRow> = Vec::new();
191
192    for line in data.lines().filter(|l| !l.trim().is_empty()) {
193        if line.len() > MAX_TRACE_LINE_BYTES {
194            return Err(OmegaError::Persist(format!(
195                "trajectory replay line exceeds {MAX_TRACE_LINE_BYTES} byte limit"
196            )));
197        }
198        if rows >= MAX_TRACE_ROWS {
199            return Err(OmegaError::Persist(format!(
200                "trajectory replay row count exceeds {MAX_TRACE_ROWS} limit"
201            )));
202        }
203        let v: serde_json::Value =
204            serde_json::from_str(line).map_err(|e| OmegaError::Persist(e.to_string()))?;
205        rows += 1;
206        let step = v.get("step").and_then(|x| x.as_u64()).unwrap_or(0);
207        let action = v
208            .get("action")
209            .and_then(|x| x.as_str())
210            .unwrap_or("-")
211            .to_string();
212        let patched = v.get("patched").and_then(|x| x.as_bool()).unwrap_or(false);
213        if patched {
214            patches += 1;
215        }
216        let avg_err = v.get("avg_err").and_then(|x| x.as_f64());
217        if first_avg_err.is_none() {
218            first_avg_err = avg_err;
219        }
220        if avg_err.is_some() {
221            last_avg_err = avg_err;
222        }
223        *actions.entry(action.clone()).or_insert(0) += 1;
224        let goal = v
225            .get("goal")
226            .and_then(|x| x.as_str())
227            .map(|s| s.to_string());
228        tail_buf.push(TrajectoryReplayRow {
229            step,
230            action,
231            patched,
232            avg_err,
233            goal,
234            l2_decision: v
235                .get("l2_decision")
236                .cloned()
237                .and_then(|value| serde_json::from_value(value).ok()),
238            l2_gate_state: v
239                .get("l2_gate_state")
240                .cloned()
241                .and_then(|value| serde_json::from_value(value).ok())
242                .unwrap_or_default(),
243            l2_alpha: v
244                .get("l2_alpha")
245                .and_then(|value| value.as_f64())
246                .unwrap_or(0.0),
247            l2_expert_weights: v
248                .get("l2_expert_weights")
249                .cloned()
250                .and_then(|value| serde_json::from_value(value).ok())
251                .unwrap_or_default(),
252            l2_beta: v
253                .get("l2_beta")
254                .and_then(|value| value.as_f64())
255                .unwrap_or(0.0),
256            l2_lyapunov_potential: v
257                .get("l2_lyapunov_potential")
258                .and_then(|value| value.as_f64())
259                .unwrap_or(1.0),
260            l2_lyapunov_veto: v
261                .get("l2_lyapunov_veto")
262                .and_then(|value| value.as_bool())
263                .unwrap_or(false),
264            l2_meta_cache_hit: v
265                .get("l2_meta_cache_hit")
266                .and_then(|value| value.as_bool())
267                .unwrap_or(false),
268            l2_dayan_residual: v
269                .get("l2_dayan_residual")
270                .and_then(|value| value.as_f64())
271                .unwrap_or(0.0),
272            l2_applied_policy: v
273                .get("l2_applied_policy")
274                .cloned()
275                .and_then(|value| serde_json::from_value(value).ok())
276                .unwrap_or_default(),
277            l2_pending_policy: v
278                .get("l2_pending_policy")
279                .cloned()
280                .and_then(|value| serde_json::from_value(value).ok())
281                .unwrap_or_default(),
282        });
283    }
284
285    let mut action_counts: Vec<_> = actions.into_iter().collect();
286    action_counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
287
288    let tail = if tail_buf.len() > tail_n {
289        tail_buf.split_off(tail_buf.len() - tail_n)
290    } else {
291        tail_buf
292    };
293
294    Ok(TrajectoryReplaySummary {
295        path: path.display().to_string(),
296        rows,
297        patches,
298        first_avg_err,
299        last_avg_err,
300        action_counts,
301        tail,
302    })
303}