Skip to main content

aria_engine_core/
trace.rs

1use serde::{Deserialize, Serialize};
2
3use crate::action::Action;
4use crate::condition::Condition;
5use crate::graph::Graph;
6use crate::policy::{DiffPolicy, MatchPolicy};
7
8/// A single trace entry for JSONL export.
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct TraceEntry {
11    /// Discrete step counter
12    pub t: u64,
13    /// Action taken
14    pub action: String,
15    /// Residual after step
16    pub res: f64,
17    /// Field energy after step
18    pub energy: f64,
19    /// Graph size |G| = |V| + |E|
20    pub graph_size: usize,
21    /// Conditioning
22    pub condition: String,
23}
24
25/// Full trace: a sequence of entries.
26///
27/// The header (`config_*` fields) must carry everything `aria emit` needs to
28/// replay Φ byte-for-byte without a matching `--config`: `n_modes`,
29/// `latent_dim`, and `eps` alone are not enough. `seed`, `schedule`,
30/// `condition`, and `match_policy` select the trajectory; `diff_policy`
31/// (consumed by `Engine::apply`), `stutter_k` (consumed by the scheduler),
32/// and `optical`/`merge_tau` (consumed by `engine_with` when the backends are
33/// built) all change the replayed latents just as much. `initial_graph`
34/// records `G₀` so a run seeded with a non-empty graph is self-describing
35/// rather than silently replayed from `Graph::empty()`. Omitting any of these
36/// makes replay silently diverge from the run that produced the trace (see
37/// `aria emit`'s doc comment).
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct Trace {
40    pub config_n_modes: usize,
41    pub config_latent_dim: usize,
42    pub config_eps: f64,
43    /// Seed the run used — `None` only if the run itself used no fixed seed.
44    pub config_seed: Option<u64>,
45    /// Schedule string ("opmd" or a custom action-char sequence).
46    pub config_schedule: String,
47    /// Conditioning a_t the run used.
48    pub config_condition: Condition,
49    /// Match policy ℙ3 the run used.
50    pub config_match_policy: MatchPolicy,
51    /// Diffusion policy for `Diff_G(z)` — consumed by `Engine::apply`.
52    pub config_diff_policy: DiffPolicy,
53    /// Stutter budget K (𝐂5) — consumed by the scheduler.
54    pub config_stutter_k: u64,
55    /// Optical backend selection (`"fft"`/`"householder"`, `None` = automatic)
56    /// — consumed by `engine_with` when the backend is built.
57    pub config_optical: Option<String>,
58    /// Graph merge distance threshold τ (spec §0.4) — consumed by
59    /// `engine_with` via `SimGraphBackend::with_merge_tau`.
60    pub config_merge_tau: f64,
61    /// The graph the run started from (`G₀`). `None` iff the run started from
62    /// `Graph::empty()`; recorded (not just a flag) so a seeded run stays
63    /// self-describing. `aria emit` replays from an empty graph, so it must
64    /// reject a trace whose `initial_graph` is non-empty rather than silently
65    /// diverge.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub initial_graph: Option<Graph>,
68    pub entries: Vec<TraceEntry>,
69}
70
71impl Trace {
72    #[allow(clippy::too_many_arguments)]
73    pub fn new(
74        n_modes: usize,
75        latent_dim: usize,
76        eps: f64,
77        seed: Option<u64>,
78        schedule: &str,
79        condition: Condition,
80        match_policy: MatchPolicy,
81        diff_policy: DiffPolicy,
82        stutter_k: u64,
83        optical: Option<String>,
84        merge_tau: f64,
85        initial_graph: Option<Graph>,
86    ) -> Self {
87        Trace {
88            config_n_modes: n_modes,
89            config_latent_dim: latent_dim,
90            config_eps: eps,
91            config_seed: seed,
92            config_schedule: schedule.to_string(),
93            config_condition: condition,
94            config_match_policy: match_policy,
95            config_diff_policy: diff_policy,
96            config_stutter_k: stutter_k,
97            config_optical: optical,
98            config_merge_tau: merge_tau,
99            initial_graph,
100            entries: Vec::new(),
101        }
102    }
103
104    pub fn push(
105        &mut self,
106        t: u64,
107        action: Action,
108        residual: f64,
109        energy: f64,
110        graph_size: usize,
111        condition: &str,
112    ) {
113        self.entries.push(TraceEntry {
114            t,
115            action: action.symbol().to_string(),
116            res: residual,
117            energy,
118            graph_size,
119            condition: condition.to_string(),
120        });
121    }
122
123    /// Export as JSONL string.
124    pub fn to_jsonl(&self) -> String {
125        let mut out = String::new();
126        // Header line with config. `initial_graph` is omitted (not null) when
127        // the run started from `Graph::empty()`, mirroring the struct's
128        // `skip_serializing_if` so empty-graph headers stay clean.
129        let mut header = serde_json::json!({
130            "type": "config",
131            "n_modes": self.config_n_modes,
132            "latent_dim": self.config_latent_dim,
133            "eps": self.config_eps,
134            "seed": self.config_seed,
135            "schedule": self.config_schedule,
136            "condition": self.config_condition,
137            "match_policy": self.config_match_policy,
138            "diff_policy": self.config_diff_policy,
139            "stutter_k": self.config_stutter_k,
140            "optical": self.config_optical,
141            "merge_tau": self.config_merge_tau,
142        });
143        if let Some(ref g0) = self.initial_graph {
144            header["initial_graph"] = serde_json::json!(g0);
145        }
146        out.push_str(&serde_json::to_string(&header).unwrap());
147        out.push('\n');
148        for entry in &self.entries {
149            out.push_str(&serde_json::to_string(entry).unwrap());
150            out.push('\n');
151        }
152        out
153    }
154
155    /// Action symbol sequence for trace pattern matching.
156    pub fn action_sequence(&self) -> String {
157        self.entries
158            .iter()
159            .map(|e| e.action.as_str())
160            .collect::<Vec<_>>()
161            .join("")
162    }
163}
164
165/// The `G₀` to record in a trace header.
166///
167/// Returns `None` for an empty `G₀` so the common canonical-init header stays
168/// free of a graph blob; a non-empty `G₀` is cloned verbatim so the trace
169/// stays self-describing (and `aria emit`, which replays from
170/// `Graph::empty()`, can reject it loudly rather than silently diverge).
171///
172/// Shared by every trace producer (the engine's `run_monitored*` loops and
173/// the streaming verifier) so the empty-vs-recorded rule lives in exactly one
174/// place.
175pub fn initial_graph_of(g0: &Graph) -> Option<Graph> {
176    if g0.size() == 0 {
177        None
178    } else {
179        Some(g0.clone())
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    /// The header must carry everything `aria emit` needs to replay Φ
188    /// without a matching `--config` — a regression test for the bug where
189    /// only n_modes/latent_dim/eps were recorded and seed/schedule/
190    /// condition/match_policy silently fell back to defaults on replay.
191    #[test]
192    fn header_round_trips_seed_schedule_condition_match_policy() {
193        let trace = Trace::new(
194            256,
195            64,
196            1.0,
197            Some(7),
198            "opdms",
199            Condition::WorldModel,
200            MatchPolicy::Merge,
201            DiffPolicy::GraphConditioned,
202            3,
203            Some("fft".to_string()),
204            0.7,
205            None,
206        );
207        let jsonl = trace.to_jsonl();
208        let header: serde_json::Value =
209            serde_json::from_str(jsonl.lines().next().unwrap()).unwrap();
210
211        assert_eq!(header["seed"], serde_json::json!(7));
212        assert_eq!(header["schedule"], serde_json::json!("opdms"));
213        assert_eq!(header["condition"], serde_json::json!("world_model"));
214        assert_eq!(header["match_policy"], serde_json::json!("merge"));
215    }
216
217    /// The header must also carry the inputs that change the replayed latents
218    /// but were silently dropped before: `diff_policy` (consumed by
219    /// `Engine::apply`), `stutter_k` (the scheduler), and `optical`/
220    /// `merge_tau` (`engine_with`). Regression test for the review finding
221    /// that `diff_policy = "graph_conditioned"` replayed as `Identity`.
222    #[test]
223    fn header_round_trips_diff_policy_stutter_k_optical_merge_tau() {
224        let trace = Trace::new(
225            256,
226            64,
227            1.0,
228            Some(7),
229            "opmd",
230            Condition::Token,
231            MatchPolicy::Merge,
232            DiffPolicy::GraphConditioned,
233            4,
234            Some("householder".to_string()),
235            0.25,
236            None,
237        );
238        let jsonl = trace.to_jsonl();
239        let header: serde_json::Value =
240            serde_json::from_str(jsonl.lines().next().unwrap()).unwrap();
241
242        assert_eq!(header["diff_policy"], serde_json::json!("graph_conditioned"));
243        assert_eq!(header["stutter_k"], serde_json::json!(4));
244        assert_eq!(header["optical"], serde_json::json!("householder"));
245        assert_eq!(header["merge_tau"], serde_json::json!(0.25));
246        // An empty G₀ is omitted from the header entirely, not stored as null.
247        assert!(header.get("initial_graph").is_none());
248    }
249
250    /// A run seeded with a non-empty `G₀` records it so the trace is
251    /// self-describing; `aria emit` must reject it rather than replay from
252    /// `Graph::empty()`.
253    #[test]
254    fn header_records_a_non_empty_initial_graph() {
255        let g0 = Graph::seed(crate::graph::GraphNode {
256            id: 0,
257            embedding: vec![0.0; 64],
258            node_type: crate::graph::NodeType::Observation,
259            timestamp: 0,
260        });
261        let trace = Trace::new(
262            256,
263            64,
264            1.0,
265            Some(7),
266            "opmd",
267            Condition::Token,
268            MatchPolicy::Identity,
269            DiffPolicy::Identity,
270            2,
271            None,
272            0.5,
273            Some(g0),
274        );
275        let jsonl = trace.to_jsonl();
276        let header: serde_json::Value =
277            serde_json::from_str(jsonl.lines().next().unwrap()).unwrap();
278
279        let recorded = header
280            .get("initial_graph")
281            .expect("a non-empty G₀ must be recorded");
282        let recorded: Graph = serde_json::from_value(recorded.clone()).unwrap();
283        assert_eq!(recorded.node_count(), 1);
284    }
285
286    #[test]
287    fn header_seed_is_null_when_run_had_none() {
288        let trace = Trace::new(
289            256,
290            64,
291            1.0,
292            None,
293            "opmd",
294            Condition::Token,
295            MatchPolicy::Identity,
296            DiffPolicy::Identity,
297            2,
298            None,
299            0.5,
300            None,
301        );
302        let jsonl = trace.to_jsonl();
303        let header: serde_json::Value =
304            serde_json::from_str(jsonl.lines().next().unwrap()).unwrap();
305        assert!(header["seed"].is_null());
306    }
307}