Skip to main content

a2a_protocol_server/tool_loop/journal/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! A durable journal of a tool-loop run: what a restarted replica needs to
5//! carry on, and what an auditor needs to say what the run did (adversarial
6//! review, "task durability does not yet establish durable arbitrary
7//! workflows", 2026-11-12).
8//!
9//! # What was lost, and what is kept
10//!
11//! A run's conversation, its record of calls already answered and its trace
12//! lived in memory for the run. A replica that died mid-run lost them, and the
13//! next attempt began again: the model was asked afresh and every tool it chose
14//! ran again. With a [`StepJournal`] installed
15//! ([`ToolLoop::with_journal`](super::ToolLoop::with_journal)) the loop writes a
16//! [`RunCheckpoint`] at each step, and a run begun again under the same key
17//! (the task and message it answers) **resumes**: the conversation is restored,
18//! calls already answered are not asked for or run again, and the model is
19//! asked only for what comes next.
20//!
21//! * **Resume points.** After each model reply, before each call and after
22//!   each call. A checkpoint carries the whole conversation, so a resume
23//!   reads one record.
24//! * **Pins.** The checkpoint records the model's name and digests of the
25//!   preamble, the tool set (names, descriptions, schemas, read-only flags)
26//!   and the loop's modes, plus any labels the deployment adds
27//!   ([`with_pin`](super::ToolLoop::with_pin): a policy version, a skill
28//!   bundle digest). A run resumed under different pins is **refused**
29//!   ([`LoopError::PinMismatch`](super::LoopError::PinMismatch)), not
30//!   continued under a model or a tool set it did not begin with.
31//! * **Action receipts.** A receipt is written *before* a call runs
32//!   ([`ReceiptState::Started`]) and updated when it ends. A call whose receipt
33//!   is still `Started` on resume may have run: the loop re-runs it only if the
34//!   idempotency secret was set explicitly
35//!   ([`with_idempotency_secret`](super::ToolLoop::with_idempotency_secret)),
36//!   so that its key is the same on every replica and the backend can
37//!   deduplicate; otherwise the run fails
38//!   ([`LoopError::Indeterminate`](super::LoopError::Indeterminate)) rather than
39//!   guess. **External effects still need the backend's idempotency**: the
40//!   journal makes a repeat rare and visible, not impossible.
41//! * **Fail closed.** A checkpoint the journal cannot write stops the run
42//!   *before* the call it was about to record
43//!   ([`LoopError::Journal`](super::LoopError::Journal)).
44//! * **Fencing.** Each checkpoint has a revision, and a write is accepted only
45//!   if it follows the one stored, so a replica that lost its claim cannot
46//!   overwrite a newer run's progress ([`JournalError::Conflict`]).
47//! * **Pending approvals.** A call a policy says needs approval parks the run
48//!   here with the digest of that exact call; see
49//!   [`PolicyDecision::RequireApproval`](super::PolicyDecision::RequireApproval).
50//!
51//! * **A finished run is kept, not deleted.** Its final answer is written as a
52//!   *completed* checkpoint, under the same revision fence as every other
53//!   write, before the loop returns it. A run begun again under that key
54//!   returns the stored answer, asks no model and runs no tool, so a process
55//!   that died between the answer and the task's `Completed` publishes the
56//!   same answer when the run is replayed (adversarial review N04,
57//!   2026-11-13; until then the checkpoint was deleted before the executor
58//!   published, and an unfenced delete of a stale run could remove a newer
59//!   run's checkpoint). The loop never deletes; [`StepJournal::sweep`] does,
60//!   on the deployment's retention schedule, and [`StepJournal::clear`] only
61//!   the revision it is given.
62//! * **Who a run is for, and how long it is kept** (N07). Each entry carries
63//!   its owner (tenant, authenticated caller, task) in fields of their own,
64//!   so [`StepJournal::runs_of`] can list a person's runs for an access
65//!   request, [`StepJournal::erase`] can delete them, and
66//!   [`StepJournal::sweep`] can drop completed runs past a replay window and
67//!   unfinished ones past a longer one. A run's content (the conversation,
68//!   tool arguments and results, the trace) is in the entry's body, which
69//!   `ToolLoop::with_journal_cipher` (the `encryption` feature) seals with a
70//!   `ContentCipher`; without one the body is JSON.
71//!
72//! The journal is the run's, not the task's: it is keyed by what the loop is
73//! given as its scope. Neither the task store's erasure nor the audit log's
74//! reaches it: call [`StepJournal::erase`] alongside them. Compensation
75//! (undoing a call that ran) and retry policy beyond the model retry are not
76//! here.
77
78use std::collections::{BTreeMap, HashMap};
79use std::future::Future;
80use std::pin::Pin;
81
82use serde::{Deserialize, Serialize};
83
84use super::model::{ChatMessage, ToolCall};
85
86mod memory;
87#[cfg(feature = "postgres")]
88mod postgres;
89#[cfg(feature = "sqlite")]
90mod sqlite;
91
92#[cfg(test)]
93mod tests;
94
95pub use memory::InMemoryStepJournal;
96#[cfg(feature = "postgres")]
97pub use postgres::PostgresStepJournal;
98#[cfg(feature = "sqlite")]
99pub use sqlite::SqliteStepJournal;
100
101/// The checkpoint format's version. A checkpoint of another version is refused.
102pub const CHECKPOINT_VERSION: u32 = 1;
103
104/// What a run was begun with, which a resume must still be.
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106#[non_exhaustive]
107pub struct Pins {
108    /// The model's name.
109    pub model: String,
110    /// `sha256:<hex>` of the preamble.
111    pub preamble: String,
112    /// `sha256:<hex>` of the tool set: each tool's name, description, schema
113    /// and read-only flag, by name.
114    pub tools: String,
115    /// `sha256:<hex>` of the loop's modes (recovery, argument check, trace).
116    pub modes: String,
117    /// The deployment's own pins ([`ToolLoop::with_pin`](super::ToolLoop::with_pin)).
118    pub labels: BTreeMap<String, String>,
119}
120
121/// Where a call stands.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(rename_all = "snake_case")]
124#[non_exhaustive]
125pub enum ReceiptState {
126    /// Written before the call ran; the call may or may not have.
127    Started,
128    /// The call ran and the tool answered.
129    Ran,
130    /// The call failed, or was refused before it ran.
131    Failed,
132    /// An identical call had already run; this one was answered from that.
133    NotRun,
134    /// Waiting for a person's decision.
135    AwaitingApproval,
136}
137
138/// One call's record.
139#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140#[non_exhaustive]
141pub struct ActionReceipt {
142    /// The turn whose reply asked for the call. With the id, what names one
143    /// call in a run: a provider may use an id again in a later turn
144    /// (adversarial review N08, 2026-11-13).
145    #[serde(default)]
146    pub turn: usize,
147    /// The provider's id for the call.
148    pub call_id: String,
149    /// The tool.
150    pub tool: String,
151    /// `sha256:<hex>` of the arguments, never the arguments.
152    pub arguments: String,
153    /// Where the call stands.
154    pub state: ReceiptState,
155}
156
157impl ActionReceipt {
158    /// Whether this is the receipt of call `call_id` of turn `turn`.
159    pub(crate) fn is(&self, turn: usize, call_id: &str) -> bool {
160        self.turn == turn && self.call_id == call_id
161    }
162}
163
164/// A call parked for a person's decision.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166#[non_exhaustive]
167pub struct PendingApproval {
168    /// The call, exactly as the model made it.
169    pub call: ToolCall,
170    /// `sha256:<hex>` of the call as an action: tool, arguments, requester,
171    /// tenant and task ([`call_digest`](super::call_digest)).
172    pub digest: String,
173    /// What the person is shown.
174    pub summary: String,
175    /// The requester: the authenticated caller whose run this is.
176    pub principal: Option<String>,
177    /// The tenant the run belongs to.
178    pub tenant: Option<String>,
179    /// The task the run belongs to.
180    pub task: Option<String>,
181}
182
183/// Everything a run needs to carry on.
184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
185#[non_exhaustive]
186pub struct RunCheckpoint {
187    /// [`CHECKPOINT_VERSION`].
188    pub version: u32,
189    /// Counts the checkpoint's writes; a write is accepted only as the
190    /// successor of the revision stored (`0` stored means none).
191    pub revision: u64,
192    /// What the run was begun with.
193    pub pins: Pins,
194    /// The turn the checkpoint was written in.
195    pub turn: usize,
196    /// Whether the last assistant turn's calls were recovered from text.
197    pub recovered: bool,
198    /// The conversation so far.
199    pub messages: Vec<ChatMessage>,
200    /// The caller's trace so far.
201    pub trace: Vec<String>,
202    /// What each call that ran returned, by idempotency key.
203    pub done: HashMap<String, String>,
204    /// Every call, in order.
205    pub receipts: Vec<ActionReceipt>,
206    /// The call waiting for a decision, if one is.
207    pub pending_approval: Option<PendingApproval>,
208    /// The run's final answer, once it has one: the run is over, and a run
209    /// begun again under its key returns this.
210    #[serde(default)]
211    pub answer: Option<FinalAnswer>,
212}
213
214/// What a finished run answered.
215#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
216#[non_exhaustive]
217pub struct FinalAnswer {
218    /// The model's final text.
219    pub text: String,
220    /// Why the final reply stopped, as the provider said.
221    pub finish_reason: Option<String>,
222}
223
224/// Why a journal did not do what it was asked.
225#[derive(Debug, Clone, PartialEq, Eq)]
226#[non_exhaustive]
227pub enum JournalError {
228    /// The write did not follow the revision stored: another writer got there.
229    Conflict,
230    /// The store failed, or held something unreadable.
231    Store(String),
232}
233
234impl std::fmt::Display for JournalError {
235    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
236        match self {
237            Self::Conflict => f.write_str("another writer advanced the run's checkpoint"),
238            Self::Store(e) => write!(f, "the run journal failed: {e}"),
239        }
240    }
241}
242
243impl std::error::Error for JournalError {}
244
245/// What a journal's methods return.
246pub type JournalFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, JournalError>> + Send + 'a>>;
247
248/// Whose run an entry is: from the authenticated request, never from what the
249/// model wrote. What [`StepJournal::runs_of`] and [`StepJournal::erase`] find
250/// a run by.
251#[derive(Debug, Clone, Default, PartialEq, Eq)]
252#[non_exhaustive]
253pub struct RunOwner {
254    /// The request's tenant.
255    pub tenant: Option<String>,
256    /// The authenticated caller the run answers.
257    pub principal: Option<String>,
258    /// The task the run belongs to.
259    pub task: Option<String>,
260}
261
262impl RunOwner {
263    /// An owner from its three parts.
264    #[must_use]
265    pub const fn new(
266        tenant: Option<String>,
267        principal: Option<String>,
268        task: Option<String>,
269    ) -> Self {
270        Self {
271            tenant,
272            principal,
273            task,
274        }
275    }
276
277    /// Whether this is `principal`'s, in `tenant` when one is given.
278    #[must_use]
279    pub fn is_of(&self, principal: &str, tenant: Option<&str>) -> bool {
280        self.principal.as_deref() == Some(principal)
281            && tenant.is_none_or(|t| self.tenant.as_deref() == Some(t))
282    }
283}
284
285/// One run as a [`StepJournal`] stores it. The journal reads `revision`,
286/// `owner`, `completed` and `updated_at_ms`; `body` is opaque to it.
287#[derive(Debug, Clone, PartialEq, Eq)]
288#[non_exhaustive]
289pub struct JournalEntry {
290    /// Counts the run's writes; see [`StepJournal::save`].
291    pub revision: u64,
292    /// Whose run it is.
293    pub owner: RunOwner,
294    /// Whether the run has its final answer.
295    pub completed: bool,
296    /// When the entry was written, in Unix milliseconds.
297    pub updated_at_ms: i64,
298    /// The [`RunCheckpoint`]: JSON, or sealed by the loop's journal cipher
299    /// (a string beginning [`SEALED_CHECKPOINT_PREFIX`]).
300    pub body: String,
301}
302
303impl JournalEntry {
304    /// An entry from its parts.
305    #[must_use]
306    pub const fn new(
307        revision: u64,
308        owner: RunOwner,
309        completed: bool,
310        updated_at_ms: i64,
311        body: String,
312    ) -> Self {
313        Self {
314            revision,
315            owner,
316            completed,
317            updated_at_ms,
318            body,
319        }
320    }
321
322    /// The checkpoint, when the body is not sealed: for an operator reading
323    /// a journal written without a cipher.
324    ///
325    /// # Errors
326    ///
327    /// [`JournalError::Store`] when the body is sealed or unreadable.
328    pub fn checkpoint(&self) -> Result<RunCheckpoint, JournalError> {
329        if self.body.starts_with(SEALED_CHECKPOINT_PREFIX) {
330            return Err(JournalError::Store(
331                "the checkpoint is sealed; the loop's journal cipher opens it".to_owned(),
332            ));
333        }
334        from_text(&self.body)
335    }
336
337    /// What [`StepJournal::runs_of`] lists of this entry under `key`.
338    #[must_use]
339    pub fn summary(&self, key: &str) -> RunSummary {
340        RunSummary {
341            key: key.to_owned(),
342            revision: self.revision,
343            owner: self.owner.clone(),
344            completed: self.completed,
345            updated_at_ms: self.updated_at_ms,
346        }
347    }
348}
349
350/// What [`StepJournal::runs_of`] lists of a run: everything but its content.
351#[derive(Debug, Clone, PartialEq, Eq)]
352#[non_exhaustive]
353pub struct RunSummary {
354    /// The run's key.
355    pub key: String,
356    /// Its revision.
357    pub revision: u64,
358    /// Whose run it is.
359    pub owner: RunOwner,
360    /// Whether it has its final answer.
361    pub completed: bool,
362    /// When it was last written, in Unix milliseconds.
363    pub updated_at_ms: i64,
364}
365
366/// The prefix of a checkpoint body sealed by the loop's journal cipher.
367pub const SEALED_CHECKPOINT_PREFIX: &str = "a2a-sealed-run:v1:";
368
369/// Where a run's checkpoints are kept.
370///
371/// An implementation must make [`save`](Self::save) and
372/// [`clear`](Self::clear) atomic compare-and-sets on the revision: that is
373/// the fence that keeps a replica which lost its claim from overwriting, or
374/// deleting, a newer run's progress.
375pub trait StepJournal: Send + Sync + 'static {
376    /// The entry stored under `key`, if there is one.
377    fn load<'a>(&'a self, key: &'a str) -> JournalFuture<'a, Option<JournalEntry>>;
378
379    /// Stores `entry` under `key` only if the revision stored is
380    /// `entry.revision - 1` (none stored counts as `0`), and returns
381    /// [`JournalError::Conflict`] otherwise.
382    fn save<'a>(&'a self, key: &'a str, entry: &'a JournalEntry) -> JournalFuture<'a, ()>;
383
384    /// Deletes the entry under `key` only if its revision is `revision`:
385    /// [`JournalError::Conflict`] when another revision is stored, `Ok` when
386    /// none is. A stale run's delete cannot remove a newer run's entry.
387    fn clear<'a>(&'a self, key: &'a str, revision: u64) -> JournalFuture<'a, ()>;
388
389    /// Deletes completed runs last written before `completed_before_ms` and
390    /// unfinished ones last written before `unfinished_before_ms` (Unix
391    /// milliseconds); returns how many went. A run still going when its entry
392    /// is swept is refused its next write ([`JournalError::Conflict`]: none
393    /// stored takes only revision 1), so the unfinished cutoff must be well
394    /// past the longest run and its approvals.
395    fn sweep(&self, completed_before_ms: i64, unfinished_before_ms: i64) -> JournalFuture<'_, u64>;
396
397    /// Every run of `principal`, in `tenant` when one is given, without its
398    /// content: for an access request, and to know what
399    /// [`erase`](Self::erase) would delete.
400    fn runs_of<'a>(
401        &'a self,
402        principal: &'a str,
403        tenant: Option<&'a str>,
404    ) -> JournalFuture<'a, Vec<RunSummary>>;
405
406    /// Deletes every run of `principal`, in `tenant` when one is given;
407    /// returns how many went. What a person's erasure must call for the
408    /// journal: the task store's and the audit log's do not reach it. A
409    /// person named only inside a run's content (a tool argument, a message)
410    /// is not found by this.
411    fn erase<'a>(&'a self, principal: &'a str, tenant: Option<&'a str>) -> JournalFuture<'a, u64>;
412}
413
414/// The time now in Unix milliseconds, for an entry's `updated_at_ms`.
415pub(super) fn now_ms() -> i64 {
416    i64::try_from(
417        std::time::SystemTime::now()
418            .duration_since(std::time::UNIX_EPOCH)
419            .map_or(0, |d| d.as_millis()),
420    )
421    .unwrap_or(i64::MAX)
422}
423
424pub(super) fn to_text(checkpoint: &RunCheckpoint) -> Result<String, JournalError> {
425    serde_json::to_string(checkpoint)
426        .map_err(|e| JournalError::Store(format!("a checkpoint could not be written: {e}")))
427}
428
429pub(super) fn from_text(text: &str) -> Result<RunCheckpoint, JournalError> {
430    serde_json::from_str(text)
431        .map_err(|e| JournalError::Store(format!("a stored checkpoint is unreadable: {e}")))
432}