Skip to main content

adk_kernel/stores/
neo4j.rs

1//! The Neo4j [`ProcessStore`] (spec 3.2 §7.1, §13 Q8, feature `neo4j`), and the helpers the
2//! kernel's other Neo4j stores share.
3
4use std::future::Future;
5use std::time::Duration;
6
7use async_trait::async_trait;
8use chrono::NaiveDate;
9use neo4rs::{Graph, Neo4jErrorKind, Query, Row, Txn, query};
10
11use super::{
12    ProcessFilter, ProcessStore, SpendScope, UsageTotals, counters, day_number, stored_amount,
13    stored_micro_usd, stored_total,
14};
15use crate::bus::SpendDelta;
16use crate::error::{KernelError, Result};
17use crate::partition::PartitionId;
18use crate::process::ProcessMeta;
19use crate::sched::QueueClass;
20use crate::wake::WakeSet;
21
22/// The backend name in [`KernelError::Store`].
23pub(super) const BACKEND: &str = "neo4j";
24
25/// Attempts at a statement that fails with a transient error, such as a detected deadlock,
26/// before the error is returned.
27const ATTEMPTS: u32 = 30;
28
29/// Schema codes that mean an `IF NOT EXISTS` statement raced another one and lost.
30const SCHEMA_ALREADY_EXISTS: [&str; 4] = [
31    "Neo.ClientError.Schema.EquivalentSchemaRuleAlreadyExists",
32    "Neo.ClientError.Schema.ConstraintAlreadyExists",
33    "Neo.ClientError.Schema.IndexAlreadyExists",
34    "Neo.ClientError.Schema.ConstraintWithNameAlreadyExists",
35];
36
37/// Two `MERGE`s creating one node at once: the loser's retry finds the node.
38const CONSTRAINT_VIOLATION: &str = "Neo.ClientError.Schema.ConstraintValidationFailed";
39
40pub(super) fn store_error(action: &str, error: &dyn std::fmt::Display) -> KernelError {
41    KernelError::Store { backend: BACKEND, reason: format!("could not {action}: {error}") }
42}
43
44/// Connects to the server at `uri`.
45pub(super) async fn connect(uri: &str, user: &str, password: &str) -> Result<Graph> {
46    Graph::new(uri, user, password).await.map_err(|error| store_error("connect to Neo4j", &error))
47}
48
49/// The hex of `text`'s UTF-8 bytes, which orders as the bytes do whatever the database's
50/// string collation, so `ORDER BY` on it follows byte order as on every backend.
51pub(super) fn order_key(text: &str) -> String {
52    text.bytes().map(|byte| format!("{byte:02x}")).collect()
53}
54
55/// Runs one store call to completion on a task of its own.
56///
57/// neo4rs connections are not cancellation-safe: a call dropped between sending a bolt
58/// message and reading its response returns the connection to the pool with that response
59/// unread, and every later response on it is one behind. The kernel drops store calls when
60/// a request or a worker attempt ends, so every call finishes its exchange on its own task
61/// and a dropped caller only loses the result.
62pub(super) async fn detached<T: Send + 'static>(
63    call: impl Future<Output = Result<T>> + Send + 'static,
64) -> Result<T> {
65    match tokio::spawn(call).await {
66        Ok(result) => result,
67        Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
68        Err(error) => Err(store_error("finish a Neo4j call", &error)),
69    }
70}
71
72fn neo4j_code(error: &neo4rs::Error) -> Option<&str> {
73    match error {
74        neo4rs::Error::Neo4j(error) => Some(error.code()),
75        _ => None,
76    }
77}
78
79/// Whether running the statement again can succeed: a transient error, such as a detected
80/// deadlock, or a `MERGE` that lost a race to create its node.
81fn retryable(error: &neo4rs::Error) -> bool {
82    match error {
83        neo4rs::Error::Neo4j(neo4j) => {
84            neo4j.kind() == Neo4jErrorKind::Transient || neo4j.code() == CONSTRAINT_VIOLATION
85        }
86        _ => false,
87    }
88}
89
90/// Small randomized pause before retry `attempt`, growing with the attempt number.
91fn backoff(attempt: u32) -> Duration {
92    let jitter = u64::from(uuid::Uuid::new_v4().as_bytes()[0]) % 10;
93    Duration::from_millis(u64::from(attempt.min(20)) * 5 + jitter)
94}
95
96/// Runs `attempt` until it succeeds, fails with an error running it again cannot fix, or
97/// has failed [`ATTEMPTS`] times.
98pub(super) async fn retry<T, F, Fut>(action: &str, mut attempt: F) -> Result<T>
99where
100    F: FnMut() -> Fut,
101    Fut: Future<Output = std::result::Result<T, neo4rs::Error>>,
102{
103    let mut tries = 1;
104    loop {
105        match attempt().await {
106            Err(error) if retryable(&error) && tries < ATTEMPTS => {
107                tokio::time::sleep(backoff(tries)).await;
108                tries += 1;
109            }
110            result => return result.map_err(|error| store_error(action, &error)),
111        }
112    }
113}
114
115/// Every row of an auto-commit `query`.
116async fn fetch(graph: &Graph, query: Query) -> std::result::Result<Vec<Row>, neo4rs::Error> {
117    let mut stream = graph.execute(query).await?;
118    let mut rows = Vec::new();
119    while let Some(row) = stream.next().await? {
120        rows.push(row);
121    }
122    Ok(rows)
123}
124
125/// Every row of `query`, run as an auto-commit statement and retried as [`retry`] does.
126pub(super) async fn rows(graph: &Graph, query: Query, action: &str) -> Result<Vec<Row>> {
127    retry(action, || fetch(graph, query.clone())).await
128}
129
130/// Every row of `query`, run inside `txn`.
131pub(super) async fn txn_rows(
132    txn: &mut Txn,
133    query: Query,
134) -> std::result::Result<Vec<Row>, neo4rs::Error> {
135    let mut stream = txn.execute(query).await?;
136    let mut rows = Vec::new();
137    while let Some(row) = stream.next(&mut *txn).await? {
138        rows.push(row);
139    }
140    Ok(rows)
141}
142
143/// Column `name` of `row`.
144pub(super) fn column<T: serde::de::DeserializeOwned>(row: &Row, name: &str) -> Result<T> {
145    row.get::<T>(name).map_err(|error| KernelError::Store {
146        backend: BACKEND,
147        reason: format!("a stored row's column `{name}` is unreadable: {error}"),
148    })
149}
150
151/// The integer column `name` of the first row, 0 when there is none.
152pub(super) fn count(rows: &[Row], name: &str) -> Result<i64> {
153    rows.first().map_or(Ok(0), |row| column::<i64>(row, name))
154}
155
156/// JSON text a store wrote, read back.
157pub(super) fn json<T: serde::de::DeserializeOwned>(what: &str, text: &str) -> Result<T> {
158    serde_json::from_str(text).map_err(|error| KernelError::Store {
159        backend: BACKEND,
160        reason: format!("a stored {what} is corrupt: {error}"),
161    })
162}
163
164/// Runs idempotent schema statements, tolerating a concurrent `migrate` that created the
165/// same rule first.
166pub(super) async fn run_schema(graph: &Graph, statements: &[&str]) -> Result<()> {
167    for statement in statements {
168        let mut tries = 1;
169        loop {
170            match graph.run(query(statement)).await {
171                Ok(()) => break,
172                Err(error)
173                    if neo4j_code(&error)
174                        .is_some_and(|code| SCHEMA_ALREADY_EXISTS.contains(&code)) =>
175                {
176                    break;
177                }
178                Err(error) if tries < ATTEMPTS && retryable(&error) => {
179                    tokio::time::sleep(backoff(tries)).await;
180                    tries += 1;
181                }
182                Err(error) => return Err(store_error("create the Neo4j schema", &error)),
183            }
184        }
185    }
186    Ok(())
187}
188
189/// The `LIMIT` clause of a list, with its parameter.
190pub(super) fn limit_clause(limit: Option<usize>) -> (String, Option<i64>) {
191    match limit {
192        Some(limit) => {
193            (" LIMIT $limit".to_string(), Some(i64::try_from(limit).unwrap_or(i64::MAX)))
194        }
195        None => (String::new(), None),
196    }
197}
198
199/// The `WHERE` clause joining `conditions`, empty when there are none.
200pub(super) fn where_clause(conditions: &[&str]) -> String {
201    if conditions.is_empty() {
202        String::new()
203    } else {
204        format!(" WHERE {}", conditions.join(" AND "))
205    }
206}
207
208const PUT: &str = "\
209MERGE (p:AdkKernelProcess {pid: $pid}) \
210SET p = {pid: $pid, order_key: $order_key, partition: $partition, queue: $queue, kind: $kind, \
211    labels: $labels, suspend_requested: $suspend_requested, parent: $parent, wake: $wake, \
212    suspended_by: $suspended_by, agenda_item: $agenda_item}";
213
214const COLUMNS: &str = "\
215RETURN p.pid AS pid, p.parent AS parent, p.partition AS partition, p.queue AS queue, \
216    p.kind AS kind, p.wake AS wake, p.suspended_by AS suspended_by, \
217    p.suspend_requested AS suspend_requested, p.agenda_item AS agenda_item, p.labels AS labels";
218
219const ADD_SPEND: &str = "\
220MERGE (s:AdkKernelSpend {key: $key}) \
221ON CREATE SET s.pid = $pid, s.partition = $partition, s.day = $day, s.micro_usd = 0 \
222SET s.micro_usd = s.micro_usd + $amount \
223WITH s \
224UNWIND range(0, size($names) - 1) AS i \
225MERGE (u:AdkKernelUsage {key: $key + ':' + $names[i]}) \
226ON CREATE SET u.pid = $pid, u.partition = $partition, u.day = $day, u.counter = $names[i], \
227    u.amount = 0 \
228SET u.amount = u.amount + $amounts[i]";
229
230/// A [`ProcessStore`] in Neo4j, shared by every replica (spec 3.2 §7.1, §13 Q8, feature
231/// `neo4j`).
232///
233/// | Label | Key (unique) | Properties |
234/// |-------|--------------|------------|
235/// | `AdkKernelProcess` | `pid` | `order_key` (the hex of the pid), `partition`, `queue`, `suspend_requested` and, when set, `parent` and `agenda_item`, the properties `list` filters on; `kind`, `labels` and, when set, `wake` and `suspended_by` as JSON text |
236/// | `AdkKernelSpend` | `key`: the hex of the pid and the partition with the day | `pid`, `partition`, `day` (days from the common era) and `micro_usd` |
237/// | `AdkKernelUsage` | `key`: the spend key with the counter's name | `pid`, `partition`, `day`, `counter` (model calls, total tokens or a unit) and `amount` |
238///
239/// `list` orders by `order_key`, so pids order by their UTF-8 bytes whatever the database's
240/// collation. `set_wake`, `set_queue` and `set_suspend_requested` each set one property, so
241/// writers changing different fields of one row never lose each other's update.
242/// `add_spend` adds to the stored total in one statement, under the write lock Cypher takes
243/// on a property updated from its own value, so concurrent additions all count; deleting a
244/// process keeps its spend. Every call runs on a task of its own, because a neo4rs
245/// connection dropped mid-exchange is left out of step. Call [`migrate`](Self::migrate)
246/// once per database to create the constraints and indexes.
247///
248/// # Example
249///
250/// ```rust,no_run
251/// # async fn example() -> adk_kernel::Result<()> {
252/// let store =
253///     adk_kernel::Neo4jProcessStore::connect("bolt://localhost:7687", "neo4j", "password").await?;
254/// store.migrate().await?;
255/// # Ok(())
256/// # }
257/// ```
258#[derive(Clone)]
259pub struct Neo4jProcessStore {
260    graph: Graph,
261}
262
263impl std::fmt::Debug for Neo4jProcessStore {
264    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
265        f.debug_struct("Neo4jProcessStore").finish_non_exhaustive()
266    }
267}
268
269impl Neo4jProcessStore {
270    /// A store over `graph`, such as the connection `adk_session::Neo4jRunStore::from_graph`
271    /// uses, so the kernel's nodes sit beside the run, schedule and governance stores.
272    pub fn from_graph(graph: Graph) -> Self {
273        Self { graph }
274    }
275
276    /// Connects to the server at `uri`.
277    ///
278    /// # Errors
279    ///
280    /// Returns [`KernelError::Store`] when the server cannot be reached.
281    pub async fn connect(uri: &str, user: &str, password: &str) -> Result<Self> {
282        Ok(Self::from_graph(connect(uri, user, password).await?))
283    }
284
285    /// The connection the store uses.
286    pub fn graph(&self) -> &Graph {
287        &self.graph
288    }
289
290    /// Creates the constraints and indexes the store relies on; one that exists is kept.
291    ///
292    /// # Errors
293    ///
294    /// Returns [`KernelError::Store`] when a schema statement fails.
295    pub async fn migrate(&self) -> Result<()> {
296        let graph = self.graph.clone();
297        detached(async move {
298            run_schema(
299                &graph,
300                &[
301                    "CREATE CONSTRAINT adk_kernel_process_pid IF NOT EXISTS \
302                     FOR (p:AdkKernelProcess) REQUIRE p.pid IS UNIQUE",
303                    "CREATE INDEX adk_kernel_process_order IF NOT EXISTS \
304                     FOR (p:AdkKernelProcess) ON (p.order_key)",
305                    "CREATE INDEX adk_kernel_process_partition IF NOT EXISTS \
306                     FOR (p:AdkKernelProcess) ON (p.partition)",
307                    "CREATE INDEX adk_kernel_process_queue IF NOT EXISTS \
308                     FOR (p:AdkKernelProcess) ON (p.queue)",
309                    "CREATE INDEX adk_kernel_process_parent IF NOT EXISTS \
310                     FOR (p:AdkKernelProcess) ON (p.parent)",
311                    "CREATE CONSTRAINT adk_kernel_spend_key IF NOT EXISTS \
312                     FOR (s:AdkKernelSpend) REQUIRE s.key IS UNIQUE",
313                    "CREATE INDEX adk_kernel_spend_pid IF NOT EXISTS \
314                     FOR (s:AdkKernelSpend) ON (s.pid)",
315                    "CREATE INDEX adk_kernel_spend_partition IF NOT EXISTS \
316                     FOR (s:AdkKernelSpend) ON (s.partition)",
317                    "CREATE CONSTRAINT adk_kernel_usage_key IF NOT EXISTS \
318                     FOR (u:AdkKernelUsage) REQUIRE u.key IS UNIQUE",
319                    "CREATE INDEX adk_kernel_usage_pid IF NOT EXISTS \
320                     FOR (u:AdkKernelUsage) ON (u.pid)",
321                    "CREATE INDEX adk_kernel_usage_partition IF NOT EXISTS \
322                     FOR (u:AdkKernelUsage) ON (u.partition)",
323                ],
324            )
325            .await
326        })
327        .await
328    }
329
330    /// Runs `update`, which returns `matched`, on the row of `pid`, failing when there is
331    /// none.
332    async fn update(&self, pid: &str, update: Query) -> Result<()> {
333        let graph = self.graph.clone();
334        let matched = detached(async move {
335            count(&rows(&graph, update, "update the process table").await?, "matched")
336        })
337        .await?;
338        if matched == 0 {
339            return Err(KernelError::NotFound { pid: pid.into() });
340        }
341        Ok(())
342    }
343}
344
345/// Reads a row back into the [`ProcessMeta`] that was put, or `None` for a node a concurrent
346/// `delete` removed after the statement matched it: Neo4j reads committed data, so its
347/// properties then read as null, as if the read had come after the delete.
348fn decode(row: &Row) -> Result<Option<ProcessMeta>> {
349    let optional = |name: &str| column::<Option<String>>(row, name);
350    let (Some(pid), Some(partition), Some(queue), Some(kind), Some(labels)) = (
351        optional("pid")?,
352        optional("partition")?,
353        optional("queue")?,
354        optional("kind")?,
355        optional("labels")?,
356    ) else {
357        return Ok(None);
358    };
359    Ok(Some(ProcessMeta {
360        pid,
361        parent: optional("parent")?,
362        partition: PartitionId::new(partition),
363        queue: QueueClass::from_name(&queue),
364        kind: json("process kind", &kind)?,
365        wake: optional("wake")?.map(|wake| json("wake set", &wake)).transpose()?,
366        suspended_by: optional("suspended_by")?
367            .map(|suspension| json("suspension", &suspension))
368            .transpose()?,
369        suspend_requested: column::<Option<bool>>(row, "suspend_requested")?.unwrap_or(false),
370        agenda_item: optional("agenda_item")?,
371        labels: json("label set", &labels)?,
372    }))
373}
374
375#[async_trait]
376impl ProcessStore for Neo4jProcessStore {
377    async fn put(&self, meta: ProcessMeta) -> Result<()> {
378        let statement = query(PUT)
379            .param("pid", meta.pid.as_str())
380            .param("order_key", order_key(&meta.pid))
381            .param("partition", meta.partition.as_str())
382            .param("queue", meta.queue.as_str())
383            .param("kind", serde_json::to_string(&meta.kind)?)
384            .param("labels", serde_json::to_string(&meta.labels)?)
385            .param("suspend_requested", meta.suspend_requested)
386            .param("parent", meta.parent.clone())
387            .param("wake", meta.wake.as_ref().map(serde_json::to_string).transpose()?)
388            .param(
389                "suspended_by",
390                meta.suspended_by.as_ref().map(serde_json::to_string).transpose()?,
391            )
392            .param("agenda_item", meta.agenda_item.clone());
393        let graph = self.graph.clone();
394        detached(async move {
395            rows(&graph, statement, "write the process table").await?;
396            Ok(())
397        })
398        .await
399    }
400
401    async fn get(&self, pid: &str) -> Result<Option<ProcessMeta>> {
402        let statement =
403            query(&format!("MATCH (p:AdkKernelProcess {{pid: $pid}}) {COLUMNS}")).param("pid", pid);
404        let graph = self.graph.clone();
405        detached(async move {
406            Ok(match rows(&graph, statement, "read the process table").await?.first() {
407                Some(row) => decode(row)?,
408                None => None,
409            })
410        })
411        .await
412    }
413
414    async fn list(&self, filter: &ProcessFilter) -> Result<Vec<ProcessMeta>> {
415        let mut conditions = Vec::new();
416        if filter.partition.is_some() {
417            conditions.push("p.partition = $partition");
418        }
419        if filter.queue.is_some() {
420            conditions.push("p.queue = $queue");
421        }
422        if filter.parent.is_some() {
423            conditions.push("p.parent = $parent");
424        }
425        if filter.suspend_requested.is_some() {
426            conditions.push("p.suspend_requested = $suspend_requested");
427        }
428        let (limit, limit_value) = limit_clause(filter.limit);
429        let statement = query(&format!(
430            "MATCH (p:AdkKernelProcess){} {COLUMNS} ORDER BY p.order_key{limit}",
431            where_clause(&conditions)
432        ))
433        .param("partition", filter.partition.as_ref().map(|partition| partition.as_str()))
434        .param("queue", filter.queue.as_ref().map(|queue| queue.as_str()))
435        .param("parent", filter.parent.clone())
436        .param("suspend_requested", filter.suspend_requested)
437        .param("limit", limit_value);
438        let graph = self.graph.clone();
439        detached(async move {
440            let rows = rows(&graph, statement, "list processes").await?;
441            rows.iter().filter_map(|row| decode(row).transpose()).collect()
442        })
443        .await
444    }
445
446    async fn set_wake(&self, pid: &str, wake: Option<WakeSet>) -> Result<()> {
447        let statement = query(
448            "MATCH (p:AdkKernelProcess {pid: $pid}) SET p.wake = $wake \
449             RETURN count(p) AS matched",
450        )
451        .param("pid", pid)
452        .param("wake", wake.as_ref().map(serde_json::to_string).transpose()?);
453        self.update(pid, statement).await
454    }
455
456    async fn set_queue(&self, pid: &str, queue: QueueClass) -> Result<()> {
457        let statement = query(
458            "MATCH (p:AdkKernelProcess {pid: $pid}) SET p.queue = $queue \
459             RETURN count(p) AS matched",
460        )
461        .param("pid", pid)
462        .param("queue", queue.as_str());
463        self.update(pid, statement).await
464    }
465
466    async fn delete(&self, pid: &str) -> Result<bool> {
467        let statement =
468            query("MATCH (p:AdkKernelProcess {pid: $pid}) DELETE p RETURN count(*) AS deleted")
469                .param("pid", pid);
470        let graph = self.graph.clone();
471        detached(async move {
472            Ok(count(&rows(&graph, statement, "delete from the process table").await?, "deleted")?
473                > 0)
474        })
475        .await
476    }
477
478    async fn set_suspend_requested(&self, pid: &str, requested: bool) -> Result<()> {
479        let statement = query(
480            "MATCH (p:AdkKernelProcess {pid: $pid}) SET p.suspend_requested = $requested \
481             RETURN count(p) AS matched",
482        )
483        .param("pid", pid)
484        .param("requested", requested);
485        self.update(pid, statement).await
486    }
487
488    async fn add_spend(
489        &self,
490        pid: &str,
491        partition: &PartitionId,
492        day: NaiveDate,
493        delta: SpendDelta,
494    ) -> Result<()> {
495        let day = day_number(day);
496        let mut names = Vec::new();
497        let mut amounts = Vec::new();
498        for (name, amount) in counters(&delta) {
499            names.push(name.to_string());
500            amounts.push(stored_amount(BACKEND, name, amount)?);
501        }
502        let statement = query(ADD_SPEND)
503            .param("key", format!("{}:{}:{day}", order_key(pid), order_key(partition.as_str())))
504            .param("pid", pid)
505            .param("partition", partition.as_str())
506            .param("day", day)
507            .param("amount", stored_micro_usd(BACKEND, &delta)?)
508            .param("names", names)
509            .param("amounts", amounts);
510        let graph = self.graph.clone();
511        detached(async move {
512            rows(&graph, statement, "add to the spend totals").await?;
513            Ok(())
514        })
515        .await
516    }
517
518    async fn spend(
519        &self,
520        scope: &SpendScope,
521        from: NaiveDate,
522        to_inclusive: NaiveDate,
523    ) -> Result<u64> {
524        let (field, key) = match scope {
525            SpendScope::Process(pid) => ("pid", pid.as_str()),
526            SpendScope::Partition(partition) => ("partition", partition.as_str()),
527        };
528        let statement = query(&format!(
529            "MATCH (s:AdkKernelSpend) WHERE s.{field} = $key AND s.day >= $from AND s.day <= $to \
530             RETURN coalesce(sum(s.micro_usd), 0) AS total"
531        ))
532        .param("key", key)
533        .param("from", day_number(from))
534        .param("to", day_number(to_inclusive));
535        let graph = self.graph.clone();
536        let total = detached(async move {
537            count(&rows(&graph, statement, "sum the spend totals").await?, "total")
538        })
539        .await?;
540        stored_total(BACKEND, total)
541    }
542
543    async fn usage(
544        &self,
545        scope: &SpendScope,
546        from: NaiveDate,
547        to_inclusive: NaiveDate,
548    ) -> Result<UsageTotals> {
549        let (field, key) = match scope {
550            SpendScope::Process(pid) => ("pid", pid.clone()),
551            SpendScope::Partition(partition) => ("partition", partition.as_str().to_string()),
552        };
553        let statement = query(&format!(
554            "MATCH (u:AdkKernelUsage) WHERE u.{field} = $key AND u.day >= $from AND u.day <= $to \
555             RETURN u.counter AS counter, sum(u.amount) AS total"
556        ))
557        .param("key", key)
558        .param("from", day_number(from))
559        .param("to", day_number(to_inclusive));
560        let mut totals = UsageTotals {
561            micro_usd: self.spend(scope, from, to_inclusive).await?,
562            ..UsageTotals::default()
563        };
564        let graph = self.graph.clone();
565        let counters =
566            detached(async move { rows(&graph, statement, "sum the usage totals").await }).await?;
567        for row in &counters {
568            let name: String = column(row, "counter")?;
569            let amount: i64 = column(row, "total")?;
570            totals.add_counter(&name, stored_total(BACKEND, amount)?);
571        }
572        Ok(totals)
573    }
574}