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 hidden live incoming edges between live memory notes, grouped
408 /// by target ID and relation, without returning source IDs or namespaces.
409 ///
410 /// IDs and relations use their canonical stored spellings. `None` covers
411 /// every relation; `Some` covers only the supplied relations. Visibility
412 /// is compared with the edge's stored namespace. Implementations must not
413 /// open a read capability outside the reader's visible namespace set.
414 async fn count_hidden_incoming_memory_edges(
415 &self,
416 target_ids: &[String],
417 relations: Option<&[String]>,
418 visible_namespaces: &[String],
419 ) -> StorageResult<Vec<(String, String, u64)>> {
420 let _ = (target_ids, relations, visible_namespaces);
421 Err(StorageError::Unsupported {
422 capability: StorageCapability::Graph,
423 operation: "count_hidden_incoming_memory_edges".into(),
424 message: "this backend does not implement hidden incoming memory edge counts".into(),
425 })
426 }
427
428 /// Count edges grouped by relation, ignoring soft-deleted rows. Cheap
429 /// aggregate (`GROUP BY relation`) used to report the true per-relation
430 /// population for full-graph audits (#702.3).
431 async fn count_edges_by_relation(&self) -> StorageResult<Vec<(EdgeRelation, u64)>>;
432 /// Count edges grouped by relation across the given namespaces in one
433 /// aggregate query.
434 async fn count_edges_by_relation_in_namespaces(
435 &self,
436 namespaces: &[String],
437 ) -> StorageResult<Vec<(EdgeRelation, u64)>> {
438 match namespaces.len() {
439 0 => Ok(Vec::new()),
440 1 => self.count_edges_by_relation().await,
441 _ => Err(StorageError::Unsupported {
442 capability: StorageCapability::Graph,
443 operation: "count_edges_by_relation_in_namespaces".into(),
444 message: "this backend does not implement batched namespace relation counts".into(),
445 }),
446 }
447 }
448 /// Count live edges grouped by the base each endpoint resolves against.
449 ///
450 /// A relation breakdown cannot answer this: relations do not determine
451 /// endpoint bases, and the same relation appears on both sides of the
452 /// structure/provenance line. One aggregate query, same shape and cost as
453 /// the relation counts.
454 async fn count_edges_by_endpoint_base(&self) -> StorageResult<EdgeEndpointBaseCounts> {
455 Err(StorageError::Unsupported {
456 capability: StorageCapability::Graph,
457 operation: "count_edges_by_endpoint_base".into(),
458 message: "this backend does not implement endpoint-base edge counts".into(),
459 })
460 }
461 /// Count live edges by endpoint base across the given namespaces in one
462 /// aggregate query.
463 async fn count_edges_by_endpoint_base_in_namespaces(
464 &self,
465 namespaces: &[String],
466 ) -> StorageResult<EdgeEndpointBaseCounts> {
467 match namespaces.len() {
468 0 => Ok(EdgeEndpointBaseCounts::default()),
469 1 => self.count_edges_by_endpoint_base().await,
470 _ => Err(StorageError::Unsupported {
471 capability: StorageCapability::Graph,
472 operation: "count_edges_by_endpoint_base_in_namespaces".into(),
473 message: "this backend does not implement batched namespace endpoint-base counts"
474 .into(),
475 }),
476 }
477 }
478 /// Count live edges across the given namespaces grouped by relation and,
479 /// within each relation, by the base each endpoint resolves against.
480 ///
481 /// The live edge total, the relation counts and the endpoint-base counts
482 /// describe one population, so one grouped scan answers all three:
483 /// summing each relation's buckets gives its relation count, and summing
484 /// the buckets across relations gives the endpoint-base counts. Asking for
485 /// them as three aggregates walks the edge table and its endpoint probes
486 /// three times. Backends without this aggregate report `Unsupported`, and
487 /// callers fall back to the three single-purpose counts.
488 async fn count_edges_by_relation_and_endpoint_base_in_namespaces(
489 &self,
490 namespaces: &[String],
491 ) -> StorageResult<Vec<(EdgeRelation, EdgeEndpointBaseCounts)>> {
492 let _ = namespaces;
493 Err(StorageError::Unsupported {
494 capability: StorageCapability::Graph,
495 operation: "count_edges_by_relation_and_endpoint_base_in_namespaces".into(),
496 message: "this backend does not implement the combined relation and endpoint-base \
497 edge count"
498 .into(),
499 })
500 }
501 /// Seek-pagination page of edges ordered by `id` ascending, using an
502 /// indexed range scan (`id > after`) against the `(namespace, id)`
503 /// primary key instead of `OFFSET`. `after` is exclusive; `None` starts
504 /// from the beginning of the set. This remains an efficient compatibility
505 /// path for a fixed edge set, but random UUIDs inserted concurrently may
506 /// sort behind an issued boundary. Public concurrent walks use
507 /// [`Self::query_edges_sequence_after`] instead (#1424).
508 async fn query_edges_after(
509 &self,
510 filter: EdgeFilter,
511 after: Option<Uuid>,
512 limit: u32,
513 ) -> StorageResult<EdgeSeekPage>;
514 /// Resolve an edge id to its immutable insertion sequence.
515 async fn edge_sequence(&self, _id: Uuid) -> StorageResult<Option<i64>> {
516 Err(StorageError::Unsupported {
517 capability: StorageCapability::Graph,
518 operation: "edge_sequence".into(),
519 message: "this backend does not implement edge insertion sequences".into(),
520 })
521 }
522 /// Resolve edge ids to immutable insertion sequences. Implementations may
523 /// override this to batch the lookup; the default preserves correctness.
524 async fn edge_sequences(&self, ids: &[Uuid]) -> StorageResult<Vec<(Uuid, i64)>> {
525 let mut resolved = Vec::with_capacity(ids.len());
526 for id in ids {
527 if let Some(sequence) = self.edge_sequence(*id).await? {
528 resolved.push((*id, sequence));
529 }
530 }
531 Ok(resolved)
532 }
533 /// Seek-pagination page ordered by immutable insertion sequence. This is
534 /// the stable public-list contract for walks overlapping inserts (#1424).
535 async fn query_edges_sequence_after(
536 &self,
537 _filter: EdgeFilter,
538 _after: Option<SeekCursor>,
539 _limit: u32,
540 ) -> StorageResult<SeekPage<Edge>> {
541 Err(StorageError::Unsupported {
542 capability: StorageCapability::Graph,
543 operation: "query_edges_sequence_after".into(),
544 message: "this backend does not implement insertion-sequence edge pagination".into(),
545 })
546 }
547 /// Return immediate neighbors of a graph node.
548 async fn neighbors(
549 &self,
550 node_id: Uuid,
551 query: NeighborQuery,
552 ) -> StorageResult<Vec<NeighborHit>>;
553 /// Return one deterministic neighbor page. `after` is exclusive and
554 /// `neighbor_kinds`, when present, filters entity and note kinds before
555 /// the limit is applied. Backends that do not implement kind-aware paging
556 /// retain an explicit unsupported result rather than silently returning a
557 /// misleading page.
558 async fn neighbors_page(
559 &self,
560 node_id: Uuid,
561 mut query: NeighborQuery,
562 after: Option<NeighborCursor>,
563 neighbor_kinds: Option<Vec<String>>,
564 ) -> StorageResult<Vec<NeighborHit>> {
565 if neighbor_kinds
566 .as_ref()
567 .is_some_and(|kinds| !kinds.is_empty())
568 {
569 return Err(StorageError::Unsupported {
570 capability: StorageCapability::Graph,
571 operation: "neighbors_page".into(),
572 message: "this backend does not implement neighbor kind filtering".into(),
573 });
574 }
575 let limit = query.limit;
576 query.limit = None;
577 let mut hits = self.neighbors(node_id, query).await?;
578 if let Some(cursor) = after {
579 hits.retain(|hit| cursor.is_after(hit));
580 }
581 if let Some(limit) = limit {
582 hits.truncate(limit as usize);
583 }
584 Ok(hits)
585 }
586 /// Return neighbors in BOTH directions in a single call, each tagged with
587 /// the direction (`Out`/`In`) it was found in. `query.direction` is
588 /// ignored — this always fetches both directions.
589 ///
590 /// Exists so a caller that needs both-direction neighbors labeled by
591 /// direction (e.g. the `context` verb) can do so with one storage query
592 /// instead of two separate direction-scoped `neighbors` calls. The
593 /// default implementation preserves the original two-call behavior for
594 /// backends that don't override it; `SqlGraphStore` overrides this with a
595 /// single `UNION ALL` query that projects a direction literal per arm.
596 async fn neighbors_both_directions(
597 &self,
598 node_id: Uuid,
599 query: NeighborQuery,
600 ) -> StorageResult<Vec<DirectedNeighborHit>> {
601 let mut out_query = query.clone();
602 out_query.direction = Direction::Out;
603 let mut in_query = query;
604 in_query.direction = Direction::In;
605 let mut result = Vec::new();
606 for hit in self.neighbors(node_id, out_query).await? {
607 result.push(DirectedNeighborHit {
608 hit,
609 direction: Direction::Out,
610 });
611 }
612 for hit in self.neighbors(node_id, in_query).await? {
613 result.push(DirectedNeighborHit {
614 hit,
615 direction: Direction::In,
616 });
617 }
618 Ok(result)
619 }
620 /// Fetch multiple edges by their link IDs in a single round-trip.
621 ///
622 /// IDs that are not found (absent or soft-deleted) are silently skipped;
623 /// the returned `Vec` may be shorter than `ids`. Backends that support
624 /// batched `IN (...)` queries should override this; the default loops
625 /// `get_edge` so non-SQLite backends keep compiling unchanged.
626 ///
627 /// Callers must chunk large ID lists before calling if they need a strict
628 /// size bound; this method does not enforce a maximum.
629 async fn get_edges(&self, ids: &[LinkId]) -> StorageResult<Vec<Edge>> {
630 let mut out = Vec::with_capacity(ids.len());
631 for &id in ids {
632 if let Some(edge) = self.get_edge(id).await? {
633 out.push(edge);
634 }
635 }
636 Ok(out)
637 }
638 /// Read live edges in input order, retaining each row's decode outcome.
639 ///
640 /// The vector has exactly one entry per input, including duplicates and
641 /// missing/soft-deleted IDs (`Ok(None)`). An inner error belongs to that
642 /// input; an outer error is a statement/admission failure for the batch.
643 /// Callers must bound batches and select errors in their original order.
644 /// The default preserves backend support with point reads; SQLite batches.
645 async fn get_edge_read_outcomes(
646 &self,
647 ids: &[LinkId],
648 ) -> StorageResult<Vec<StorageResult<Option<Edge>>>> {
649 let mut outcomes = Vec::with_capacity(ids.len());
650 for &id in ids {
651 outcomes.push(self.get_edge(id).await);
652 }
653 Ok(outcomes)
654 }
655
656 /// Return neighbors for multiple source nodes in a single round-trip,
657 /// yielding `(source_id, hit)` pairs.
658 ///
659 /// The `query` parameters (direction, relations, min_weight) are applied
660 /// uniformly to every source node. `query.limit` is applied **per source**:
661 /// each source returns at most `limit` hits. Backends that support batched
662 /// `source_id IN (...)` queries should override this; the default loops
663 /// `neighbors` so non-SQLite backends keep compiling unchanged.
664 async fn batch_neighbors(
665 &self,
666 sources: &[Uuid],
667 query: NeighborQuery,
668 ) -> StorageResult<Vec<(Uuid, NeighborHit)>> {
669 let mut out = Vec::new();
670 for &src in sources {
671 let hits = self.neighbors(src, query.clone()).await?;
672 for hit in hits {
673 out.push((src, hit));
674 }
675 }
676 Ok(out)
677 }
678 /// Bounded multi-hop BFS traversal from the given roots.
679 ///
680 /// Implementations must validate [`TraversalRequest::validate`], count
681 /// adjacency rows before first-visit de-duplication against the request's
682 /// shared execution budget, stop a root as soon as its effective result
683 /// limit is filled, and return an error rather than partial paths when the
684 /// work or time budget expires. Minimum-depth BFS selection is normative;
685 /// same-depth tie ordering is not.
686 async fn traverse(&self, request: TraversalRequest) -> StorageResult<Vec<GraphPath>>;
687 /// Hard-delete every incident edge (source or target) for `node_id`, regardless of soft-delete
688 /// state. Used during endpoint hard-delete to prevent dangling `graph_edges` rows (ADR-002
689 /// no-dangling-references contract).
690 async fn purge_incident_edges(&self, node_id: Uuid) -> StorageResult<u64>;
691}