fathomdb-query 0.5.3

Query AST, builder, and SQL compiler for the fathomdb agent datastore
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
use std::fmt::Write;

use crate::{Predicate, QueryAst, QueryStep, TraverseDirection};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DrivingTable {
    Nodes,
    FtsNodes,
    VecNodes,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExecutionHints {
    pub recursion_limit: usize,
    pub hard_limit: usize,
}

pub fn choose_driving_table(ast: &QueryAst) -> DrivingTable {
    let has_deterministic_id_filter = ast.steps.iter().any(|step| {
        matches!(
            step,
            QueryStep::Filter(Predicate::LogicalIdEq(_) | Predicate::SourceRefEq(_))
        )
    });

    if has_deterministic_id_filter {
        DrivingTable::Nodes
    } else if ast
        .steps
        .iter()
        .any(|step| matches!(step, QueryStep::VectorSearch { .. }))
    {
        DrivingTable::VecNodes
    } else if ast
        .steps
        .iter()
        .any(|step| matches!(step, QueryStep::TextSearch { .. }))
    {
        DrivingTable::FtsNodes
    } else {
        DrivingTable::Nodes
    }
}

pub fn execution_hints(ast: &QueryAst) -> ExecutionHints {
    let step_limit = ast
        .steps
        .iter()
        .find_map(|step| {
            if let QueryStep::Traverse { max_depth, .. } = step {
                Some(*max_depth)
            } else {
                None
            }
        })
        .unwrap_or(0);
    let expansion_limit = ast
        .expansions
        .iter()
        .map(|expansion| expansion.max_depth)
        .max()
        .unwrap_or(0);
    let recursion_limit = step_limit.max(expansion_limit);

    ExecutionHints {
        recursion_limit,
        // FIX(review): was .max(1000) — always produced >= 1000, ignoring user's final_limit.
        // Options considered: (A) use final_limit directly with default, (B) .min(MAX) ceiling,
        // (C) decouple from final_limit. Chose (A): the CTE LIMIT should honor the user's
        // requested limit; the depth bound (compile.rs:177) already constrains recursion.
        hard_limit: ast.final_limit.unwrap_or(1000),
    }
}

#[allow(clippy::too_many_lines)]
pub fn shape_signature(ast: &QueryAst) -> String {
    let mut signature = String::new();
    let _ = write!(&mut signature, "Root({})", ast.root_kind);

    for step in &ast.steps {
        match step {
            QueryStep::Search { limit, .. } => {
                let _ = write!(&mut signature, "-Search(limit={limit})");
            }
            QueryStep::VectorSearch { limit, .. } => {
                let _ = write!(&mut signature, "-Vector(limit={limit})");
            }
            QueryStep::TextSearch { limit, .. } => {
                let _ = write!(&mut signature, "-Text(limit={limit})");
            }
            QueryStep::Traverse {
                direction,
                label,
                max_depth,
                filter: _,
            } => {
                let dir = match direction {
                    TraverseDirection::In => "in",
                    TraverseDirection::Out => "out",
                };
                let _ = write!(
                    &mut signature,
                    "-Traverse(direction={dir},label={label},depth={max_depth})"
                );
            }
            QueryStep::Filter(predicate) => match predicate {
                Predicate::LogicalIdEq(_) => signature.push_str("-Filter(logical_id_eq)"),
                Predicate::KindEq(_) => signature.push_str("-Filter(kind_eq)"),
                Predicate::JsonPathEq { path, .. } => {
                    let _ = write!(&mut signature, "-Filter(json_eq:{path})");
                }
                Predicate::JsonPathCompare { path, op, .. } => {
                    let op = match op {
                        crate::ComparisonOp::Gt => "gt",
                        crate::ComparisonOp::Gte => "gte",
                        crate::ComparisonOp::Lt => "lt",
                        crate::ComparisonOp::Lte => "lte",
                    };
                    let _ = write!(&mut signature, "-Filter(json_cmp:{path}:{op})");
                }
                Predicate::SourceRefEq(_) => signature.push_str("-Filter(source_ref_eq)"),
                Predicate::ContentRefNotNull => {
                    signature.push_str("-Filter(content_ref_not_null)");
                }
                Predicate::ContentRefEq(_) => signature.push_str("-Filter(content_ref_eq)"),
                Predicate::JsonPathFusedEq { path, .. } => {
                    let _ = write!(&mut signature, "-Filter(json_fused_eq:{path})");
                }
                Predicate::JsonPathFusedTimestampCmp { path, op, .. } => {
                    let op = match op {
                        crate::ComparisonOp::Gt => "gt",
                        crate::ComparisonOp::Gte => "gte",
                        crate::ComparisonOp::Lt => "lt",
                        crate::ComparisonOp::Lte => "lte",
                    };
                    let _ = write!(&mut signature, "-Filter(json_fused_ts_cmp:{path}:{op})");
                }
                Predicate::JsonPathFusedBoolEq { path, .. } => {
                    let _ = write!(&mut signature, "-Filter(json_fused_bool_eq:{path})");
                }
                Predicate::EdgePropertyEq { path, .. } => {
                    let _ = write!(&mut signature, "-Filter(edge_eq:{path})");
                }
                Predicate::EdgePropertyCompare { path, op, .. } => {
                    let op = match op {
                        crate::ComparisonOp::Gt => "gt",
                        crate::ComparisonOp::Gte => "gte",
                        crate::ComparisonOp::Lt => "lt",
                        crate::ComparisonOp::Lte => "lte",
                    };
                    let _ = write!(&mut signature, "-Filter(edge_cmp:{path}:{op})");
                }
                Predicate::JsonPathFusedIn { path, values } => {
                    let _ = write!(
                        &mut signature,
                        "-Filter(json_fused_in:{path}:n={})",
                        values.len()
                    );
                }
                Predicate::JsonPathIn { path, values } => {
                    let _ = write!(&mut signature, "-Filter(json_in:{path}:n={})", values.len());
                }
            },
        }
    }

    for expansion in &ast.expansions {
        let dir = match expansion.direction {
            TraverseDirection::In => "in",
            TraverseDirection::Out => "out",
        };
        let edge_filter_str = match &expansion.edge_filter {
            None => String::new(),
            Some(Predicate::EdgePropertyEq { path, .. }) => {
                format!(",edge_eq:{path}")
            }
            Some(Predicate::EdgePropertyCompare { path, op, .. }) => {
                let op_str = match op {
                    crate::ComparisonOp::Gt => "gt",
                    crate::ComparisonOp::Gte => "gte",
                    crate::ComparisonOp::Lt => "lt",
                    crate::ComparisonOp::Lte => "lte",
                };
                format!(",edge_cmp:{path}:{op_str}")
            }
            Some(p) => unreachable!("edge_filter predicate {p:?} not handled in shape_signature"),
        };
        let _ = write!(
            &mut signature,
            "-Expand(slot={},direction={dir},label={},depth={}{})",
            expansion.slot, expansion.label, expansion.max_depth, edge_filter_str
        );
    }

    for edge_expansion in &ast.edge_expansions {
        let dir = match edge_expansion.direction {
            TraverseDirection::In => "in",
            TraverseDirection::Out => "out",
        };
        let _ = write!(
            &mut signature,
            "-EdgeExpand(slot={},direction={dir},label={},depth={},edge_filter={},endpoint_filter={})",
            edge_expansion.slot,
            edge_expansion.label,
            edge_expansion.max_depth,
            edge_expansion.edge_filter.is_some(),
            edge_expansion.endpoint_filter.is_some(),
        );
    }

    if let Some(limit) = ast.final_limit {
        let _ = write!(&mut signature, "-Limit({limit})");
    }

    signature
}

#[cfg(test)]
mod tests {
    use crate::{DrivingTable, QueryBuilder, TraverseDirection};

    use super::{choose_driving_table, execution_hints};

    #[test]
    fn deterministic_filter_overrides_vector_driver() {
        let ast = QueryBuilder::nodes("Meeting")
            .vector_search("budget", 5)
            .filter_logical_id_eq("meeting-123")
            .into_ast();

        assert_eq!(choose_driving_table(&ast), DrivingTable::Nodes);
    }

    #[test]
    fn hard_limit_honors_user_specified_limit_below_default() {
        let ast = QueryBuilder::nodes("Meeting")
            .traverse(TraverseDirection::Out, "HAS_TASK", 3)
            .limit(10)
            .into_ast();

        let hints = execution_hints(&ast);
        assert_eq!(
            hints.hard_limit, 10,
            "hard_limit must honor user's final_limit"
        );
    }

    #[test]
    fn hard_limit_defaults_to_1000_when_no_limit_set() {
        let ast = QueryBuilder::nodes("Meeting")
            .traverse(TraverseDirection::Out, "HAS_TASK", 3)
            .into_ast();

        let hints = execution_hints(&ast);
        assert_eq!(hints.hard_limit, 1000, "hard_limit defaults to 1000");
    }

    #[test]
    fn shape_signature_differs_for_different_edge_filters() {
        use crate::{ComparisonOp, ExpansionSlot, Predicate, QueryAst, ScalarValue};

        let base_expansion = ExpansionSlot {
            slot: "tasks".to_owned(),
            direction: TraverseDirection::Out,
            label: "HAS_TASK".to_owned(),
            max_depth: 1,
            filter: None,
            edge_filter: None,
        };

        let ast_no_filter = QueryAst {
            root_kind: "Meeting".to_owned(),
            steps: vec![],
            expansions: vec![base_expansion.clone()],
            edge_expansions: vec![],
            final_limit: None,
        };

        let ast_with_eq_filter = QueryAst {
            root_kind: "Meeting".to_owned(),
            steps: vec![],
            expansions: vec![ExpansionSlot {
                edge_filter: Some(Predicate::EdgePropertyEq {
                    path: "$.rel".to_owned(),
                    value: ScalarValue::Text("cites".to_owned()),
                }),
                ..base_expansion.clone()
            }],
            edge_expansions: vec![],
            final_limit: None,
        };

        let ast_with_cmp_filter = QueryAst {
            root_kind: "Meeting".to_owned(),
            steps: vec![],
            expansions: vec![ExpansionSlot {
                edge_filter: Some(Predicate::EdgePropertyCompare {
                    path: "$.weight".to_owned(),
                    op: ComparisonOp::Gt,
                    value: ScalarValue::Integer(5),
                }),
                ..base_expansion
            }],
            edge_expansions: vec![],
            final_limit: None,
        };

        let sig_no_filter = super::shape_signature(&ast_no_filter);
        let sig_eq_filter = super::shape_signature(&ast_with_eq_filter);
        let sig_cmp_filter = super::shape_signature(&ast_with_cmp_filter);

        assert_ne!(
            sig_no_filter, sig_eq_filter,
            "no edge_filter and EdgePropertyEq must produce different signatures"
        );
        assert_ne!(
            sig_no_filter, sig_cmp_filter,
            "no edge_filter and EdgePropertyCompare must produce different signatures"
        );
        assert_ne!(
            sig_eq_filter, sig_cmp_filter,
            "EdgePropertyEq and EdgePropertyCompare must produce different signatures"
        );
    }

    #[test]
    fn shape_signature_differs_for_different_edge_expansions() {
        use crate::{EdgeExpansionSlot, Predicate, QueryAst, ScalarValue};

        let base = EdgeExpansionSlot {
            slot: "cites".to_owned(),
            direction: TraverseDirection::Out,
            label: "CITES".to_owned(),
            max_depth: 1,
            endpoint_filter: None,
            edge_filter: None,
        };

        let ast_no_edge_expansions = QueryAst {
            root_kind: "Paper".to_owned(),
            steps: vec![],
            expansions: vec![],
            edge_expansions: vec![],
            final_limit: None,
        };

        let ast_with_edge_expansion = QueryAst {
            root_kind: "Paper".to_owned(),
            steps: vec![],
            expansions: vec![],
            edge_expansions: vec![base.clone()],
            final_limit: None,
        };

        let ast_with_different_slot_name = QueryAst {
            root_kind: "Paper".to_owned(),
            steps: vec![],
            expansions: vec![],
            edge_expansions: vec![EdgeExpansionSlot {
                slot: "references".to_owned(),
                ..base.clone()
            }],
            final_limit: None,
        };

        let ast_with_edge_filter = QueryAst {
            root_kind: "Paper".to_owned(),
            steps: vec![],
            expansions: vec![],
            edge_expansions: vec![EdgeExpansionSlot {
                edge_filter: Some(Predicate::EdgePropertyEq {
                    path: "$.rel".to_owned(),
                    value: ScalarValue::Text("primary".to_owned()),
                }),
                ..base.clone()
            }],
            final_limit: None,
        };

        let ast_with_endpoint_filter = QueryAst {
            root_kind: "Paper".to_owned(),
            steps: vec![],
            expansions: vec![],
            edge_expansions: vec![EdgeExpansionSlot {
                endpoint_filter: Some(Predicate::KindEq("Paper".to_owned())),
                ..base
            }],
            final_limit: None,
        };

        let sig_none = super::shape_signature(&ast_no_edge_expansions);
        let sig_basic = super::shape_signature(&ast_with_edge_expansion);
        let sig_diff_slot = super::shape_signature(&ast_with_different_slot_name);
        let sig_edge = super::shape_signature(&ast_with_edge_filter);
        let sig_endpoint = super::shape_signature(&ast_with_endpoint_filter);

        assert_ne!(
            sig_none, sig_basic,
            "presence of edge_expansions must change signature"
        );
        assert_ne!(
            sig_basic, sig_diff_slot,
            "different edge_expansion slot names must change signature"
        );
        assert_ne!(
            sig_basic, sig_edge,
            "edge_filter presence must change signature"
        );
        assert_ne!(
            sig_basic, sig_endpoint,
            "endpoint_filter presence must change signature"
        );
    }
}