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 /// Filter by priority.
93 Priority,
94 /// Filter by comment activity: a comment created or last edited at or after an instant.
95 ///
96 /// Applied locally, it costs a read of the source's comments for every task the source's
97 /// other predicates kept — which is what a plan naming it there is saying.
98 CommentedSince,
99 /// Search titles.
100 SearchTitle,
101 /// Search bodies.
102 SearchContent,
103 /// Filter by owning project.
104 Project,
105 /// Read the source's documents.
106 ///
107 /// Not a filter, and reported only as [`unavailable`](SourcePlan::unavailable): a
108 /// source declaring it has no documents contributes no document rows and there is
109 /// nothing for the engine to narrow, which is the same shape `Project` takes for a
110 /// source with no project table.
111 Document,
112 /// Walk dependency edges backwards.
113 ReverseDependencies,
114}
115
116/// One source's failure, kept beside the results the other sources returned.
117///
118/// Written with a `class` beside the error, which is not a field here: it is computed by
119/// [`classify`](crate::failure::classify) as the entry is written, so it cannot disagree
120/// with the error it classifies, and a document read back in has it recomputed rather than
121/// trusted.
122#[derive(Debug, Clone, PartialEq, Deserialize)]
123pub struct SourceFailure {
124 /// The source that failed.
125 pub source: SourceName,
126 /// Why.
127 pub error: SourceError,
128}
129
130// A `SourceFailure` as it is written: the failure, and its class. Its doc comment is the
131// schema's description, which is why it is `SourceFailure`'s own sentence.
132/// One source's failure, kept beside the results the other sources returned.
133#[derive(Serialize, JsonSchema)]
134#[schemars(rename = "SourceFailure")]
135struct ClassifiedSourceFailure<'a> {
136 /// The source that failed.
137 source: &'a SourceName,
138 /// Why.
139 error: &'a SourceError,
140 /// Whether repeating the request unchanged could change this source's answer.
141 class: FailureClass,
142}
143
144impl<'a> From<&'a SourceFailure> for ClassifiedSourceFailure<'a> {
145 fn from(failure: &'a SourceFailure) -> Self {
146 Self {
147 source: &failure.source,
148 error: &failure.error,
149 class: classify(Some(&failure.error)),
150 }
151 }
152}
153
154impl Serialize for SourceFailure {
155 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
156 ClassifiedSourceFailure::from(self).serialize(serializer)
157 }
158}
159
160impl JsonSchema for SourceFailure {
161 fn schema_name() -> std::borrow::Cow<'static, str> {
162 ClassifiedSourceFailure::schema_name()
163 }
164
165 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
166 ClassifiedSourceFailure::json_schema(generator)
167 }
168}
169
170/// The engine's own resume token: one plugin cursor per source stream, opaque to the
171/// caller exactly as a plugin's cursor is opaque to the engine.
172///
173/// Rendered as lower-case hex, which is not obfuscation — the inside is not a secret —
174/// but the one property a token a person copies off a terminal has to have: it survives
175/// a shell. The document underneath holds a plugin's own cursor, and a cursor may hold
176/// anything at all, so a token spelled as the raw JSON would carry quotes, braces and
177/// spaces straight into the next command line. Hex has no character a shell reads.
178///
179/// # What a token is and is not checked for
180///
181/// Both ways in go through [`parse`](Self::parse) — including deserialising one — and
182/// what that establishes is **structural**: the string is hex, the bytes are this
183/// engine's own resume document, and every state in it is well formed. It does not, and
184/// cannot, establish that this engine is the one that wrote it. A token is not a
185/// credential and carries nothing secret; forging one buys a caller nothing they could
186/// not have asked for outright, since every cursor inside is handed straight back to the
187/// source that issued it and is validated there.
188///
189/// What a forged token *could* do is name a stream this configuration has no source for,
190/// or resume further into a page than the engine ever pages. Both are refused where the
191/// token meets the query it is resuming, by
192/// [`Engine`](crate::Engine) — see `EngineError::Token` — because only the engine knows
193/// which sources are configured and what page ceiling each declares.
194#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
195#[serde(try_from = "String", into = "String")]
196pub struct PageToken(String);
197
198impl PageToken {
199 /// Encode where every stream still walking picks up.
200 ///
201 /// Crate-private on purpose: what a token *means* is the engine's, and a caller able
202 /// to build one from parts could name a stream no query addressed. A caller with a
203 /// token in hand reaches it through [`parse`](Self::parse) instead, which checks its
204 /// structure — see this type's own note for what that does and does not establish.
205 ///
206 /// Infallible: a stream state is a source name, a stream kind, an optional cursor
207 /// and a count, and none of those can fail to serialise.
208 ///
209 /// Only ever reached with at least one stream, because a walk with nothing left to
210 /// resume reports no token at all — which is why [`parse`](Self::parse) refuses an
211 /// empty one.
212 pub(crate) fn encode(query: &str, owed: Option<Owed>, streams: &[StreamState]) -> Self {
213 let document = serde_json::to_string(&Resumption {
214 query: query.to_owned(),
215 owed,
216 streams: streams.to_vec(),
217 })
218 .expect("a resumption is plain data and always serialises");
219 Self(to_hex(&document))
220 }
221
222 /// Accept a token from a caller — a `--page` argument, or a deserialised response —
223 /// refusing anything that is not this engine's own resume document.
224 ///
225 /// Structural only, deliberately: see the type's own note for what this establishes
226 /// and what [`Engine`](crate::Engine) checks instead.
227 ///
228 /// # Errors
229 ///
230 /// Returns [`SourceError::Malformed`] when `raw` is not hex, is not this engine's
231 /// document, or holds a state that is not well formed.
232 pub fn parse(raw: impl Into<String>) -> Result<Self, SourceError> {
233 let token = Self(raw.into());
234 token.resumption()?;
235 Ok(token)
236 }
237
238 /// Borrow the underlying token.
239 #[must_use]
240 pub fn as_str(&self) -> &str {
241 &self.0
242 }
243
244 /// Where each stream claims to pick up.
245 ///
246 /// Infallible, and that is a property of the type rather than an assumption: the only
247 /// two ways to obtain a `PageToken` are [`encode`](Self::encode), which built this
248 /// document, and [`parse`](Self::parse), which refuses anything that does not decode
249 /// — and deserialising one goes through `parse`. So a token that does not decode
250 /// never exists to be read here. Whether what it *says* is usable against the query
251 /// being resumed is the engine's to decide, not this type's.
252 pub(crate) fn decode(&self) -> Resumption {
253 self.resumption()
254 .expect("every way to build a PageToken validates it")
255 }
256
257 /// The document inside, or why this is not one of this engine's tokens.
258 fn resumption(&self) -> Result<Resumption, SourceError> {
259 let document = from_hex(&self.0).ok_or_else(|| SourceError::Malformed {
260 message: "that is not a page token this engine writes: it is not even hex".to_owned(),
261 })?;
262 let resumption: Resumption =
263 serde_json::from_str(&document).map_err(|error| SourceError::Malformed {
264 message: format!("that is not a page token this engine writes: {error}"),
265 })?;
266 let streams = &resumption.streams;
267 // A token with nothing to resume is one this engine never writes: `encode` is
268 // reached only while at least one stream still has rows to give, and a walk with
269 // none reports no token at all. Accepting one would answer an empty page and exit
270 // zero, which reads as a walk that ended rather than as the mistake it is.
271 if streams.is_empty() {
272 return Err(SourceError::Malformed {
273 message: "that is not a page token this engine writes: it resumes nothing"
274 .to_owned(),
275 });
276 }
277 Ok(resumption)
278 }
279}
280
281/// Deserialising a token goes through [`PageToken::parse`], so a response carrying
282/// a token this engine never issued is refused where it is read.
283impl TryFrom<String> for PageToken {
284 type Error = SourceError;
285
286 fn try_from(value: String) -> Result<Self, Self::Error> {
287 Self::parse(value)
288 }
289}
290
291/// A token is its string, so serialising one is that string and nothing else — the
292/// checking all happens on the way in, where a caller's input is.
293impl From<PageToken> for String {
294 fn from(value: PageToken) -> Self {
295 value.0
296 }
297}
298
299impl std::fmt::Display for PageToken {
300 /// The opaque string a caller passes back as `--page`.
301 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
302 f.write_str(&self.0)
303 }
304}
305
306/// Render `document` as lower-case hex.
307fn to_hex(document: &str) -> String {
308 let mut rendered = String::with_capacity(document.len() * 2);
309 for byte in document.as_bytes() {
310 rendered.push(nibble(byte >> 4));
311 rendered.push(nibble(byte & 0x0f));
312 }
313 rendered
314}
315
316fn nibble(value: u8) -> char {
317 char::from_digit(u32::from(value), 16).expect("a nibble is a hex digit")
318}
319
320/// Read hex back, or `None` when `raw` is not hex of valid UTF-8.
321fn from_hex(raw: &str) -> Option<String> {
322 if !raw.len().is_multiple_of(2) {
323 return None;
324 }
325 let digits: Vec<u8> = raw
326 .chars()
327 .map(|digit| digit.to_digit(16))
328 .collect::<Option<Vec<u32>>>()?
329 .into_iter()
330 .map(|digit| u8::try_from(digit).expect("a hex digit fits in a byte"))
331 .collect();
332 let bytes: Vec<u8> = digits
333 .chunks(2)
334 .map(|pair| (pair[0] << 4) | pair[1])
335 .collect();
336 String::from_utf8(bytes).ok()
337}