macrame/graph/subgraph.rs
1//! The in-memory graph loaded from `links_current`, and its loader (§5.4).
2//!
3//! A `Subgraph` is derivative state (Doctrine VI): every field is re-derivable
4//! from the ledger, nothing here is authoritative, and dropping one loses
5//! nothing. That is what lets analytics run on a snapshot without a third clock
6//! — the graph is the topology as of one instant, and the instant is the
7//! caller's `now_ts`, not a property of the structure.
8
9use std::collections::BTreeMap;
10
11use crate::connection::{Annotation, Database};
12use crate::error::{BulkResult, DbError, Result};
13
14/// Edges returned to a caller asking for a node with no edges in that direction.
15const NO_EDGES: &[EdgeRef] = &[];
16
17/// A transient, in-memory graph loaded from `links_current`.
18///
19/// The maps are `BTreeMap`, not `HashMap`, so iteration follows node id order.
20/// Every algorithm in [`crate::graph`] inherits its determinism from that
21/// choice, and Louvain in particular returns a different partition under a
22/// randomised iteration order.
23///
24/// # Closure
25///
26/// **Every id appearing in `out_adj` or `in_adj` — as a key or as an
27/// [`EdgeRef::node`] — is a key of `nodes`.** `drop_dangling_adjacency` — private,
28/// and named here because it is the sole establisher — establishes it and
29/// [`Subgraph::is_closed`] checks it; every algorithm in
30/// [`crate::graph`] is written assuming it and none of them re-checks.
31///
32/// It did not hold before Wave 1 (defect Z), and the way it failed is the reason
33/// it is now stated on the type rather than left to the loader. Adjacency comes
34/// from `links_current`, which carries edges to retired concepts; `hydrate`
35/// filters `retired = 0`. So a retired neighbour left an `EdgeRef` pointing at
36/// an id with no `NodeData`, and the five algorithms each met that differently:
37/// `louvain` panicked on the missing map entry, `scc` emitted the absent node as
38/// a phantom component of its own, `k_core` counted a degree of 2 where one edge
39/// was in the graph, and `dijkstra` returned a finite distance to a node the
40/// caller could not then look up. Four handlings of one violated invariant, none
41/// of them chosen — and the panic was the least damaging, because the other
42/// three answer.
43///
44/// Dangling entries are **dropped** rather than admitted with a tombstone node.
45/// A retired concept is not visible (§4.1), analytics over a graph is analytics
46/// over what is visible, and the alternative pushes a three-state node onto
47/// every present and future algorithm to preserve edges whose endpoint the
48/// caller is not entitled to read. Retirement is the supported path — concepts
49/// are never deleted (D-022) — so this is ordinary use, not a corner.
50///
51/// # Why the fields are private (0.8.0, B1, D-114)
52///
53/// They were `pub` through 0.7.0, and the three maps were the crate's most
54/// widely read data structure. That made **every detail of the representation
55/// part of the public API** — the `BTreeMap`, the `String` keys, the fact that
56/// adjacency is stored as two maps at all — none of which was ever a promise
57/// anyone intended to make.
58///
59/// The immediate reason is D-087: interning the keys to `u32` cannot be done
60/// at all while `EdgeRef::node` is a public `String`. The break is taken **once**, here, with the representation
61/// unchanged, so that anything depending on the old shape fails against code
62/// that still behaves identically.
63///
64/// Accessors return borrowed views, so nothing here costs an allocation that
65/// field access did not.
66///
67/// # The interior is measured, and it is changing (0.13.27, W10.3, [D-200])
68///
69/// The three maps above are still keyed by `String`, and every traversal of an
70/// edge is therefore a `BTreeMap<String, _>` descent with a full comparison at
71/// each level. §2.5 of the 0.12.0 review estimated 5–20× from a dense
72/// index-based interior and stated that it had read the code rather than
73/// benchmarked it. `examples/subgraph_interior.rs` benchmarks it: with the
74/// conversion excluded, a CSR transcription of `louvain` runs **9.6×–15.3×**
75/// faster and one of `dijkstra` **12×–25×**, from 48 nodes to the 49,152-node
76/// budget ceiling, under both short and ULID-shaped ids. On realistic
77/// two-to-four-hop neighbourhoods the algorithms are **a third to two thirds**
78/// of what a caller waits for, so this is not a small term.
79///
80/// What the measurement changed is *where* the dense view is built. §2.5
81/// proposed building it at the boundary; done there the conversion costs one
82/// string lookup per **edge endpoint** — the very cost being removed — and the
83/// whole operation is a **loss** for `dijkstra`, which has a single pass to earn
84/// the build back. In-crate it costs one lookup per **node**, because [D-115]
85/// already interned everything an [`EdgeRef`] carries, and that asymmetry is why
86/// the change belongs here rather than in a caller.
87///
88/// **0.13.28 is that rewrite** ([D-201]), and the maps above are unchanged by
89/// it. `Subgraph::build_dense` — crate-private — produces a borrowed CSR view and
90/// the algorithms in [`crate::graph`] run on that; at the budget ceiling `louvain` goes
91/// 675 ms → 75 ms, `scc` 310 → 34, `dijkstra` 125 → 28, and `k_core` breaks
92/// even. The view is built per call and deliberately not cached — see
93/// `build_dense` and D-201 for why the byte budget decides that.
94///
95/// [D-115]: ../../docs/architecture/s13-decision-register.md#d-115
96/// [D-200]: ../../docs/architecture/s13-decision-register.md#d-200
97#[derive(Debug, Clone, Default)]
98pub struct Subgraph {
99 nodes: BTreeMap<String, NodeData>,
100 out_adj: BTreeMap<String, Vec<EdgeRef>>,
101 in_adj: BTreeMap<String, Vec<EdgeRef>>,
102 /// Every string an `EdgeRef` carries. See [`Interner`].
103 pool: Interner,
104}
105
106/// The attributes of one node, as of the instant the graph was loaded.
107///
108/// Fields are private for the reason given on [`Subgraph`]; `content` is the
109/// one whose type is expected to move.
110#[derive(Debug, Clone, PartialEq)]
111pub struct NodeData {
112 title: String,
113 /// **`None` means "not loaded", not "empty" (0.8.0, B3, D-116).**
114 ///
115 /// Document text is not loaded unless a caller asks. No algorithm reads it
116 /// — `dijkstra`, `astar`, `scc`, `k_core`, `louvain` and `modularity` touch
117 /// topology and weight only — and at realistic document sizes it is most of
118 /// the byte budget, so the default load spent the budget on bytes nothing
119 /// would look at.
120 ///
121 /// An `Option` rather than an empty `String` because a sentinel that is a
122 /// *valid value of the type* cannot be told apart from the real thing: a
123 /// concept with genuinely empty content and one whose content was not
124 /// requested are different facts, and they differ exactly when a caller is
125 /// deciding whether to go back to the database. Same refusal
126 /// [D-096](../../docs/architecture/s13-decision-register.md) made for the
127 /// open interval.
128 content: Option<String>,
129 embedding_model: Option<String>,
130 valid_from: String,
131 valid_to: String,
132}
133
134impl NodeData {
135 /// A node with no content and no embedding model — what the default load
136 /// produces. Use [`Self::with_content`] and [`Self::with_embedding_model`]
137 /// to add either.
138 pub fn new(
139 title: impl Into<String>,
140 valid_from: impl Into<String>,
141 valid_to: impl Into<String>,
142 ) -> Self {
143 Self {
144 title: title.into(),
145 content: None,
146 embedding_model: None,
147 valid_from: valid_from.into(),
148 valid_to: valid_to.into(),
149 }
150 }
151
152 #[must_use]
153 pub fn with_content(mut self, content: impl Into<String>) -> Self {
154 self.content = Some(content.into());
155 self
156 }
157
158 #[must_use]
159 pub fn with_embedding_model(mut self, model: Option<String>) -> Self {
160 self.embedding_model = model;
161 self
162 }
163
164 pub fn title(&self) -> &str {
165 &self.title
166 }
167
168 /// The document text, or `None` when it was not requested.
169 ///
170 /// **`None` is not an empty document.** See the field's own note: the
171 /// default load does not fetch content, so a caller that did not ask gets
172 /// `None` and can tell that apart from a concept whose content really is
173 /// `""`.
174 pub fn content(&self) -> Option<&str> {
175 self.content.as_deref()
176 }
177
178 pub fn embedding_model(&self) -> Option<&str> {
179 self.embedding_model.as_deref()
180 }
181
182 pub fn valid_from(&self) -> &str {
183 &self.valid_from
184 }
185
186 pub fn valid_to(&self) -> &str {
187 &self.valid_to
188 }
189}
190
191/// The string pool an interned [`EdgeRef`] indexes into (0.8.0, B2, D-115).
192///
193/// One pool for every string an edge carries — node ids, edge types and the two
194/// timestamps — because they dedupe against each other for free and the whole
195/// point is that the cost is per **distinct string** rather than per edge.
196///
197/// Indices are handed out first-seen. **Nothing observable depends on them**:
198/// node order comes from `nodes`, which is still a `BTreeMap` keyed by id, and
199/// adjacency order is the order edges were added, exactly as before. That is
200/// the deliberate answer to D-063's warning that "determinism stops being
201/// structural and becomes procedural" — it does not, because the node map was
202/// never what needed interning. `node_order_does_not_depend_on_construction_order`
203/// is the gate that holds it.
204#[derive(Debug, Clone, Default)]
205struct Interner {
206 strings: Vec<String>,
207 index: BTreeMap<String, u32>,
208 /// Running payload total, maintained on insert.
209 ///
210 /// **Not recomputed.** The first version of the loader called
211 /// `estimated_bytes()` before and after every edge to charge the marginal
212 /// pool cost, which is O(pool) per row and made loading quadratic — the
213 /// exact defect [D-047](../../docs/architecture/s13-decision-register.md)
214 /// diagnosed and fixed, re-introduced by the change that was supposed to
215 /// make loading *cheaper*. `loading_scales_linearly_in_the_number_of_edges`
216 /// caught it, which is what that test is for.
217 bytes: usize,
218}
219
220impl Interner {
221 /// Intern `s`, returning its index and **how many bytes that cost** — zero
222 /// when the string was already pooled.
223 ///
224 /// The caller needs the marginal figure to charge the byte budget as it
225 /// loads, and it has to be O(1) or the budget check is quadratic again.
226 fn intern(&mut self, s: &str) -> (u32, usize) {
227 if let Some(&i) = self.index.get(s) {
228 return (i, 0);
229 }
230 let i = u32::try_from(self.strings.len())
231 .expect("a subgraph cannot hold 2^32 distinct strings within any byte budget");
232 self.strings.push(s.to_string());
233 self.index.insert(s.to_string(), i);
234 let cost = Self::entry_bytes(s);
235 self.bytes += cost;
236 (i, cost)
237 }
238
239 /// Once in `strings`, once as the key of `index`, plus both containers'
240 /// per-entry overhead.
241 fn entry_bytes(s: &str) -> usize {
242 2 * s.len() + std::mem::size_of::<String>() + std::mem::size_of::<u32>()
243 }
244
245 fn get(&self, i: u32) -> &str {
246 &self.strings[i as usize]
247 }
248
249 /// Payload bytes held by the pool, counted the way [`Subgraph::node_bytes`]
250 /// counts: string bytes plus per-item overhead.
251 ///
252 /// **This is the arithmetic D-063 asked for.** Its objection to interning
253 /// was that an id table "stores every id a second time, partly cancelling
254 /// the memory win". It is counted here rather than argued about: the
255 /// duplication is per distinct string, the saving is per edge entry, and
256 /// `estimated_bytes()` reports the sum so a caller can see both.
257 fn estimated_bytes(&self) -> usize {
258 self.bytes
259 }
260}
261
262/// One end of an edge in an adjacency list — **interned** (0.8.0, B2, D-115).
263///
264/// Five fields, no heap payload, `size_of` 24 bytes against 104 bytes of struct
265/// plus around 250 of strings before. Every field but the weight is an index
266/// into its [`Subgraph`]'s pool, so reading one needs the graph:
267///
268/// ```ignore
269/// for e in graph.out_edges("a") {
270/// println!("{} {} {}", e.node(&graph), e.edge_type(&graph), e.weight());
271/// }
272/// ```
273///
274/// That is the visible cost of the change, and it is the reason B1 had to
275/// privatise these fields first: a public `node: String` cannot become a `u32`.
276/// The win is **reachability**, not speed ([D-073](../../docs/architecture/s13-decision-register.md)'s
277/// category): graphs that did not fit the byte budget start fitting.
278///
279/// # Invariants
280///
281/// An `EdgeRef` is tied to the specific [`Subgraph`] it was retrieved from.
282/// Querying it against a different one — via an accessor like [`Self::node`],
283/// or via derived `PartialEq` — is a **logic error** that will silently return
284/// incorrect data or report equality where none exists. Because the handle is
285/// `Copy` it can be stored in a struct that outlives the graph; it stays
286/// well-formed and becomes meaningless without its pool.
287///
288/// `PartialEq` is the sharp edge, and it is kept rather than removed: *within*
289/// one graph, index equality is exactly the comparison a caller wants, and it
290/// is cheaper and stricter than comparing five strings. Across two graphs it
291/// compares indices that mean different things — a wrong answer that needs no
292/// accessor call at all, so it sits outside the mental model of "querying".
293/// Before interning, `==` compared the strings and could not be wrong this way.
294///
295/// This logic error does not result in undefined behaviour — every index goes
296/// through bounds-checked slice indexing and there is no `unsafe` here — but
297/// the results are otherwise unspecified.
298///
299/// The handle is intentionally **not** lifetime-branded, which would make the
300/// invariant a compile error, because that propagates a generic parameter
301/// through every algorithm and every signature that mentions a `Subgraph`. See
302/// D-115 for the argument and for what to do if this is ever hit in practice.
303#[derive(Clone, Copy, PartialEq)]
304pub struct EdgeRef {
305 node: u32,
306 edge_type: u32,
307 weight: f64,
308 valid_from: u32,
309 valid_to: u32,
310}
311
312/// Written by hand so a failing `assert_eq!` cannot be mistaken for one about
313/// strings.
314///
315/// The derived form printed `EdgeRef { node: 3, edge_type: 1, .. }`, which
316/// reads as data and is not: those are pool indices, meaningless without the
317/// graph. The `#` is there to say so at a glance.
318impl std::fmt::Debug for EdgeRef {
319 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
320 write!(
321 f,
322 "EdgeRef(node=#{}, type=#{}, w={}, from=#{}, to=#{})",
323 self.node, self.edge_type, self.weight, self.valid_from, self.valid_to
324 )
325 }
326}
327
328impl EdgeRef {
329 /// The far end of the edge: the target in `out_edges`, the source in
330 /// `in_edges`.
331 ///
332 /// Takes the graph because the string lives in its pool. `graph` must be
333 /// the one this edge came from; passing another is a programming error and
334 /// will panic or answer nonsense, exactly as indexing the wrong slice would.
335 pub fn node<'a>(&self, graph: &'a Subgraph) -> &'a str {
336 graph.pool.get(self.node)
337 }
338
339 pub fn edge_type<'a>(&self, graph: &'a Subgraph) -> &'a str {
340 graph.pool.get(self.edge_type)
341 }
342
343 /// The only field that is not interned, because an `f64` is already 8 bytes
344 /// and a pool of them would cost more than it saved.
345 pub fn weight(&self) -> f64 {
346 self.weight
347 }
348
349 pub fn valid_from<'a>(&self, graph: &'a Subgraph) -> &'a str {
350 graph.pool.get(self.valid_from)
351 }
352
353 pub fn valid_to<'a>(&self, graph: &'a Subgraph) -> &'a str {
354 graph.pool.get(self.valid_to)
355 }
356}
357
358impl Subgraph {
359 /// Whether `id` is a hydrated node of this graph.
360 ///
361 /// By the closure invariant this is also the answer to "may an algorithm
362 /// look this id up", which is why every algorithm asks it rather than
363 /// probing adjacency.
364 pub fn contains_node(&self, id: &str) -> bool {
365 self.nodes.contains_key(id)
366 }
367
368 /// The attributes of `id`, or `None` when it is not in the graph.
369 pub fn node(&self, id: &str) -> Option<&NodeData> {
370 self.nodes.get(id)
371 }
372
373 /// Node ids in ascending order.
374 ///
375 /// The order is `BTreeMap`'s and is load-bearing rather than incidental:
376 /// Louvain breaks ties by first-seen community and returns a different
377 /// partition under a randomised order.
378 pub fn node_ids(&self) -> impl ExactSizeIterator<Item = &str> + '_ {
379 self.nodes.keys().map(String::as_str)
380 }
381
382 pub fn node_count(&self) -> usize {
383 self.nodes.len()
384 }
385
386 /// Every node with its attributes, in id order.
387 pub fn nodes(&self) -> impl ExactSizeIterator<Item = (&str, &NodeData)> + '_ {
388 self.nodes.iter().map(|(id, d)| (id.as_str(), d))
389 }
390
391 /// The outgoing index: each node that has outgoing edges, with them.
392 ///
393 /// For one node prefer [`Self::out_edges`]. This exists for callers that
394 /// must walk the whole index — the Python `to_dict`, and the diagnostics.
395 pub fn out_adjacency(&self) -> impl Iterator<Item = (&str, &[EdgeRef])> + '_ {
396 self.out_adj
397 .iter()
398 .map(|(id, e)| (id.as_str(), e.as_slice()))
399 }
400
401 /// The incoming index. See [`Self::out_adjacency`].
402 pub fn in_adjacency(&self) -> impl Iterator<Item = (&str, &[EdgeRef])> + '_ {
403 self.in_adj
404 .iter()
405 .map(|(id, e)| (id.as_str(), e.as_slice()))
406 }
407
408 /// Add or replace a node, returning what was there before.
409 ///
410 /// Public so that callers who build a graph by hand — the test fixtures,
411 /// the diagnostics — can still do so now the fields are private. It does
412 /// **not** establish the closure invariant on its own: adjacency naming an
413 /// id never inserted is still dangling, exactly as before.
414 pub fn insert_node(&mut self, id: impl Into<String>, data: NodeData) -> Option<NodeData> {
415 self.nodes.insert(id.into(), data)
416 }
417
418 /// Outgoing edges of `node`, empty when it has none or is absent.
419 pub fn out_edges(&self, node: &str) -> &[EdgeRef] {
420 self.out_adj.get(node).map_or(NO_EDGES, Vec::as_slice)
421 }
422
423 /// Incoming edges of `node`, empty when it has none or is absent.
424 pub fn in_edges(&self, node: &str) -> &[EdgeRef] {
425 self.in_adj.get(node).map_or(NO_EDGES, Vec::as_slice)
426 }
427
428 /// Undirected edge count incident to `node`, counting parallel edges once
429 /// each and a self-loop twice.
430 pub fn degree(&self, node: &str) -> usize {
431 self.out_edges(node).len() + self.in_edges(node).len()
432 }
433
434 /// Undirected weight incident to `node`. Summed over both directions, so
435 /// summing this over all nodes gives `2 * total_weight`.
436 pub fn weighted_degree(&self, node: &str) -> f64 {
437 self.out_edges(node).iter().map(|e| e.weight).sum::<f64>()
438 + self.in_edges(node).iter().map(|e| e.weight).sum::<f64>()
439 }
440
441 /// Total edge weight, each edge counted once — the `m` of the modularity
442 /// formulas.
443 pub fn total_weight(&self) -> f64 {
444 self.out_adj
445 .values()
446 .flat_map(|edges| edges.iter().map(|e| e.weight))
447 .sum()
448 }
449
450 pub fn edge_count(&self) -> usize {
451 self.out_adj.values().map(Vec::len).sum()
452 }
453
454 /// Remove adjacency entries whose endpoint is not a hydrated node.
455 ///
456 /// This is what establishes the closure invariant on the type's docs, and it
457 /// runs after `hydrate` because that is the first moment the set of visible
458 /// nodes is known — the walk is over `links_current`, which does not record
459 /// retirement.
460 ///
461 /// A node left with no edges keeps its (now empty) entry only if it had one;
462 /// entries emptied by the prune are removed outright, so `out_adj` and
463 /// `in_adj` do not accumulate keys for nodes that turned out to have nothing.
464 /// Keys that are themselves not hydrated go too, which covers the case where
465 /// the *source* is the retired concept rather than the target.
466 ///
467 /// The byte accounting is deliberately not rewound. `bytes` bounded the load
468 /// as it ran and refused early on that basis, so a graph that would have fit
469 /// after pruning can still be refused before it. That is conservative in the
470 /// safe direction — the budget exists to stop an allocation, and the
471 /// allocation happens during the walk, not after it.
472 fn drop_dangling_adjacency(&mut self) {
473 // Destructured so `nodes` is borrowed separately from the two maps being
474 // mutated — the same borrow through `self` inside the closure would not
475 // compile.
476 let Subgraph {
477 nodes,
478 out_adj,
479 in_adj,
480 pool,
481 } = self;
482
483 for adj in [out_adj, in_adj] {
484 adj.retain(|id, edges| {
485 if !nodes.contains_key(id) {
486 return false;
487 }
488 edges.retain(|e| nodes.contains_key(pool.get(e.node)));
489 !edges.is_empty()
490 });
491 }
492 }
493
494 /// Whether the closure invariant holds. Used by tests and `debug_assert`s.
495 ///
496 /// Cheap enough to call in a test and O(V + E), so not on any hot path.
497 ///
498 /// **The `debug_assert`s were only a claim until 0.10.0** (W4.8). This
499 /// sentence shipped in 0.6.0 and none existed in `src/`; they now sit at the
500 /// entry of `dijkstra`, `astar`, `scc`, `k_core` and `louvain`
501 /// (`algorithms::CLOSURE`). Writing them was the fix rather than weakening
502 /// the sentence: the type docs above say every algorithm assumes closure and
503 /// none re-checks it, and an assert is the auditable form of that.
504 pub fn is_closed(&self) -> bool {
505 self.out_adj
506 .iter()
507 .chain(self.in_adj.iter())
508 .all(|(id, edges)| {
509 self.nodes.contains_key(id)
510 && edges
511 .iter()
512 .all(|e| self.nodes.contains_key(self.pool.get(e.node)))
513 })
514 }
515
516 /// Record an edge in both directions.
517 ///
518 /// Both indices are maintained together because every undirected quantity
519 /// here — degree, k-core peeling, Louvain's `k_i` — reads them as a pair. An
520 /// `in_adj` that lags `out_adj` would not fail loudly; it would return a
521 /// plausible wrong number.
522 /// **Public since 0.8.0.** The callers that used to push into both maps by
523 /// hand cannot now the fields are private, and routing them through the one
524 /// function that maintains the pair is the point rather than a consolation:
525 /// hand-written adjacency was two chances to get the reverse edge wrong,
526 /// and every such call site was already doing the `back.node = source`
527 /// dance itself. `edge.node` is expected to be `target`; the reverse entry
528 /// is derived here.
529 /// Returns the bytes this edge added to [`Self::estimated_bytes`] — the two
530 /// fixed-size entries plus whatever strings were genuinely new. The loader
531 /// charges its budget with it, and it is O(1) by construction.
532 pub fn add_edge(
533 &mut self,
534 source: &str,
535 target: &str,
536 edge_type: &str,
537 weight: f64,
538 valid_from: &str,
539 valid_to: &str,
540 ) -> usize {
541 let (src, b1) = self.pool.intern(source);
542 let (tgt, b2) = self.pool.intern(target);
543 let (ty, b3) = self.pool.intern(edge_type);
544 let (from, b4) = self.pool.intern(valid_from);
545 let (to, b5) = self.pool.intern(valid_to);
546 let pooled = b1 + b2 + b3 + b4 + b5;
547
548 self.out_adj
549 .entry(source.to_string())
550 .or_default()
551 .push(EdgeRef {
552 node: tgt,
553 edge_type: ty,
554 weight,
555 valid_from: from,
556 valid_to: to,
557 });
558 self.in_adj
559 .entry(target.to_string())
560 .or_default()
561 .push(EdgeRef {
562 node: src,
563 edge_type: ty,
564 weight,
565 valid_from: from,
566 valid_to: to,
567 });
568 2 * std::mem::size_of::<EdgeRef>() + pooled
569 }
570
571 /// Build the integer-indexed view [`super::algorithms`] runs on
572 /// (0.13.28, W10.3b, [D-201]).
573 ///
574 /// **The per-edge term has no strings in it**, and that is the whole reason
575 /// the method is here rather than in a caller. [`Interner`] already holds
576 /// every string an [`EdgeRef`] carries, so an edge's far end is a pool
577 /// index; mapping the pool onto dense indices costs one lookup **per node**,
578 /// after which every edge is a `Vec` index. [D-200] measured the same view
579 /// built through the public API, where the far end is only reachable as a
580 /// `&str` and the mapping costs a lookup per *edge endpoint*: 1.8x-2.1x on
581 /// `louvain` and a **loss** on `dijkstra`, which has one pass to earn the
582 /// build back.
583 ///
584 /// Dense indices are `nodes`' key order, so index order and id order are the
585 /// same relation and every tie broken by id is broken identically by index.
586 ///
587 /// # The two orders this relies on
588 ///
589 /// `nodes`, `out_adj` and `in_adj` are `BTreeMap`s over the same key type,
590 /// and by the closure invariant every adjacency key is a key of `nodes`.
591 /// So the three are **merge-walkable**: the flat arrays are filled in one
592 /// forward pass, with one string comparison per node rather than a
593 /// `BTreeMap` descent per node, and no per-node allocation at all. Only the
594 /// pool mapping needs real lookups, and it needs `V` of them.
595 ///
596 /// [D-200]: ../../docs/architecture/s13-decision-register.md#d-200
597 /// [D-201]: ../../docs/architecture/s13-decision-register.md#d-201
598 pub(crate) fn build_dense(&self) -> super::dense::Dense<'_> {
599 use super::dense::Dense;
600
601 debug_assert!(
602 self.is_closed(),
603 "`build_dense` on a graph that violates the closure invariant: \
604 adjacency references a node that is not in `nodes`"
605 );
606
607 let ids: Vec<&str> = self.nodes.keys().map(String::as_str).collect();
608 let n = ids.len();
609
610 // Pool index -> dense index. One string lookup per node; a pooled string
611 // that is not a node id (an edge type, a timestamp) keeps the sentinel.
612 let mut pool_to_dense = vec![Dense::not_a_node(); self.pool.strings.len()];
613 for (dense, id) in ids.iter().enumerate() {
614 if let Some(&pooled) = self.pool.index.get(*id) {
615 pool_to_dense[pooled as usize] =
616 u32::try_from(dense).expect("a subgraph cannot hold 2^32 nodes");
617 }
618 }
619
620 // `ids` and an adjacency map are both in key order, and every
621 // adjacency key is a key of `nodes`, so this is a merge rather than a
622 // lookup per key: one string comparison per node instead of a
623 // `BTreeMap` descent. The `while` guard makes it a merge rather than a
624 // lockstep walk, so a key that is *not* a node — the closure invariant
625 // broken in a release build — is skipped instead of stalling the walk.
626 let flatten = |adj: &BTreeMap<String, Vec<EdgeRef>>| -> (Vec<(u32, f64)>, Vec<u32>) {
627 let total: usize = adj.values().map(Vec::len).sum();
628 let mut flat = Vec::with_capacity(total);
629 let mut at = Vec::with_capacity(n + 1);
630 let mut keys = adj.iter().peekable();
631
632 for id in &ids {
633 at.push(u32::try_from(flat.len()).expect("a subgraph cannot hold 2^32 edges"));
634 while keys.peek().is_some_and(|(k, _)| k.as_str() < *id) {
635 keys.next();
636 }
637 if keys.peek().is_some_and(|(k, _)| k.as_str() == *id) {
638 let (_, edges) = keys.next().expect("just peeked");
639 flat.extend(
640 edges
641 .iter()
642 .map(|e| (pool_to_dense[e.node as usize], e.weight)),
643 );
644 }
645 }
646 at.push(u32::try_from(flat.len()).expect("a subgraph cannot hold 2^32 edges"));
647 (flat, at)
648 };
649
650 let (out, out_at) = flatten(&self.out_adj);
651 let (inn, inn_at) = flatten(&self.in_adj);
652
653 Dense::from_parts(ids, out, out_at, inn, inn_at)
654 }
655
656 /// Estimated payload bytes for one node, keyed by `id`.
657 ///
658 /// The per-item functions are the single definition of the estimate.
659 /// [`Self::estimated_bytes`] sums them over a whole graph; the loader adds
660 /// them as it inserts, so the running total it checks against the budget and
661 /// the total a caller can compute are the same arithmetic rather than two
662 /// descriptions of it. `load_subgraph_totals_agree_with_the_derivation`
663 /// pins that they stay equal.
664 fn node_bytes(id: &str, d: &NodeData) -> usize {
665 id.len()
666 + d.title.len()
667 + d.content.as_ref().map_or(0, String::len)
668 + d.embedding_model.as_ref().map_or(0, String::len)
669 + d.valid_from.len()
670 + d.valid_to.len()
671 + std::mem::size_of::<NodeData>()
672 }
673
674 /// Estimated payload bytes for one adjacency entry.
675 ///
676 /// An edge occupies two of these — one in `out_adj`, one in `in_adj` — so a
677 /// caller accounting for a newly added edge counts it twice.
678 /// **24 bytes, and nothing else** since B2 (D-115).
679 ///
680 /// Before interning this summed four string lengths as well, around 189
681 /// bytes for a ULID-keyed edge. The strings did not disappear — they moved
682 /// into the pool, where they are counted once per *distinct* value by
683 /// [`Interner::estimated_bytes`] rather than once per edge entry.
684 fn edge_bytes(_e: &EdgeRef) -> usize {
685 std::mem::size_of::<EdgeRef>()
686 }
687
688 /// Estimated heap footprint (D-007).
689 ///
690 /// Deliberately an estimate of the *payload*, not a precise `size_of` walk:
691 /// the budget exists to stop a dense neighbourhood exhausting memory, and a
692 /// figure that tracks string bytes and per-item overhead is accurate enough
693 /// for that.
694 ///
695 /// **O(V + E), and therefore not for use inside a loop over rows.** The
696 /// loader used to call this per row, which made loading O(E²): 500 edges in
697 /// 26 ms, 1,000 in 76 ms, 2,000 in 231 ms — time tripling for each doubling.
698 /// The byte budget is what bounds a load, and the budget *check* was the
699 /// thing that did not scale (D-047).
700 pub fn estimated_bytes(&self) -> usize {
701 let nodes: usize = self
702 .nodes
703 .iter()
704 .map(|(id, d)| Self::node_bytes(id, d))
705 .sum();
706 let edges: usize = self
707 .out_adj
708 .values()
709 .chain(self.in_adj.values())
710 .flat_map(|v| v.iter())
711 .map(Self::edge_bytes)
712 .sum();
713 nodes + edges + self.pool.estimated_bytes()
714 }
715
716 /// Write one derived result per node under `label` (§5.4, D-041).
717 ///
718 /// Goes through [`Database::write_analytics_annotations`], which chunks at
719 /// [`crate::connection::chunk_rows::ANNOTATIONS`] and sends on the
720 /// low-priority channel,
721 /// so a community assignment over a large subgraph cannot starve interactive
722 /// writes.
723 ///
724 /// Rows land in `analytics_annotations`, which carries no log trigger.
725 /// Before 0.5.4 this method built a `ConceptUpsert` per node and put the
726 /// value in `content`, so writing back a partition **overwrote every
727 /// annotated concept's document text** — and, because the write went through
728 /// the ledger, recorded each rerun of the algorithm as a fresh version of a
729 /// world that had not changed. The old doc comment defended that as "a
730 /// normal bitemporal write," which was true of the mechanism and false of
731 /// the intent: it is the right mechanism for a domain fact, and a community
732 /// label is not one.
733 ///
734 /// `values` is keyed by node id; nodes absent from it are not annotated.
735 ///
736 /// Inherits [`BulkInterrupted`](crate::BulkInterrupted) from the chunked
737 /// path it delegates to (0.13.8, W7.6): a write-back that fails partway has
738 /// annotated some of the nodes, and rerunning the algorithm over the whole
739 /// subgraph is only the right response because the caller can see that it
740 /// is.
741 pub async fn write_back_annotations(
742 &self,
743 db: &Database,
744 label: &str,
745 values: &BTreeMap<String, String>,
746 ) -> BulkResult<usize> {
747 let rows: Vec<Annotation> = self
748 .nodes
749 .keys()
750 .filter_map(|id| {
751 values
752 .get(id)
753 .map(|value| Annotation::new(id.clone(), label, value.clone()))
754 })
755 .collect();
756
757 db.write_analytics_annotations(rows).await
758 }
759}
760
761impl Database {
762 /// Load the topology reachable from `start_node` within `max_hops` (§5.4).
763 ///
764 /// Runs on the read connection, so it cannot contend with the write actor.
765 /// `byte_budget` bounds the result: a hub node in a dense graph can reach
766 /// most of the database in three hops, and the budget is what turns that
767 /// into [`DbError::SubgraphTooLarge`] rather than into an allocation
768 /// failure.
769 ///
770 /// Unfiltered: every edge type, **every weight**. See
771 /// [`Self::load_subgraph_with`] for the filtered form, which this delegates
772 /// to.
773 ///
774 /// `min_weight` is `NEG_INFINITY` rather than
775 /// [`TraversalBuilder`](super::TraversalBuilder)'s default
776 /// of `0.0`, and the difference is load-bearing. A floor of `0.0` silently
777 /// drops negative-weight edges — which is precisely the input
778 /// [`DbError::NegativeEdgeWeight`] exists to *report*, since Dijkstra and A*
779 /// are unsound over them and D-039 chose to refuse at the boundary rather
780 /// than return a shortest path that is merely a path. Delegating with the
781 /// builder default turned that typed refusal into a graph quietly missing
782 /// edges; `a_negative_edge_weight_is_refused_at_load` caught it.
783 ///
784 /// So the two mechanisms are made to agree instead of overlapping: an edge a
785 /// caller has **not** filtered out reaches the weight guard, and an edge they
786 /// have is theirs to exclude. See [`Self::load_subgraph_with`] for what that
787 /// means when a caller passes a default builder.
788 pub async fn load_subgraph(
789 &self,
790 start_node: &str,
791 max_hops: u32,
792 now_ts: &str,
793 byte_budget: usize,
794 ) -> Result<Subgraph> {
795 self.load_subgraph_with(
796 &super::TraversalBuilder::new(start_node)
797 .max_depth(max_hops as usize)
798 .min_weight(f64::NEG_INFINITY),
799 now_ts,
800 byte_budget,
801 )
802 .await
803 }
804
805 /// Load the topology a [`TraversalBuilder`](super::TraversalBuilder)
806 /// describes, as a [`Subgraph`]
807 /// (§5.4, D-073).
808 ///
809 /// `load_subgraph` took neither `edge_types` nor `min_weight` while
810 /// `TraversalBuilder` took both — the same walk over the same table with two
811 /// fewer knobs. That was a **reachability** limit rather than a convenience
812 /// one: the byte budget bounds the *unfiltered* neighbourhood, so a caller
813 /// wanting one edge type out of a hub got [`DbError::SubgraphTooLarge`] for a
814 /// graph whose filtered form would have fitted easily, and filtering the
815 /// returned `Subgraph` afterwards cannot help because the refusal happens
816 /// during the walk.
817 ///
818 /// # The filters apply to the walk *and* to the returned edges
819 ///
820 /// This is the decision the change turned on, and the two are separable.
821 /// `TraversalBuilder` applies its filters to the **recursive step** — which
822 /// edges are followed — while this loader's final projection returns every
823 /// edge of every node it reached. Wiring the two together naively gives a
824 /// caller who asked for `CITES` a graph reached via `CITES` and populated
825 /// with `KNOWS` edges as well, which is surprising enough to be read as a
826 /// bug.
827 ///
828 /// So both halves filter. If a caller names edge types or a minimum weight,
829 /// they are asking for a subgraph **of those edges**: the walk uses them to
830 /// bound which nodes are reached, and the projection uses them to decide
831 /// which adjacency lands in the result. `load_subgraph` passes a default
832 /// builder — no types, weight ≥ 0 — so its behaviour is unchanged.
833 ///
834 /// # `min_weight` and the negative-weight guard
835 ///
836 /// [`TraversalBuilder`](super::TraversalBuilder) defaults `min_weight` to
837 /// `0.0`, so a **default
838 /// builder passed here filters negative-weight edges out** rather than
839 /// letting them reach [`DbError::NegativeEdgeWeight`]. That is a real
840 /// difference from [`Self::load_subgraph`], which passes `NEG_INFINITY`.
841 ///
842 /// It is deliberate and it is the coherent reading: a caller who states a
843 /// weight floor has asked to exclude what falls below it, and excluding it
844 /// is not an error. A caller who states none should be told, because
845 /// Dijkstra and A* are unsound over negative weights. Pass
846 /// `.min_weight(f64::NEG_INFINITY)` to get the guard with a filtered builder.
847 ///
848 /// # The traversal's instants are honoured (0.13.2, W7.1, F-35)
849 ///
850 /// They were not. This loader bound `now_ts` where the builder bound the
851 /// traversal's own instant, so a historical `TraversalBuilder` passed here
852 /// **silently returned the present** — the walk and the projection both read
853 /// live topology while the caller had asked for Tuesday's, with nothing said.
854 /// Found while splitting `as_of` and fixed in the same change, because the
855 /// fix is the same one: `TraversalBuilder::bind_params` is now the single
856 /// producer of the parameter list and both call sites take it, so the two
857 /// cannot bind different instants at `?3` again.
858 ///
859 /// `attribute_mode` is still ignored: hydration here is always the live
860 /// concept row, which is what a `Subgraph` has always carried. That is a
861 /// narrower gap than the one above and a deliberate one — a `Subgraph` is
862 /// the input to the six algorithms, none of which reads a title.
863 pub async fn load_subgraph_with(
864 &self,
865 traversal: &super::TraversalBuilder,
866 now_ts: &str,
867 byte_budget: usize,
868 ) -> Result<Subgraph> {
869 let start_node = traversal.start_node.as_str();
870 let conn = self.read_conn();
871 let mut graph = Subgraph::default();
872 // Running payload total, carried through the load and into `hydrate`.
873 // See `estimated_bytes` for why this is not recomputed per row (D-047).
874 let mut bytes = 0usize;
875
876 // Placeholder layout is `TraversalBuilder`'s to decide and
877 // `bind_params` to fill; see `edge_type_base` for why it is computed
878 // there rather than agreed here.
879 let edge_filter = traversal.edge_filter_sql();
880 let link_source = traversal.link_source();
881
882 // A transaction-time traversal folds the log, and the fold can be short.
883 // Checked before the query rather than after, so an unanswerable instant
884 // is a named refusal instead of a subgraph that is quietly missing edges.
885 traversal.check_recorded_reach(conn).await?;
886
887 // Topology first. The recursion itself is `TraversalBuilder::walk_cte`
888 // and is **not** duplicated here (T0.1): this file and `builder.rs` held
889 // byte-identical copies, and they had already drifted once — D-073 found
890 // this loader taking neither `edge_types` nor `min_weight` while the
891 // builder took both.
892 let sql = format!(
893 "{}{}",
894 traversal.walk_cte(),
895 format_args!(
896 r#"
897-- **The `DISTINCT` is why this query is superlinear, and it is not removable.**
898--
899-- Wave 3 measured `load_subgraph` at 12.5x for 10x the nodes and could not say
900-- why; Wave 4 answered it from the plan. `EXPLAIN` reports
901-- `USE TEMP B-TREE FOR DISTINCT`: an O(E log E) sort over the output, and
902-- n log n predicts ~13.3x for 10x, against the 12.5x measured. That is the term.
903--
904-- It is load-bearing: two branches can reach the same node, so a node appears in
905-- `walk` at more than one depth and the join would otherwise emit its edges once
906-- per depth. Without `DISTINCT` a caller gets duplicate edges.
907--
908-- **Corrected in 0.6.0 (T0.1), and the correction is not that the analysis was
909-- wrong.** Everything above holds, and D-070's two rejected fixes were measured
910-- honestly. What was wrong was the fixture: `benches/` seeds a chain of stars,
911-- which is a *tree*, and in a tree there is exactly one path to each node — so
912-- the term that actually dominated was identically 1 and invisible. D-070
913-- concluded the growth was "inherent to producing a deduplicated result", which
914-- is true of trees and false of graphs. The real cost was the walk enumerating
915-- **paths** rather than nodes; see `walk_cte`. On a 328-edge layered graph at
916-- depth 6 that was 299,593 walk rows and 428 ms, against 49 rows and 0.1 ms now.
917-- The `DISTINCT` stays, and it is no longer the leading term.
918--
919-- The filters appear **twice**, and that is the contract (D-073). The walk uses
920-- them to bound which nodes are reached; the projection uses them to decide
921-- which adjacency lands in the result. Filtering only the walk would hand a
922-- caller who asked for `CITES` a graph reached via `CITES` and populated with
923-- every other edge type those nodes happen to have.
924SELECT DISTINCT l.source_id, l.target_id, l.edge_type, l.weight, l.valid_from, l.valid_to
925FROM walk w
926JOIN {link_source} l ON l.source_id = w.node_id
927WHERE l.valid_from <= ?3 AND ?3 < l.valid_to
928 AND l.weight >= ?4
929 {edge_filter}
930ORDER BY l.source_id, l.target_id, l.edge_type
931"#
932 )
933 );
934
935 let params = traversal.bind_params(now_ts);
936
937 let mut rows = conn.query(&sql, params).await?;
938
939 while let Some(row) = rows.next().await? {
940 let source: String = row.get(0)?;
941 let target: String = row.get(1)?;
942 let weight: f64 = row.get(3)?;
943
944 // Dijkstra and A* are only correct for non-negative weights, and the
945 // schema does not constrain the column. Refusing here keeps the
946 // wrongness at the boundary: the alternative is a shortest path that
947 // is merely a path, returned with no indication of it.
948 //
949 // **The `is_nan()` arm is unreachable on a file this schema created
950 // (T0.3, D-078).** SQLite stores a NaN double as NULL, so
951 // `weight REAL NOT NULL` refuses it — measured on libSQL 0.9.30
952 // through `assert_edge`, through a raw `INSERT` binding NaN, and
953 // through a raw `INSERT` computing `0.0/0.0` in the engine; all three
954 // fail with `NOT NULL constraint failed`. §4.7 used to list NaN as a
955 // gap this loader covered, which had it backwards.
956 //
957 // Kept anyway, as defence rather than decoration: a future engine
958 // that stores NaN as a real double would make it live again, and the
959 // cost of a comparison per edge against reading a shortest path
960 // computed over NaN is not a close call. `storage_boundary_tests`
961 // pins the engine's current behaviour, so that change would arrive
962 // as a failing test rather than as a silent answer.
963 if weight < 0.0 || weight.is_nan() {
964 return Err(DbError::NegativeEdgeWeight {
965 source_id: source,
966 target_id: target,
967 weight,
968 });
969 }
970
971 let edge_type: String = row.get(2)?;
972 let valid_from: String = row.get(4)?;
973 let valid_to: String = row.get(5)?;
974
975 // Accounted before the insert, and the arithmetic is far simpler
976 // than it was: an interned entry is a fixed 24 bytes whichever
977 // endpoint it names, so the two entries `add_edge` writes cost the
978 // same and there is no id-length asymmetry to get wrong.
979 //
980 // The strings have not vanished, they have moved into the pool, so
981 // what a *new* distinct string costs is charged here too. Only the
982 // ones actually new: `intern` dedupes, and charging every edge for
983 // its type and timestamps would re-introduce exactly the per-edge
984 // cost B2 removes.
985 bytes += graph.add_edge(&source, &target, &edge_type, weight, &valid_from, &valid_to);
986
987 if bytes > byte_budget {
988 return Err(DbError::SubgraphTooLarge {
989 n: bytes,
990 budget: byte_budget,
991 });
992 }
993 }
994
995 // Every endpoint is a node, plus the start itself so a lone node still
996 // loads as a one-node graph rather than an empty one.
997 let mut ids: Vec<String> = graph
998 .out_adj
999 .keys()
1000 .chain(graph.in_adj.keys())
1001 .cloned()
1002 .collect();
1003 ids.push(start_node.to_string());
1004 ids.sort();
1005 ids.dedup();
1006
1007 hydrate(
1008 conn,
1009 &mut graph,
1010 &ids,
1011 bytes,
1012 byte_budget,
1013 traversal.content,
1014 )
1015 .await?;
1016 graph.drop_dangling_adjacency();
1017 Ok(graph)
1018 }
1019}
1020
1021use crate::util::limits::HYDRATE_CHUNK;
1022
1023/// Fill in `nodes` from `concepts` for the ids the topology touched.
1024/// Attach node attributes, continuing the caller's byte accounting.
1025///
1026/// `bytes_so_far` is the topology's payload total; this adds each node as it
1027/// lands and refuses as soon as the running total passes the budget rather than
1028/// after the whole set is in hand. Checking once at the end would allocate the
1029/// whole oversized result before declining to return it, which is the failure
1030/// the budget exists to prevent rather than to report.
1031///
1032/// **One query per [`HYDRATE_CHUNK`] ids, not one per node (defect AE).** The
1033/// previous version issued a round trip per id: 400 nodes cost 400 of them and
1034/// 13.2 ms, essentially all of it latency rather than work, and linear in node
1035/// count on a path whose whole purpose is to bound the result by *bytes*.
1036async fn hydrate(
1037 conn: &libsql::Connection,
1038 graph: &mut Subgraph,
1039 ids: &[String],
1040 bytes_so_far: usize,
1041 byte_budget: usize,
1042 with_content: bool,
1043) -> Result<()> {
1044 let mut bytes = bytes_so_far;
1045
1046 for chunk in ids.chunks(HYDRATE_CHUNK) {
1047 // Only the placeholders are built; the ids themselves are bound.
1048 let list = (1..=chunk.len())
1049 .map(|i| format!("?{i}"))
1050 .collect::<Vec<_>>()
1051 .join(", ");
1052 let sql = format!(
1053 "SELECT id, title, content, embedding_model, valid_from, valid_to \
1054 FROM concepts WHERE retired = 0 AND id IN ({list})"
1055 );
1056 let params: Vec<libsql::Value> = chunk
1057 .iter()
1058 .map(|id| libsql::Value::Text(id.clone()))
1059 .collect();
1060
1061 let mut rows = conn.query(&sql, params).await?;
1062 while let Some(row) = rows.next().await? {
1063 let id: String = row.get(0)?;
1064 let data = NodeData {
1065 title: row.get(1)?,
1066 content: if with_content { row.get(2).ok() } else { None },
1067 embedding_model: row.get(3).ok(),
1068 valid_from: row.get(4)?,
1069 valid_to: row.get(5)?,
1070 };
1071 bytes += Subgraph::node_bytes(&id, &data);
1072 graph.nodes.insert(id, data);
1073
1074 if bytes > byte_budget {
1075 return Err(DbError::SubgraphTooLarge {
1076 n: bytes,
1077 budget: byte_budget,
1078 });
1079 }
1080 }
1081 }
1082
1083 Ok(())
1084}
1085
1086#[cfg(test)]
1087mod tests {
1088 use super::*;
1089
1090 #[test]
1091 fn adding_an_edge_indexes_it_in_both_directions() {
1092 let mut g = Subgraph::default();
1093 g.add_edge(
1094 "A",
1095 "B",
1096 "KNOWS",
1097 0.5,
1098 "2026-01-01T00:00:00.000000Z",
1099 "9999-12-31T23:59:59.999999Z",
1100 );
1101
1102 assert_eq!(g.out_edges("A").len(), 1);
1103 assert_eq!(g.out_edges("A")[0].node(&g), "B");
1104 assert_eq!(g.in_edges("B").len(), 1);
1105 assert_eq!(g.in_edges("B")[0].node(&g), "A", "in_adj holds the source");
1106
1107 // The undirected view has to agree with itself: total degree is twice
1108 // the edge weight total, which is the identity every undirected
1109 // quantity in `algorithms` is derived from.
1110 assert_eq!(g.degree("A") + g.degree("B"), 2);
1111 assert_eq!(g.weighted_degree("A") + g.weighted_degree("B"), 1.0);
1112 assert_eq!(g.total_weight(), 0.5);
1113 }
1114
1115 #[test]
1116 fn a_missing_node_has_no_edges_rather_than_panicking() {
1117 let g = Subgraph::default();
1118 assert!(g.out_edges("nobody").is_empty());
1119 assert!(g.in_edges("nobody").is_empty());
1120 assert_eq!(g.degree("nobody"), 0);
1121 assert_eq!(g.weighted_degree("nobody"), 0.0);
1122 }
1123}