rusty_agent_runtime/journal.rs
1//! The effect journal: the Flight Recorder's append-only run evidence, plus
2//! the determinism seams ([`Clock`], [`RngSource`]) that let a recorded run
3//! be re-driven exactly.
4//!
5//! A [`Journal`] is created per run (one `Executor::run` call) and receives
6//! every effect the executor observes: super-step boundaries, node
7//! inputs/outputs, interrupts, resumes, routing decisions, and checkpoint
8//! writes. Nodes, models, and tools record their own calls (model, tool,
9//! remote, WASM) through the same journal when handed a clone — the
10//! [`EventDraft`] builder is the public recording API.
11//!
12//! Two properties make the journal evidence rather than logs:
13//!
14//! - **Causal order.** Every event carries a monotonic `seq` and the id of
15//! its causal parent, assigned by the journal at record time. The journal
16//! — not wall time — defines the run's order.
17//! - **Tamper-evident head.** Recording chains a SHA-256 head hash over the
18//! canonical serialization of each event. Checkpoints stamp the head as a
19//! [`crate::record::JournalRef`], binding state and evidence together.
20//!
21//! # Determinism seams
22//!
23//! The executor sources every timestamp and every random id through
24//! [`Clock`] and [`RngSource`], configured per run via
25//! `RunConfig::with_clock` / `RunConfig::with_rng`. Defaults
26//! ([`Clock::System`], [`RngSource::System`]) are byte-identical to the
27//! pre-R0.5 behavior. A [`Clock::Logical`] + [`RngSource::Seeded`] pair
28//! makes event timestamps, latencies, event ids, run ids, and checkpoint ids
29//! reproducible — the precondition for exact replay.
30//!
31//! The in-memory journal is the v1 store; [`JournalSnapshot`] is its
32//! serde-complete export form (events plus the artifact payloads they
33//! reference), the unit portable replay fixtures are built from.
34//!
35//! # Artifact persistence seam (R0.7 wave 4)
36//!
37//! Payloads over [`INLINE_PAYLOAD_MAX_BYTES`] have always been
38//! content-addressed ([`ArtifactRef`]) with their bytes embedded in the
39//! snapshot's artifact map — a self-contained fixture contract that
40//! [`Journal::snapshot`] keeps. W4 adds the *other* half of the contract:
41//! an external, content-addressed [`ArtifactStore`] the snapshot can
42//! reference instead ([`JournalSnapshot::artifact_refs`]), so a server
43//! persisting journals stops rewriting the same large payload bytes at
44//! every checkpoint boundary. Writes dedupe by construction (the hash is
45//! the identity); reads verify integrity on every fetch. The seam is
46//! additive: snapshots with embedded bytes — everything written before W4,
47//! and replay fixtures by design — deserialize and load exactly as before.
48
49use std::collections::BTreeMap;
50use std::path::PathBuf;
51use std::sync::{Arc, Mutex, MutexGuard};
52
53use async_trait::async_trait;
54use chrono::{DateTime, Utc};
55use rand::SeedableRng;
56use rand_chacha::ChaCha8Rng;
57use serde::{Deserialize, Serialize};
58use serde_json::Value;
59
60use crate::llm::Usage;
61use crate::record::{
62 canonicalize_value, sha256_hex, ArtifactRef, Effect, EffectReceipt, EventStatus, PayloadRef,
63 RunEvent, RunEventKind, INLINE_PAYLOAD_MAX_BYTES,
64};
65
66/// The `NodeConfig::extra` key under which the executor passes the
67/// node-input journal event id of the current invocation.
68///
69/// Node code that records its own effects (model calls, tool calls) reads
70/// this key to parent them correctly: a model call's causal parent is the
71/// invocation that made it. Reserved by the runtime — applications must not
72/// set it themselves, and it travels in `NodeConfig::extra` over the worker
73/// wire protocol so remote nodes can parent their evidence the same way.
74pub const PARENT_EVENT_KEY: &str = "rusty.parent_event";
75
76/// The run's time source. All executor timestamps — event `recorded_at`,
77/// measured latencies, checkpoint `created_at` — are read through it.
78///
79/// `Clone` is cheap (a shared handle), so the same clock can serve the
80/// executor, every spawned node task, and an attached journal.
81#[derive(Debug, Clone, Default)]
82pub enum Clock {
83 /// Wall-clock UTC (`chrono::Utc::now`). The default; identical to
84 /// pre-R0.5 behavior.
85 #[default]
86 System,
87
88 /// A deterministic logical clock. Starts at `start_ms` (epoch millis)
89 /// and advances by `tick_ms` on **every read**. Two runs with the same
90 /// parameters observe the same timestamp sequence, which is what makes
91 /// recorded evidence reproducible.
92 ///
93 /// The tick-on-read semantics mean timestamps reflect how many clock
94 /// reads happened, not how much wall time passed — that is the point:
95 /// the journal's logical order is defined by `seq`, and timestamps
96 /// become a deterministic attribute rather than a second, unreliable
97 /// clock.
98 Logical(LogicalClock),
99}
100
101impl Clock {
102 /// A logical clock starting at `start_ms` (epoch millis), advancing
103 /// `tick_ms` per read.
104 pub fn logical(start_ms: u64, tick_ms: u64) -> Self {
105 Clock::Logical(LogicalClock {
106 state: Arc::new(Mutex::new(LogicalClockState {
107 now_ms: start_ms,
108 tick_ms,
109 })),
110 })
111 }
112
113 /// The current time. Under [`Clock::Logical`], every call advances the
114 /// clock by its tick.
115 pub fn now(&self) -> DateTime<Utc> {
116 match self {
117 Clock::System => Utc::now(),
118 Clock::Logical(logical) => {
119 let mut state = logical.lock();
120 let millis = state.now_ms;
121 state.now_ms = state.now_ms.saturating_add(state.tick_ms);
122 // Epoch millis are always representable; the logical clock
123 // is the only caller-controlled input and saturates.
124 DateTime::from_timestamp_millis(millis.min(i64::MAX as u64) as i64)
125 .unwrap_or(DateTime::UNIX_EPOCH)
126 }
127 }
128 }
129
130 /// The current logical clock value in milliseconds (the value stamped
131 /// into [`crate::record::CheckpointHeader::logical_clock`]). Reads
132 /// through the same seam as [`Clock::now`], so logical clocks tick.
133 pub fn now_ms(&self) -> u64 {
134 self.now().timestamp_millis().max(0) as u64
135 }
136}
137
138/// Shared state of a [`Clock::Logical`] handle.
139#[derive(Debug, Clone)]
140pub struct LogicalClock {
141 state: Arc<Mutex<LogicalClockState>>,
142}
143
144#[derive(Debug)]
145struct LogicalClockState {
146 now_ms: u64,
147 tick_ms: u64,
148}
149
150impl LogicalClock {
151 fn lock(&self) -> MutexGuard<'_, LogicalClockState> {
152 // Poison means a recording path panicked mid-read; the clock value
153 // itself is plain data and stays coherent, so recovering is safe.
154 self.state.lock().unwrap_or_else(|e| e.into_inner())
155 }
156}
157
158/// The run's randomness source. Checkpoint ids and run ids are minted
159/// through it — the only entropy the executor consumes.
160#[derive(Debug, Clone, Default)]
161pub enum RngSource {
162 /// Operating-system entropy (`uuid::Uuid::new_v4`). The default;
163 /// identical to pre-R0.5 behavior.
164 #[default]
165 System,
166
167 /// A deterministic ChaCha8 stream seeded from a `u64`. Two runs with the
168 /// same seed mint the same id sequence, so journals and checkpoints of a
169 /// re-driven run reproduce the original's ids.
170 Seeded(SeededRng),
171}
172
173impl RngSource {
174 /// A seeded RNG drawing from one ChaCha8 stream per handle clone.
175 pub fn seeded(seed: u64) -> Self {
176 RngSource::Seeded(SeededRng {
177 rng: Arc::new(Mutex::new(ChaCha8Rng::seed_from_u64(seed))),
178 })
179 }
180
181 /// Mint a UUID (v4 layout in both modes: variant/version bits are set
182 /// explicitly for seeded draws, so downstream consumers cannot
183 /// distinguish the source from the bits).
184 pub fn uuid(&self) -> uuid::Uuid {
185 match self {
186 RngSource::System => uuid::Uuid::new_v4(),
187 RngSource::Seeded(seeded) => {
188 use rand::RngCore as _;
189 let mut bytes = [0u8; 16];
190 let mut rng = seeded.rng.lock().unwrap_or_else(|e| e.into_inner());
191 rng.fill_bytes(&mut bytes);
192 uuid::Builder::from_random_bytes(bytes).into_uuid()
193 }
194 }
195 }
196
197 /// Convenience: [`RngSource::uuid`] as a string.
198 pub fn uuid_string(&self) -> String {
199 self.uuid().to_string()
200 }
201
202 /// A uniform draw from `[0, 1)` with 53 bits of mantissa (R0.10 wave 2).
203 ///
204 /// The runtime's decision points consume entropy beyond id minting:
205 /// backoff jitter, the digital twin's fault schedules and schedule
206 /// randomization, and stochastic shadow policies exploring by seeded
207 /// draw. Sourcing those draws through the same seam as ids keeps a
208 /// seeded run's *entire* draw sequence reproducible — a twin run
209 /// reproduces exactly from its seed and fixture. The system mode derives
210 /// its draw from OS entropy via [`RngSource::uuid`], the same source the
211 /// system mode already trusts for ids.
212 pub fn next_f64(&self) -> f64 {
213 let bits = match self {
214 RngSource::System => {
215 let bytes = self.uuid().into_bytes();
216 u64::from_le_bytes(bytes[..8].try_into().expect("a uuid is 16 bytes"))
217 }
218 RngSource::Seeded(seeded) => {
219 use rand::RngCore as _;
220 seeded
221 .rng
222 .lock()
223 .unwrap_or_else(|e| e.into_inner())
224 .next_u64()
225 }
226 };
227 (bits >> 11) as f64 / 9_007_199_254_740_992.0
228 }
229}
230
231/// A shared ChaCha8 stream behind a mutex (interior mutability lets the
232/// executor pass `&self` while node tasks draw ids).
233#[derive(Debug, Clone)]
234pub struct SeededRng {
235 rng: Arc<Mutex<ChaCha8Rng>>,
236}
237
238/// A not-yet-sequenced event: everything about a [`RunEvent`] except the
239/// fields only the journal can assign (`id`, `run_id`, `thread_id`, `seq`,
240/// `recorded_at`). Build via [`EventDraft::new`] plus the builder methods,
241/// then hand to [`Journal::record`].
242#[derive(Debug, Clone)]
243pub struct EventDraft {
244 kind: RunEventKind,
245 effect: Effect,
246 node_id: Option<String>,
247 input: Option<Value>,
248 output: Option<Value>,
249 latency_ms: Option<u64>,
250 tokens: Option<Usage>,
251 cost_usd: Option<f64>,
252 status: EventStatus,
253 parent: Option<String>,
254}
255
256impl EventDraft {
257 /// A draft of kind `kind` produced by an effect of class `effect`.
258 pub fn new(kind: RunEventKind, effect: Effect) -> Self {
259 Self {
260 kind,
261 effect,
262 node_id: None,
263 input: None,
264 output: None,
265 latency_ms: None,
266 tokens: None,
267 cost_usd: None,
268 status: EventStatus::Ok,
269 parent: None,
270 }
271 }
272
273 /// The node this event is about.
274 pub fn node(mut self, node_id: impl Into<String>) -> Self {
275 self.node_id = Some(node_id.into());
276 self
277 }
278
279 /// The input payload. Large values are content-addressed by the journal
280 /// at record time (see [`INLINE_PAYLOAD_MAX_BYTES`]).
281 pub fn input(mut self, value: Value) -> Self {
282 self.input = Some(value);
283 self
284 }
285
286 /// The output payload; same large-value handling as [`EventDraft::input`].
287 pub fn output(mut self, value: Value) -> Self {
288 self.output = Some(value);
289 self
290 }
291
292 /// The measured latency of the recorded operation, in milliseconds.
293 pub fn latency_ms(mut self, latency_ms: u64) -> Self {
294 self.latency_ms = Some(latency_ms);
295 self
296 }
297
298 /// Token usage reported for a model call.
299 pub fn tokens(mut self, usage: Usage) -> Self {
300 self.tokens = Some(usage);
301 self
302 }
303
304 /// Monetary cost of the recorded operation in USD.
305 pub fn cost_usd(mut self, cost: f64) -> Self {
306 self.cost_usd = Some(cost);
307 self
308 }
309
310 /// The outcome status (defaults to [`EventStatus::Ok`]).
311 pub fn status(mut self, status: EventStatus) -> Self {
312 self.status = status;
313 self
314 }
315
316 /// The causal parent: the id of the event that caused this one.
317 pub fn parent(mut self, parent: impl Into<String>) -> Self {
318 self.parent = Some(parent.into());
319 self
320 }
321}
322
323/// The journal's mutable interior, behind one mutex. All fields advance
324/// together on every append, so poisoning cannot leave them inconsistent —
325/// recovery on poison is safe.
326#[derive(Debug)]
327struct JournalInner {
328 events: Vec<RunEvent>,
329 /// Content-addressed payloads too large to inline, keyed by SHA-256 hex.
330 /// `BTreeMap` so snapshot serialization order is canonical.
331 artifacts: BTreeMap<String, Value>,
332 /// Running chained head hash: `H_0 = sha256("")`,
333 /// `H_n = sha256(H_{n-1} || canonical_json(event_n))`.
334 head_hash: String,
335}
336
337/// An append-only, in-memory journal of one run's [`RunEvent`]s.
338///
339/// Cheap to clone: clones share the same journal (one `Arc` layer inside),
340/// which is how node closures record model/tool calls into the same journal
341/// the executor is writing. Thread-safe; `Send + Sync`.
342///
343/// The journal stamps every event with its `run_id`/`thread_id`, the next
344/// sequence number, and a `recorded_at` read from its own [`Clock`] — so
345/// events recorded from inside nodes (whose code cannot see the executor's
346/// clock) are still timestamped through the run's determinism seam.
347#[derive(Debug, Clone)]
348pub struct Journal {
349 run_id: String,
350 thread_id: String,
351 clock: Clock,
352 inner: Arc<Mutex<JournalInner>>,
353}
354
355impl Journal {
356 /// A fresh journal for `run_id` / `thread_id`, timestamping events from
357 /// `clock`.
358 pub fn new(run_id: impl Into<String>, thread_id: impl Into<String>, clock: Clock) -> Self {
359 Self {
360 run_id: run_id.into(),
361 thread_id: thread_id.into(),
362 clock,
363 inner: Arc::new(Mutex::new(JournalInner {
364 events: Vec::new(),
365 artifacts: BTreeMap::new(),
366 head_hash: sha256_hex(b""),
367 })),
368 }
369 }
370
371 /// Rebuild a journal from a [`JournalSnapshot`] (e.g. a replay fixture).
372 ///
373 /// The head hash is recomputed from the events rather than trusted from
374 /// the snapshot, so a corrupted or edited fixture is detected here
375 /// instead of deep inside a replay. Returns `None`-style failure as a
376 /// [`crate::error::RustyError::Serialization`] when an event fails to
377 /// serialize (not realistically possible for well-formed snapshots).
378 pub fn from_snapshot(snapshot: JournalSnapshot, clock: Clock) -> crate::error::Result<Self> {
379 // An externalized snapshot cannot resolve payloads without its
380 // store; refusing here beats a journal that silently answers `None`
381 // for artifact resolutions deep inside a replay.
382 if !snapshot.artifact_refs.is_empty() {
383 return Err(crate::error::RustyError::Serialization(
384 serde_json::Error::io(std::io::Error::new(
385 std::io::ErrorKind::InvalidData,
386 "journal snapshot references an external artifact store; \
387 load it with Journal::from_snapshot_with_store",
388 )),
389 ));
390 }
391 let mut head_hash = sha256_hex(b"");
392 for event in &snapshot.events {
393 head_hash = chained_hash(&head_hash, event)?;
394 }
395 if head_hash != snapshot.head_hash {
396 return Err(crate::error::RustyError::Serialization(
397 serde_json::Error::io(std::io::Error::new(
398 std::io::ErrorKind::InvalidData,
399 format!(
400 "journal snapshot head hash mismatch: events recompute to \
401 {head_hash}, snapshot claims {}",
402 snapshot.head_hash
403 ),
404 )),
405 ));
406 }
407 let run_id = snapshot.run_id.clone();
408 let thread_id = snapshot.thread_id.clone();
409 Ok(Self {
410 run_id,
411 thread_id,
412 clock,
413 inner: Arc::new(Mutex::new(JournalInner {
414 events: snapshot.events,
415 artifacts: snapshot.artifacts,
416 head_hash,
417 })),
418 })
419 }
420
421 /// The run this journal records.
422 pub fn run_id(&self) -> &str {
423 &self.run_id
424 }
425
426 /// The thread the run belongs to.
427 pub fn thread_id(&self) -> &str {
428 &self.thread_id
429 }
430
431 /// The clock events are timestamped from.
432 pub fn clock(&self) -> &Clock {
433 &self.clock
434 }
435
436 fn lock(&self) -> MutexGuard<'_, JournalInner> {
437 self.inner.lock().unwrap_or_else(|e| e.into_inner())
438 }
439
440 /// Append one event and return its id (`{run_id}:{seq}`).
441 ///
442 /// The journal assigns the sequence number and timestamp, promotes
443 /// oversized payloads into the artifact map (replacing them with
444 /// [`PayloadRef::Artifact`] references), and chains the head hash over
445 /// the canonical serialization of the appended event.
446 pub fn record(&self, draft: EventDraft) -> String {
447 let recorded_at = self.clock.now();
448 let mut inner = self.lock();
449 let seq = inner.events.len() as u64;
450 let id = format!("{}:{seq}", self.run_id);
451
452 let input = draft
453 .input
454 .map(|value| store_payload(&mut inner.artifacts, value));
455 let output = draft
456 .output
457 .map(|value| store_payload(&mut inner.artifacts, value));
458
459 let event = RunEvent {
460 id: id.clone(),
461 run_id: self.run_id.clone(),
462 thread_id: self.thread_id.clone(),
463 node_id: draft.node_id,
464 seq,
465 kind: draft.kind,
466 effect: draft.effect,
467 input,
468 output,
469 latency_ms: draft.latency_ms,
470 tokens: draft.tokens,
471 cost_usd: draft.cost_usd,
472 status: draft.status,
473 parent: draft.parent,
474 recorded_at,
475 };
476
477 // Hash chaining over the canonical serialization: payload maps are
478 // key-sorted before hashing (see `canonicalized_for_hash`), so the
479 // hash is stable for identical event content regardless of the
480 // serde_json map backend a build ends up with. Serialization of a
481 // just-constructed event cannot realistically fail; if it somehow
482 // does, the event is still recorded — evidence must not be lost to
483 // a hashing defect — and the head chains over a fixed marker
484 // instead.
485 match serde_json::to_vec(&canonicalized_for_hash(&event)) {
486 Ok(bytes) => {
487 inner.head_hash = sha256_hex(&[inner.head_hash.as_bytes(), &bytes].concat());
488 }
489 Err(e) => {
490 tracing::warn!(error = %e, "failed to serialize event for head hash");
491 inner.head_hash =
492 sha256_hex(&[inner.head_hash.as_bytes(), b"!unhashable"].concat());
493 }
494 }
495 inner.events.push(event);
496 id
497 }
498
499 /// The recorded events in sequence order.
500 pub fn events(&self) -> Vec<RunEvent> {
501 self.lock().events.clone()
502 }
503
504 /// Number of recorded events.
505 pub fn len(&self) -> usize {
506 self.lock().events.len()
507 }
508
509 /// `true` when nothing has been recorded.
510 pub fn is_empty(&self) -> bool {
511 self.len() == 0
512 }
513
514 /// The current head hash (chained SHA-256 over all recorded events).
515 pub fn head_hash(&self) -> String {
516 self.lock().head_hash.clone()
517 }
518
519 /// The journal head as a [`crate::record::JournalRef`], for stamping
520 /// into checkpoints.
521 pub fn head_ref(&self) -> crate::record::JournalRef {
522 let inner = self.lock();
523 crate::record::JournalRef {
524 events: inner.events.len() as u64,
525 sha256: inner.head_hash.clone(),
526 }
527 }
528
529 /// A serde-complete export of the journal: every event plus the artifact
530 /// payloads they reference. The unit a portable replay fixture is built
531 /// from.
532 ///
533 /// Bytes stay embedded by design: the fixture contract (self-contained,
534 /// loadable anywhere) outranks the size optimization. Persistence paths
535 /// that want the optimization use [`Journal::snapshot_externalized`].
536 pub fn snapshot(&self) -> JournalSnapshot {
537 let inner = self.lock();
538 JournalSnapshot {
539 run_id: self.run_id.clone(),
540 thread_id: self.thread_id.clone(),
541 events: inner.events.clone(),
542 artifacts: inner.artifacts.clone(),
543 artifact_refs: BTreeMap::new(),
544 head_hash: inner.head_hash.clone(),
545 }
546 }
547
548 /// Export the journal with its artifact payloads spilled to an external
549 /// [`ArtifactStore`]: the snapshot records content addresses
550 /// ([`JournalSnapshot::artifact_refs`]) instead of embedding bytes.
551 ///
552 /// This is the persistence-path export (R0.7 wave 4): a server
553 /// rewriting journal snapshots at every checkpoint boundary stores each
554 /// oversized payload once per content, not once per snapshot — re-puts
555 /// dedupe on the content address, so artifact-addressed retry traffic is
556 /// cheap. Load with [`Journal::from_snapshot_with_store`].
557 pub async fn snapshot_externalized(
558 &self,
559 store: &dyn ArtifactStore,
560 ) -> crate::error::Result<JournalSnapshot> {
561 let mut snapshot = self.snapshot();
562 let artifacts = std::mem::take(&mut snapshot.artifacts);
563 for (sha256, value) in artifacts {
564 // The canonical serialization the artifact map was keyed on
565 // (`store_payload`); infallible for a Value in practice.
566 let bytes = serde_json::to_vec(&value).expect("a serde_json::Value always serializes");
567 let reference = store.put(&bytes).await?;
568 debug_assert_eq!(
569 reference.sha256, sha256,
570 "artifact map keys are content addresses by construction"
571 );
572 snapshot.artifact_refs.insert(sha256, reference);
573 }
574 Ok(snapshot)
575 }
576
577 /// Rebuild a journal from an externalized snapshot
578 /// ([`Journal::snapshot_externalized`]): every referenced artifact is
579 /// fetched through `store` — integrity-verified on read by the store's
580 /// contract — and re-embedded, after which the load is the ordinary
581 /// hash-verified [`Journal::from_snapshot`].
582 pub async fn from_snapshot_with_store(
583 mut snapshot: JournalSnapshot,
584 store: &dyn ArtifactStore,
585 clock: Clock,
586 ) -> crate::error::Result<Self> {
587 let refs = std::mem::take(&mut snapshot.artifact_refs);
588 for (sha256, reference) in refs {
589 let bytes = store.get(&reference.sha256).await?;
590 let value: Value = serde_json::from_slice(&bytes).map_err(|e| {
591 crate::error::RustyError::Serialization(serde_json::Error::io(std::io::Error::new(
592 std::io::ErrorKind::InvalidData,
593 format!("artifact `{sha256}` is not valid JSON: {e}"),
594 )))
595 })?;
596 snapshot.artifacts.insert(sha256, value);
597 }
598 Self::from_snapshot(snapshot, clock)
599 }
600
601 /// Resolve a [`PayloadRef`] to its value, looking through the artifact
602 /// map. `None` for artifact references whose bytes are absent (a
603 /// truncated snapshot — detectable via [`Journal::from_snapshot`]'s hash
604 /// check).
605 pub fn resolve(&self, payload: &PayloadRef) -> Option<Value> {
606 match payload {
607 PayloadRef::Inline(value) => Some(value.clone()),
608 PayloadRef::Artifact(reference) => {
609 self.lock().artifacts.get(&reference.sha256).cloned()
610 }
611 }
612 }
613
614 /// Journal an effect receipt (R0.6 Durable Work): the effect's own
615 /// confirmation of an `Idempotent` side effect, recorded as a
616 /// [`RunEventKind::EffectReceipt`] event with the receipt as its output
617 /// payload and `parent` as its causal parent — the task lifecycle event
618 /// that completed the effect once task lifecycle journaling lands; until
619 /// then, the run's journal head is the honest parent (the receipt was
620 /// caused by everything the run did before the task settled).
621 ///
622 /// Recording here — one canonical shape, as with model/tool calls — is
623 /// what lets [`JournalSnapshot::find_effect_receipt`] serve the receipt
624 /// during replay instead of re-sending the effect.
625 pub fn record_effect_receipt(&self, receipt: &EffectReceipt, parent: Option<String>) -> String {
626 let mut draft = EventDraft::new(RunEventKind::EffectReceipt, Effect::Idempotent)
627 // Serialization of a just-built receipt cannot realistically
628 // fail; if it somehow does, record the payload the event must
629 // not lose rather than drop the evidence.
630 .output(serde_json::to_value(receipt).unwrap_or_else(
631 |_| serde_json::json!({ "idempotency_key": receipt.idempotency_key }),
632 ));
633 if let Some(parent) = parent {
634 draft = draft.parent(parent);
635 }
636 self.record(draft)
637 }
638
639 /// Bind a memory source to this journal (R0.8 Rusty Learn, wave 1): the
640 /// governed-memory seam. The returned handle journals every read as
641 /// [`RunEventKind::MemoryRead`] ([`Effect::ReadOnly`], with the resolved
642 /// query plus budget as the request and the assembly as the output) and
643 /// every write as [`RunEventKind::MemoryWrite`] ([`Effect::Idempotent`]
644 /// under the derived key), so exact replay serves the journaled assembly
645 /// instead of re-querying the store.
646 ///
647 /// Node closures capture the handle exactly the way they capture a
648 /// [`Journal`] clone for recording model and tool calls; causal
649 /// parentage comes from the invocation's node-input event id
650 /// ([`PARENT_EVENT_KEY`]).
651 pub fn memory(&self, source: crate::memory::MemorySource) -> crate::memory::JournaledMemory {
652 crate::memory::JournaledMemory::new(self, source)
653 }
654}
655
656/// Store `value` inline or — when its serialized size exceeds
657/// [`INLINE_PAYLOAD_MAX_BYTES`] — in the artifact map, returning the
658/// reference to record on the event.
659fn store_payload(artifacts: &mut BTreeMap<String, Value>, value: Value) -> PayloadRef {
660 let Ok(bytes) = serde_json::to_vec(&value) else {
661 // A Value that fails to serialize is a contradiction; keep it inline
662 // rather than drop evidence.
663 return PayloadRef::Inline(value);
664 };
665 if bytes.len() <= INLINE_PAYLOAD_MAX_BYTES {
666 return PayloadRef::Inline(value);
667 }
668 let reference = ArtifactRef {
669 sha256: sha256_hex(&bytes),
670 bytes: bytes.len() as u64,
671 };
672 artifacts.entry(reference.sha256.clone()).or_insert(value);
673 PayloadRef::Artifact(reference)
674}
675
676/// `sha256(prev || canonical_json(event))` — the head-hash chain step,
677/// shared by [`Journal::record`] and [`Journal::from_snapshot`].
678fn chained_hash(prev: &str, event: &RunEvent) -> crate::error::Result<String> {
679 let bytes = serde_json::to_vec(&canonicalized_for_hash(event))?;
680 Ok(sha256_hex(&[prev.as_bytes(), &bytes].concat()))
681}
682
683/// Recompute the chained head over `events` from the genesis hash — the
684/// verification-path half of the chain contract, shared by
685/// [`Journal::from_snapshot`] and the run-receipt verifier
686/// ([`crate::receipt::verify_receipt`]) so a receipt's head and the
687/// journal's head are the same bytes by construction.
688pub(crate) fn recompute_head_hash(events: &[RunEvent]) -> crate::error::Result<String> {
689 let mut head_hash = sha256_hex(b"");
690 for event in events {
691 head_hash = chained_hash(&head_hash, event)?;
692 }
693 Ok(head_hash)
694}
695
696/// The event as the head-hash chain covers it: identical except that every
697/// inline payload value is key-sorted recursively.
698///
699/// The chain's contract is "same content, same hash" — a replay that
700/// reproduces every event exactly must reproduce the head. That held
701/// trivially while serde_json's map was BTreeMap-backed everywhere; the
702/// `preserve_order` feature (pulled in transitively by `cedar-policy-core`
703/// when the server's `capsules` feature is enabled — see
704/// [`canonicalize_value`]) makes `Value` serialization order-sensitive, so
705/// a payload rebuilt in a different key-insertion order would hash
706/// differently while comparing equal. Canonicalizing only the payload
707/// values — struct fields keep their declaration order — preserves every
708/// hash a BTreeMap build ever produced byte-for-byte while making the
709/// chain backend-independent.
710fn canonicalized_for_hash(event: &RunEvent) -> RunEvent {
711 fn canonicalized_payload(payload: &Option<PayloadRef>) -> Option<PayloadRef> {
712 match payload {
713 Some(PayloadRef::Inline(value)) => Some(PayloadRef::Inline(canonicalize_value(value))),
714 other => other.clone(),
715 }
716 }
717 let mut canonical = event.clone();
718 canonical.input = canonicalized_payload(&event.input);
719 canonical.output = canonicalized_payload(&event.output);
720 canonical
721}
722
723/// A content-addressed blob store for journal artifacts (R0.7 wave 4).
724///
725/// The addressing contract predates the store: [`ArtifactRef`] has always
726/// content-addressed oversized payloads by SHA-256 — W4 adds where the
727/// bytes *live* when they leave the journal snapshot. The hash is the
728/// identity, so writes dedupe by construction (re-sent large inputs
729/// reference the same object) and readers can prove they got the bytes they
730/// asked for.
731///
732/// Error mapping: IO failures use the implementation's module convention
733/// ([`RustyError::Serialization`](crate::error::RustyError::Serialization)
734/// here in the journal, `Checkpoint` in the Postgres backend); an
735/// **integrity failure** — bytes that do not re-hash to their address — is
736/// always a `Serialization` error with `InvalidData`, the same shape
737/// [`Journal::from_snapshot`] uses for a tampered snapshot.
738#[async_trait]
739pub trait ArtifactStore: Send + Sync {
740 /// Store `bytes`, returning their content address. Idempotent: storing
741 /// identical bytes twice yields the same address and (at most) one
742 /// stored object.
743 async fn put(&self, bytes: &[u8]) -> crate::error::Result<ArtifactRef>;
744
745 /// Fetch the bytes for a content address. Integrity is verified on
746 /// every read: the returned bytes re-hash to the requested address, or
747 /// this errors — a store that cannot prove its bytes are the addressed
748 /// bytes is corruption, not data.
749 async fn get(&self, sha256: &str) -> crate::error::Result<Vec<u8>>;
750
751 /// Whether the store holds an address (existence only, no integrity
752 /// check — use [`ArtifactStore::get`] when the bytes matter).
753 async fn contains(&self, sha256: &str) -> crate::error::Result<bool>;
754}
755
756/// Map an IO error into the journal module's error convention.
757fn artifact_io_error(context: String, e: std::io::Error) -> crate::error::RustyError {
758 crate::error::RustyError::Serialization(serde_json::Error::io(std::io::Error::new(
759 e.kind(),
760 format!("{context}: {e}"),
761 )))
762}
763
764/// Filesystem [`ArtifactStore`]: one file per artifact at
765/// `{dir}/{sha256}`, written with the same atomic temp-write-then-rename
766/// discipline the JSON-file checkpointer uses — a crash mid-write can never
767/// leave a truncated blob behind (and a truncated blob would be caught by
768/// the read-side integrity check anyway).
769#[derive(Debug, Clone)]
770pub struct FileArtifactStore {
771 dir: PathBuf,
772}
773
774impl FileArtifactStore {
775 /// A store rooted at `dir` (created lazily on first `put`).
776 pub fn new(dir: impl Into<PathBuf>) -> Self {
777 Self { dir: dir.into() }
778 }
779
780 /// The root directory artifacts are stored under.
781 pub fn dir(&self) -> &std::path::Path {
782 &self.dir
783 }
784
785 fn artifact_path(&self, sha256: &str) -> PathBuf {
786 self.dir.join(sha256)
787 }
788}
789
790#[async_trait]
791impl ArtifactStore for FileArtifactStore {
792 async fn put(&self, bytes: &[u8]) -> crate::error::Result<ArtifactRef> {
793 let reference = ArtifactRef {
794 sha256: sha256_hex(bytes),
795 bytes: bytes.len() as u64,
796 };
797 let path = self.artifact_path(&reference.sha256);
798 // Dedupe by construction: an existing file under the address IS
799 // these bytes (or corruption the read side will catch) — re-puts of
800 // the same content are a no-op, which is what makes
801 // artifact-addressed retry traffic cheap.
802 if tokio::fs::try_exists(&path)
803 .await
804 .map_err(|e| artifact_io_error(format!("stat artifact `{}`", path.display()), e))?
805 {
806 return Ok(reference);
807 }
808 tokio::fs::create_dir_all(&self.dir).await.map_err(|e| {
809 artifact_io_error(format!("create artifact dir `{}`", self.dir.display()), e)
810 })?;
811 crate::checkpoint::JsonFileCheckpointer::atomic_write(&path, bytes).await?;
812 Ok(reference)
813 }
814
815 async fn get(&self, sha256: &str) -> crate::error::Result<Vec<u8>> {
816 let path = self.artifact_path(sha256);
817 let bytes = tokio::fs::read(&path)
818 .await
819 .map_err(|e| artifact_io_error(format!("read artifact `{sha256}`"), e))?;
820 let actual = sha256_hex(&bytes);
821 if actual != sha256 {
822 return Err(crate::error::RustyError::Serialization(
823 serde_json::Error::io(std::io::Error::new(
824 std::io::ErrorKind::InvalidData,
825 format!(
826 "artifact integrity failure: `{sha256}` re-hashes to `{actual}`; \
827 the stored bytes are corrupt"
828 ),
829 )),
830 ));
831 }
832 Ok(bytes)
833 }
834
835 async fn contains(&self, sha256: &str) -> crate::error::Result<bool> {
836 tokio::fs::try_exists(self.artifact_path(sha256))
837 .await
838 .map_err(|e| artifact_io_error(format!("stat artifact `{sha256}`"), e))
839 }
840}
841
842/// The serde-complete export form of a [`Journal`]: run identity, the full
843/// event sequence, the artifact payloads referenced by events, and the head
844/// hash binding them. Round-trips through JSON unchanged; load with
845/// [`Journal::from_snapshot`] to re-verify the head.
846#[derive(Debug, Clone, Serialize, Deserialize)]
847pub struct JournalSnapshot {
848 /// The recorded run's id.
849 pub run_id: String,
850
851 /// The thread the run belongs to.
852 pub thread_id: String,
853
854 /// Every recorded event, in sequence order.
855 pub events: Vec<RunEvent>,
856
857 /// Content-addressed payloads referenced by events (SHA-256 hex → value).
858 pub artifacts: BTreeMap<String, Value>,
859
860 /// Payloads whose bytes live in an external [`ArtifactStore`] instead
861 /// of embedded in `artifacts` (R0.7 wave 4; see
862 /// [`Journal::snapshot_externalized`]). Additive: absent from the wire
863 /// when empty, so pre-W4 snapshots — and replay fixtures, which embed
864 /// by design — keep their exact shape. Load with
865 /// [`Journal::from_snapshot_with_store`].
866 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
867 pub artifact_refs: BTreeMap<String, ArtifactRef>,
868
869 /// The chained head hash over `events`.
870 pub head_hash: String,
871}
872
873impl JournalSnapshot {
874 /// The effect-receipt replay lookup (R0.6 Durable Work): the journaled
875 /// [`EffectReceipt`] for `idempotency_key`, when one exists.
876 ///
877 /// This is the queue-dispatched analogue of the seq-ordered serving
878 /// cursor exact replay uses for model and tool calls: a task's effect
879 /// lands outside the run's super-step order, so receipts are matched by
880 /// the idempotency key the effect ran under, not by sequence. A
881 /// re-driven run (or a replayed activity) asks "did this key already
882 /// land?" and serves the receipt instead of re-sending the effect.
883 ///
884 /// Malformed receipt payloads (a hand-edited journal) are skipped rather
885 /// than fatal — integrity failures of the snapshot itself are caught by
886 /// [`Journal::from_snapshot`]'s hash check at load time.
887 pub fn find_effect_receipt(&self, idempotency_key: &str) -> Option<EffectReceipt> {
888 self.receipts()
889 .find(|receipt| receipt.idempotency_key == idempotency_key)
890 }
891
892 /// The effect-kernel receipt lookup (R0.7): the journaled
893 /// [`EffectReceipt`] for a deterministic effect id, when one exists.
894 ///
895 /// Where [`JournalSnapshot::find_effect_receipt`] answers "did this key
896 /// already land?", this answers the recovery question the typed kernel
897 /// asks: "did *this exact effect* — this kind, this input, this key, in
898 /// this run scope — already commit?" (see
899 /// [`crate::effects::derive_effect_id`]). Receipts journaled before the
900 /// kernel (no `effect_id` on the wire) simply never match here and keep
901 /// being served by the key lookup — the two lookups coexist, the id
902 /// lookup strictly sharper.
903 pub fn find_effect_receipt_by_effect_id(
904 &self,
905 effect_id: &crate::effects::EffectId,
906 ) -> Option<EffectReceipt> {
907 self.receipts()
908 .find(|receipt| receipt.effect_id.as_deref() == Some(effect_id.as_str()))
909 }
910
911 /// Every well-formed receipt journaled in this snapshot, in sequence
912 /// order. Malformed receipt payloads (a hand-edited journal) are skipped
913 /// rather than fatal — integrity failures of the snapshot itself are
914 /// caught by [`Journal::from_snapshot`]'s hash check at load time.
915 fn receipts(&self) -> impl Iterator<Item = EffectReceipt> + '_ {
916 self.events
917 .iter()
918 .filter(|event| event.kind == RunEventKind::EffectReceipt)
919 .filter_map(|event| {
920 let value = match event.output.as_ref()? {
921 PayloadRef::Inline(value) => value.clone(),
922 PayloadRef::Artifact(reference) => {
923 self.artifacts.get(&reference.sha256)?.clone()
924 }
925 };
926 serde_json::from_value(value).ok()
927 })
928 }
929}
930
931#[cfg(test)]
932mod tests {
933 use super::*;
934 use serde_json::json;
935
936 fn journal() -> Journal {
937 Journal::new("run-1", "thread-1", Clock::System)
938 }
939
940 #[test]
941 fn record_assigns_sequence_and_deterministic_ids() {
942 let j = journal();
943 let a = j.record(EventDraft::new(RunEventKind::SuperStepStart, Effect::Pure));
944 let b = j.record(
945 EventDraft::new(RunEventKind::NodeInput, Effect::Pure)
946 .node("n")
947 .parent(a.clone()),
948 );
949 assert_eq!(a, "run-1:0");
950 assert_eq!(b, "run-1:1");
951 let events = j.events();
952 assert_eq!(events[1].seq, 1);
953 assert_eq!(events[1].parent.as_deref(), Some("run-1:0"));
954 assert_eq!(events[1].node_id.as_deref(), Some("n"));
955 assert_eq!(j.len(), 2);
956 assert!(!j.is_empty());
957 }
958
959 #[test]
960 fn large_payloads_are_content_addressed_and_resolvable() {
961 let j = journal();
962 let big = json!({"blob": "x".repeat(INLINE_PAYLOAD_MAX_BYTES)});
963 j.record(
964 EventDraft::new(RunEventKind::ModelCall, Effect::NonIdempotent).output(big.clone()),
965 );
966 let event = &j.events()[0];
967 let reference = match event.output.as_ref() {
968 Some(PayloadRef::Artifact(reference)) => reference.clone(),
969 other => panic!("expected artifact reference, got {other:?}"),
970 };
971 assert_eq!(
972 reference.bytes as usize,
973 serde_json::to_vec(&big).unwrap().len()
974 );
975 assert_eq!(j.resolve(event.output.as_ref().unwrap()), Some(big));
976 }
977
978 #[test]
979 fn head_hash_advances_and_binds_content() {
980 let j1 = journal();
981 let j2 = journal();
982 assert_eq!(j1.head_hash(), j2.head_hash());
983 let draft = || EventDraft::new(RunEventKind::SuperStepStart, Effect::Pure);
984 j1.record(draft());
985 assert_ne!(j1.head_hash(), j2.head_hash());
986 j2.record(draft());
987 // Same event content (modulo timestamps — system clock here, so the
988 // hashes may differ; only the advance is asserted).
989 assert_ne!(j1.head_hash(), j2.head_hash());
990 }
991
992 #[test]
993 fn snapshot_roundtrip_reverifies_head() {
994 let j = journal();
995 j.record(
996 EventDraft::new(RunEventKind::SuperStepStart, Effect::Pure).input(json!({"step": 0})),
997 );
998 j.record(
999 EventDraft::new(RunEventKind::NodeInput, Effect::Pure)
1000 .node("a")
1001 .output(json!({"blob": "y".repeat(INLINE_PAYLOAD_MAX_BYTES)})),
1002 );
1003 let snapshot = j.snapshot();
1004 let wire = serde_json::to_string(&snapshot).unwrap();
1005 let parsed: JournalSnapshot = serde_json::from_str(&wire).unwrap();
1006 let rebuilt = Journal::from_snapshot(parsed, Clock::System).unwrap();
1007 assert_eq!(rebuilt.head_hash(), j.head_hash());
1008 assert_eq!(rebuilt.events(), j.events());
1009
1010 // A tampered snapshot is rejected on load.
1011 let mut tampered = j.snapshot();
1012 tampered.events[0].status = EventStatus::Error;
1013 assert!(Journal::from_snapshot(tampered, Clock::System).is_err());
1014 }
1015
1016 #[test]
1017 fn head_hash_is_stable_across_payload_key_order() {
1018 // The two payloads are the same logical value parsed from text with
1019 // different key orders. Value equality is order-insensitive under
1020 // either serde_json map backend, but serialization order is not:
1021 // under `preserve_order` (cedar-policy-core's transitive demand)
1022 // the parses keep their insertion orders, so chaining hashes over
1023 // the raw event would produce different heads for equal content —
1024 // the exact failure mode `canonicalized_for_hash` exists to close.
1025 let forward: Value =
1026 serde_json::from_str(r#"{"alpha": 1, "beta": {"x": 1, "y": 2}, "gamma": [3]}"#)
1027 .unwrap();
1028 let reverse: Value =
1029 serde_json::from_str(r#"{"gamma": [3], "beta": {"y": 2, "x": 1}, "alpha": 1}"#)
1030 .unwrap();
1031 assert_eq!(forward, reverse);
1032
1033 let journal_a = Journal::new("run-1", "thread-1", Clock::logical(1_000_000, 5));
1034 let journal_b = Journal::new("run-1", "thread-1", Clock::logical(1_000_000, 5));
1035 journal_a.record(
1036 EventDraft::new(RunEventKind::NodeInput, Effect::Pure)
1037 .node("n")
1038 .input(forward.clone())
1039 .output(reverse.clone()),
1040 );
1041 journal_b.record(
1042 EventDraft::new(RunEventKind::NodeInput, Effect::Pure)
1043 .node("n")
1044 .input(reverse)
1045 .output(forward),
1046 );
1047 assert_eq!(journal_a.events(), journal_b.events());
1048 assert_eq!(journal_a.head_hash(), journal_b.head_hash());
1049
1050 // The from_snapshot path re-chains through `chained_hash`; a
1051 // roundtrip through the wire must reproduce the same head.
1052 let snapshot: JournalSnapshot =
1053 serde_json::from_str(&serde_json::to_string(&journal_a.snapshot()).unwrap()).unwrap();
1054 let rebuilt = Journal::from_snapshot(snapshot, Clock::System).unwrap();
1055 assert_eq!(rebuilt.head_hash(), journal_a.head_hash());
1056 }
1057
1058 #[test]
1059 fn logical_clock_ticks_deterministically() {
1060 let clock = Clock::logical(1_000_000, 5);
1061 let a = clock.now();
1062 let b = clock.now();
1063 assert_eq!(b.timestamp_millis() - a.timestamp_millis(), 5);
1064 assert_eq!(a.timestamp_millis(), 1_000_000);
1065
1066 let same = Clock::logical(1_000_000, 5);
1067 assert_eq!(same.now(), a);
1068 assert_eq!(same.now(), b);
1069 }
1070
1071 #[test]
1072 fn seeded_rng_mints_reproducible_v4_uuids() {
1073 let a = RngSource::seeded(42);
1074 let b = RngSource::seeded(42);
1075 assert_eq!(a.uuid(), b.uuid());
1076 assert_eq!(a.uuid(), b.uuid());
1077 let id = a.uuid();
1078 assert_eq!(id.get_version(), Some(uuid::Version::Random));
1079 // Different seeds diverge.
1080 assert_ne!(RngSource::seeded(1).uuid(), RngSource::seeded(2).uuid());
1081 }
1082
1083 #[test]
1084 fn system_defaults_match_pre_r05_shapes() {
1085 assert!(matches!(Clock::default(), Clock::System));
1086 assert!(matches!(RngSource::default(), RngSource::System));
1087 }
1088
1089 fn receipt(key: &str) -> EffectReceipt {
1090 EffectReceipt {
1091 provider: "stripe".into(),
1092 provider_id: "ch_3PKd".into(),
1093 idempotency_key: key.into(),
1094 task_id: Some("task-9".into()),
1095 effect_id: None,
1096 }
1097 }
1098
1099 #[test]
1100 fn effect_receipt_records_with_parentage_and_is_findable_by_key() {
1101 let j = journal();
1102 let step = j.record(EventDraft::new(RunEventKind::SuperStepStart, Effect::Pure));
1103 let event_id = j.record_effect_receipt(&receipt("run-1:charge:7"), Some(step.clone()));
1104
1105 let events = j.events();
1106 let recorded = events.last().unwrap();
1107 assert_eq!(recorded.id, event_id);
1108 assert_eq!(recorded.kind, RunEventKind::EffectReceipt);
1109 // The receipt is an Idempotent effect's confirmation — declared as
1110 // such so the replay/retry policies classify it like any other event.
1111 assert_eq!(recorded.effect, Effect::Idempotent);
1112 assert_eq!(recorded.parent.as_deref(), Some(step.as_str()));
1113
1114 // The lookup serves the receipt by idempotency key, and only it.
1115 let snapshot = j.snapshot();
1116 assert_eq!(
1117 snapshot.find_effect_receipt("run-1:charge:7"),
1118 Some(receipt("run-1:charge:7"))
1119 );
1120 assert_eq!(snapshot.find_effect_receipt("run-1:charge:8"), None);
1121
1122 // The journaled snapshot survives the integrity-verified reload with
1123 // the receipt still servable (the crash boundary the receipt exists
1124 // to cross).
1125 let rebuilt = Journal::from_snapshot(snapshot, Clock::System).unwrap();
1126 let snapshot = rebuilt.snapshot();
1127 assert_eq!(
1128 snapshot.find_effect_receipt("run-1:charge:7"),
1129 Some(receipt("run-1:charge:7"))
1130 );
1131 }
1132
1133 #[test]
1134 fn effect_receipt_records_without_a_parent() {
1135 let j = journal();
1136 j.record_effect_receipt(&receipt("k"), None);
1137 let event = j.events().pop().unwrap();
1138 assert_eq!(event.parent, None);
1139 }
1140
1141 #[test]
1142 fn effect_receipt_is_findable_by_effect_id() {
1143 use crate::effects::derive_effect_id;
1144
1145 let j = journal();
1146 // The recovery shape: the run re-derives the id of the effect it is
1147 // about to perform; the journal answers with the committed receipt.
1148 let committed = derive_effect_id(
1149 "run-1",
1150 "charge_card",
1151 &sha256_hex(b"input"),
1152 Some("run-1:charge:7"),
1153 );
1154 let mut with_id = receipt("run-1:charge:7");
1155 with_id.effect_id = Some(committed.as_str().to_owned());
1156 j.record_effect_receipt(&with_id, None);
1157 // A pre-kernel receipt (no effect id) coexisting in the same journal.
1158 j.record_effect_receipt(&receipt("run-1:legacy:1"), None);
1159
1160 let snapshot = j.snapshot();
1161 assert_eq!(
1162 snapshot.find_effect_receipt_by_effect_id(&committed),
1163 Some(with_id)
1164 );
1165 // An uncommitted derivation finds nothing, and a legacy receipt
1166 // without an effect id never matches the id lookup.
1167 let other = derive_effect_id(
1168 "run-1",
1169 "charge_card",
1170 &sha256_hex(b"input"),
1171 Some("run-1:charge:8"),
1172 );
1173 assert_eq!(snapshot.find_effect_receipt_by_effect_id(&other), None);
1174 assert!(snapshot
1175 .find_effect_receipt_by_effect_id(&derive_effect_id("run-1", "legacy", "x", None))
1176 .is_none());
1177 }
1178
1179 // ---- Artifact store + persistence seam (R0.7 wave 4) ----
1180
1181 /// Unique temp root under the OS temp dir, removed on drop.
1182 struct TestDir(PathBuf);
1183
1184 impl TestDir {
1185 fn new() -> Self {
1186 Self(std::env::temp_dir().join(format!("rusty-artifact-test-{}", uuid::Uuid::new_v4())))
1187 }
1188 }
1189
1190 impl Drop for TestDir {
1191 fn drop(&mut self) {
1192 let _ = std::fs::remove_dir_all(&self.0);
1193 }
1194 }
1195
1196 fn big_payload() -> Value {
1197 json!({"blob": "x".repeat(INLINE_PAYLOAD_MAX_BYTES)})
1198 }
1199
1200 #[tokio::test]
1201 async fn file_artifact_store_roundtrip_and_dedupe() {
1202 let tmp = TestDir::new();
1203 let store = FileArtifactStore::new(tmp.0.clone());
1204
1205 let bytes = serde_json::to_vec(&big_payload()).unwrap();
1206 let reference = store.put(&bytes).await.unwrap();
1207 assert_eq!(reference.sha256, sha256_hex(&bytes));
1208 assert_eq!(reference.bytes as usize, bytes.len());
1209 assert!(store.contains(&reference.sha256).await.unwrap());
1210 assert!(!store.contains(&sha256_hex(b"never stored")).await.unwrap());
1211
1212 // Dedupe by construction: re-putting the same content is a no-op
1213 // returning the same address, and the file count stays one.
1214 let again = store.put(&bytes).await.unwrap();
1215 assert_eq!(again, reference);
1216 assert_eq!(std::fs::read_dir(&tmp.0).unwrap().count(), 1);
1217
1218 // Read verifies integrity and returns the addressed bytes.
1219 assert_eq!(store.get(&reference.sha256).await.unwrap(), bytes);
1220 }
1221
1222 #[tokio::test]
1223 async fn file_artifact_store_detects_corruption_on_read() {
1224 let tmp = TestDir::new();
1225 let store = FileArtifactStore::new(tmp.0.clone());
1226
1227 let bytes = b"genuine payload".repeat(1024);
1228 let reference = store.put(&bytes).await.unwrap();
1229 // Tamper with the stored bytes: the next read must fail integrity,
1230 // not return corrupt data.
1231 std::fs::write(tmp.0.join(&reference.sha256), b"tampered").unwrap();
1232 let err = store.get(&reference.sha256).await.unwrap_err();
1233 assert!(err.to_string().contains("integrity failure"), "got: {err}");
1234
1235 // A missing artifact is an error, never an empty read.
1236 assert!(store.get(&sha256_hex(b"missing")).await.is_err());
1237 }
1238
1239 #[tokio::test]
1240 async fn externalized_snapshot_spills_and_resolves_artifacts() {
1241 let tmp = TestDir::new();
1242 let store = FileArtifactStore::new(tmp.0.clone());
1243
1244 let j = journal();
1245 let big = big_payload();
1246 j.record(EventDraft::new(RunEventKind::SuperStepStart, Effect::Pure));
1247 j.record(
1248 EventDraft::new(RunEventKind::ModelCall, Effect::NonIdempotent).output(big.clone()),
1249 );
1250
1251 let externalized = j.snapshot_externalized(&store).await.unwrap();
1252 // Bytes left the snapshot: the artifact map is empty, the reference
1253 // ledger points at the store, and the wire shows it.
1254 assert!(externalized.artifacts.is_empty());
1255 assert_eq!(externalized.artifact_refs.len(), 1);
1256 let wire = serde_json::to_string(&externalized).unwrap();
1257 assert!(wire.contains("\"artifact_refs\""));
1258
1259 // The event still references the same content address, and the
1260 // store holds the bytes under it.
1261 let event = &externalized.events[1];
1262 let Some(PayloadRef::Artifact(reference)) = event.output.as_ref() else {
1263 panic!("large payload must be artifact-referenced");
1264 };
1265 assert!(store.contains(&reference.sha256).await.unwrap());
1266
1267 // Loading an externalized snapshot WITHOUT the store is a hard
1268 // error — never a silently unresolvable journal.
1269 let parsed: JournalSnapshot = serde_json::from_str(&wire).unwrap();
1270 assert!(Journal::from_snapshot(parsed, Clock::System).is_err());
1271
1272 // With the store, the load resolves artifacts and re-verifies the
1273 // head hash over events.
1274 let parsed: JournalSnapshot = serde_json::from_str(&wire).unwrap();
1275 let rebuilt = Journal::from_snapshot_with_store(parsed, &store, Clock::System)
1276 .await
1277 .unwrap();
1278 assert_eq!(rebuilt.head_hash(), j.head_hash());
1279 assert_eq!(
1280 rebuilt.resolve(rebuilt.events()[1].output.as_ref().unwrap()),
1281 Some(big)
1282 );
1283
1284 // Re-externalizing the rebuilt journal re-puts nothing new (dedupe).
1285 let re = rebuilt.snapshot_externalized(&store).await.unwrap();
1286 assert_eq!(re.artifact_refs, externalized.artifact_refs);
1287 }
1288
1289 #[test]
1290 fn embedded_byte_snapshots_keep_deserializing() {
1291 // The pre-W4 wire shape: no `artifact_refs` key at all.
1292 let j = journal();
1293 j.record(
1294 EventDraft::new(RunEventKind::SuperStepStart, Effect::Pure).input(json!({"s": 0})),
1295 );
1296 let snapshot = j.snapshot();
1297 let mut wire: serde_json::Map<String, Value> =
1298 serde_json::from_str(&serde_json::to_string(&snapshot).unwrap()).unwrap();
1299 assert!(
1300 wire.remove("artifact_refs").is_none(),
1301 "embedded snapshots must not emit artifact_refs"
1302 );
1303 let text = serde_json::to_string(&Value::Object(wire)).unwrap();
1304 let parsed: JournalSnapshot = serde_json::from_str(&text).unwrap();
1305 assert!(parsed.artifact_refs.is_empty());
1306 // And the snapshot loads through the ordinary integrity-verified path.
1307 let rebuilt = Journal::from_snapshot(parsed, Clock::System).unwrap();
1308 assert_eq!(rebuilt.head_hash(), j.head_hash());
1309 }
1310}