Skip to main content

sightloom_index/
query_ast.rs

1//! Composable boolean query AST over subjects (foundation).
2//!
3//! Compiles to [`crate::SubjectQuery`] where possible; supports AND/OR/NOT trees
4//! for hosts that need boolean composition without a full planner/NL bridge.
5
6use crate::{
7    Page, QueryOrder, SpatialQuery, SubjectHit, SubjectQuery, ThenSeenIn, VisionIndex,
8    execute_spatial_query, execute_subject_query,
9};
10use sightloom_core::{MediaTime, SourceId, SubjectId, ZoneId};
11
12/// Atomic subject predicate.
13#[derive(Clone, Debug, PartialEq)]
14pub enum SubjectPredicate {
15    /// Restrict to subject ids.
16    Subjects(Vec<SubjectId>),
17    /// Seen on source.
18    SeenOn(SourceId),
19    /// Zone stay.
20    SeenInZone(ZoneId),
21    /// Then-seen-in chain.
22    ThenSeenIn(ThenSeenIn),
23    /// Route contains zone subsequence.
24    RouteContains(Vec<ZoneId>),
25    /// Time window.
26    During {
27        /// Start.
28        start: MediaTime,
29        /// End.
30        end: MediaTime,
31    },
32    /// Min dwell.
33    MinDwellNs(i64),
34    /// Min confidence.
35    MinConfidence(f32),
36    /// Spatial region (intersects any sample box).
37    Spatial(SpatialQuery),
38}
39
40/// Boolean query tree.
41#[derive(Clone, Debug, PartialEq)]
42pub enum QueryNode {
43    /// All children must match.
44    And(Vec<QueryNode>),
45    /// Any child matches.
46    Or(Vec<QueryNode>),
47    /// Negation (subjects that do **not** match the child).
48    Not(Box<QueryNode>),
49    /// Leaf predicate.
50    Pred(SubjectPredicate),
51}
52
53impl QueryNode {
54    /// Leaf helper.
55    #[must_use]
56    pub fn pred(p: SubjectPredicate) -> Self {
57        Self::Pred(p)
58    }
59
60    /// AND helper.
61    #[must_use]
62    pub fn and(nodes: impl Into<Vec<QueryNode>>) -> Self {
63        Self::And(nodes.into())
64    }
65
66    /// OR helper.
67    #[must_use]
68    pub fn or(nodes: impl Into<Vec<QueryNode>>) -> Self {
69        Self::Or(nodes.into())
70    }
71
72    /// NOT helper (named to avoid clashing with `std::ops::Not`).
73    #[must_use]
74    pub fn negate(node: QueryNode) -> Self {
75        Self::Not(Box::new(node))
76    }
77}
78
79/// Executes a boolean query AST, returning subject hits.
80///
81/// Implementation: evaluates leaves to subject-id sets, then composes with
82/// set algebra, and finally materializes hits via a subject-id filter query.
83#[must_use]
84pub fn execute_query_ast(index: &VisionIndex, root: &QueryNode) -> Vec<SubjectHit> {
85    let universe = all_subject_ids(index);
86    let matched = eval_node(index, root, &universe);
87    if matched.is_empty() {
88        return Vec::new();
89    }
90    let mut q = SubjectQuery::new();
91    q.subject_ids = matched;
92    q.order = QueryOrder::SubjectIdAsc;
93    q.page = Page::default();
94    execute_subject_query(index, &q)
95}
96
97fn all_subject_ids(index: &VisionIndex) -> Vec<SubjectId> {
98    let mut ids = Vec::new();
99    for sample in index.tracks.effective_samples() {
100        if let Some(id) = sample.subject_id
101            && !ids.contains(&id)
102        {
103            ids.push(id);
104        }
105    }
106    ids.sort_by_key(|id| id.0);
107    ids
108}
109
110fn eval_node(index: &VisionIndex, node: &QueryNode, universe: &[SubjectId]) -> Vec<SubjectId> {
111    match node {
112        QueryNode::And(children) => {
113            let mut acc: Option<Vec<SubjectId>> = None;
114            for child in children {
115                let set = eval_node(index, child, universe);
116                acc = Some(match acc {
117                    None => set,
118                    Some(prev) => intersect(&prev, &set),
119                });
120            }
121            acc.unwrap_or_else(|| universe.to_vec())
122        }
123        QueryNode::Or(children) => {
124            let mut acc = Vec::new();
125            for child in children {
126                for id in eval_node(index, child, universe) {
127                    if !acc.contains(&id) {
128                        acc.push(id);
129                    }
130                }
131            }
132            acc.sort_by_key(|id| id.0);
133            acc
134        }
135        QueryNode::Not(child) => {
136            let inner = eval_node(index, child, universe);
137            universe
138                .iter()
139                .copied()
140                .filter(|id| !inner.contains(id))
141                .collect()
142        }
143        QueryNode::Pred(p) => eval_pred(index, p),
144    }
145}
146
147fn eval_pred(index: &VisionIndex, pred: &SubjectPredicate) -> Vec<SubjectId> {
148    match pred {
149        SubjectPredicate::Subjects(ids) => {
150            let mut out = ids.clone();
151            out.sort_by_key(|id| id.0);
152            out.dedup();
153            out
154        }
155        SubjectPredicate::SeenOn(source) => subject_ids_from_hits(execute_subject_query(
156            index,
157            &SubjectQuery::new().seen_on(*source),
158        )),
159        SubjectPredicate::SeenInZone(zone) => subject_ids_from_hits(execute_subject_query(
160            index,
161            &SubjectQuery::new().seen_in(*zone),
162        )),
163        SubjectPredicate::ThenSeenIn(chain) => subject_ids_from_hits(execute_subject_query(
164            index,
165            &SubjectQuery::new().then_seen_in(chain.first, chain.then, chain.within_ns),
166        )),
167        SubjectPredicate::RouteContains(zones) => subject_ids_from_hits(execute_subject_query(
168            index,
169            &SubjectQuery::new().route_contains(zones.clone()),
170        )),
171        SubjectPredicate::During { start, end } => subject_ids_from_hits(execute_subject_query(
172            index,
173            &SubjectQuery::new().during(*start, *end),
174        )),
175        SubjectPredicate::MinDwellNs(ns) => subject_ids_from_hits(execute_subject_query(
176            index,
177            &SubjectQuery::new().with_min_dwell_ns(*ns),
178        )),
179        SubjectPredicate::MinConfidence(c) => subject_ids_from_hits(execute_subject_query(
180            index,
181            &SubjectQuery::new().with_min_confidence(*c),
182        )),
183        SubjectPredicate::Spatial(spatial) => {
184            let hits = execute_spatial_query(index, spatial);
185            let mut ids = Vec::new();
186            for h in hits {
187                if let Some(id) = h.subject_id
188                    && !ids.contains(&id)
189                {
190                    ids.push(id);
191                }
192            }
193            ids.sort_by_key(|id| id.0);
194            ids
195        }
196    }
197}
198
199fn subject_ids_from_hits(hits: Vec<SubjectHit>) -> Vec<SubjectId> {
200    let mut ids: Vec<SubjectId> = hits.into_iter().map(|h| h.subject_id).collect();
201    ids.sort_by_key(|id| id.0);
202    ids.dedup();
203    ids
204}
205
206fn intersect(a: &[SubjectId], b: &[SubjectId]) -> Vec<SubjectId> {
207    a.iter().copied().filter(|id| b.contains(id)).collect()
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use crate::{TrackSample, VisionIndex};
214    use sightloom_core::{MediaTime, SourceId, SubjectId, TrackId};
215
216    fn sample(subject: u64, frame: u64, source: u32) -> TrackSample {
217        TrackSample {
218            sample_id: 0,
219            supersedes: None,
220            revision: 0,
221            idempotency_key: 0,
222            source_id: SourceId(source),
223            frame_index: frame,
224            pts: MediaTime::new(frame as i64, 1).unwrap(),
225            track_id: TrackId(1),
226            track_uid: None,
227            subject_id: Some(SubjectId(subject)),
228            class_id: None,
229            left: 0.0,
230            top: 0.0,
231            right: 1.0,
232            bottom: 1.0,
233            confidence: 0.9,
234            mask_ref: 0,
235        }
236    }
237
238    #[test]
239    fn and_or_not_compose() {
240        let mut index = VisionIndex::new("ast");
241        index.push_track(sample(1, 0, 1));
242        index.push_track(sample(2, 0, 1));
243        index.push_track(sample(3, 0, 2));
244
245        let on1 = QueryNode::pred(SubjectPredicate::SeenOn(SourceId(1)));
246        let only1 = QueryNode::and(vec![
247            on1.clone(),
248            QueryNode::pred(SubjectPredicate::Subjects(vec![SubjectId(1)])),
249        ]);
250        let hits = execute_query_ast(&index, &only1);
251        assert_eq!(hits.len(), 1);
252        assert_eq!(hits[0].subject_id, SubjectId(1));
253
254        let not_on1 = QueryNode::negate(on1);
255        let hits2 = execute_query_ast(&index, &not_on1);
256        assert_eq!(hits2.len(), 1);
257        assert_eq!(hits2[0].subject_id, SubjectId(3));
258    }
259}