Skip to main content

onetaskgraph_core/
plan.rs

1//! What the engine did, carried back with every response.
2//!
3//! The point of a capability declaration is that two sources answer the same
4//! query differently and both answers are correct. These types make that visible
5//! instead of leaving a user to guess why one source was fast and another was not:
6//! `--explain` renders a [`QueryPlan`] and `--json` carries it as a field.
7
8use onetaskgraph_plugin_api::{SourceError, SourceName};
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11
12use crate::engine::{Owed, Resumption, StreamState};
13
14/// One page of engine output, with the plan that produced it.
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
16pub struct QueryResponse<T> {
17    /// This page's items, already qualified and merged across sources.
18    pub items: Vec<T>,
19    /// Where to resume, or `None` when every source is exhausted.
20    pub next: Option<PageToken>,
21    /// What each source was asked to do, and what the engine did instead.
22    pub plan: QueryPlan,
23    /// Sources that failed. One failure never fails the whole query.
24    pub errors: Vec<SourceFailure>,
25}
26
27/// What the engine did, per source.
28#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
29pub struct QueryPlan {
30    /// One entry per source the query reached.
31    pub per_source: Vec<SourcePlan>,
32}
33
34/// What one source was asked for, and what happened to each predicate.
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
36pub struct SourcePlan {
37    /// The configured source this describes.
38    pub source: SourceName,
39    /// The plugin kind behind it.
40    // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this restates at a new site the justification already recorded at `Capabilities.max_page_size` (capability.rs) and `PageRequest.limit` (query.rs): `kind: String` is approved contract text. It is also the one field that could not be narrowed even if it were free — a plan must carry the kind a subprocess-hosted plugin reports, an open vocabulary no compile-time type can enumerate.
41    pub kind: String,
42    /// Predicates the source applied itself.
43    ///
44    /// The four predicate vectors below partition one set of outcomes, and nothing in
45    /// the type says so: a `Predicate` could appear in two of them at once, or in none.
46    /// One `Vec<(Predicate, Outcome)>` — or a map keyed by predicate — would make that
47    /// unrepresentable. See the directive below for why it stays as it is.
48    // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this
49    // restates at a new site the justification already recorded at
50    // `Capabilities.max_page_size` (capability.rs) and `PageRequest.limit` (query.rs):
51    // `SourcePlan`'s four-vector shape is approved contract text, reproduced field for
52    // field, and `--json` publishes it as the wire format both SDKs are generated from.
53    // Collapsing the four vectors into one outcome-tagged collection is a change to that
54    // contract, which is the contract owner's call and is expressly forbidden to any node
55    // of this plan while other nodes are being written against this text. The finding is
56    // correct and is surfaced as a contract defect rather than dismissed: the contract can
57    // represent a plan its own rules forbid.
58    pub pushed_down: Vec<Predicate>,
59    /// Predicates the engine applied in memory over a wider result set.
60    pub applied_locally: Vec<Predicate>,
61    /// Predicates the engine answered by a bounded scan of the source.
62    pub emulated: Vec<Predicate>,
63    /// Predicates neither side could answer, so the result is unconstrained.
64    ///
65    /// Never [`Predicate::ReverseDependencies`]: `DependencySupport` has no
66    /// unsupported variant, so a reverse-dependency read is answered natively or
67    /// emulated by the engine's bounded scan, never abandoned. The type cannot say
68    /// so — see the directive below.
69    // llmlint: ignore[invalid_states_unrepresentable] SECOND PERMITTED REASON — this
70    // restates at a new site the justification already recorded at
71    // `Capabilities.max_page_size` (capability.rs) and `PageRequest.limit` (query.rs):
72    // `unavailable: Vec<Predicate>` and the `Predicate` enum are both approved contract
73    // text, so a narrower element type here is the contract owner's call, not this
74    // crate's. The finding is correct and is being surfaced as a contract defect rather
75    // than dismissed: the contract can express a state its own rules forbid.
76    pub unavailable: Vec<Predicate>,
77    /// How many pages the engine pulled from this source to answer.
78    pub pages_fetched: u32,
79}
80
81/// One thing a query can ask of a source.
82#[derive(
83    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
84)]
85#[serde(rename_all = "kebab-case")]
86pub enum Predicate {
87    /// Filter by label name.
88    Label,
89    /// Filter by status category.
90    Status,
91    /// Search titles.
92    SearchTitle,
93    /// Search bodies.
94    SearchContent,
95    /// Filter by owning project.
96    Project,
97    /// Walk dependency edges backwards.
98    ReverseDependencies,
99}
100
101/// One source's failure, kept beside the results the other sources returned.
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
103pub struct SourceFailure {
104    /// The source that failed.
105    pub source: SourceName,
106    /// Why.
107    pub error: SourceError,
108}
109
110/// The engine's own resume token: one plugin cursor per source stream, opaque to the
111/// caller exactly as a plugin's cursor is opaque to the engine.
112///
113/// Rendered as lower-case hex, which is not obfuscation — the inside is not a secret —
114/// but the one property a token a person copies off a terminal has to have: it survives
115/// a shell. The document underneath holds a plugin's own cursor, and a cursor may hold
116/// anything at all, so a token spelled as the raw JSON would carry quotes, braces and
117/// spaces straight into the next command line. Hex has no character a shell reads.
118///
119/// # What a token is and is not checked for
120///
121/// Both ways in go through [`parse`](Self::parse) — including deserialising one — and
122/// what that establishes is **structural**: the string is hex, the bytes are this
123/// engine's own resume document, and every state in it is well formed. It does not, and
124/// cannot, establish that this engine is the one that wrote it. A token is not a
125/// credential and carries nothing secret; forging one buys a caller nothing they could
126/// not have asked for outright, since every cursor inside is handed straight back to the
127/// source that issued it and is validated there.
128///
129/// What a forged token *could* do is name a stream this configuration has no source for,
130/// or resume further into a page than the engine ever pages. Both are refused where the
131/// token meets the query it is resuming, by
132/// [`Engine`](crate::Engine) — see `EngineError::Token` — because only the engine knows
133/// which sources are configured and what page ceiling each declares.
134#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
135#[serde(try_from = "String", into = "String")]
136pub struct PageToken(String);
137
138impl PageToken {
139    /// Encode where every stream still walking picks up.
140    ///
141    /// Crate-private on purpose: what a token *means* is the engine's, and a caller able
142    /// to build one from parts could name a stream no query addressed. A caller with a
143    /// token in hand reaches it through [`parse`](Self::parse) instead, which checks its
144    /// structure — see this type's own note for what that does and does not establish.
145    ///
146    /// Infallible: a stream state is a source name, a stream kind, an optional cursor
147    /// and a count, and none of those can fail to serialise.
148    ///
149    /// Only ever reached with at least one stream, because a walk with nothing left to
150    /// resume reports no token at all — which is why [`parse`](Self::parse) refuses an
151    /// empty one.
152    pub(crate) fn encode(query: &str, owed: Option<Owed>, streams: &[StreamState]) -> Self {
153        let document = serde_json::to_string(&Resumption {
154            query: query.to_owned(),
155            owed,
156            streams: streams.to_vec(),
157        })
158        .expect("a resumption is plain data and always serialises");
159        Self(to_hex(&document))
160    }
161
162    /// Accept a token from a caller — a `--page` argument, or a deserialised response —
163    /// refusing anything that is not this engine's own resume document.
164    ///
165    /// Structural only, deliberately: see the type's own note for what this establishes
166    /// and what [`Engine`](crate::Engine) checks instead.
167    ///
168    /// # Errors
169    ///
170    /// Returns [`SourceError::Malformed`] when `raw` is not hex, is not this engine's
171    /// document, or holds a state that is not well formed.
172    pub fn parse(raw: impl Into<String>) -> Result<Self, SourceError> {
173        let token = Self(raw.into());
174        token.resumption()?;
175        Ok(token)
176    }
177
178    /// Borrow the underlying token.
179    #[must_use]
180    pub fn as_str(&self) -> &str {
181        &self.0
182    }
183
184    /// Where each stream claims to pick up.
185    ///
186    /// Infallible, and that is a property of the type rather than an assumption: the only
187    /// two ways to obtain a `PageToken` are [`encode`](Self::encode), which built this
188    /// document, and [`parse`](Self::parse), which refuses anything that does not decode
189    /// — and deserialising one goes through `parse`. So a token that does not decode
190    /// never exists to be read here. Whether what it *says* is usable against the query
191    /// being resumed is the engine's to decide, not this type's.
192    pub(crate) fn decode(&self) -> Resumption {
193        self.resumption()
194            .expect("every way to build a PageToken validates it")
195    }
196
197    /// The document inside, or why this is not one of this engine's tokens.
198    fn resumption(&self) -> Result<Resumption, SourceError> {
199        let document = from_hex(&self.0).ok_or_else(|| SourceError::Malformed {
200            message: "that is not a page token this engine writes: it is not even hex".to_owned(),
201        })?;
202        let resumption: Resumption =
203            serde_json::from_str(&document).map_err(|error| SourceError::Malformed {
204                message: format!("that is not a page token this engine writes: {error}"),
205            })?;
206        let streams = &resumption.streams;
207        // A token with nothing to resume is one this engine never writes: `encode` is
208        // reached only while at least one stream still has rows to give, and a walk with
209        // none reports no token at all. Accepting one would answer an empty page and exit
210        // zero, which reads as a walk that ended rather than as the mistake it is.
211        if streams.is_empty() {
212            return Err(SourceError::Malformed {
213                message: "that is not a page token this engine writes: it resumes nothing"
214                    .to_owned(),
215            });
216        }
217        Ok(resumption)
218    }
219}
220
221/// Deserialising a token goes through [`PageToken::parse`], so a response carrying
222/// a token this engine never issued is refused where it is read.
223impl TryFrom<String> for PageToken {
224    type Error = SourceError;
225
226    fn try_from(value: String) -> Result<Self, Self::Error> {
227        Self::parse(value)
228    }
229}
230
231/// A token is its string, so serialising one is that string and nothing else — the
232/// checking all happens on the way in, where a caller's input is.
233impl From<PageToken> for String {
234    fn from(value: PageToken) -> Self {
235        value.0
236    }
237}
238
239impl std::fmt::Display for PageToken {
240    /// The opaque string a caller passes back as `--page`.
241    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
242        f.write_str(&self.0)
243    }
244}
245
246/// Render `document` as lower-case hex.
247fn to_hex(document: &str) -> String {
248    let mut rendered = String::with_capacity(document.len() * 2);
249    for byte in document.as_bytes() {
250        rendered.push(nibble(byte >> 4));
251        rendered.push(nibble(byte & 0x0f));
252    }
253    rendered
254}
255
256fn nibble(value: u8) -> char {
257    char::from_digit(u32::from(value), 16).expect("a nibble is a hex digit")
258}
259
260/// Read hex back, or `None` when `raw` is not hex of valid UTF-8.
261fn from_hex(raw: &str) -> Option<String> {
262    if !raw.len().is_multiple_of(2) {
263        return None;
264    }
265    let digits: Vec<u8> = raw
266        .chars()
267        .map(|digit| digit.to_digit(16))
268        .collect::<Option<Vec<u32>>>()?
269        .into_iter()
270        .map(|digit| u8::try_from(digit).expect("a hex digit fits in a byte"))
271        .collect();
272    let bytes: Vec<u8> = digits
273        .chunks(2)
274        .map(|pair| (pair[0] << 4) | pair[1])
275        .collect();
276    String::from_utf8(bytes).ok()
277}