1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
// Project: clickhouse-dfe
// File: src/error.rs
// Purpose: Crate error enum, upstream mapping and retry classification
// Language: Rust
//
// License: Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED
//! Contains [`Error`] and corresponding [`Result`].
use serde::{de, ser};
use std::{error::Error as StdError, fmt, io, result, str::Utf8Error};
/// A result with a specified [`Error`] type.
pub type Result<T, E = Error> = result::Result<T, E>;
type BoxedError = Box<dyn StdError + Send + Sync>;
/// Represents all possible errors.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
#[allow(missing_docs)]
pub enum Error {
#[error("invalid params: {0}")]
InvalidParams(#[source] BoxedError),
#[error("network error: {0}")]
Network(#[source] BoxedError),
#[error("compression error: {0}")]
Compression(#[source] BoxedError),
#[error("decompression error: {0}")]
Decompression(#[source] BoxedError),
#[error("no rows returned by a query that expected to return at least one row")]
RowNotFound,
#[error("sequences must have a known size ahead of time")]
SequenceMustHaveLength,
#[error("`deserialize_any` is not supported")]
DeserializeAnyNotSupported,
#[error("not enough data, probably a row type mismatches a database schema")]
NotEnoughData,
#[error("string is not valid utf8")]
InvalidUtf8Encoding(#[from] Utf8Error),
#[error("tag for enum is not valid")]
InvalidTagEncoding(usize),
#[error("max number of types in the Variant data type is 255, got {0}")]
VariantDiscriminatorIsOutOfBound(usize),
#[error("a custom error message from serde: {0}")]
Custom(String),
/// Background worker task exited; the inserter is no longer
/// accepting commands. Terminal: construct a fresh inserter,
/// don't retry the same handle.
#[error("background worker task has exited; the inserter is no longer accepting commands")]
WorkerExited,
/// Structured server-side exception parsed from the response.
/// Preferred over [`Error::BadResponse`] when the server returned
/// a recognisable `Code: NNN. DB::Exception: ...` body. Callers
/// can match on `code` for typed handling and use
/// [`Error::is_retriable`] for conservative retry classification.
#[error("server error code {code}: {message}")]
ServerException {
/// `X-ClickHouse-Exception-Code` from the response header.
/// Signed `int` on the wire (cpp-client + server source);
/// codes are small positives in practice.
code: i32,
/// Exception name extracted from `(UPPERCASE_NAME)` near
/// the end of the message. `None` when the parser couldn't
/// recognise it (older CH versions, custom error paths).
name: Option<String>,
/// Cleaned message body, stripped of the `Code: N.`,
/// `DB::Exception:` prefix, exception-name parens, and
/// `(version ...)` suffix.
message: String,
/// Server-side stack trace if `Stack trace:` was present in
/// the body.
stack_trace: Option<String>,
},
#[error("bad response: {0}")]
BadResponse(String),
/// A transport-level failure that a fresh attempt may not hit --
/// a pool-acquire timeout, a closed pool, a hook failure. Typed so
/// retry classification does not have to match on message text.
#[error("transient transport failure: {0}")]
Transient(String),
/// A connection could not be opened: an unresolvable host, a host
/// that resolved to no addresses, an empty endpoint list. Typed for
/// the same reason as [`Error::Transient`].
#[error("connect failed: {0}")]
Connect(String),
#[error("timeout expired")]
TimedOut,
#[error("error while parsing columns header from the response: {0}")]
InvalidColumnsHeader(#[source] BoxedError),
#[error("schema mismatch: {0}")]
SchemaMismatch(String),
#[error("unsupported: {0}")]
Unsupported(String),
/// A dynamic-insert failure, kept typed so a caller can tell a stale
/// schema (re-fetch and retry) from a permanent rejection.
#[cfg(feature = "dynamic")]
#[cfg_attr(docsrs, doc(cfg(feature = "dynamic")))]
#[error(transparent)]
Dynamic(#[from] crate::dynamic::DynamicError),
#[error("{0}")]
Other(BoxedError),
}
// Variant-by-variant where the name matches, `Other` otherwise.
// Upstream's enum is `#[non_exhaustive]`, so a variant added there later
// lands in `Other` until this mapping is extended.
impl From<clickhouse::error::Error> for Error {
fn from(error: clickhouse::error::Error) -> Self {
use clickhouse::error::Error as Up;
match error {
Up::InvalidParams(e) => Self::InvalidParams(e),
Up::Network(e) => Self::Network(e),
Up::Compression(e) => Self::Compression(e),
Up::Decompression(e) => Self::Decompression(e),
Up::RowNotFound => Self::RowNotFound,
Up::SequenceMustHaveLength => Self::SequenceMustHaveLength,
Up::DeserializeAnyNotSupported => Self::DeserializeAnyNotSupported,
Up::NotEnoughData => Self::NotEnoughData,
Up::InvalidUtf8Encoding(e) => Self::InvalidUtf8Encoding(e),
Up::InvalidTagEncoding(n) => Self::InvalidTagEncoding(n),
Up::VariantDiscriminatorIsOutOfBound(n) => Self::VariantDiscriminatorIsOutOfBound(n),
Up::Custom(s) => Self::Custom(s),
Up::BadResponse(s) => Self::BadResponse(s),
Up::TimedOut => Self::TimedOut,
Up::InvalidColumnsHeader(e) => Self::InvalidColumnsHeader(e),
Up::SchemaMismatch(s) => Self::SchemaMismatch(s),
Up::Unsupported(s) => Self::Unsupported(s),
other => Self::Other(Box::new(other)),
}
}
}
impl ser::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Self {
Self::Custom(msg.to_string())
}
}
impl de::Error for Error {
fn custom<T: fmt::Display>(msg: T) -> Self {
Self::Custom(msg.to_string())
}
}
impl From<Error> for io::Error {
fn from(error: Error) -> Self {
io::Error::other(error)
}
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Self {
// Unwraps an `Error` this crate boxed on the way out, so a round trip
// through `io::Error` keeps the variant.
match error.downcast::<Self>() {
Ok(inner) => inner,
Err(other) => Self::Other(other.into()),
}
}
}
impl Error {
/// Conservative retriability classification.
///
/// Returns `true` for errors that *might* succeed on retry --
/// transport-level (`Network`, `TimedOut`, `Transient`, `Connect`),
/// a known set of transient server-side codes, and the dynamic-insert
/// failures that clear once the schema is re-read.
///
/// Returns `false` for everything else, including unknown server codes:
/// a caller wanting a more aggressive retry should match on the variant.
/// The code table is [`is_retriable_code`][Self::is_retriable_code].
#[must_use]
pub fn is_retriable(&self) -> bool {
match self {
// `Transient` and `Connect` are only ever built for a
// condition a fresh attempt may not hit, so they classify
// here rather than on their message text.
Self::Network(_) | Self::TimedOut | Self::Transient(_) | Self::Connect(_) => true,
Self::ServerException { code, .. } => Self::is_retriable_code(*code),
// A stale, missing or unreadable schema is fixed by re-reading it;
// an unsupported type or a bad value is not.
#[cfg(feature = "dynamic")]
Self::Dynamic(e) => matches!(
e,
crate::dynamic::DynamicError::SchemaFetch { .. }
| crate::dynamic::DynamicError::SchemaMismatch { .. }
| crate::dynamic::DynamicError::EmptySchema { .. }
),
_ => false,
}
}
/// ClickHouse error codes considered transient for retry. See
/// `src/Common/ErrorCodes.cpp` upstream for the canonical list.
/// Conservative -- false negatives are expected, false positives
/// should be rare. Each entry names its upstream macro.
#[must_use]
pub fn is_retriable_code(code: i32) -> bool {
matches!(
code,
// TIMEOUT_EXCEEDED
159 |
// TOO_SLOW (merge queue lag; usually transient)
160 |
// TOO_MANY_SIMULTANEOUS_QUERIES
202 |
// SOCKET_TIMEOUT
209 |
// NETWORK_ERROR
210 |
// ABORTED (operator KILL or shutdown -- replayable on
// another node)
236 |
// MEMORY_LIMIT_EXCEEDED (often transient under brief
// memory pressure)
241 |
// TOO_MANY_PARTS (transient under heavy ingest)
252 |
// ALL_CONNECTION_TRIES_FAILED
279 |
// LIMIT_EXCEEDED (transient quota)
290 |
// UNKNOWN_STATUS_OF_INSERT (the "did my INSERT land?"
// ambiguity code -- documented mitigation is retry with
// an insert_deduplication_token, which the
// batch_isolation token variant ships)
319 |
// RECEIVED_ERROR_TOO_MANY_REQUESTS (server proxied a 429
// from a downstream resource -- S3, Kafka, HTTP storage)
364 |
// PART_IS_TEMPORARILY_LOCKED (mutate/merge contention)
384 |
// CANNOT_SCHEDULE_TASK (task scheduler full)
439 |
// DEADLOCK_AVOIDED (server-side avoidance; succeeds on retry)
473 |
// UNKNOWN_STATUS_OF_TRANSACTION (transaction analogue of
// UNKNOWN_STATUS_OF_INSERT -- same "did it land?" ambiguity)
659 |
// TOO_MANY_UNAVAILABLE_SHARDS (transient cluster condition)
904 |
// KEEPER_EXCEPTION (replicated-metadata hiccup)
999
)
}
}
#[cfg(test)]
mod tests {
use crate::error::Error;
use std::io;
#[test]
fn roundtrip_io_error() {
let orig = Error::NotEnoughData;
// Error -> io::Error
let orig_str = orig.to_string();
let io = io::Error::from(orig);
assert_eq!(io.kind(), io::ErrorKind::Other);
assert_eq!(io.to_string(), orig_str);
// io::Error -> Error
let orig = Error::from(io);
assert!(matches!(orig, Error::NotEnoughData));
}
#[test]
fn error_traits() {
fn assert_traits<T: std::error::Error + Send + Sync>() {}
assert_traits::<Error>();
}
#[test]
fn is_retriable_classifies_known_transient_codes() {
let make = |code: i32| Error::ServerException {
code,
name: None,
message: String::new(),
stack_trace: None,
};
// Sampled from the retriable table -- known transient codes.
for &code in &[
159i32, 160, 202, 209, 210, 236, 241, 252, 279, 290, 319, 364, 384, 439, 473, 659, 904,
999,
] {
assert!(make(code).is_retriable(), "code {code} should be retriable");
}
// Sampled known-not-retriable codes (auth, schema, parse).
for &code in &[36i32, 60, 117, 192, 195, 469] {
assert!(
!make(code).is_retriable(),
"code {code} should NOT be retriable"
);
}
}
#[test]
fn is_retriable_for_transport_errors() {
assert!(Error::TimedOut.is_retriable());
assert!(Error::Transient("pool acquire timed out".into()).is_retriable());
assert!(Error::Connect("no address for host".into()).is_retriable());
// A foreign `io::Error` lands in `Other`, which stays terminal.
let foreign: Error = io::Error::new(io::ErrorKind::ConnectionReset, "reset").into();
assert!(!foreign.is_retriable());
}
#[test]
fn is_retriable_code_defaults_unknown_to_not_retriable() {
// A ClickHouse release can ship codes this table has never seen; until
// it is extended, a caller sees them as terminal rather than looping.
for &code in &[0i32, 1, 12345, 99999, i32::MAX] {
assert!(
!Error::is_retriable_code(code),
"unknown code {code} should default to NOT retriable"
);
}
}
/// The consumer branches on this to decide between re-reading the schema
/// and dead-lettering the batch, so the split has to hold.
#[cfg(feature = "dynamic")]
#[test]
fn dynamic_schema_failures_are_retriable_but_bad_data_is_not() {
use crate::dynamic::DynamicError;
let retriable = [
DynamicError::EmptySchema {
table: "db.t".into(),
},
DynamicError::SchemaMismatch {
table: "db.t".into(),
message: "drift".into(),
},
DynamicError::SchemaFetch {
table: "db.t".into(),
source: clickhouse::error::Error::TimedOut,
},
];
for e in retriable {
assert!(Error::from(e).is_retriable());
}
let terminal = [
DynamicError::UnsupportedType {
column: "c".into(),
type_str: "Point".into(),
},
DynamicError::EncodingError {
column: "c".into(),
message: "UInt8 value out of range".into(),
},
];
for e in terminal {
assert!(!Error::from(e).is_retriable());
}
}
/// `#[error(transparent)]`, so the wrapper adds no prefix and `source()`
/// reaches the original query failure.
#[cfg(feature = "dynamic")]
#[test]
fn dynamic_errors_pass_through_display_and_source() {
use std::error::Error as _;
let err = Error::from(crate::dynamic::DynamicError::SchemaFetch {
table: "db.t".into(),
source: clickhouse::error::Error::TimedOut,
});
assert_eq!(
err.to_string(),
"failed to fetch schema for 'db.t': timeout expired"
);
// `transparent` forwards `source()`, so the query failure is reachable.
let source = err.source().expect("the query failure is the source");
assert_eq!(source.to_string(), "timeout expired");
}
}