Skip to main content

adk_kernel/stores/
agent_neo4j.rs

1//! The Neo4j [`AgentStore`] (spec 3.3 §5.7, §10 K7, feature `neo4j`).
2
3use async_trait::async_trait;
4use neo4rs::{Graph, Query, Row, query};
5
6use super::neo4j::{
7    column, connect, count, detached, json, order_key, retry, rows, run_schema, txn_rows,
8};
9use crate::agents::{AgentRecord, AgentStore};
10use crate::error::{KernelError, Result};
11
12/// Finds or creates the agent's node at version 0 and takes its write lock inside the
13/// transaction: Cypher locks a node before reading a property a `SET` updates from its own
14/// value. A transaction that rolls back removes a node it created.
15const LOCK: &str = "\
16MERGE (a:AdkKernelAgent {id: $id}) ON CREATE SET a.version = 0, a.order_key = $order_key \
17SET a.lock_seq = coalesce(a.lock_seq, 0) + 1";
18
19const VERSION: &str = "MATCH (a:AdkKernelAgent {id: $id}) RETURN a.version AS version";
20
21const WRITE: &str = "\
22MATCH (a:AdkKernelAgent {id: $id}) \
23SET a.version = $version, a.state = $state, a.record = $record";
24
25/// An [`AgentStore`] in Neo4j, shared by every replica (spec 3.3 §5.7, §10 K7, feature
26/// `neo4j`).
27///
28/// One `AdkKernelAgent` node per agent, unique by `id`: `version` and `state`, the
29/// properties a write compares and a delete reads, `order_key` (the hex of the id, so
30/// `list` orders by the id's UTF-8 bytes whatever the database's collation), and `record`,
31/// the record as JSON text. `put_if_version` write-locks the node inside a transaction
32/// before it reads the version, so of two replicas changing one agent from the same version
33/// the second sees the first's write and changes nothing. Every call runs on a task of its
34/// own, as the [process store](crate::Neo4jProcessStore) explains.
35///
36/// # Example
37///
38/// ```rust,no_run
39/// # async fn example() -> adk_kernel::Result<()> {
40/// let store =
41///     adk_kernel::stores::Neo4jAgentStore::connect("bolt://localhost:7687", "neo4j", "password").await?;
42/// store.migrate().await?;
43/// # Ok(())
44/// # }
45/// ```
46#[derive(Clone)]
47pub struct Neo4jAgentStore {
48    graph: Graph,
49}
50
51impl std::fmt::Debug for Neo4jAgentStore {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        f.debug_struct("Neo4jAgentStore").finish_non_exhaustive()
54    }
55}
56
57impl Neo4jAgentStore {
58    /// A store over `graph`, such as the process store's.
59    pub fn from_graph(graph: Graph) -> Self {
60        Self { graph }
61    }
62
63    /// Connects to the server at `uri`.
64    ///
65    /// # Errors
66    ///
67    /// Returns [`KernelError::Store`] when the server cannot be reached.
68    pub async fn connect(uri: &str, user: &str, password: &str) -> Result<Self> {
69        Ok(Self::from_graph(connect(uri, user, password).await?))
70    }
71
72    /// The connection the store uses.
73    pub fn graph(&self) -> &Graph {
74        &self.graph
75    }
76
77    /// Creates the constraint the store relies on; one that exists is kept.
78    ///
79    /// # Errors
80    ///
81    /// Returns [`KernelError::Store`] when a schema statement fails.
82    pub async fn migrate(&self) -> Result<()> {
83        let graph = self.graph.clone();
84        detached(async move {
85            run_schema(
86                &graph,
87                &["CREATE CONSTRAINT adk_kernel_agent_id IF NOT EXISTS \
88                   FOR (a:AdkKernelAgent) REQUIRE a.id IS UNIQUE"],
89            )
90            .await
91        })
92        .await
93    }
94}
95
96fn stored_version(version: u64) -> Result<i64> {
97    i64::try_from(version).map_err(|_| KernelError::Store {
98        backend: super::neo4j::BACKEND,
99        reason: format!("agent version {version} exceeds a signed 64-bit integer"),
100    })
101}
102
103/// Reads a row back into its record, or `None` for a node without one: a concurrent
104/// transaction's node not written yet, or one a `delete` removed after the statement
105/// matched it.
106fn decode(row: &Row) -> Result<Option<AgentRecord>> {
107    column::<Option<String>>(row, "record")?.map(|record| json("agent", &record)).transpose()
108}
109
110/// Writes `write` over the agent `id` when its stored version is `expected`, in one
111/// transaction that write-locks the node first.
112async fn put_once(
113    graph: &Graph,
114    id: &str,
115    expected: i64,
116    write: Query,
117) -> std::result::Result<bool, neo4rs::Error> {
118    let mut txn = graph.start_txn().await?;
119    txn.run(query(LOCK).param("id", id).param("order_key", order_key(id))).await?;
120    let version = txn_rows(&mut txn, query(VERSION).param("id", id))
121        .await?
122        .first()
123        .and_then(|row| row.get::<Option<i64>>("version").ok().flatten())
124        .unwrap_or(0);
125    if version != expected {
126        txn.rollback().await?;
127        return Ok(false);
128    }
129    txn.run(write).await?;
130    txn.commit().await?;
131    Ok(true)
132}
133
134#[async_trait]
135impl AgentStore for Neo4jAgentStore {
136    async fn put_if_version(&self, record: AgentRecord, expected: u64) -> Result<bool> {
137        let write = query(WRITE)
138            .param("id", record.id.as_str())
139            .param("version", stored_version(record.version)?)
140            .param("state", record.state.as_str())
141            .param("record", serde_json::to_string(&record)?);
142        let expected = stored_version(expected)?;
143        let (graph, id) = (self.graph.clone(), record.id.clone());
144        detached(async move {
145            retry("write the agent table", || put_once(&graph, &id, expected, write.clone())).await
146        })
147        .await
148    }
149
150    async fn get(&self, id: &str) -> Result<Option<AgentRecord>> {
151        let statement =
152            query("MATCH (a:AdkKernelAgent {id: $id}) RETURN a.record AS record").param("id", id);
153        let graph = self.graph.clone();
154        detached(async move {
155            Ok(match rows(&graph, statement, "read the agent table").await?.first() {
156                Some(row) => decode(row)?,
157                None => None,
158            })
159        })
160        .await
161    }
162
163    async fn list(&self) -> Result<Vec<AgentRecord>> {
164        let statement = query(
165            "MATCH (a:AdkKernelAgent) WHERE a.record IS NOT NULL RETURN a.record AS record \
166             ORDER BY a.order_key",
167        );
168        let graph = self.graph.clone();
169        detached(async move {
170            let rows = rows(&graph, statement, "list the agent table").await?;
171            rows.iter().filter_map(|row| decode(row).transpose()).collect()
172        })
173        .await
174    }
175
176    async fn delete(&self, id: &str) -> Result<bool> {
177        let statement = query(
178            "MATCH (a:AdkKernelAgent {id: $id}) WHERE a.state = 'proposed' DELETE a \
179             RETURN count(*) AS deleted",
180        )
181        .param("id", id);
182        let graph = self.graph.clone();
183        detached(async move {
184            Ok(count(&rows(&graph, statement, "delete from the agent table").await?, "deleted")?
185                > 0)
186        })
187        .await
188    }
189}