Skip to main content

riffdb_client_rust/
status.rs

1//! Fail-closed validation of public gRPC failures.
2
3use std::error::Error;
4use std::fmt;
5
6use riffdb_errors::{
7    ApplicationError, ApplicationErrorCode, MAX_APPLICATION_ERROR_BYTES, PublicError,
8    PublicErrorKind, PublicErrorStatusCode,
9};
10use riffdb_proto::{
11    ApplicationErrorWireError, MAX_PUBLIC_ERROR_BYTES, PublicErrorWireError,
12    decode_application_error, decode_public_error,
13};
14use tonic::{Code, Status};
15
16use crate::ids::IdentifierGenerationError;
17
18const AUTHENTICATION_FAILED: &str = "authentication failed";
19const REQUEST_CANCELLED: &str = "request was cancelled";
20const REQUEST_DEADLINE_ELAPSED: &str = "request deadline elapsed";
21const RESPONSE_TOO_LARGE: &str = "response exceeds the service limit";
22const EMERGENCY_INTERNAL: &str = "an internal error occurred";
23const TONIC_MISSING_STATUS_TRAILER: &str = "protocol error: missing grpc-status trailer, stream was terminated without a final status (possible truncation by a proxy or load balancer)";
24const TONIC_UNEXPECTED_EOF: &str = "Unexpected EOF decoding stream.";
25
26/// A valid details-free status from a closed non-`PublicError` boundary.
27#[derive(Clone, Copy, Debug, Eq, PartialEq)]
28pub enum DetailsFreeStatus {
29    /// Authentication failed before an API-neutral request context existed.
30    Unauthenticated,
31    /// Cancellation was proven before the applicable admission boundary.
32    Cancelled,
33    /// The request deadline elapsed before a protected result was released.
34    DeadlineExceeded,
35    /// One complete service result exceeded the response budget.
36    ResponseTooLarge,
37    /// Internal containment could not obtain a real incident identifier.
38    EmergencyInternal,
39    /// The transport became unavailable without a structured server result.
40    TransportUnavailable,
41}
42
43/// The closed reason an untrusted gRPC failure was rejected.
44#[derive(Clone, Copy, Debug, Eq, PartialEq)]
45pub enum ProtocolFailureKind {
46    /// A status that requires `PublicError` detail carried none.
47    MissingPublicErrorDetails,
48    /// Structured detail exceeded the exact 16 KiB ceiling.
49    OversizedPublicErrorDetails,
50    /// Structured detail was not valid Protobuf.
51    MalformedPublicErrorDetails,
52    /// Structured detail named an unknown public-error kind.
53    UnknownPublicErrorKind,
54    /// Structured detail violated its closed field/detail invariants.
55    InvalidPublicErrorDetails,
56    /// The gRPC code disagreed with the checked public error class.
57    StatusCodeMismatch,
58    /// `grpc-message` disagreed with the checked registry-owned safe message.
59    StatusMessageMismatch,
60    /// A details-free closed status carried an unrecognized code/message pair.
61    InvalidDetailsFreeStatus,
62    /// A request built by the caller failed public structural validation.
63    InvalidOutboundMessage,
64    /// A successful response or stream item failed public structural validation.
65    InvalidInboundMessage,
66    /// An application RPC carried no application error details.
67    MissingApplicationErrorDetails,
68    /// Application error details exceeded their exact ceiling.
69    OversizedApplicationErrorDetails,
70    /// Application error details were malformed or noncanonical.
71    InvalidApplicationErrorDetails,
72    /// The application status code disagreed with its checked semantic code.
73    ApplicationStatusCodeMismatch,
74    /// The application status message disagreed with its registry-owned message.
75    ApplicationStatusMessageMismatch,
76}
77
78/// A bounded protocol failure containing no peer-provided text or bytes.
79#[derive(Clone, Copy, Debug, Eq, PartialEq)]
80pub struct ProtocolFailure {
81    kind: ProtocolFailureKind,
82}
83
84impl ProtocolFailure {
85    pub(crate) const fn new(kind: ProtocolFailureKind) -> Self {
86        Self { kind }
87    }
88
89    /// Returns the closed validation failure kind.
90    #[must_use]
91    pub const fn kind(self) -> ProtocolFailureKind {
92        self.kind
93    }
94}
95
96impl fmt::Display for ProtocolFailure {
97    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98        formatter.write_str("the RiffDB gRPC peer returned an invalid protocol response")
99    }
100}
101
102impl Error for ProtocolFailure {}
103
104/// The public client's explicit unresolved idempotent-operation disposition.
105#[derive(Clone, Copy, Debug, Eq, PartialEq)]
106pub struct OutcomeUnknown;
107
108impl fmt::Display for OutcomeUnknown {
109    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
110        formatter.write_str("the command outcome remains unknown")
111    }
112}
113
114impl Error for OutcomeUnknown {}
115
116/// A closed failure returned by the Rust SDK.
117#[derive(Debug)]
118pub enum ClientError {
119    /// A fully checked public-safe RiffDB failure.
120    Public(PublicError),
121    /// A fully checked symbolic application failure.
122    Application(Box<ApplicationError>),
123    /// A valid status from a closed details-free boundary.
124    DetailsFree(DetailsFreeStatus),
125    /// The peer violated the public gRPC contract.
126    Protocol(ProtocolFailure),
127    /// A local UUIDv7 source failed before the next submission.
128    IdentifierGeneration(IdentifierGenerationError),
129    /// Channel construction or connection failed before a typed response existed.
130    ConnectionFailure,
131    /// Verified TLS configuration, trust-root, connection, or peer failure.
132    Tls(crate::TlsClientFailure),
133    /// Automatic same-input recovery exhausted its explicit attempt budget.
134    OutcomeUnknown(OutcomeUnknown),
135}
136
137impl ClientError {
138    /// Validates an untrusted non-OK gRPC status without trusting its message.
139    #[must_use]
140    pub fn from_status(status: Status) -> Self {
141        checked_status(status)
142    }
143
144    /// Returns a checked public error, when this is one.
145    #[must_use]
146    pub const fn public_error(&self) -> Option<&PublicError> {
147        match self {
148            Self::Public(error) => Some(error),
149            Self::Application(_)
150            | Self::DetailsFree(_)
151            | Self::Protocol(_)
152            | Self::IdentifierGeneration(_)
153            | Self::ConnectionFailure
154            | Self::Tls(_)
155            | Self::OutcomeUnknown(_) => None,
156        }
157    }
158
159    /// Returns a checked symbolic application failure, when this is one.
160    #[must_use]
161    pub const fn application_error(&self) -> Option<&ApplicationError> {
162        match self {
163            Self::Application(error) => Some(error),
164            Self::Public(_)
165            | Self::DetailsFree(_)
166            | Self::Protocol(_)
167            | Self::IdentifierGeneration(_)
168            | Self::ConnectionFailure
169            | Self::Tls(_)
170            | Self::OutcomeUnknown(_) => None,
171        }
172    }
173}
174
175impl fmt::Display for ClientError {
176    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
177        match self {
178            Self::Public(error) => error.fmt(formatter),
179            Self::Application(error) => error.fmt(formatter),
180            Self::DetailsFree(status) => formatter.write_str(match status {
181                DetailsFreeStatus::Unauthenticated => AUTHENTICATION_FAILED,
182                DetailsFreeStatus::Cancelled => REQUEST_CANCELLED,
183                DetailsFreeStatus::DeadlineExceeded => REQUEST_DEADLINE_ELAPSED,
184                DetailsFreeStatus::ResponseTooLarge => RESPONSE_TOO_LARGE,
185                DetailsFreeStatus::EmergencyInternal => EMERGENCY_INTERNAL,
186                DetailsFreeStatus::TransportUnavailable => "the gRPC transport is unavailable",
187            }),
188            Self::Protocol(error) => error.fmt(formatter),
189            Self::IdentifierGeneration(error) => error.fmt(formatter),
190            Self::ConnectionFailure => formatter.write_str("the gRPC channel could not connect"),
191            Self::Tls(error) => error.fmt(formatter),
192            Self::OutcomeUnknown(error) => error.fmt(formatter),
193        }
194    }
195}
196
197impl Error for ClientError {}
198
199pub(crate) fn checked_status(status: Status) -> ClientError {
200    let details = status.details();
201    if details.is_empty() {
202        return checked_details_free_status(
203            status.code(),
204            status.message(),
205            Error::source(&status).is_some(),
206        );
207    }
208    if details.len() > MAX_PUBLIC_ERROR_BYTES {
209        return protocol(ProtocolFailureKind::OversizedPublicErrorDetails);
210    }
211
212    let error = match decode_public_error(details) {
213        Ok(error) => error,
214        Err(error) => return protocol(map_wire_error(error)),
215    };
216    if status.code() != code_for_public_error(&error) {
217        return protocol(ProtocolFailureKind::StatusCodeMismatch);
218    }
219    if status.message() != error.safe_message() {
220        return protocol(ProtocolFailureKind::StatusMessageMismatch);
221    }
222    ClientError::Public(error)
223}
224
225pub(crate) fn checked_application_status(status: Status) -> ClientError {
226    let details = status.details();
227    if details.is_empty() {
228        let checked = checked_details_free_status(
229            status.code(),
230            status.message(),
231            Error::source(&status).is_some(),
232        );
233        return match checked {
234            ClientError::DetailsFree(DetailsFreeStatus::EmergencyInternal)
235            | ClientError::DetailsFree(DetailsFreeStatus::TransportUnavailable) => checked,
236            _ => protocol(ProtocolFailureKind::MissingApplicationErrorDetails),
237        };
238    }
239    if details.len() > MAX_APPLICATION_ERROR_BYTES {
240        return protocol(ProtocolFailureKind::OversizedApplicationErrorDetails);
241    }
242    let error = match decode_application_error(details) {
243        Ok(error) => error,
244        Err(error) => return protocol(map_application_wire_error(error)),
245    };
246    if status.code() != code_for_application(error.code()) {
247        return protocol(ProtocolFailureKind::ApplicationStatusCodeMismatch);
248    }
249    if status.message() != error.safe_message() {
250        return protocol(ProtocolFailureKind::ApplicationStatusMessageMismatch);
251    }
252    ClientError::Application(Box::new(error))
253}
254
255fn checked_details_free_status(code: Code, message: &str, has_local_source: bool) -> ClientError {
256    let status = match (code, message) {
257        (Code::Unauthenticated, AUTHENTICATION_FAILED) => DetailsFreeStatus::Unauthenticated,
258        (Code::Cancelled, REQUEST_CANCELLED) => DetailsFreeStatus::Cancelled,
259        (Code::DeadlineExceeded, REQUEST_DEADLINE_ELAPSED) => DetailsFreeStatus::DeadlineExceeded,
260        (Code::ResourceExhausted, RESPONSE_TOO_LARGE) => DetailsFreeStatus::ResponseTooLarge,
261        (Code::Internal, EMERGENCY_INTERNAL) => DetailsFreeStatus::EmergencyInternal,
262        // Tonic attaches a source to most locally synthesized transport errors,
263        // and synthesizes exact source-free statuses when an HTTP/2 response
264        // stream terminates mid-body or before the trailing grpc-status frame.
265        (Code::Unknown, TONIC_MISSING_STATUS_TRAILER) | (Code::Internal, TONIC_UNEXPECTED_EOF) => {
266            DetailsFreeStatus::TransportUnavailable
267        }
268        (_, _) if has_local_source => DetailsFreeStatus::TransportUnavailable,
269        (
270            _,
271            AUTHENTICATION_FAILED
272            | REQUEST_CANCELLED
273            | REQUEST_DEADLINE_ELAPSED
274            | RESPONSE_TOO_LARGE
275            | EMERGENCY_INTERNAL,
276        ) => {
277            return protocol(ProtocolFailureKind::InvalidDetailsFreeStatus);
278        }
279        _ => return protocol(ProtocolFailureKind::MissingPublicErrorDetails),
280    };
281    ClientError::DetailsFree(status)
282}
283
284const fn code_for_public_error(error: &PublicError) -> Code {
285    tonic_code(error.status_code())
286}
287
288const fn tonic_code(code: PublicErrorStatusCode) -> Code {
289    match code {
290        PublicErrorStatusCode::InvalidArgument => Code::InvalidArgument,
291        PublicErrorStatusCode::AlreadyExists => Code::AlreadyExists,
292        PublicErrorStatusCode::PermissionDenied => Code::PermissionDenied,
293        PublicErrorStatusCode::DeadlineExceeded => Code::DeadlineExceeded,
294        PublicErrorStatusCode::FailedPrecondition => Code::FailedPrecondition,
295        PublicErrorStatusCode::ResourceExhausted => Code::ResourceExhausted,
296        PublicErrorStatusCode::Unavailable => Code::Unavailable,
297        PublicErrorStatusCode::Unknown => Code::Unknown,
298        PublicErrorStatusCode::Internal => Code::Internal,
299    }
300}
301
302const fn code_for_application(code: ApplicationErrorCode) -> Code {
303    match code {
304        ApplicationErrorCode::InvalidRequest
305        | ApplicationErrorCode::InputInvalid
306        | ApplicationErrorCode::QueryInvalid
307        | ApplicationErrorCode::CursorInvalid => Code::InvalidArgument,
308        ApplicationErrorCode::AuthorizationDenied | ApplicationErrorCode::CapabilityRevoked => {
309            Code::PermissionDenied
310        }
311        ApplicationErrorCode::ContractMismatch
312        | ApplicationErrorCode::QueryUnavailable
313        | ApplicationErrorCode::ModuleUnavailable
314        | ApplicationErrorCode::CommandExecutionFailed
315        | ApplicationErrorCode::HistoryIncarnationMismatch
316        | ApplicationErrorCode::FollowerMode
317        | ApplicationErrorCode::PrimaryFenced
318        | ApplicationErrorCode::HistoryPruned
319        | ApplicationErrorCode::ProjectionDiverged
320        | ApplicationErrorCode::SnapshotRetired
321        | ApplicationErrorCode::FreshnessUnsatisfied
322        | ApplicationErrorCode::ProjectedSourceRequired => Code::FailedPrecondition,
323        ApplicationErrorCode::ResponseTooLarge | ApplicationErrorCode::Overloaded => {
324            Code::ResourceExhausted
325        }
326        ApplicationErrorCode::StorageUnavailable => Code::Unavailable,
327        ApplicationErrorCode::OutcomeUnknown => Code::Unknown,
328        ApplicationErrorCode::OperationCancelled => Code::Cancelled,
329        ApplicationErrorCode::DeadlineExceeded => Code::DeadlineExceeded,
330        ApplicationErrorCode::InternalDefect | ApplicationErrorCode::ProtocolInvalid => {
331            Code::Internal
332        }
333        ApplicationErrorCode::IdempotencyKeyReuse => Code::AlreadyExists,
334    }
335}
336
337const fn map_wire_error(error: PublicErrorWireError) -> ProtocolFailureKind {
338    match error {
339        PublicErrorWireError::MessageTooLarge => ProtocolFailureKind::OversizedPublicErrorDetails,
340        PublicErrorWireError::MalformedEncoding | PublicErrorWireError::PreflightLimitExceeded => {
341            ProtocolFailureKind::MalformedPublicErrorDetails
342        }
343        PublicErrorWireError::UnknownKind => ProtocolFailureKind::UnknownPublicErrorKind,
344        PublicErrorWireError::InconsistentBoundary
345        | PublicErrorWireError::InvalidIncidentId
346        | PublicErrorWireError::MissingInternalIncident
347        | PublicErrorWireError::InvalidValidationDetails
348        | PublicErrorWireError::InvalidContractMismatchDetails
349        | PublicErrorWireError::InvalidExecutionFailureDetails => {
350            ProtocolFailureKind::InvalidPublicErrorDetails
351        }
352    }
353}
354
355const fn map_application_wire_error(error: ApplicationErrorWireError) -> ProtocolFailureKind {
356    match error {
357        ApplicationErrorWireError::MessageTooLarge => {
358            ProtocolFailureKind::OversizedApplicationErrorDetails
359        }
360        ApplicationErrorWireError::MalformedEncoding
361        | ApplicationErrorWireError::PreflightLimitExceeded
362        | ApplicationErrorWireError::UnknownField
363        | ApplicationErrorWireError::DuplicateField
364        | ApplicationErrorWireError::UnknownCode
365        | ApplicationErrorWireError::UnknownOperation
366        | ApplicationErrorWireError::UnknownFix
367        | ApplicationErrorWireError::InconsistentRegistry
368        | ApplicationErrorWireError::InvalidContext
369        | ApplicationErrorWireError::MissingInternalIncident => {
370            ProtocolFailureKind::InvalidApplicationErrorDetails
371        }
372    }
373}
374
375const fn protocol(kind: ProtocolFailureKind) -> ClientError {
376    ClientError::Protocol(ProtocolFailure::new(kind))
377}
378
379pub(crate) const fn is_retryable(error: &ClientError) -> bool {
380    match error {
381        ClientError::Public(error) => matches!(
382            error.recovery_action(),
383            riffdb_errors::RecoveryAction::Retry
384                | riffdb_errors::RecoveryAction::ResolveWithSameIdempotencyKey
385        ),
386        ClientError::Application(error) => matches!(
387            error.recovery_action(),
388            riffdb_errors::ApplicationRecoveryAction::Retry
389                | riffdb_errors::ApplicationRecoveryAction::ResolveWithSameIdempotencyKey
390        ),
391        ClientError::DetailsFree(DetailsFreeStatus::TransportUnavailable) => true,
392        ClientError::DetailsFree(_)
393        | ClientError::Protocol(_)
394        | ClientError::IdentifierGeneration(_)
395        | ClientError::ConnectionFailure
396        | ClientError::Tls(_)
397        | ClientError::OutcomeUnknown(_) => false,
398    }
399}
400
401pub(crate) const fn carries_uncertainty(error: &ClientError) -> bool {
402    matches!(
403        error,
404        ClientError::Public(error) if matches!(error.kind(), PublicErrorKind::OutcomeUnknown)
405    ) || matches!(
406        error,
407        ClientError::Application(error)
408            if matches!(error.code(), ApplicationErrorCode::OutcomeUnknown)
409    ) || matches!(
410        error,
411        ClientError::DetailsFree(DetailsFreeStatus::TransportUnavailable)
412            | ClientError::OutcomeUnknown(_)
413    )
414}
415
416#[cfg(test)]
417mod tests {
418    use std::sync::Arc;
419
420    use riffdb_errors::ErrorClass;
421
422    use super::*;
423
424    #[derive(Debug)]
425    struct LocalTransportFailure;
426
427    impl fmt::Display for LocalTransportFailure {
428        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
429            formatter.write_str("local channel failure")
430        }
431    }
432
433    impl Error for LocalTransportFailure {}
434
435    #[test]
436    fn details_free_boundaries_require_exact_code_and_static_message() {
437        assert!(matches!(
438            checked_status(Status::new(Code::Unauthenticated, AUTHENTICATION_FAILED)),
439            ClientError::DetailsFree(DetailsFreeStatus::Unauthenticated)
440        ));
441        assert!(matches!(
442            checked_status(Status::new(Code::ResourceExhausted, RESPONSE_TOO_LARGE)),
443            ClientError::DetailsFree(DetailsFreeStatus::ResponseTooLarge)
444        ));
445        assert!(matches!(
446            checked_status(Status::new(Code::Internal, RESPONSE_TOO_LARGE)),
447            ClientError::Protocol(ProtocolFailure {
448                kind: ProtocolFailureKind::InvalidDetailsFreeStatus
449            })
450        ));
451    }
452
453    #[test]
454    fn source_free_unavailable_without_public_error_details_fails_closed() {
455        let canary = "peer supplied diagnostic secret";
456        let error = checked_status(Status::new(Code::Unavailable, canary));
457        assert!(!error.to_string().contains(canary));
458        assert!(!is_retryable(&error));
459        assert!(!carries_uncertainty(&error));
460        assert_protocol_kind(error, ProtocolFailureKind::MissingPublicErrorDetails);
461    }
462
463    #[test]
464    fn source_bearing_local_unavailable_is_transport_loss_without_trusting_message() {
465        let canary = "local diagnostic secret";
466        let mut status = Status::new(Code::Unavailable, canary);
467        status.set_source(Arc::new(LocalTransportFailure));
468        let error = checked_status(status);
469        assert!(matches!(
470            &error,
471            ClientError::DetailsFree(DetailsFreeStatus::TransportUnavailable)
472        ));
473        assert!(is_retryable(&error));
474        assert!(carries_uncertainty(&error));
475        assert!(!error.to_string().contains(canary));
476    }
477
478    #[test]
479    fn source_bearing_local_h2_protocol_failure_is_transport_loss() {
480        let canary = "local h2 response-frame diagnostic";
481        let mut status = Status::new(Code::Internal, canary);
482        status.set_source(Arc::new(LocalTransportFailure));
483        let error = checked_status(status);
484        assert!(matches!(
485            &error,
486            ClientError::DetailsFree(DetailsFreeStatus::TransportUnavailable)
487        ));
488        assert!(is_retryable(&error));
489        assert!(carries_uncertainty(&error));
490        assert!(!error.to_string().contains(canary));
491
492        let source_free = checked_status(Status::new(Code::Internal, canary));
493        assert_protocol_kind(source_free, ProtocolFailureKind::MissingPublicErrorDetails);
494    }
495
496    #[test]
497    fn tonic_stream_truncation_statuses_map_to_transport_unavailable() {
498        for status in [
499            Status::new(Code::Unknown, TONIC_MISSING_STATUS_TRAILER),
500            Status::new(Code::Internal, TONIC_UNEXPECTED_EOF),
501        ] {
502            let public_checked = checked_status(status.clone());
503            assert!(matches!(
504                &public_checked,
505                ClientError::DetailsFree(DetailsFreeStatus::TransportUnavailable)
506            ));
507            assert!(is_retryable(&public_checked));
508            assert!(carries_uncertainty(&public_checked));
509            assert!(!public_checked.to_string().contains(status.message()));
510
511            let app_checked = checked_application_status(status);
512            assert!(matches!(
513                &app_checked,
514                ClientError::DetailsFree(DetailsFreeStatus::TransportUnavailable)
515            ));
516            assert!(is_retryable(&app_checked));
517            assert!(carries_uncertainty(&app_checked));
518        }
519
520        assert_protocol_kind(
521            checked_status(Status::new(Code::Internal, TONIC_MISSING_STATUS_TRAILER)),
522            ProtocolFailureKind::MissingPublicErrorDetails,
523        );
524        assert_protocol_kind(
525            checked_application_status(Status::new(Code::Unknown, TONIC_UNEXPECTED_EOF)),
526            ProtocolFailureKind::MissingApplicationErrorDetails,
527        );
528    }
529
530    #[test]
531    fn missing_malformed_and_oversized_details_fail_closed() {
532        assert_protocol_kind(
533            checked_status(Status::new(Code::PermissionDenied, "authorization denied")),
534            ProtocolFailureKind::MissingPublicErrorDetails,
535        );
536        assert_protocol_kind(
537            checked_status(Status::with_details(
538                Code::PermissionDenied,
539                "authorization denied",
540                vec![0xff].into(),
541            )),
542            ProtocolFailureKind::MalformedPublicErrorDetails,
543        );
544        assert_protocol_kind(
545            checked_status(Status::with_details(
546                Code::PermissionDenied,
547                "authorization denied",
548                vec![0_u8; MAX_PUBLIC_ERROR_BYTES + 1].into(),
549            )),
550            ProtocolFailureKind::OversizedPublicErrorDetails,
551        );
552    }
553
554    #[test]
555    fn checked_public_error_requires_consistent_status_and_message() {
556        let details = authorization_denied_bytes();
557        let checked = checked_status(Status::with_details(
558            Code::PermissionDenied,
559            "operation is not authorized",
560            details.clone().into(),
561        ));
562        assert!(matches!(
563            checked,
564            ClientError::Public(ref error)
565                if error.kind() == PublicErrorKind::AuthorizationDenied
566        ));
567
568        assert_protocol_kind(
569            checked_status(Status::with_details(
570                Code::InvalidArgument,
571                "operation is not authorized",
572                details.clone().into(),
573            )),
574            ProtocolFailureKind::StatusCodeMismatch,
575        );
576        assert_protocol_kind(
577            checked_status(Status::with_details(
578                Code::PermissionDenied,
579                "caller supplied text",
580                details.into(),
581            )),
582            ProtocolFailureKind::StatusMessageMismatch,
583        );
584    }
585
586    #[test]
587    fn checked_application_error_rejects_downgrade_status_and_message_drift() {
588        let application = ApplicationError::new(
589            ApplicationErrorCode::AuthorizationDenied,
590            riffdb_errors::ApplicationOperation::ExecuteQuery,
591            riffdb_errors::ApplicationErrorContext::empty(),
592            None,
593        );
594        let details = riffdb_proto::encode_application_error(&application);
595        let checked = checked_application_status(Status::with_details(
596            Code::PermissionDenied,
597            application.safe_message(),
598            details.clone().into(),
599        ));
600        assert!(matches!(
601            checked,
602            ClientError::Application(ref error) if error.as_ref() == &application
603        ));
604        assert_protocol_kind(
605            checked_application_status(Status::with_details(
606                Code::InvalidArgument,
607                application.safe_message(),
608                details.clone().into(),
609            )),
610            ProtocolFailureKind::ApplicationStatusCodeMismatch,
611        );
612        assert_protocol_kind(
613            checked_application_status(Status::with_details(
614                Code::PermissionDenied,
615                "peer supplied authorization detail",
616                details.into(),
617            )),
618            ProtocolFailureKind::ApplicationStatusMessageMismatch,
619        );
620
621        let legacy_kernel_details = authorization_denied_bytes();
622        assert_protocol_kind(
623            checked_application_status(Status::with_details(
624                Code::PermissionDenied,
625                "operation is not authorized",
626                legacy_kernel_details.into(),
627            )),
628            ProtocolFailureKind::InvalidApplicationErrorDetails,
629        );
630    }
631
632    #[test]
633    fn concurrency_deadline_status_preserves_the_complete_retry_contract() {
634        let details = contextless_error_bytes(
635            4,
636            "concurrency_deadline_exceeded",
637            "concurrency deadline exceeded",
638            2,
639        );
640        let checked = checked_status(Status::with_details(
641            Code::DeadlineExceeded,
642            "concurrency deadline exceeded",
643            details.into(),
644        ));
645        let ClientError::Public(error) = checked else {
646            panic!("checked public error")
647        };
648        assert_eq!(error.kind(), PublicErrorKind::ConcurrencyDeadlineExceeded);
649        assert_eq!(error.code(), "concurrency_deadline_exceeded");
650        assert_eq!(error.safe_message(), "concurrency deadline exceeded");
651        assert_eq!(
652            error.recovery_action(),
653            riffdb_errors::RecoveryAction::Retry
654        );
655        assert_eq!(error.class(), ErrorClass::DeadlineExceeded);
656    }
657
658    #[test]
659    fn unknown_public_error_kind_never_becomes_retryable() {
660        let details = contextless_error_bytes(99, "future", "future", 2);
661        assert_protocol_kind(
662            checked_status(Status::with_details(
663                Code::Unavailable,
664                "future",
665                details.into(),
666            )),
667            ProtocolFailureKind::UnknownPublicErrorKind,
668        );
669    }
670
671    #[test]
672    fn staged_public_errors_preserve_retryability_and_certainty() {
673        let overloaded = ClientError::Public(PublicError::overloaded());
674        assert!(is_retryable(&overloaded));
675        assert!(!carries_uncertainty(&overloaded));
676
677        let mismatch = ClientError::Public(PublicError::history_incarnation_mismatch());
678        assert!(!is_retryable(&mismatch));
679        assert!(!carries_uncertainty(&mismatch));
680
681        let pruned = ClientError::Public(PublicError::history_pruned());
682        assert!(!is_retryable(&pruned));
683        assert!(!carries_uncertainty(&pruned));
684
685        let overloaded_app = ClientError::Application(Box::new(ApplicationError::new(
686            ApplicationErrorCode::Overloaded,
687            riffdb_errors::ApplicationOperation::ExecuteQuery,
688            riffdb_errors::ApplicationErrorContext::empty(),
689            None,
690        )));
691        assert!(is_retryable(&overloaded_app));
692        assert!(!carries_uncertainty(&overloaded_app));
693
694        let mismatch_app = ClientError::Application(Box::new(ApplicationError::new(
695            ApplicationErrorCode::HistoryIncarnationMismatch,
696            riffdb_errors::ApplicationOperation::ExecuteQuery,
697            riffdb_errors::ApplicationErrorContext::empty(),
698            None,
699        )));
700        assert!(!is_retryable(&mismatch_app));
701        assert!(!carries_uncertainty(&mismatch_app));
702
703        let pruned_app = ClientError::Application(Box::new(ApplicationError::new(
704            ApplicationErrorCode::HistoryPruned,
705            riffdb_errors::ApplicationOperation::ExecuteQuery,
706            riffdb_errors::ApplicationErrorContext::empty(),
707            None,
708        )));
709        assert!(!is_retryable(&pruned_app));
710        assert!(!carries_uncertainty(&pruned_app));
711    }
712
713    #[test]
714    fn staged_public_status_codes_accept_kind_level_overrides() {
715        let overloaded_details =
716            contextless_error_bytes(11, "overloaded", "service is over capacity", 2);
717        let checked = checked_status(Status::with_details(
718            Code::ResourceExhausted,
719            "service is over capacity",
720            overloaded_details.into(),
721        ));
722        assert!(matches!(
723            checked,
724            ClientError::Public(ref error) if error.kind() == PublicErrorKind::Overloaded
725        ));
726
727        let mismatch_details = contextless_error_bytes(
728            10,
729            "history_incarnation_mismatch",
730            "observed history predates a database restore",
731            1,
732        );
733        let checked = checked_status(Status::with_details(
734            Code::FailedPrecondition,
735            "observed history predates a database restore",
736            mismatch_details.into(),
737        ));
738        assert!(matches!(
739            checked,
740            ClientError::Public(ref error)
741                if error.kind() == PublicErrorKind::HistoryIncarnationMismatch
742        ));
743
744        let pruned_details =
745            contextless_error_bytes(12, "history_pruned", "requested history has been pruned", 1);
746        let checked = checked_status(Status::with_details(
747            Code::FailedPrecondition,
748            "requested history has been pruned",
749            pruned_details.into(),
750        ));
751        assert!(matches!(
752            checked,
753            ClientError::Public(ref error) if error.kind() == PublicErrorKind::HistoryPruned
754        ));
755    }
756
757    fn authorization_denied_bytes() -> Vec<u8> {
758        contextless_error_bytes(3, "authorization_denied", "operation is not authorized", 4)
759    }
760
761    fn contextless_error_bytes(
762        kind: u8,
763        code: &str,
764        safe_message: &str,
765        recovery_action: u8,
766    ) -> Vec<u8> {
767        let mut bytes = Vec::new();
768        push_varint_field(&mut bytes, 1, kind);
769        push_string_field(&mut bytes, 2, code);
770        push_string_field(&mut bytes, 3, safe_message);
771        push_varint_field(&mut bytes, 4, recovery_action);
772        bytes
773    }
774
775    fn push_varint_field(output: &mut Vec<u8>, field: u8, value: u8) {
776        output.push(field << 3);
777        output.push(value);
778    }
779
780    fn push_string_field(output: &mut Vec<u8>, field: u8, value: &str) {
781        output.push((field << 3) | 2);
782        output.push(u8::try_from(value.len()).expect("short fixture"));
783        output.extend_from_slice(value.as_bytes());
784    }
785
786    fn assert_protocol_kind(error: ClientError, expected: ProtocolFailureKind) {
787        assert!(matches!(
788            error,
789            ClientError::Protocol(failure) if failure.kind() == expected
790        ));
791    }
792}