Skip to main content

khive_runtime/
search_audit.rs

1//! Content-free execution facts for one search dispatch.
2//!
3//! Arms are recorded when their futures run, even if they return no hits or
4//! degrade. This is separate from hit provenance and executed-work counters.
5//! Request-owned spawned children explicitly inherit the recorder; detached
6//! background work never does. Every dispatch masks its parent's recorder.
7
8use std::future::Future;
9use std::sync::atomic::{AtomicU8, Ordering};
10use std::sync::Arc;
11
12/// Retrieval arm that has started executing in this dispatch.
13#[derive(Clone, Copy)]
14pub enum SearchArm {
15    Text = 1,
16    Vector = 2,
17}
18
19/// The union of arms started by this dispatch and its joined children.
20#[derive(Clone, Copy, Default)]
21pub(crate) struct SearchArms(u8);
22
23impl SearchArms {
24    pub(crate) fn as_str(self) -> &'static str {
25        match self.0 {
26            1 => "text",
27            2 => "vector",
28            3 => "both",
29            _ => "none",
30        }
31    }
32}
33
34tokio::task_local! {
35    static CURRENT: Option<Arc<AtomicU8>>;
36}
37
38pub(crate) fn capture<F: Future>(
39    enabled: bool,
40    future: F,
41) -> impl Future<Output = (F::Output, SearchArms)> {
42    // Box before returning: an async constructor would retain F inline until
43    // first poll and grow every enclosing dispatch state machine.
44    let future = Box::pin(future);
45    async move {
46        // Check the parent at poll time: this future can be constructed before
47        // its caller enters an outer search scope.
48        let has_parent = CURRENT
49            .try_with(|recorder| recorder.is_some())
50            .unwrap_or(false);
51        if !enabled && !has_parent {
52            return (future.await, SearchArms::default());
53        }
54        let recorder = enabled.then(|| Arc::new(AtomicU8::new(0)));
55        let output = CURRENT.scope(recorder.clone(), future).await;
56        let arms = recorder.map_or(0, |r| r.load(Ordering::Relaxed));
57        (output, SearchArms(arms))
58    }
59}
60
61/// Record an actual arm entry. No allocation or effect outside search dispatch.
62pub fn record(arm: SearchArm) {
63    let _ = CURRENT.try_with(|recorder| {
64        if let Some(recorder) = recorder {
65            recorder.fetch_or(arm as u8, Ordering::Relaxed);
66        }
67    });
68}
69
70/// Capture before spawning a request-owned child, and re-enter inside it.
71/// The returned future must be joined before the dispatch audit is produced.
72pub fn inherit<F: Future>(future: F) -> impl Future<Output = F::Output> {
73    let recorder = CURRENT.try_with(Clone::clone).ok().flatten();
74    let future = Box::pin(future);
75    async move { CURRENT.scope(recorder, future).await }
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    fn large_child() -> impl Future<Output = u8> {
83        let bytes = std::hint::black_box([7_u8; 32 * 1024]);
84        async move {
85            tokio::task::yield_now().await;
86            std::hint::black_box(bytes)[0]
87        }
88    }
89
90    #[tokio::test]
91    async fn capture_and_inherit_box_children_before_returning() {
92        for enabled in [false, true] {
93            let future = capture(enabled, large_child());
94            assert!(
95                std::mem::size_of_val(&future) < 4096,
96                "capture must not retain the 32 KiB child inline"
97            );
98            let (value, arms) = future.await;
99            assert_eq!(value, 7);
100            assert_eq!(arms.as_str(), "none");
101        }
102        let future = inherit(large_child());
103        assert!(
104            std::mem::size_of_val(&future) < 4096,
105            "inherit must not retain the 32 KiB child inline"
106        );
107        assert_eq!(future.await, 7);
108    }
109
110    #[tokio::test]
111    async fn non_search_capture_masks_a_parent_entered_after_construction() {
112        let child = capture(false, async {
113            tokio::task::yield_now().await;
114            record(SearchArm::Vector);
115        });
116        let (_, outer) = capture(true, async {
117            record(SearchArm::Text);
118            let (_, masked) = child.await;
119            assert_eq!(masked.as_str(), "none");
120        })
121        .await;
122        assert_eq!(outer.as_str(), "text");
123    }
124
125    #[tokio::test]
126    async fn joined_children_union_arms_and_nested_dispatches_are_isolated() {
127        let (_, outer) = capture(true, async {
128            record(SearchArm::Text);
129            tokio::spawn(inherit(async { record(SearchArm::Vector) }))
130                .await
131                .unwrap();
132            let (_, nested) = capture(true, async { record(SearchArm::Text) }).await;
133            assert_eq!(nested.as_str(), "text");
134        })
135        .await;
136        assert_eq!(outer.as_str(), "both");
137
138        let (_, outer) = capture(true, async {
139            capture(false, async { record(SearchArm::Vector) }).await;
140            // Uninherited background work must not contaminate the parent.
141            tokio::spawn(async { record(SearchArm::Text) })
142                .await
143                .unwrap();
144        })
145        .await;
146        assert_eq!(outer.as_str(), "none");
147    }
148
149    #[tokio::test]
150    async fn concurrent_dispatches_keep_distinct_arm_sets() {
151        let ((_, text), (_, vector)) = tokio::join!(
152            capture(true, async {
153                record(SearchArm::Text);
154                tokio::task::yield_now().await;
155            }),
156            capture(true, async {
157                record(SearchArm::Vector);
158                tokio::task::yield_now().await;
159            }),
160        );
161        assert_eq!(text.as_str(), "text");
162        assert_eq!(vector.as_str(), "vector");
163    }
164}