waratah_compute/error.rs
1//! Typed errors for the compute coordinator.
2
3use std::time::Duration;
4
5use thiserror::Error;
6use waratah_exec::ExecError;
7use waratah_router::RouterError;
8use waratah_storage::{PartitionAxis, StorageError};
9
10/// Failure on the compute write or SELECT path.
11#[derive(Debug, Error)]
12pub enum ComputeError {
13 /// RDF term / quad encoding or decoding failed.
14 #[error(transparent)]
15 Storage(#[from] StorageError),
16
17 /// The query is not valid SPARQL.
18 ///
19 /// Known semantic peg phrases (GROUP BY projection, BIND override, …) are
20 /// rewritten at parse time; other parser dumps are stored as-is.
21 #[error("SPARQL syntax error: {0}")]
22 Sparql(String),
23
24 /// Valid SPARQL that the MVP query engine does not implement.
25 #[error("unsupported SPARQL: {0}")]
26 UnsupportedSparql(String),
27
28 /// An executor invariant was violated — a route the code was
29 /// supposed to make unreachable was taken. Always a bug: the query
30 /// aborts loudly instead of returning a silently wrong answer.
31 #[error("internal executor error: {0}")]
32 Internal(String),
33
34 /// Static cluster address lookup failed.
35 #[error(transparent)]
36 Router(#[from] RouterError),
37
38 /// gRPC transport or channel connect failure.
39 #[error("transport error: {0}")]
40 Transport(#[from] tonic::transport::Error),
41
42 /// A single hexastore axis rejected or failed the insert after retries.
43 #[error("hexastore insert on axis {axis} failed after {attempts} attempt(s): {message}")]
44 HexastoreInsert {
45 /// Axis that failed.
46 axis: PartitionAxis,
47 /// Attempts made (including the first).
48 attempts: u32,
49 /// Last status / error message.
50 message: String,
51 },
52
53 /// A hexastore `ScanPattern` failed after retries.
54 #[error("hexastore scan on axis {axis} failed after {attempts} attempt(s): {message}")]
55 HexastoreScan {
56 /// Axis that failed.
57 axis: PartitionAxis,
58 /// Attempts made (including the first).
59 attempts: u32,
60 /// Last status / error message.
61 message: String,
62 },
63
64 /// A hexastore `FlushMemtables` failed after retries.
65 #[error("hexastore flush on axis {axis} failed after {attempts} attempt(s): {message}")]
66 HexastoreFlush {
67 /// Axis that failed.
68 axis: PartitionAxis,
69 /// Attempts made (including the first).
70 attempts: u32,
71 /// Last status / error message.
72 message: String,
73 },
74
75 /// A hexastore `CompactRange` failed after retries.
76 #[error("hexastore compact on axis {axis} failed after {attempts} attempt(s): {message}")]
77 HexastoreCompact {
78 /// Axis that failed.
79 axis: PartitionAxis,
80 /// Attempts made (including the first).
81 attempts: u32,
82 /// Last status / error message.
83 message: String,
84 },
85
86 /// String-registry `FlushMemtables` failed after retries.
87 #[error("registry flush failed after {attempts} attempt(s): {message}")]
88 RegistryFlush {
89 /// Attempts made (including the first).
90 attempts: u32,
91 /// Last status / error message.
92 message: String,
93 },
94
95 /// String-registry `CompactRange` failed after retries.
96 #[error("registry compact failed after {attempts} attempt(s): {message}")]
97 RegistryCompact {
98 /// Attempts made (including the first).
99 attempts: u32,
100 /// Last status / error message.
101 message: String,
102 },
103
104 /// String-registry `RegisterStrings` failed after retries.
105 #[error("register strings failed after {attempts} attempt(s): {message}")]
106 RegisterStrings {
107 /// Attempts made (including the first).
108 attempts: u32,
109 /// Last status / error message.
110 message: String,
111 },
112
113 /// String-registry `ResolveStrings` failed after retries.
114 #[error("resolve strings failed after {attempts} attempt(s): {message}")]
115 ResolveStrings {
116 /// Attempts made (including the first).
117 attempts: u32,
118 /// Last status / error message.
119 message: String,
120 },
121
122 /// A registry response did not line up with the hashes requested.
123 #[error("registry returned {got} values for {want} hashes")]
124 RegistryResponseLength {
125 /// Values received.
126 got: usize,
127 /// Hashes requested.
128 want: usize,
129 },
130
131 /// Sketch profile decode / stats-path failure (Phase 7).
132 #[error("stats error: {0}")]
133 Stats(String),
134
135 /// S-axis named-graph catalog RPC failed after retries.
136 #[error("named-graph catalog failed after {attempts} attempt(s): {message}")]
137 NamedGraphCatalog {
138 /// Attempts made (including the first).
139 attempts: u32,
140 /// Last status / error message.
141 message: String,
142 },
143
144 /// Every hexastore axis failed; no durable write.
145 #[error("all hexastore axes failed: {0}")]
146 AllAxesFailed(String),
147
148 /// A property-path walk discovered more distinct `(start, end)` pairs than
149 /// the configured budget. This is a circuit breaker, not a SPARQL hop cap:
150 /// results are not silently truncated.
151 #[error(
152 "property path exceeded pair budget of {budget} (discovered {discovered} distinct pairs)"
153 )]
154 PathPairBudget {
155 /// Configured maximum distinct pairs.
156 budget: u64,
157 /// Pairs materialised before aborting.
158 discovered: u64,
159 },
160
161 /// Cooperative cancellation: the query's cancel token was set.
162 #[error("query cancelled")]
163 Cancelled,
164
165 /// The query's wall-clock deadline was reached during execution.
166 #[error("query deadline exceeded")]
167 DeadlineExceeded,
168
169 /// Query intern table hit `u32::MAX` distinct terms.
170 #[error("too many unique terms")]
171 TooManyTerms,
172
173 /// TermId page spill / external sort / Grace join filesystem failure.
174 #[error("query spill: {0}")]
175 Spill(String),
176
177 /// Filesystem I/O while reading an RDF ingest file.
178 #[error(transparent)]
179 Io(#[from] std::io::Error),
180
181 /// RDF file extension is not a known syntax (and not a `.gz` wrapper of one).
182 #[error("unsupported RDF format for {}", path.display())]
183 UnsupportedRdfFormat {
184 /// Path whose extension could not be mapped to an RDF syntax.
185 path: std::path::PathBuf,
186 },
187
188 /// Oxigraph parser rejected the RDF input.
189 #[error("failed to parse RDF {}: {source}", path.display())]
190 RdfParse {
191 /// File being parsed.
192 path: std::path::PathBuf,
193 /// Parser failure.
194 #[source]
195 source: oxrdfio::RdfParseError,
196 },
197
198 /// Base IRI derived from the file path (or supplied by the caller) is not valid.
199 #[error("invalid RDF base IRI {iri}: {source}")]
200 InvalidBaseIri {
201 /// IRI that failed to parse.
202 iri: String,
203 /// Parse failure.
204 #[source]
205 source: oxrdf::IriParseError,
206 },
207
208 /// Named-graph IRI supplied for ingest is not a valid IRI.
209 #[error("invalid named graph IRI {iri}: {source}")]
210 InvalidGraphIri {
211 /// IRI that failed to parse.
212 iri: String,
213 /// Parse failure.
214 #[source]
215 source: oxrdf::IriParseError,
216 },
217
218 /// A quad violated a Waratah data-validity rule and was rejected before
219 /// any RPC was sent. Today the single rule: the object of an
220 /// exactly-`rdf:type` predicate must be an IRI or a blank node — RDF
221 /// syntax permits a literal there, but a literal class is semantically
222 /// wrong and the TSG index assumes node-only slot-0 terms (all node
223 /// encodings are exactly 17 bytes). Unconditional on every write path;
224 /// this is a data-validity contract, not a `--strict-sparql` query
225 /// deviation.
226 #[error("invalid quad: {0}")]
227 InvalidQuad(String),
228
229 /// A typed literal violated a plugin data-validity rule and was rejected
230 /// before the failing write chunk issued any RPC.
231 #[error("invalid RDF literal: {0}")]
232 InvalidLiteral(String),
233
234 /// The RDF parser thread panicked.
235 #[error("RDF parser thread panicked")]
236 ParserThreadPanicked,
237
238 /// This compute backend does not accept writes (test mocks without ingest).
239 #[error("RDF ingest is not supported by this backend")]
240 IngestUnsupported,
241}
242
243impl From<ExecError> for ComputeError {
244 fn from(err: ExecError) -> Self {
245 match err {
246 ExecError::TooManyTerms => Self::TooManyTerms,
247 ExecError::ProbeFilter(msg) => Self::UnsupportedSparql(msg),
248 other => Self::UnsupportedSparql(other.to_string()),
249 }
250 }
251}
252
253impl ComputeError {
254 /// Whether a tonic status is worth retrying in MVP (idempotent Put).
255 pub fn is_transient_status(status: &tonic::Status) -> bool {
256 matches!(
257 status.code(),
258 tonic::Code::Unavailable
259 | tonic::Code::DeadlineExceeded
260 | tonic::Code::ResourceExhausted
261 | tonic::Code::Aborted
262 | tonic::Code::Internal
263 )
264 }
265}
266
267/// How many times to retry a transient RPC before giving up.
268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
269pub struct RetryPolicy {
270 /// Total attempts including the first call (must be ≥ 1).
271 pub max_attempts: u32,
272 /// Sleep between attempts (fixed; exponential backoff arrives with Raft).
273 pub backoff: Duration,
274}
275
276impl RetryPolicy {
277 /// Three attempts with a short fixed backoff — enough for flaky local ports.
278 pub fn default_dev() -> Self {
279 Self {
280 max_attempts: 3,
281 backoff: Duration::from_millis(10),
282 }
283 }
284
285 /// Single attempt (unit tests that inject exact failure counts).
286 pub fn none() -> Self {
287 Self {
288 max_attempts: 1,
289 backoff: Duration::ZERO,
290 }
291 }
292}
293
294impl Default for RetryPolicy {
295 fn default() -> Self {
296 Self::default_dev()
297 }
298}
299
300/// Run `call` under `policy`, retrying only transient statuses.
301///
302/// `on_failure` turns the attempt count and last message into the typed error
303/// for that call site (insert, register, scan, resolve).
304pub(crate) async fn with_retry<T, Fut>(
305 policy: RetryPolicy,
306 mut call: impl FnMut() -> Fut,
307 on_failure: impl Fn(u32, String) -> ComputeError,
308) -> Result<T, ComputeError>
309where
310 Fut: Future<Output = Result<T, tonic::Status>>,
311{
312 let mut attempts = 0;
313 let mut last_message = String::new();
314 while attempts < policy.max_attempts {
315 attempts += 1;
316 match call().await {
317 Ok(value) => return Ok(value),
318 Err(status) if ComputeError::is_transient_status(&status) => {
319 last_message = status.to_string();
320 if attempts < policy.max_attempts && !policy.backoff.is_zero() {
321 tokio::time::sleep(policy.backoff).await;
322 }
323 }
324 Err(status) => return Err(on_failure(attempts, status.to_string())),
325 }
326 }
327 Err(on_failure(attempts, last_message))
328}
329
330/// Run `call` under `policy` like [`with_retry`], but stop immediately —
331/// no retry, no backoff — when the failing status carries `escalate_on`,
332/// and hand the status itself back so the caller can switch transport.
333///
334/// Used by the eager scan path: a unary `ResourceExhausted` (response larger
335/// than one gRPC message) is deterministic, so retrying the same unary call
336/// is futile — compute escalates to the streaming endpoint instead. The
337/// failing status is returned (not just its message) so the caller can
338/// branch on the code.
339pub(crate) async fn with_retry_escalate<T, Fut>(
340 policy: RetryPolicy,
341 mut call: impl FnMut() -> Fut,
342 escalate_on: tonic::Code,
343) -> Result<T, (u32, tonic::Status)>
344where
345 Fut: Future<Output = Result<T, tonic::Status>>,
346{
347 let mut attempts = 0;
348 while attempts < policy.max_attempts {
349 attempts += 1;
350 match call().await {
351 Ok(value) => return Ok(value),
352 Err(status) if status.code() == escalate_on => return Err((attempts, status)),
353 Err(status) if ComputeError::is_transient_status(&status) => {
354 if attempts < policy.max_attempts && !policy.backoff.is_zero() {
355 tokio::time::sleep(policy.backoff).await;
356 } else {
357 return Err((attempts, status));
358 }
359 }
360 Err(status) => return Err((attempts, status)),
361 }
362 }
363 Err((
364 attempts,
365 tonic::Status::internal("no scan attempt was made"),
366 ))
367}