Skip to main content

a2a_protocol_server/tool_loop/journal/
postgres.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`StepJournal`] in PostgreSQL: runs every replica sharing the database can
5//! resume, kept across restarts.
6
7use std::sync::Arc;
8
9use a2a_protocol_types::error::{A2aError, A2aResult};
10use sqlx::Row;
11use sqlx::postgres::{PgPool, PgRow};
12
13use super::{JournalEntry, JournalError, JournalFuture, RunOwner, RunSummary, StepJournal};
14use crate::metrics::{Metrics, NoopMetrics};
15use crate::store::pg_retry;
16
17/// The table, and what 2026-11-13 added to it (N07): who the run is for and
18/// whether it is finished, added to a table an earlier build created too.
19const SCHEMA: [&str; 7] = [
20    "CREATE TABLE IF NOT EXISTS a2a_run_journal (
21        run_key    TEXT PRIMARY KEY,
22        revision   BIGINT NOT NULL,
23        body       TEXT NOT NULL,
24        updated_at BIGINT NOT NULL
25    )",
26    "ALTER TABLE a2a_run_journal ADD COLUMN IF NOT EXISTS tenant TEXT",
27    "ALTER TABLE a2a_run_journal ADD COLUMN IF NOT EXISTS principal TEXT",
28    "ALTER TABLE a2a_run_journal ADD COLUMN IF NOT EXISTS task TEXT",
29    "ALTER TABLE a2a_run_journal ADD COLUMN IF NOT EXISTS completed BOOLEAN NOT NULL DEFAULT FALSE",
30    "CREATE INDEX IF NOT EXISTS idx_a2a_run_journal_principal ON a2a_run_journal(principal, tenant)",
31    "CREATE INDEX IF NOT EXISTS idx_a2a_run_journal_updated ON a2a_run_journal(completed, updated_at)",
32];
33
34const COLUMNS: &str = "run_key, revision, body, updated_at, tenant, principal, task, completed";
35
36/// Checkpoints in a PostgreSQL table, `a2a_run_journal`, created if absent.
37///
38/// A read runs again once if its connection was lost
39/// (`pg_retry::retry`). A write does not: a lost connection does not prove it
40/// did not commit, and a second run of a compare-and-set on the revision would
41/// then report a conflict for a checkpoint that was written, so a write is
42/// run on a connection pinged first (`pg_retry::checked`) and its failure is
43/// the caller's to see.
44#[derive(Clone)]
45pub struct PostgresStepJournal {
46    pool: PgPool,
47    metrics: Arc<dyn Metrics>,
48}
49
50impl std::fmt::Debug for PostgresStepJournal {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct("PostgresStepJournal")
53            .finish_non_exhaustive()
54    }
55}
56
57impl PostgresStepJournal {
58    /// Uses `pool`, usually the task store's, and creates the table under the
59    /// crate's schema lock, so replicas starting together do not race.
60    ///
61    /// # Errors
62    ///
63    /// [`A2aError::internal`] if the table cannot be created.
64    pub async fn from_pool(pool: PgPool) -> A2aResult<Self> {
65        crate::store::pg_schema::apply(&pool, &SCHEMA)
66            .await
67            .map_err(|e| A2aError::internal(format!("run journal migrate: {e}")))?;
68        Ok(Self {
69            pool,
70            metrics: Arc::new(NoopMetrics),
71        })
72    }
73
74    /// Reports a read run again after a lost connection to `metrics`
75    /// (`Metrics::on_store_retry`).
76    #[must_use]
77    pub fn with_metrics(mut self, metrics: Arc<dyn Metrics>) -> Self {
78        self.metrics = metrics;
79        self
80    }
81}
82
83fn failed(what: &str, e: &sqlx::Error) -> JournalError {
84    JournalError::Store(format!("{what}: {e}"))
85}
86
87fn revision_of(r: u64) -> Result<i64, JournalError> {
88    i64::try_from(r).map_err(|_| JournalError::Store("a revision past i64".to_owned()))
89}
90
91/// The key and the entry a row holds.
92fn entry_of(row: &PgRow) -> (String, JournalEntry) {
93    let entry = JournalEntry::new(
94        u64::try_from(row.get::<i64, _>(1)).unwrap_or(0),
95        RunOwner::new(row.get(4), row.get(5), row.get(6)),
96        row.get(7),
97        row.get(3),
98        row.get(2),
99    );
100    (row.get(0), entry)
101}
102
103impl StepJournal for PostgresStepJournal {
104    fn load<'a>(&'a self, key: &'a str) -> JournalFuture<'a, Option<JournalEntry>> {
105        Box::pin(async move {
106            let sql = format!("SELECT {COLUMNS} FROM a2a_run_journal WHERE run_key = $1");
107            let row = pg_retry::retry(self.metrics.as_ref(), || {
108                sqlx::query(sqlx::AssertSqlSafe(sql.as_str()))
109                    .bind(key)
110                    .fetch_optional(&self.pool)
111            })
112            .await
113            .map_err(|e| failed("load", &e))?;
114            Ok(row.map(|r| entry_of(&r).1))
115        })
116    }
117
118    fn save<'a>(&'a self, key: &'a str, entry: &'a JournalEntry) -> JournalFuture<'a, ()> {
119        Box::pin(async move {
120            let revision = revision_of(entry.revision)?;
121            let owner = &entry.owner;
122            let written = if revision == 1 {
123                pg_retry::checked(
124                    sqlx::query(
125                        "INSERT INTO a2a_run_journal
126                            (run_key, revision, body, updated_at, tenant, principal, task, completed)
127                         VALUES ($1, 1, $2, $3, $4, $5, $6, $7) ON CONFLICT (run_key) DO NOTHING",
128                    )
129                    .bind(key)
130                    .bind(&entry.body)
131                    .bind(entry.updated_at_ms)
132                    .bind(&owner.tenant)
133                    .bind(&owner.principal)
134                    .bind(&owner.task)
135                    .bind(entry.completed)
136                    .execute(&self.pool),
137                )
138                .await
139            } else {
140                pg_retry::checked(
141                    sqlx::query(
142                        "UPDATE a2a_run_journal SET revision = $2, body = $3, updated_at = $4,
143                            tenant = $5, principal = $6, task = $7, completed = $8
144                         WHERE run_key = $1 AND revision = $9",
145                    )
146                    .bind(key)
147                    .bind(revision)
148                    .bind(&entry.body)
149                    .bind(entry.updated_at_ms)
150                    .bind(&owner.tenant)
151                    .bind(&owner.principal)
152                    .bind(&owner.task)
153                    .bind(entry.completed)
154                    .bind(revision - 1)
155                    .execute(&self.pool),
156                )
157                .await
158            }
159            .map_err(|e| failed("save", &e))?;
160            if written.rows_affected() == 1 {
161                Ok(())
162            } else {
163                Err(JournalError::Conflict)
164            }
165        })
166    }
167
168    fn clear<'a>(&'a self, key: &'a str, revision: u64) -> JournalFuture<'a, ()> {
169        Box::pin(async move {
170            let revision = revision_of(revision)?;
171            // Checked, not retried; and only at the revision given, so a stale
172            // run's delete cannot remove a newer run's checkpoint (N04).
173            let done = pg_retry::checked(
174                sqlx::query("DELETE FROM a2a_run_journal WHERE run_key = $1 AND revision = $2")
175                    .bind(key)
176                    .bind(revision)
177                    .execute(&self.pool),
178            )
179            .await
180            .map_err(|e| failed("clear", &e))?;
181            if done.rows_affected() == 1 {
182                return Ok(());
183            }
184            let other: Option<i64> = pg_retry::retry(self.metrics.as_ref(), || {
185                sqlx::query_scalar("SELECT revision FROM a2a_run_journal WHERE run_key = $1")
186                    .bind(key)
187                    .fetch_optional(&self.pool)
188            })
189            .await
190            .map_err(|e| failed("clear", &e))?;
191            other.map_or(Ok(()), |_| Err(JournalError::Conflict))
192        })
193    }
194
195    fn sweep(&self, completed_before_ms: i64, unfinished_before_ms: i64) -> JournalFuture<'_, u64> {
196        Box::pin(async move {
197            // Retried: a second run of a cutoff delete deletes nothing more.
198            let done = pg_retry::retry(self.metrics.as_ref(), || {
199                sqlx::query(
200                    "DELETE FROM a2a_run_journal
201                     WHERE (completed AND updated_at < $1) OR (NOT completed AND updated_at < $2)",
202                )
203                .bind(completed_before_ms)
204                .bind(unfinished_before_ms)
205                .execute(&self.pool)
206            })
207            .await
208            .map_err(|e| failed("sweep", &e))?;
209            Ok(done.rows_affected())
210        })
211    }
212
213    fn runs_of<'a>(
214        &'a self,
215        principal: &'a str,
216        tenant: Option<&'a str>,
217    ) -> JournalFuture<'a, Vec<RunSummary>> {
218        Box::pin(async move {
219            let sql = format!(
220                "SELECT {COLUMNS} FROM a2a_run_journal
221                 WHERE principal = $1 AND ($2::TEXT IS NULL OR tenant = $2) ORDER BY run_key"
222            );
223            let rows = pg_retry::retry(self.metrics.as_ref(), || {
224                sqlx::query(sqlx::AssertSqlSafe(sql.as_str()))
225                    .bind(principal)
226                    .bind(tenant)
227                    .fetch_all(&self.pool)
228            })
229            .await
230            .map_err(|e| failed("runs_of", &e))?;
231            Ok(rows
232                .iter()
233                .map(|r| {
234                    let (key, entry) = entry_of(r);
235                    entry.summary(&key)
236                })
237                .collect())
238        })
239    }
240
241    fn erase<'a>(&'a self, principal: &'a str, tenant: Option<&'a str>) -> JournalFuture<'a, u64> {
242        Box::pin(async move {
243            // Retried: a second run of the delete deletes nothing more.
244            let done = pg_retry::retry(self.metrics.as_ref(), || {
245                sqlx::query(
246                    "DELETE FROM a2a_run_journal
247                     WHERE principal = $1 AND ($2::TEXT IS NULL OR tenant = $2)",
248                )
249                .bind(principal)
250                .bind(tenant)
251                .execute(&self.pool)
252            })
253            .await
254            .map_err(|e| failed("erase", &e))?;
255            Ok(done.rows_affected())
256        })
257    }
258}