Skip to main content

macrame/graph/
builder.rs

1use crate::error::Result;
2use crate::temporal::as_of::NodeAttributes;
3
4/// Attribute hydration mode for temporal traversals (§5.2).
5#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
6pub enum AttributeMode {
7    /// Live attributes from concepts table. Fast. Documented as WRONG for historical text.
8    Current,
9    /// Attributes as believed at ts, hydrated from transaction_log.
10    AtTime,
11    /// Topology only; concepts join is omitted.
12    ///
13    /// **Use [`TraversalBuilder::execute_ids`], not [`TraversalBuilder::execute`].**
14    /// `execute` returns `Vec<NodeAttributes>`, and there are no attributes to
15    /// return under this mode, so it answers `Ok(vec![])` — which a caller
16    /// cannot tell apart from a traversal that reached nothing. `execute_ids`
17    /// returns exactly what this mode is for, and distinguishes the two cases by
18    /// construction.
19    ///
20    /// Kept rather than removed (Wave 4.5) because it is meaningful where the
21    /// mode is a *parameter* — `hydrate_attributes` and `FilteredVectorSearch`
22    /// both take one and are right to accept "no attributes" as a choice. It is
23    /// only `execute`'s return type that cannot express it.
24    Omit,
25}
26
27/// Recursive CTE traversal query builder (§5.2).
28#[derive(Debug, Clone)]
29pub struct TraversalBuilder {
30    pub start_node: String,
31    pub max_depth: usize,
32    pub edge_types: Vec<String>,
33    pub min_weight: f64,
34    /// `None` means *defaulted*, not `Current` (T3.2, D-085).
35    ///
36    /// The distinction is the whole mechanism. `Current` chosen by a caller who
37    /// knows what it means is a legitimate, fast answer; `Current` arrived at by
38    /// never touching the setting, on a query about the past, is a wrong answer
39    /// nobody asked for. Those two produce identical behaviour and must not be
40    /// stored identically, so the field records which happened.
41    ///
42    /// Public for construction-by-struct-literal, which is why it is an `Option`
43    /// here rather than a private `bool` beside the mode: a caller building the
44    /// struct directly should have to write down the same thing the builder
45    /// method records.
46    pub attribute_mode: Option<AttributeMode>,
47    /// The valid-time instant to traverse at, if it is not the present.
48    ///
49    /// Added in 0.6.0 so "as of Tuesday" is *expressible*. Before this, the
50    /// instant arrived as `execute`'s `now_ts` parameter and a historical
51    /// traversal was indistinguishable from a live one — which is why the
52    /// mismatch with `AttributeMode::Current` could only ever be a `warn!`:
53    /// nothing in the call had the information needed to raise an error.
54    pub as_of: Option<String>,
55}
56
57impl TraversalBuilder {
58    pub fn new(start_node: impl Into<String>) -> Self {
59        Self {
60            start_node: start_node.into(),
61            max_depth: 3,
62            edge_types: Vec::new(),
63            min_weight: 0.0,
64            attribute_mode: None,
65            as_of: None,
66        }
67    }
68
69    pub fn max_depth(mut self, depth: usize) -> Self {
70        self.max_depth = depth;
71        self
72    }
73
74    pub fn edge_types(mut self, types: Vec<String>) -> Self {
75        self.edge_types = types;
76        self
77    }
78
79    pub fn min_weight(mut self, weight: f64) -> Self {
80        self.min_weight = weight;
81        self
82    }
83
84    /// State the attribute mode explicitly.
85    ///
86    /// Calling this is what turns `Current` from a default into a decision, and
87    /// [`Self::execute`] treats the two differently on a historical traversal —
88    /// see [`Self::as_of`].
89    pub fn attribute_mode(mut self, mode: AttributeMode) -> Self {
90        self.attribute_mode = Some(mode);
91        self
92    }
93
94    /// Traverse the graph as it was at `ts` rather than at the present (§5.2).
95    ///
96    /// # Setting this makes the attribute mode a required decision (T3.2, D-085)
97    ///
98    /// A historical traversal has two independent temporal questions, and until
99    /// 0.6.0 only one of them was asked. The topology comes from `ts`. The node
100    /// *attributes* — titles, content — come from wherever
101    /// [`AttributeMode`] says, and the default said `Current`, which is live
102    /// text. So `as_of(Tuesday)` returned Tuesday's graph wearing today's
103    /// titles, and reported that through a `tracing::warn!` — invisible in any
104    /// application that has not configured a subscriber, which is most of them
105    /// at first run.
106    ///
107    /// So: with `as_of` set and no [`Self::attribute_mode`] call,
108    /// [`Self::execute`] returns [`DbError::AttributeModeUnstated`] rather than
109    /// guessing. Both answers stay available and neither is silent:
110    ///
111    /// ```no_run
112    /// # use macrame::graph::{AttributeMode, TraversalBuilder};
113    /// # async fn f(conn: &libsql::Connection, now: &str) -> macrame::Result<()> {
114    /// // Tuesday's graph with Tuesday's titles — usually what was meant.
115    /// let then = TraversalBuilder::new("a")
116    ///     .as_of("2026-01-06T00:00:00.000000Z")
117    ///     .attribute_mode(AttributeMode::AtTime)
118    ///     .execute(conn, now)
119    ///     .await?;
120    ///
121    /// // Tuesday's topology with today's titles — legitimate, and now stated.
122    /// let mixed = TraversalBuilder::new("a")
123    ///     .as_of("2026-01-06T00:00:00.000000Z")
124    ///     .attribute_mode(AttributeMode::Current)
125    ///     .execute(conn, now)
126    ///     .await?;
127    /// # Ok(()) }
128    /// ```
129    ///
130    /// A traversal with no `as_of` is a query about now, where `Current` and
131    /// `AtTime` agree about which text to return, so the default stands and no
132    /// caller has to change.
133    pub fn as_of(mut self, ts: impl Into<String>) -> Self {
134        self.as_of = Some(ts.into());
135        self
136    }
137
138    /// The instant this traversal reads at: [`Self::as_of`] if set, else `now_ts`.
139    fn instant<'a>(&'a self, now_ts: &'a str) -> &'a str {
140        self.as_of.as_deref().unwrap_or(now_ts)
141    }
142
143    /// Compile the recursive CTE query string as specified in §5.2.
144    ///
145    /// Edge types become bind placeholders, not quoted literals. An earlier
146    /// version spliced them in with `format!("'{t}'")`, which made any caller
147    /// string a SQL fragment on the *read* path — and the only validation in the
148    /// crate, [`super::edge::validate_edge_type`], runs in
149    /// [`super::EdgeAssertion::normalized`] on the *write* path, so a traversal
150    /// never passed through it. Binding removes the question rather than
151    /// answering it: unlike a table name, an edge type is a value, and values
152    /// can be parameters.
153    pub fn build_sql(&self) -> String {
154        format!(
155            "{}{}",
156            self.walk_cte(),
157            r#"
158SELECT DISTINCT w.node_id
159FROM walk w JOIN concepts c ON c.id = w.node_id
160WHERE c.retired = 0
161ORDER BY w.node_id;
162            "#
163        )
164    }
165
166    /// The `AND l.edge_type IN (…)` fragment, or empty when unfiltered.
167    ///
168    /// `?1..?4` are start, depth, `now_ts` and `min_weight`, so edge types bind
169    /// from `?5`. Both call sites push them in the same order after those four,
170    /// which is why this lives beside the CTE rather than at either of them.
171    pub(crate) fn edge_filter_sql(&self) -> String {
172        if self.edge_types.is_empty() {
173            String::new()
174        } else {
175            let placeholders: Vec<String> = (0..self.edge_types.len())
176                .map(|i| format!("?{}", i + 5))
177                .collect();
178            format!(" AND l.edge_type IN ({})", placeholders.join(", "))
179        }
180    }
181
182    /// The recursive `walk` CTE — **the one copy** (T0.1).
183    ///
184    /// [`Self::build_sql`] and `Database::load_subgraph_with` append their own
185    /// projections to this. They previously carried byte-identical copies of the
186    /// recursion in two files, and had already drifted once: D-073 found the
187    /// subgraph loader taking neither `edge_types` nor `min_weight` while this
188    /// builder took both. Two copies of a query that must agree is the same
189    /// failure class as [D-030](../../docs/architecture/s13-decision-register.md)
190    /// and D-035, applied to SQL.
191    ///
192    /// **`UNION`, not `UNION ALL`, and no `path` column (T0.1).** The shipped
193    /// form carried a `path` of visited ids and refused a target already in it,
194    /// which restricts the walk to *simple paths* — so `walk` held one row per
195    /// distinct path to each node rather than one row per node, and the trailing
196    /// `SELECT DISTINCT` collapsed the duplication only after the work was done.
197    /// On a tree that costs nothing, because a tree has exactly one path to each
198    /// node; on a graph the row count is multiplicative in branching factor per
199    /// hop. Measured on libSQL 0.9.30 over a layered fixture (root, then *L*
200    /// layers of *W*, each fully joined to the next): a **328-edge** graph at
201    /// depth 6 produced **299,593** walk rows and took **428 ms**. The same
202    /// traversal here produces 49 rows in 0.1 ms.
203    ///
204    /// `UNION` dedupes on `(node_id, depth)` as rows enter the queue, so `walk`
205    /// is bounded by `V × (depth+1)` and termination comes from the depth bound
206    /// rather than from inspecting the path. The projections keep their
207    /// `DISTINCT`, because a node still legitimately appears at several depths.
208    ///
209    /// **Equivalence, argued rather than only measured.** The old form admits
210    /// only simple paths; this one admits any walk. The reachable sets are the
211    /// same: if a walk of length `k ≤ D` reaches `X`, excising its cycles yields
212    /// a simple path of length `≤ k` that also reaches `X`. So simple-path
213    /// reachability within `D` equals walk reachability within `D`, and the two
214    /// forms differed only in how much redundant work they did to establish it.
215    /// A property test over generated graphs — cycles, self-loops, diamonds and
216    /// expired edges, the four shapes the proof steps over — compares this form
217    /// against the old one at depths 1–4 and requires identical node *and* edge
218    /// sets (`integrity_property_tests`, 512 cases).
219    ///
220    /// **It is not free on a tree, and the plan that proposed it said it was.**
221    /// `UNION` maintains a dedupe b-tree over every row entering the queue; on a
222    /// tree nothing is ever deduped, so that is pure overhead. Measured on the
223    /// star-of-stars fixture at depth 3, best of 15, stable across runs:
224    /// 1,011 nodes 1.6 ms either way, 5,051 nodes 8.9 → 9.5 ms, 10,101 nodes
225    /// 17.8 → 19.6 ms — roughly **8–10% slower** where the old form was already
226    /// optimal, against ~2,000× faster where it was not. Recorded rather than
227    /// smoothed over: the trade is overwhelmingly worth taking and it is still a
228    /// trade, and "within noise" was a claim from a different engine's numbers.
229    pub(crate) fn walk_cte(&self) -> String {
230        let edge_filter = self.edge_filter_sql();
231        format!(
232            r#"
233WITH RECURSIVE walk(node_id, depth) AS (
234    SELECT ?1, 0
235    UNION
236    SELECT l.target_id, w.depth + 1
237    FROM walk w
238    JOIN links_current l ON l.source_id = w.node_id
239    WHERE w.depth < ?2
240      AND l.valid_from <= ?3 AND ?3 < l.valid_to
241      AND l.weight >= ?4
242      {edge_filter}
243)"#
244        )
245    }
246
247    /// Node ids reachable under this traversal, in id order (§5.2).
248    ///
249    /// Reads at [`Self::as_of`] when set, else at `now_ts`. No attribute mode is
250    /// involved, so this never returns [`DbError::AttributeModeUnstated`]:
251    /// topology at an instant is unambiguous, and it is only the *pairing* with
252    /// live attributes that needed a decision.
253    pub async fn execute_ids(
254        &self,
255        conn: &libsql::Connection,
256        now_ts: &str,
257    ) -> Result<Vec<String>> {
258        let sql = self.build_sql();
259
260        let mut params: Vec<libsql::Value> = vec![
261            self.start_node.as_str().into(),
262            (self.max_depth as i64).into(),
263            self.instant(now_ts).into(),
264            self.min_weight.into(),
265        ];
266        params.extend(self.edge_types.iter().map(|t| t.as_str().into()));
267
268        let mut rows = conn.query(&sql, params).await?;
269        let mut ids = Vec::new();
270        while let Some(row) = rows.next().await? {
271            ids.push(row.get(0)?);
272        }
273        Ok(ids)
274    }
275
276    /// Execute the traversal and hydrate attributes per [`Self::attribute_mode`]
277    /// (§5.2).
278    ///
279    /// The hydration is a second step rather than a join in the CTE because the
280    /// three modes read from two different places: `Current` and `Omit` from
281    /// `concepts`, `AtTime` from `transaction_log`. The previous version always
282    /// emitted the `concepts` join, so `attribute_mode` was stored, exposed by a
283    /// builder method, and never read — a caller asking for `AtTime` got live
284    /// attributes with no indication that the mode had been ignored. That is the
285    /// exact failure Doctrine II exists to prevent, arriving as a silent wrong
286    /// answer rather than as an error.
287    ///
288    /// **[`AttributeMode::Omit`] returns `Ok(vec![])` here**, which is
289    /// indistinguishable from a traversal that reached nothing. That is a
290    /// limitation of this method's return type rather than of the mode; callers
291    /// wanting topology only should use [`Self::execute_ids`], which says what it
292    /// found.
293    ///
294    /// # Errors
295    ///
296    /// [`DbError::AttributeModeUnstated`] when [`Self::as_of`] is set and
297    /// [`Self::attribute_mode`] is not — see `as_of` for why that combination is
298    /// a question rather than a default (T3.2, D-085).
299    ///
300    /// `now_ts` is the caller's present. A traversal with `as_of` set reads
301    /// topology at that instant instead; `now_ts` is still what an
302    /// `AttributeMode::Current` hydrate means by "current".
303    pub async fn execute(
304        &self,
305        conn: &libsql::Connection,
306        now_ts: &str,
307    ) -> Result<Vec<NodeAttributes>> {
308        let mode = self.resolved_mode()?;
309        let instant = self.instant(now_ts);
310        let ids = self.execute_ids(conn, now_ts).await?;
311
312        // `Current` hydrates from `concepts`, which is live regardless of the
313        // instant, so the ts it receives only matters for `AtTime`. Passing the
314        // traversal's instant rather than `now_ts` is what makes
315        // `as_of(t) + AtTime` mean "as believed at t" — the whole point of the
316        // pairing this method now requires the caller to state.
317        crate::temporal::as_of::hydrate_attributes(conn, &ids, instant, mode).await
318    }
319
320    /// The mode to hydrate with, or the error that says the caller must choose.
321    ///
322    /// Kept separate from [`Self::execute`] so it is unit-testable without a
323    /// database: the property under test is a decision about two `Option`s, and
324    /// a test that needed a connection to check it would be testing something
325    /// else as well.
326    pub(crate) fn resolved_mode(&self) -> Result<AttributeMode> {
327        match (self.as_of.as_deref(), self.attribute_mode) {
328            (Some(as_of), None) => Err(crate::error::DbError::AttributeModeUnstated {
329                as_of: as_of.to_string(),
330            }),
331            (_, Some(mode)) => Ok(mode),
332            (None, None) => Ok(AttributeMode::Current),
333        }
334    }
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340    use crate::error::DbError;
341
342    const TUE: &str = "2026-01-06T00:00:00.000000Z";
343
344    /// The only combination that is a question, and it is now asked.
345    #[test]
346    fn as_of_without_a_stated_mode_is_an_error() {
347        let err = TraversalBuilder::new("a")
348            .as_of(TUE)
349            .resolved_mode()
350            .expect_err("past topology plus present text must not be a default");
351
352        match err {
353            DbError::AttributeModeUnstated { as_of } => assert_eq!(as_of, TUE),
354            other => panic!("got {other:?}"),
355        }
356
357        // And the message has to be actionable: a caller who reads only this
358        // should know which two calls resolve it.
359        let text = DbError::AttributeModeUnstated {
360            as_of: TUE.to_string(),
361        }
362        .to_string();
363        assert!(
364            text.contains("AtTime") && text.contains("Current"),
365            "{text}"
366        );
367    }
368
369    /// Stating `Current` on a historical traversal is legitimate and stays so.
370    ///
371    /// The fix must not be "forbid the fast path". Past topology with live text
372    /// is a real query — a caller rendering a historical diagram with today's
373    /// labels wants exactly it — and the objection was always to getting it
374    /// without asking, never to asking for it.
375    #[test]
376    fn a_stated_mode_is_honoured_on_a_historical_traversal() {
377        for mode in [
378            AttributeMode::Current,
379            AttributeMode::AtTime,
380            AttributeMode::Omit,
381        ] {
382            let got = TraversalBuilder::new("a")
383                .as_of(TUE)
384                .attribute_mode(mode)
385                .resolved_mode()
386                .unwrap();
387            assert_eq!(got, mode);
388        }
389    }
390
391    /// A traversal about now still defaults, so no existing caller changes.
392    ///
393    /// This is what keeps the change from being a breaking one for the common
394    /// case: with no `as_of`, `Current` and `AtTime` agree about which text to
395    /// return, so there is nothing to decide and nothing to ask.
396    #[test]
397    fn a_live_traversal_still_defaults_to_current() {
398        assert_eq!(
399            TraversalBuilder::new("a").resolved_mode().unwrap(),
400            AttributeMode::Current
401        );
402    }
403
404    /// `as_of` supplies the instant the walk reads at; `now_ts` is the fallback.
405    #[test]
406    fn as_of_overrides_the_execute_timestamp() {
407        let now = "2026-06-01T00:00:00.000000Z";
408        assert_eq!(TraversalBuilder::new("a").instant(now), now);
409        assert_eq!(TraversalBuilder::new("a").as_of(TUE).instant(now), TUE);
410    }
411}