Skip to main content

khive_storage/
graph.rs

1//! Graph storage capability — edge CRUD and traversal.
2
3use async_trait::async_trait;
4use chrono::{DateTime, Utc};
5use khive_types::EdgeRelation;
6use uuid::Uuid;
7
8use crate::capability::StorageCapability;
9use crate::error::StorageError;
10use crate::types::{
11    BatchWriteSummary, DeleteMode, DirectedNeighborHit, Direction, Edge, EdgeEndpointBaseCounts,
12    EdgeFilter, EdgeSeekPage, EdgeSortField, EdgeUpsertRequest, EdgeUpsertResult, GraphPath,
13    GuardedBatchOutcome, GuardedEdgeBatchUpsertOutcome, GuardedEdgeUpsertOutcome,
14    GuardedWriteOutcome, LinkId, NeighborCursor, NeighborHit, NeighborQuery, Page, PageRequest,
15    SeekCursor, SeekPage, SortOrder, SqlStatement, StorageResult, TraversalRequest,
16};
17
18/// One caller-labelled predicate evaluated inside a graph writer transaction.
19///
20/// The statement must be one SELECT (including WITH followed by SELECT) returning
21/// exactly one row and one column. SQLite INTEGER 1 passes and INTEGER 0 refuses;
22/// other values and result shapes refuse with a typed reason. The caller owns
23/// the predicate and its tables. This is trusted in-process SQL, not a sandbox.
24#[derive(Clone, Debug)]
25pub struct GraphStatementGuard {
26    pub label: String,
27    pub statement: SqlStatement,
28}
29
30/// SQLite value class observed in a guard's non-boolean result.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum GraphGuardValueKind {
33    Null,
34    Integer,
35    Real,
36    Text,
37    Blob,
38}
39
40/// Predicate or result-shape refusal from one graph statement guard.
41///
42/// SQL preparation, binding and execution failures remain storage errors.
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub enum GraphStatementGuardFailureReason {
45    PredicateFalse,
46    NoRows,
47    MultipleRows,
48    ColumnCount { actual: usize },
49    NonBoolean { kind: GraphGuardValueKind },
50}
51
52impl std::fmt::Display for GraphStatementGuardFailureReason {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        match self {
55            Self::PredicateFalse => f.write_str("predicate_false"),
56            Self::NoRows => f.write_str("zero_rows"),
57            Self::MultipleRows => f.write_str("multiple_rows"),
58            Self::ColumnCount { actual } => write!(f, "column_count({actual})"),
59            Self::NonBoolean { kind } => write!(f, "non_boolean({kind:?})"),
60        }
61    }
62}
63
64/// The first refused guard, identified by its required caller label.
65///
66/// Display includes the label and reason, never the SQL text or bound values.
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub struct GraphStatementGuardFailure {
69    pub label: String,
70    pub reason: GraphStatementGuardFailureReason,
71}
72
73impl std::fmt::Display for GraphStatementGuardFailure {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        write!(
76            f,
77            "graph statement guard {:?} failed: {}",
78            self.label, self.reason
79        )
80    }
81}
82
83/// Transaction-observed result of a guarded, create-only graph insertion.
84///
85/// Existing rows are never replaced or resurrected. A natural-key winner takes
86/// precedence when the requested ID also collides; an unrelated ID collision
87/// without a natural-key winner remains a storage error. Only Created carries
88/// a new edge and permits its corresponding lifecycle event.
89#[derive(Clone, Debug)]
90pub enum EdgeInsertIfAbsentOutcome {
91    Created(Edge),
92    ExistingLive,
93    Tombstoned,
94    GuardFailed(GraphStatementGuardFailure),
95}
96
97/// A validated symmetric-edge patch and the exact persisted snapshot it replaces.
98///
99/// The caller supplies canonical endpoints for a symmetric relation. `namespace`
100/// belongs to the stored record, independently of the store's routing namespace.
101/// Snapshot timestamps use raw microseconds so overflow is refused without a
102/// lossy timestamp conversion. Creation time, deletion state and target backend
103/// are not replaced by this request.
104#[derive(Clone, Debug)]
105pub struct SymmetricEdgeUpdateRequest {
106    pub namespace: String,
107    pub id: LinkId,
108    pub source_id: Uuid,
109    pub target_id: Uuid,
110    pub relation: EdgeRelation,
111    pub weight: f64,
112    pub metadata: Option<serde_json::Value>,
113    pub expected_updated_at_micros: i64,
114    pub expected_deleted_at_micros: Option<i64>,
115}
116
117/// Committed disposition of a guarded symmetric-edge update.
118#[derive(Debug)]
119pub enum SymmetricEdgeUpdateOutcome {
120    /// No competing natural key existed; the requested edge was updated.
121    Updated,
122    /// A live or tombstoned canonical row survived unchanged and the requested
123    /// duplicate was deleted. Its stored ID remains raw: parsing belongs after
124    /// commit, so malformed legacy data cannot change the transaction outcome.
125    Absorbed(String),
126    /// The requested row disappeared or no longer matched its revision or
127    /// deletion marker. Neither the update nor the conflict deletion occurred.
128    Stale,
129}
130
131/// Directed edge CRUD and graph traversal over the knowledge graph.
132#[async_trait]
133pub trait GraphStore: Send + Sync + 'static {
134    /// Return the newest live note of `kind` carrying the exact string `tag`
135    /// in its properties.tags array and connected to `node_id` by a live
136    /// incoming `annotates` edge in this store's namespace. Returns its UUID
137    /// and creation timestamp; equal timestamps choose the smallest UUID.
138    ///
139    /// Apply all predicates before limiting to one result. Note lookup follows
140    /// the by-ID contract; visibility is determined by the annotation edge's
141    /// namespace, not by introducing a second namespace filter on the note.
142    /// The note and edge must belong to this backend. Unsupported backends
143    /// fail explicitly rather than scanning an arbitrary annotation window.
144    async fn latest_annotating_note(
145        &self,
146        _node_id: Uuid,
147        _kind: &str,
148        _tag: &str,
149    ) -> StorageResult<Option<(Uuid, i64)>> {
150        Err(StorageError::Unsupported {
151            capability: StorageCapability::Graph,
152            operation: "latest_annotating_note".into(),
153            message: "this backend does not implement latest matching annotation lookup".into(),
154        })
155    }
156
157    /// Like `latest_annotating_note`, but also require one exact top-level
158    /// string property before selecting the newest candidate.
159    async fn latest_annotating_note_with_property(
160        &self,
161        _node_id: Uuid,
162        _kind: &str,
163        _tag: &str,
164        _property_key: &str,
165        _property_value: &str,
166    ) -> StorageResult<Option<(Uuid, i64)>> {
167        Err(StorageError::Unsupported {
168            capability: StorageCapability::Graph,
169            operation: "latest_annotating_note_with_property".into(),
170            message: "this backend does not implement latest matching annotation lookup".into(),
171        })
172    }
173
174    /// Insert or update a single edge.
175    async fn upsert_edge(&self, edge: Edge) -> StorageResult<()>;
176    /// Insert an edge only when neither its id nor natural key already
177    /// exists. Returns `true` when this call inserted the row and `false`
178    /// when an existing row won the race. The existing row is never updated.
179    ///
180    /// The default returns `Unsupported` rather than falling back to
181    /// [`GraphStore::upsert_edge`], because an upsert would overwrite the
182    /// winning row and violate this method's conditional-insert contract.
183    async fn insert_edge_if_absent(&self, _edge: Edge) -> StorageResult<bool> {
184        Err(StorageError::Unsupported {
185            capability: StorageCapability::Graph,
186            operation: "insert_edge_if_absent".into(),
187            message: "this backend does not implement conditional edge insert".into(),
188        })
189    }
190    /// Insert or update a batch of edges.
191    async fn upsert_edges(&self, edges: Vec<Edge>) -> StorageResult<BatchWriteSummary>;
192    /// Insert or replace one edge and return the transaction-observed
193    /// disposition plus preimage. Tombstone restoration is controlled by the
194    /// request rather than being an implicit side effect of every upsert.
195    async fn upsert_edge_observed(
196        &self,
197        _request: EdgeUpsertRequest,
198    ) -> StorageResult<EdgeUpsertResult> {
199        Err(StorageError::Unsupported {
200            capability: StorageCapability::Graph,
201            operation: "upsert_edge_observed".into(),
202            message: "this backend does not implement observed edge upserts".into(),
203        })
204    }
205    /// Replace an edge only when the persisted row still matches the
206    /// caller's read snapshot.
207    ///
208    /// `expected_updated_at` is the snapshot revision and
209    /// `expected_deleted_at` closes the soft-delete race. The replacement
210    /// edge's `updated_at` must be strictly greater than that persisted
211    /// revision. Returns `false` when the row disappeared, changed, or was
212    /// supplied a non-advancing replacement revision. This is the full-edge
213    /// compare-and-swap seam used when a caller derives coupled fields from
214    /// that snapshot before persistence — mirrors
215    /// [`crate::NoteStore::replace_note_if_unchanged`]. The default returns
216    /// `Unsupported` rather than falling back to an unguarded upsert and
217    /// reintroducing the stale-snapshot race.
218    async fn replace_edge_if_unchanged(
219        &self,
220        _edge: Edge,
221        _expected_updated_at: DateTime<Utc>,
222        _expected_deleted_at: Option<DateTime<Utc>>,
223    ) -> StorageResult<bool> {
224        Err(StorageError::Unsupported {
225            capability: StorageCapability::Graph,
226            operation: "replace_edge_if_unchanged".into(),
227            message: "this backend does not implement guarded edge replacement".into(),
228        })
229    }
230    /// Apply a validated symmetric-edge patch in one writer transaction.
231    ///
232    /// First require a representable revision strictly after the snapshot, even
233    /// if a competing natural key will absorb this edge. Then probe that key in
234    /// the request's record namespace, including tombstones. A competing row
235    /// survives unchanged; only the requested duplicate may be deleted. With no
236    /// competitor, replace the requested patch fields and advance its revision.
237    /// Both mutations compare the snapshot's revision and deletion marker.
238    ///
239    /// The default refuses rather than substituting an unguarded upsert or a
240    /// caller-side read/delete sequence. Errors can report unknown settlement;
241    /// callers must not infer rollback or retry an ambiguous result.
242    async fn update_symmetric_edge_if_unchanged(
243        &self,
244        _request: SymmetricEdgeUpdateRequest,
245    ) -> StorageResult<SymmetricEdgeUpdateOutcome> {
246        Err(StorageError::Unsupported {
247            capability: StorageCapability::Graph,
248            operation: "update_symmetric_edge_if_unchanged".into(),
249            message: "this backend does not implement guarded symmetric-edge updates".into(),
250        })
251    }
252    /// Insert or update a single edge, re-checking that both endpoints still
253    /// exist (and are not soft-deleted) as part of the same write, not a
254    /// separate prior read. Closes the TOCTOU window between an async
255    /// prepare-time existence check and a later, unconditional write: a
256    /// concurrent hard-delete of an endpoint that lands between the two can
257    /// otherwise leave a durably dangling edge (#769).
258    ///
259    /// Returns [`GuardedWriteOutcome::Refused`] naming exactly which
260    /// endpoint(s) were missing, determined by the guard's own in-transaction
261    /// probe — never reconstructed by a caller re-reading the endpoints after
262    /// the write already failed, since a concurrent write landing between the
263    /// refusal and any such later read could misreport which endpoint was
264    /// actually missing at write time.
265    ///
266    /// Default returns `StorageError::Unsupported`: a backend that does not
267    /// override this method cannot honor the endpoint-existence guarantee,
268    /// and silently falling back to [`GraphStore::upsert_edge`] would
269    /// reintroduce the TOCTOU window this method exists to close.
270    async fn upsert_edge_guarded(&self, _edge: Edge) -> StorageResult<GuardedWriteOutcome> {
271        Err(StorageError::Unsupported {
272            capability: StorageCapability::Graph,
273            operation: "upsert_edge_guarded".into(),
274            message: "this backend does not implement guarded edge writes".into(),
275        })
276    }
277    /// Observed form of [`GraphStore::upsert_edge_guarded`]. In addition to
278    /// the endpoint guard, it distinguishes create, live replacement, and
279    /// explicit resurrection without a caller-side read/write race.
280    async fn upsert_edge_guarded_observed(
281        &self,
282        _request: EdgeUpsertRequest,
283    ) -> StorageResult<GuardedEdgeUpsertOutcome> {
284        Err(StorageError::Unsupported {
285            capability: StorageCapability::Graph,
286            operation: "upsert_edge_guarded_observed".into(),
287            message: "this backend does not implement observed guarded edge upserts".into(),
288        })
289    }
290    /// Batch form of [`GraphStore::upsert_edge_guarded`]. All-or-nothing:
291    /// if any edge's endpoints are missing at write time, no edge from the
292    /// batch is persisted, `BatchWriteSummary::affected` is `0`, and
293    /// `GuardedBatchOutcome::refused` names the first failing batch entry and
294    /// its missing endpoint(s) — determined by the same in-transaction
295    /// pre-check that aborted the batch, not a post-hoc re-read.
296    /// Retain the original ordered input to enumerate every aborted write via
297    /// [`GuardedBatchOutcome::refusal_page`] beyond the default bounded sample.
298    ///
299    /// Default returns `StorageError::Unsupported`, for the same reason as
300    /// [`GraphStore::upsert_edge_guarded`]'s default.
301    async fn upsert_edges_guarded(&self, _edges: Vec<Edge>) -> StorageResult<GuardedBatchOutcome> {
302        Err(StorageError::Unsupported {
303            capability: StorageCapability::Graph,
304            operation: "upsert_edges_guarded".into(),
305            message: "this backend does not implement guarded edge writes".into(),
306        })
307    }
308    /// All-or-nothing observed batch form. Implementations must perform
309    /// endpoint and tombstone-policy preflight in the same write transaction
310    /// before applying any row.
311    async fn upsert_edges_guarded_observed(
312        &self,
313        _requests: Vec<EdgeUpsertRequest>,
314    ) -> StorageResult<GuardedEdgeBatchUpsertOutcome> {
315        Err(StorageError::Unsupported {
316            capability: StorageCapability::Graph,
317            operation: "upsert_edges_guarded_observed".into(),
318            message: "this backend does not implement observed guarded edge batches".into(),
319        })
320    }
321    /// Fetch an edge by link ID, returning `None` if absent. Filters soft-deleted rows.
322    async fn get_edge(&self, id: LinkId) -> StorageResult<Option<Edge>>;
323    /// Fetch an edge by link ID including soft-deleted rows. Used by the runtime hard-delete path
324    /// to locate and namespace-check an already-soft-deleted edge before purging it.
325    async fn get_edge_including_deleted(&self, id: LinkId) -> StorageResult<Option<Edge>>;
326    /// Fetch an edge by natural key (namespace, source, target, relation) including
327    /// soft-deleted rows. Used by the atomic-apply result renderer for a symmetric-relation
328    /// update whose surviving canonical row may be tombstoned (ADR-039 DO NOTHING) — the
329    /// normal `query_edges`/`list_edges` path filters `deleted_at IS NULL` and would report
330    /// "not found" for exactly that row.
331    ///
332    /// `namespace` is the natural key's own `namespace` column value (part of the
333    /// `UNIQUE(namespace, source_id, target_id, relation)` constraint this method queries by)
334    /// — it is passed explicitly rather than implied by whichever store instance `self` is,
335    /// so a caller who resolved the record's namespace independently of its own ambient token
336    /// (the atomic-apply renderer, which knows the committed edge's namespace from its prepare-
337    /// time `EdgeNaturalKey`, not from the caller's token) cannot accidentally query the wrong
338    /// namespace by relying on implicit store scoping.
339    async fn get_edge_by_natural_key_including_deleted(
340        &self,
341        namespace: &str,
342        source_id: Uuid,
343        target_id: Uuid,
344        relation: EdgeRelation,
345    ) -> StorageResult<Option<Edge>>;
346    /// Delete an edge by link ID using the specified delete mode.
347    async fn delete_edge(&self, id: LinkId, mode: DeleteMode) -> StorageResult<bool>;
348    /// Query edges with filter, sort, and pagination without an implicit
349    /// exact count. Implementations should return `total: None`; callers that
350    /// need a count use [`Self::count_edges`] explicitly.
351    async fn query_edges(
352        &self,
353        filter: EdgeFilter,
354        sort: Vec<SortOrder<EdgeSortField>>,
355        page: PageRequest,
356    ) -> StorageResult<Page<Edge>>;
357    /// Query edges across the given namespaces in one deterministic query
358    /// with real SQL paging. The multi-namespace analogue of
359    /// [`Self::query_edges`]: a single statement with `namespace IN (...)`
360    /// keeps `offset` continuation coherent, where fetching per-namespace
361    /// prefixes and slicing a client-side merge floats the window between
362    /// calls (silent duplicate/skip enumeration). Backends without batched
363    /// namespace support retain the single-namespace path and reject
364    /// multi-namespace requests explicitly. Implementations should return
365    /// `total: None`; callers that need a count use
366    /// [`Self::count_edges_in_namespaces`] explicitly.
367    async fn query_edges_in_namespaces(
368        &self,
369        namespaces: &[String],
370        filter: EdgeFilter,
371        sort: Vec<SortOrder<EdgeSortField>>,
372        page: PageRequest,
373    ) -> StorageResult<Page<Edge>> {
374        match namespaces.len() {
375            0 => Ok(Page {
376                items: Vec::new(),
377                total: None,
378            }),
379            1 => self.query_edges(filter, sort, page).await,
380            _ => Err(StorageError::Unsupported {
381                capability: StorageCapability::Graph,
382                operation: "query_edges_in_namespaces".into(),
383                message: "this backend does not implement batched namespace edge queries".into(),
384            }),
385        }
386    }
387    /// Count edges matching the given filter.
388    async fn count_edges(&self, filter: EdgeFilter) -> StorageResult<u64>;
389    /// Count edges across the given namespaces in one aggregate query.
390    /// Backends without batched namespace support retain the single-namespace
391    /// path and reject multi-namespace requests explicitly.
392    async fn count_edges_in_namespaces(
393        &self,
394        namespaces: &[String],
395        filter: EdgeFilter,
396    ) -> StorageResult<u64> {
397        match namespaces.len() {
398            0 => Ok(0),
399            1 => self.count_edges(filter).await,
400            _ => Err(StorageError::Unsupported {
401                capability: StorageCapability::Graph,
402                operation: "count_edges_in_namespaces".into(),
403                message: "this backend does not implement batched namespace edge counts".into(),
404            }),
405        }
406    }
407    /// Count edges grouped by relation, ignoring soft-deleted rows. Cheap
408    /// aggregate (`GROUP BY relation`) used to report the true per-relation
409    /// population for full-graph audits (#702.3).
410    async fn count_edges_by_relation(&self) -> StorageResult<Vec<(EdgeRelation, u64)>>;
411    /// Count edges grouped by relation across the given namespaces in one
412    /// aggregate query.
413    async fn count_edges_by_relation_in_namespaces(
414        &self,
415        namespaces: &[String],
416    ) -> StorageResult<Vec<(EdgeRelation, u64)>> {
417        match namespaces.len() {
418            0 => Ok(Vec::new()),
419            1 => self.count_edges_by_relation().await,
420            _ => Err(StorageError::Unsupported {
421                capability: StorageCapability::Graph,
422                operation: "count_edges_by_relation_in_namespaces".into(),
423                message: "this backend does not implement batched namespace relation counts".into(),
424            }),
425        }
426    }
427    /// Count live edges grouped by the base each endpoint resolves against.
428    ///
429    /// A relation breakdown cannot answer this: relations do not determine
430    /// endpoint bases, and the same relation appears on both sides of the
431    /// structure/provenance line. One aggregate query, same shape and cost as
432    /// the relation counts.
433    async fn count_edges_by_endpoint_base(&self) -> StorageResult<EdgeEndpointBaseCounts> {
434        Err(StorageError::Unsupported {
435            capability: StorageCapability::Graph,
436            operation: "count_edges_by_endpoint_base".into(),
437            message: "this backend does not implement endpoint-base edge counts".into(),
438        })
439    }
440    /// Count live edges by endpoint base across the given namespaces in one
441    /// aggregate query.
442    async fn count_edges_by_endpoint_base_in_namespaces(
443        &self,
444        namespaces: &[String],
445    ) -> StorageResult<EdgeEndpointBaseCounts> {
446        match namespaces.len() {
447            0 => Ok(EdgeEndpointBaseCounts::default()),
448            1 => self.count_edges_by_endpoint_base().await,
449            _ => Err(StorageError::Unsupported {
450                capability: StorageCapability::Graph,
451                operation: "count_edges_by_endpoint_base_in_namespaces".into(),
452                message: "this backend does not implement batched namespace endpoint-base counts"
453                    .into(),
454            }),
455        }
456    }
457    /// Count live edges across the given namespaces grouped by relation and,
458    /// within each relation, by the base each endpoint resolves against.
459    ///
460    /// The live edge total, the relation counts and the endpoint-base counts
461    /// describe one population, so one grouped scan answers all three:
462    /// summing each relation's buckets gives its relation count, and summing
463    /// the buckets across relations gives the endpoint-base counts. Asking for
464    /// them as three aggregates walks the edge table and its endpoint probes
465    /// three times. Backends without this aggregate report `Unsupported`, and
466    /// callers fall back to the three single-purpose counts.
467    async fn count_edges_by_relation_and_endpoint_base_in_namespaces(
468        &self,
469        namespaces: &[String],
470    ) -> StorageResult<Vec<(EdgeRelation, EdgeEndpointBaseCounts)>> {
471        let _ = namespaces;
472        Err(StorageError::Unsupported {
473            capability: StorageCapability::Graph,
474            operation: "count_edges_by_relation_and_endpoint_base_in_namespaces".into(),
475            message: "this backend does not implement the combined relation and endpoint-base \
476                      edge count"
477                .into(),
478        })
479    }
480    /// Seek-pagination page of edges ordered by `id` ascending, using an
481    /// indexed range scan (`id > after`) against the `(namespace, id)`
482    /// primary key instead of `OFFSET`. `after` is exclusive; `None` starts
483    /// from the beginning of the set. This remains an efficient compatibility
484    /// path for a fixed edge set, but random UUIDs inserted concurrently may
485    /// sort behind an issued boundary. Public concurrent walks use
486    /// [`Self::query_edges_sequence_after`] instead (#1424).
487    async fn query_edges_after(
488        &self,
489        filter: EdgeFilter,
490        after: Option<Uuid>,
491        limit: u32,
492    ) -> StorageResult<EdgeSeekPage>;
493    /// Resolve an edge id to its immutable insertion sequence.
494    async fn edge_sequence(&self, _id: Uuid) -> StorageResult<Option<i64>> {
495        Err(StorageError::Unsupported {
496            capability: StorageCapability::Graph,
497            operation: "edge_sequence".into(),
498            message: "this backend does not implement edge insertion sequences".into(),
499        })
500    }
501    /// Resolve edge ids to immutable insertion sequences. Implementations may
502    /// override this to batch the lookup; the default preserves correctness.
503    async fn edge_sequences(&self, ids: &[Uuid]) -> StorageResult<Vec<(Uuid, i64)>> {
504        let mut resolved = Vec::with_capacity(ids.len());
505        for id in ids {
506            if let Some(sequence) = self.edge_sequence(*id).await? {
507                resolved.push((*id, sequence));
508            }
509        }
510        Ok(resolved)
511    }
512    /// Seek-pagination page ordered by immutable insertion sequence. This is
513    /// the stable public-list contract for walks overlapping inserts (#1424).
514    async fn query_edges_sequence_after(
515        &self,
516        _filter: EdgeFilter,
517        _after: Option<SeekCursor>,
518        _limit: u32,
519    ) -> StorageResult<SeekPage<Edge>> {
520        Err(StorageError::Unsupported {
521            capability: StorageCapability::Graph,
522            operation: "query_edges_sequence_after".into(),
523            message: "this backend does not implement insertion-sequence edge pagination".into(),
524        })
525    }
526    /// Return immediate neighbors of a graph node.
527    async fn neighbors(
528        &self,
529        node_id: Uuid,
530        query: NeighborQuery,
531    ) -> StorageResult<Vec<NeighborHit>>;
532    /// Return one deterministic neighbor page. `after` is exclusive and
533    /// `neighbor_kinds`, when present, filters entity and note kinds before
534    /// the limit is applied. Backends that do not implement kind-aware paging
535    /// retain an explicit unsupported result rather than silently returning a
536    /// misleading page.
537    async fn neighbors_page(
538        &self,
539        node_id: Uuid,
540        mut query: NeighborQuery,
541        after: Option<NeighborCursor>,
542        neighbor_kinds: Option<Vec<String>>,
543    ) -> StorageResult<Vec<NeighborHit>> {
544        if neighbor_kinds
545            .as_ref()
546            .is_some_and(|kinds| !kinds.is_empty())
547        {
548            return Err(StorageError::Unsupported {
549                capability: StorageCapability::Graph,
550                operation: "neighbors_page".into(),
551                message: "this backend does not implement neighbor kind filtering".into(),
552            });
553        }
554        let limit = query.limit;
555        query.limit = None;
556        let mut hits = self.neighbors(node_id, query).await?;
557        if let Some(cursor) = after {
558            hits.retain(|hit| cursor.is_after(hit));
559        }
560        if let Some(limit) = limit {
561            hits.truncate(limit as usize);
562        }
563        Ok(hits)
564    }
565    /// Return neighbors in BOTH directions in a single call, each tagged with
566    /// the direction (`Out`/`In`) it was found in. `query.direction` is
567    /// ignored — this always fetches both directions.
568    ///
569    /// Exists so a caller that needs both-direction neighbors labeled by
570    /// direction (e.g. the `context` verb) can do so with one storage query
571    /// instead of two separate direction-scoped `neighbors` calls. The
572    /// default implementation preserves the original two-call behavior for
573    /// backends that don't override it; `SqlGraphStore` overrides this with a
574    /// single `UNION ALL` query that projects a direction literal per arm.
575    async fn neighbors_both_directions(
576        &self,
577        node_id: Uuid,
578        query: NeighborQuery,
579    ) -> StorageResult<Vec<DirectedNeighborHit>> {
580        let mut out_query = query.clone();
581        out_query.direction = Direction::Out;
582        let mut in_query = query;
583        in_query.direction = Direction::In;
584        let mut result = Vec::new();
585        for hit in self.neighbors(node_id, out_query).await? {
586            result.push(DirectedNeighborHit {
587                hit,
588                direction: Direction::Out,
589            });
590        }
591        for hit in self.neighbors(node_id, in_query).await? {
592            result.push(DirectedNeighborHit {
593                hit,
594                direction: Direction::In,
595            });
596        }
597        Ok(result)
598    }
599    /// Fetch multiple edges by their link IDs in a single round-trip.
600    ///
601    /// IDs that are not found (absent or soft-deleted) are silently skipped;
602    /// the returned `Vec` may be shorter than `ids`. Backends that support
603    /// batched `IN (...)` queries should override this; the default loops
604    /// `get_edge` so non-SQLite backends keep compiling unchanged.
605    ///
606    /// Callers must chunk large ID lists before calling if they need a strict
607    /// size bound; this method does not enforce a maximum.
608    async fn get_edges(&self, ids: &[LinkId]) -> StorageResult<Vec<Edge>> {
609        let mut out = Vec::with_capacity(ids.len());
610        for &id in ids {
611            if let Some(edge) = self.get_edge(id).await? {
612                out.push(edge);
613            }
614        }
615        Ok(out)
616    }
617    /// Read live edges in input order, retaining each row's decode outcome.
618    ///
619    /// The vector has exactly one entry per input, including duplicates and
620    /// missing/soft-deleted IDs (`Ok(None)`). An inner error belongs to that
621    /// input; an outer error is a statement/admission failure for the batch.
622    /// Callers must bound batches and select errors in their original order.
623    /// The default preserves backend support with point reads; SQLite batches.
624    async fn get_edge_read_outcomes(
625        &self,
626        ids: &[LinkId],
627    ) -> StorageResult<Vec<StorageResult<Option<Edge>>>> {
628        let mut outcomes = Vec::with_capacity(ids.len());
629        for &id in ids {
630            outcomes.push(self.get_edge(id).await);
631        }
632        Ok(outcomes)
633    }
634
635    /// Return neighbors for multiple source nodes in a single round-trip,
636    /// yielding `(source_id, hit)` pairs.
637    ///
638    /// The `query` parameters (direction, relations, min_weight) are applied
639    /// uniformly to every source node. `query.limit` is applied **per source**:
640    /// each source returns at most `limit` hits. Backends that support batched
641    /// `source_id IN (...)` queries should override this; the default loops
642    /// `neighbors` so non-SQLite backends keep compiling unchanged.
643    async fn batch_neighbors(
644        &self,
645        sources: &[Uuid],
646        query: NeighborQuery,
647    ) -> StorageResult<Vec<(Uuid, NeighborHit)>> {
648        let mut out = Vec::new();
649        for &src in sources {
650            let hits = self.neighbors(src, query.clone()).await?;
651            for hit in hits {
652                out.push((src, hit));
653            }
654        }
655        Ok(out)
656    }
657    /// Bounded multi-hop BFS traversal from the given roots.
658    ///
659    /// Implementations must validate [`TraversalRequest::validate`], count
660    /// adjacency rows before first-visit de-duplication against the request's
661    /// shared execution budget, stop a root as soon as its effective result
662    /// limit is filled, and return an error rather than partial paths when the
663    /// work or time budget expires. Minimum-depth BFS selection is normative;
664    /// same-depth tie ordering is not.
665    async fn traverse(&self, request: TraversalRequest) -> StorageResult<Vec<GraphPath>>;
666    /// Hard-delete every incident edge (source or target) for `node_id`, regardless of soft-delete
667    /// state. Used during endpoint hard-delete to prevent dangling `graph_edges` rows (ADR-002
668    /// no-dangling-references contract).
669    async fn purge_incident_edges(&self, node_id: Uuid) -> StorageResult<u64>;
670}