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