Skip to main content

adk_graph/checkpointers/
neo4j.rs

1//! Neo4j [`Checkpointer`].
2
3use async_trait::async_trait;
4use neo4rs::{Graph, Neo4jErrorKind, Query, Row, Txn, query};
5
6use super::{decode, encode, storage_error};
7use crate::checkpoint::{Checkpointer, RetentionPolicy, conflict, duplicate_id, ensure_newer};
8use crate::error::Result;
9use crate::state::Checkpoint;
10
11const BACKEND: &str = "neo4j";
12
13/// Attempts at a save that fails with a transient error, such as a detected deadlock.
14const TRANSIENT_ATTEMPTS: usize = 5;
15
16const CONSTRAINT_VIOLATION: &str = "Neo.ClientError.Schema.ConstraintValidationFailed";
17
18/// Schema codes that mean an `IF NOT EXISTS` statement raced another one and lost.
19const SCHEMA_ALREADY_EXISTS: [&str; 4] = [
20    "Neo.ClientError.Schema.EquivalentSchemaRuleAlreadyExists",
21    "Neo.ClientError.Schema.ConstraintAlreadyExists",
22    "Neo.ClientError.Schema.IndexAlreadyExists",
23    "Neo.ClientError.Schema.ConstraintWithNameAlreadyExists",
24];
25
26const SCHEMA: [&str; 3] = [
27    "CREATE CONSTRAINT adk_graph_checkpoint_id IF NOT EXISTS \
28     FOR (c:AdkGraphCheckpoint) REQUIRE c.id IS UNIQUE",
29    "CREATE CONSTRAINT adk_graph_thread_id IF NOT EXISTS \
30     FOR (t:AdkGraphThread) REQUIRE t.id IS UNIQUE",
31    "CREATE INDEX adk_graph_checkpoint_thread IF NOT EXISTS \
32     FOR (c:AdkGraphCheckpoint) ON (c.thread_id, c.version)",
33];
34
35fn neo4j_code(error: &neo4rs::Error) -> Option<&str> {
36    match error {
37        neo4rs::Error::Neo4j(error) => Some(error.code()),
38        _ => None,
39    }
40}
41
42fn is_transient(error: &neo4rs::Error) -> bool {
43    matches!(error, neo4rs::Error::Neo4j(error) if error.kind() == Neo4jErrorKind::Transient)
44}
45
46async fn txn_rows(txn: &mut Txn, query: Query) -> std::result::Result<Vec<Row>, neo4rs::Error> {
47    let mut stream = txn.execute(query).await?;
48    let mut rows = Vec::new();
49    while let Some(row) = stream.next(&mut *txn).await? {
50        rows.push(row);
51    }
52    Ok(rows)
53}
54
55/// What one save attempt concluded.
56enum Attempt {
57    Stored,
58    Behind(u64),
59}
60
61/// Neo4j-backed [`Checkpointer`].
62///
63/// Each checkpoint is an `AdkGraphCheckpoint` node holding its ID, thread, version,
64/// and the checkpoint as JSON in `data`. Each thread has an `AdkGraphThread` node
65/// holding its highest version in `head`. A save write-locks the thread node before
66/// it reads `head`, so concurrent saves of one thread run one after another and the
67/// second sees the first's version. The thread node is created by an auto-commit
68/// `MERGE` first, so a save only ever takes the write lock directly and two saves
69/// cannot deadlock upgrading a shared lock. Call [`migrate`](Self::migrate) once per
70/// database to create the uniqueness constraints.
71///
72/// # Example
73///
74/// ```rust,no_run
75/// use adk_graph::Neo4jCheckpointer;
76///
77/// # async fn example() -> adk_graph::Result<()> {
78/// let checkpointer = Neo4jCheckpointer::new("bolt://localhost:7687", "neo4j", "password").await?;
79/// checkpointer.migrate().await?;
80/// # Ok(())
81/// # }
82/// ```
83#[derive(Clone)]
84pub struct Neo4jCheckpointer {
85    graph: Graph,
86}
87
88impl std::fmt::Debug for Neo4jCheckpointer {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.debug_struct("Neo4jCheckpointer").finish_non_exhaustive()
91    }
92}
93
94impl Neo4jCheckpointer {
95    /// Connects to `uri` as `user`.
96    ///
97    /// # Errors
98    ///
99    /// Returns `GraphError::CheckpointError` when the server cannot be reached.
100    pub async fn new(uri: &str, user: &str, password: &str) -> Result<Self> {
101        let graph = Graph::new(uri, user, password)
102            .await
103            .map_err(|e| storage_error(BACKEND, format!("connection failed: {e}")))?;
104        Ok(Self::from_graph(graph))
105    }
106
107    /// Uses an existing connection, such as one shared with other Neo4j stores.
108    pub fn from_graph(graph: Graph) -> Self {
109        Self { graph }
110    }
111
112    /// Creates the constraints and index the checkpointer relies on.
113    ///
114    /// # Errors
115    ///
116    /// Returns `GraphError::CheckpointError` when a schema statement fails.
117    pub async fn migrate(&self) -> Result<()> {
118        for statement in SCHEMA {
119            let mut tries = 1;
120            loop {
121                match self.graph.run(query(statement)).await {
122                    Ok(()) => break,
123                    Err(error)
124                        if neo4j_code(&error)
125                            .is_some_and(|code| SCHEMA_ALREADY_EXISTS.contains(&code)) =>
126                    {
127                        break;
128                    }
129                    Err(error) if tries < TRANSIENT_ATTEMPTS => {
130                        tracing::debug!(error = %error, "retrying neo4j schema statement");
131                        tries += 1;
132                    }
133                    Err(error) => {
134                        return Err(storage_error(BACKEND, format!("migration failed: {error}")));
135                    }
136                }
137            }
138        }
139        Ok(())
140    }
141
142    async fn try_save(
143        &self,
144        checkpoint: &Checkpoint,
145        version: i64,
146        data: &str,
147    ) -> std::result::Result<Attempt, neo4rs::Error> {
148        self.graph
149            .run(
150                query("MERGE (:AdkGraphThread {id: $thread})")
151                    .param("thread", checkpoint.thread_id.clone()),
152            )
153            .await?;
154        let mut txn = self.graph.start_txn().await?;
155        let found = txn_rows(
156            &mut txn,
157            query(
158                "MATCH (t:AdkGraphThread {id: $thread}) SET t.lock = coalesce(t.lock, 0) + 1 \
159                 RETURN coalesce(t.head, 0) AS head",
160            )
161            .param("thread", checkpoint.thread_id.clone()),
162        )
163        .await?;
164        let head: i64 = found.first().and_then(|row| row.get("head").ok()).unwrap_or(0);
165        if head >= version {
166            let _ = txn.rollback().await;
167            return Ok(Attempt::Behind(head as u64));
168        }
169        txn.run(
170            query(
171                "MATCH (t:AdkGraphThread {id: $thread}) SET t.head = $version \
172                 CREATE (:AdkGraphCheckpoint {id: $id, thread_id: $thread, version: $version, data: $data})",
173            )
174            .param("thread", checkpoint.thread_id.clone())
175            .param("id", checkpoint.checkpoint_id.clone())
176            .param("version", version)
177            .param("data", data),
178        )
179        .await?;
180        txn.commit().await?;
181        Ok(Attempt::Stored)
182    }
183
184    async fn read(&self, statement: Query) -> Result<Vec<Checkpoint>> {
185        let mut stream =
186            self.graph.execute(statement).await.map_err(|e| storage_error(BACKEND, e))?;
187        let mut checkpoints = Vec::new();
188        while let Some(row) = stream.next().await.map_err(|e| storage_error(BACKEND, e))? {
189            let data: String = row
190                .get("data")
191                .map_err(|e| storage_error(BACKEND, format!("column 'data' unreadable: {e}")))?;
192            checkpoints.push(decode(BACKEND, &data)?);
193        }
194        Ok(checkpoints)
195    }
196}
197
198fn version_param(version: u64) -> Result<i64> {
199    i64::try_from(version)
200        .map_err(|_| storage_error(BACKEND, format!("version {version} exceeds a 64-bit integer")))
201}
202
203#[async_trait]
204impl Checkpointer for Neo4jCheckpointer {
205    async fn save(&self, checkpoint: &Checkpoint) -> Result<String> {
206        ensure_newer(checkpoint, None)?;
207        let version = version_param(checkpoint.version)?;
208        let data = encode(checkpoint)?;
209        let mut tries = 1;
210        loop {
211            match self.try_save(checkpoint, version, &data).await {
212                Ok(Attempt::Stored) => return Ok(checkpoint.checkpoint_id.clone()),
213                Ok(Attempt::Behind(head)) => return Err(conflict(checkpoint, head)),
214                Err(error) if is_transient(&error) && tries < TRANSIENT_ATTEMPTS => tries += 1,
215                Err(error) if neo4j_code(&error) == Some(CONSTRAINT_VIOLATION) => {
216                    return Err(duplicate_id(&checkpoint.checkpoint_id));
217                }
218                Err(error) => return Err(storage_error(BACKEND, error)),
219            }
220        }
221    }
222
223    async fn load(&self, thread_id: &str) -> Result<Option<Checkpoint>> {
224        Ok(self
225            .read(
226                query(
227                    "MATCH (c:AdkGraphCheckpoint {thread_id: $thread}) \
228                     RETURN c.data AS data ORDER BY c.version DESC LIMIT 1",
229                )
230                .param("thread", thread_id),
231            )
232            .await?
233            .pop())
234    }
235
236    async fn load_by_id(&self, checkpoint_id: &str) -> Result<Option<Checkpoint>> {
237        Ok(self
238            .read(
239                query("MATCH (c:AdkGraphCheckpoint {id: $id}) RETURN c.data AS data")
240                    .param("id", checkpoint_id),
241            )
242            .await?
243            .pop())
244    }
245
246    async fn list(&self, thread_id: &str) -> Result<Vec<Checkpoint>> {
247        self.read(
248            query(
249                "MATCH (c:AdkGraphCheckpoint {thread_id: $thread}) \
250                 RETURN c.data AS data ORDER BY c.version ASC",
251            )
252            .param("thread", thread_id),
253        )
254        .await
255    }
256
257    async fn list_page(
258        &self,
259        thread_id: &str,
260        before: Option<u64>,
261        limit: usize,
262    ) -> Result<Vec<Checkpoint>> {
263        self.read(
264            query(
265                "MATCH (c:AdkGraphCheckpoint {thread_id: $thread}) WHERE c.version < $before \
266                 RETURN c.data AS data ORDER BY c.version DESC LIMIT $limit",
267            )
268            .param("thread", thread_id)
269            .param("before", before.map_or(Ok(i64::MAX), version_param)?)
270            .param("limit", i64::try_from(limit).unwrap_or(i64::MAX)),
271        )
272        .await
273    }
274
275    async fn delete(&self, thread_id: &str) -> Result<()> {
276        self.graph
277            .run(
278                query(
279                    "MATCH (c:AdkGraphCheckpoint {thread_id: $thread}) DETACH DELETE c \
280                     WITH count(*) AS removed \
281                     MATCH (t:AdkGraphThread {id: $thread}) DETACH DELETE t",
282                )
283                .param("thread", thread_id),
284            )
285            .await
286            .map_err(|e| storage_error(BACKEND, e))
287    }
288
289    async fn prune(&self, thread_id: &str, policy: &RetentionPolicy) -> Result<usize> {
290        let expired = policy.expired(&self.list(thread_id).await?);
291        if expired.is_empty() {
292            return Ok(0);
293        }
294        let mut stream = self
295            .graph
296            .execute(
297                query(
298                    "MATCH (c:AdkGraphCheckpoint {thread_id: $thread}) WHERE c.id IN $ids \
299                     DETACH DELETE c RETURN count(*) AS removed",
300                )
301                .param("thread", thread_id)
302                .param("ids", expired),
303            )
304            .await
305            .map_err(|e| storage_error(BACKEND, e))?;
306        let removed: i64 = match stream.next().await.map_err(|e| storage_error(BACKEND, e))? {
307            Some(row) => row.get("removed").map_err(|e| storage_error(BACKEND, e))?,
308            None => 0,
309        };
310        Ok(removed as usize)
311    }
312}