Skip to main content

liminal_server/
error.rs

1use std::net::SocketAddr;
2
3use crate::server::participant::ParticipantServiceFatal;
4
5const RESERVED_NAMESPACE_MESSAGE: &str =
6    "SELF_STREAM_NAMESPACE_REFUSED: connection publication to reserved namespace";
7
8/// Error taxonomy for standalone liminal server deployment failures.
9#[derive(Debug, thiserror::Error)]
10pub enum ServerError {
11    /// The configuration file could not be read or parsed.
12    #[error("configuration load failed: {message}")]
13    ConfigLoad { message: String },
14
15    /// The configuration file was read but failed semantic validation.
16    #[error("configuration validation failed: {message}")]
17    ConfigValidation { message: String },
18
19    /// A connection tried to publish into the server-owned namespace.
20    #[error("{RESERVED_NAMESPACE_MESSAGE}: {channel}")]
21    ReservedNamespace {
22        /// Reserved channel the connection addressed.
23        channel: String,
24    },
25
26    /// The server could not bind its configured listener address.
27    #[error("listener bind failed for {address}: {source}")]
28    ListenerBind {
29        /// Address the server attempted to bind.
30        address: SocketAddr,
31        /// Underlying operating-system bind failure.
32        #[source]
33        source: std::io::Error,
34    },
35
36    /// The server listener failed while accepting an inbound connection.
37    #[error("listener accept failed: {message}")]
38    ListenerAccept { message: String },
39
40    /// A prior publisher finish consumed the original error.
41    #[error("self-stream publisher already finished with an error: {first_error}")]
42    SelfStreamPublisherAlreadyFinished {
43        /// Full diagnostic returned by the first finish.
44        first_error: String,
45    },
46
47    /// Durable participant-incarnation startup or allocation failed before its
48    /// result could be published.
49    #[error("participant incarnation {phase} failed: {message}")]
50    ParticipantIncarnation {
51        /// Exact server seam that failed.
52        phase: &'static str,
53        /// Underlying durable or bounded-bridge diagnostic.
54        message: String,
55    },
56
57    /// A durable connection-fate Open could not be completed in this process.
58    ///
59    /// The normal runtime shutdown path returns this typed fatal only after it has
60    /// stopped both listeners and run the ordinary connection drain/flush sequence.
61    #[error("participant service fatal: {fatal}")]
62    ParticipantServiceFatal {
63        /// First process-wide post-Open failure; later failures cannot replace it.
64        fatal: ParticipantServiceFatal,
65    },
66
67    /// Startup found durable connection-fate work that the Decision A/C producer must complete
68    /// before listener or semantic-service publication.
69    #[error(
70        "participant startup requires recovery of {open_count} connection-fate Opens beginning at sequence {first_open_sequence}"
71    )]
72    ConnectionFateRecoveryRequired {
73        /// Number of replay-validated unmatched Opens.
74        open_count: usize,
75        /// Lowest unmatched Open sequence.
76        first_open_sequence: u64,
77    },
78
79    /// The durable server-incarnation namespace has no successor.
80    #[error("participant server-incarnation namespace is exhausted")]
81    ServerIncarnationExhausted,
82
83    /// Production participant startup restore failed: the durable
84    /// conversation streams could not be scanned or replayed, so the
85    /// server-scope capacity ledger cannot be made exact and the server
86    /// refuses to start over state it cannot account for.
87    #[error("participant startup restore failed: {message}")]
88    ParticipantStartupRestore {
89        /// Underlying durable, replay, or bridge diagnostic.
90        message: String,
91    },
92
93    /// The current durable server incarnation has no collision-free connection
94    /// ordinal left, so the accepted socket was not admitted.
95    #[error(
96        "connection incarnation exhausted for server incarnation {attempted_server_incarnation}"
97    )]
98    ConnectionIncarnationExhausted {
99        /// Server incarnation whose complete ordinal suffix was examined.
100        attempted_server_incarnation: u64,
101    },
102
103    /// A connection registration found a record already present under its pid.
104    /// Enforces the pids-fresh-per-spawn supervision invariant loudly: a silent
105    /// replace would drop the displaced record's teardown-held fd guard outside
106    /// the single record-removal funnel (orphaning a live connection's stream)
107    /// and increment the `liminal_connections_active` gauge a second time with
108    /// no paired decrement. The whole registration is refused instead, leaving
109    /// the prior record — and its teardown route — intact.
110    #[error("connection registration refused: pid {pid} already has a live registry record")]
111    ConnectionPidCollision {
112        /// The connection pid that already owned a registry record.
113        pid: u64,
114    },
115
116    /// A frame requested an operation the configured services profile does not
117    /// serve (e.g. ordinary publish/subscribe/conversation traffic against the
118    /// capability-scoped worker front door). Server-internal taxonomy, not wire
119    /// vocabulary: the connection process renders it as the operation's existing
120    /// typed error frame with this error's text as the message.
121    #[error("{operation} is not supported by the {profile} services profile")]
122    UnsupportedOperation {
123        /// Human-readable description of the refused operation.
124        operation: String,
125        /// The configured services profile that refused it.
126        profile: &'static str,
127    },
128
129    /// A server→client push reply slot was dropped before a correlated reply
130    /// arrived — the connection closed (the prompt worker-death signal). Distinct
131    /// from [`Self::PushReplyTimeout`] so consumers can tell a worker that DIED
132    /// (fast failover) from one that is merely SLOW, by type rather than message.
133    #[error(
134        "push correlation {correlation_id} did not complete: the connection closed before sending a correlated push reply"
135    )]
136    PushReplyDisconnected {
137        /// Correlation id of the push whose reply will never arrive.
138        correlation_id: u64,
139    },
140
141    /// A server→client push reply did not arrive within the awaiter's timeout —
142    /// the worker is still connected but did not reply in this wait quantum. This
143    /// is BENIGN: the reply slot survives untouched and the caller may re-arm
144    /// [`PushReplyAwaiter::receive`](crate::server::connection::PushReplyAwaiter::receive)
145    /// indefinitely. It is not a worker-death signal.
146    #[error(
147        "push correlation {correlation_id} did not complete: no correlated push reply arrived within the timeout"
148    )]
149    PushReplyTimeout {
150        /// Correlation id of the push whose wait quantum elapsed.
151        correlation_id: u64,
152    },
153
154    /// A server→client push carrying an explicit reply deadline (via
155    /// [`push_to_connection_with_deadline`](crate::server::connection::ConnectionSupervisor::push_to_connection_with_deadline))
156    /// reached that deadline before a correlated reply arrived. Unlike
157    /// [`Self::PushReplyTimeout`] this is TERMINAL: the reply slot has been
158    /// removed and its §5 `max_pending_pushes_per_connection` cap admission
159    /// released. Returned PROMPTLY once the deadline is due — a `receive` call
160    /// does not hold a due expiry until its caller's quantum ends, so the
161    /// terminal outcome is independent of how the caller polls. Distinct
162    /// variant so callers classify by type, not message.
163    #[error(
164        "push correlation {correlation_id} did not complete: its reply deadline passed before a correlated push reply arrived"
165    )]
166    PushReplyExpired {
167        /// Correlation id of the push whose reply deadline passed.
168        correlation_id: u64,
169    },
170
171    /// A server→client push's correlated reply ARRIVED and was refused by the
172    /// access decision on the subject the push was made on (ACCESS-001 R2: a
173    /// connection admitted on a Lys pass has its `PushReply` decided as `serve`
174    /// on the push's retained subject, the matrix's `push_binding`). TERMINAL:
175    /// the slot is removed and its §5 cap admission released, the reply payload
176    /// is never delivered. A push made with no subject
177    /// ([`push_to_connection`](crate::server::connection::ConnectionSupervisor::push_to_connection))
178    /// to such a connection reads here too, with `reason` saying so: the
179    /// subject is recorded at push time
180    /// ([`push_to_subject`](crate::server::connection::ConnectionSupervisor::push_to_subject))
181    /// or not at all. Distinct variant so callers classify by type.
182    #[error("push correlation {correlation_id} was refused: {reason}")]
183    PushReplyRefused {
184        /// Correlation id of the push whose reply was refused.
185        correlation_id: u64,
186        /// The refusal, rendered as the four-field access refusal.
187        reason: String,
188    },
189
190    /// A server→client push was never queued for the wire: its encoded frame is
191    /// larger than the WHOLE of the connection's bounded outbound buffer, so no
192    /// amount of draining could ever make room for it. TERMINAL and CERTAIN — the
193    /// reply slot is removed, its §5 `max_pending_pushes_per_connection` admission
194    /// released, and the client never saw a `Push` frame for this correlation id.
195    ///
196    /// Deliberately NARROW. A frame that would fit an empty buffer but not the
197    /// current free space is CONGESTION, not a size defect: it keeps the
198    /// connection-teardown path and its retryable
199    /// [`Self::PushReplyDisconnected`] reading, because waiting is the correct
200    /// answer there. Sharing one outcome between the certain case and the
201    /// recoverable one would leave the caller unable to tell them apart — which
202    /// is the exact fault this variant exists to end. Distinct variant so callers
203    /// classify by type, not message.
204    ///
205    /// The WORDS carry the bound's value and say the bound was chosen, because a
206    /// reader who meets this without that context blames the server for a number
207    /// an operator set. Since every outbound bound now comes from
208    /// [`max_connection_outbound_bytes`](crate::config::types::LimitsConfig::max_connection_outbound_bytes),
209    /// that sentence is true on every occurrence rather than usually.
210    #[error(
211        "push correlation {correlation_id} was never sent: its {needed}-byte frame exceeds this \
212         connection's whole outbound buffer of {capacity} bytes, which is operator-set by \
213         `limits.max_connection_outbound_bytes`"
214    )]
215    PushFrameExceedsOutboundCapacity {
216        /// Correlation id of the push that could not be queued.
217        correlation_id: u64,
218        /// Encoded size of the rejected frame. Exceeds `capacity` on its own.
219        needed: usize,
220        /// The outbound buffer's whole capacity, which `needed` exceeds.
221        capacity: usize,
222        /// Bytes already queued when the frame was rejected. Context for the log
223        /// only: the decision is `needed` against `capacity` alone, so this frame
224        /// would not have fitted an empty buffer either.
225        queued: usize,
226    },
227
228    /// The server could not join the configured beamr distribution cluster.
229    #[error("cluster join failed: {message}")]
230    ClusterJoin { message: String },
231
232    /// Cluster state propagation through beamr distribution failed.
233    #[error("cluster sync failed: {message}")]
234    ClusterSync { message: String },
235
236    /// Graceful shutdown did not drain within the configured timeout.
237    #[error("shutdown timed out: {message}")]
238    ShutdownTimeout { message: String },
239
240    /// Durable state could not be flushed during graceful shutdown.
241    #[error("shutdown flush failed: {message}")]
242    ShutdownFlush { message: String },
243
244    /// A clean stop could not complete every connection fate parked on
245    /// candidate-lane `Precedence`. Each named durable Open is reconciled by
246    /// the next boot instead, so the stop was not clean.
247    #[error(
248        "shutdown left connection fates unsettled for the next boot to reconcile: durable Opens \
249         {open_sequences:?}"
250    )]
251    ShutdownUnsettledConnectionFates {
252        /// Durable Open sequences still parked when the stop finished.
253        open_sequences: Vec<u64>,
254    },
255
256    /// The health endpoint failed to start or serve requests.
257    #[error("health endpoint failed: {message}")]
258    HealthEndpoint { message: String },
259
260    /// A new connection was refused because the configured `max_connections`
261    /// cap (§5) is already reached. The listener drops the freshly accepted
262    /// stream, refusing the connection, rather than admitting an unbounded fleet.
263    #[error(
264        "connection refused: the configured max_connections limit of {limit} live connections is reached"
265    )]
266    ConnectionLimitReached {
267        /// The configured `max_connections` cap that was hit.
268        limit: usize,
269    },
270
271    /// An admission-time per-connection cap (§5) refused an operation: too many
272    /// subscriptions, conversations, in-flight pushes, or pending conversation
273    /// replies on one connection. The connection process renders it as the
274    /// operation's existing typed error frame with this text as the message.
275    #[error("{operation} refused: the per-connection {cap} limit of {limit} is reached")]
276    ConnectionCapReached {
277        /// Human-readable description of the refused operation.
278        operation: String,
279        /// The name of the cap that refused it (a `limits.*` config key).
280        cap: &'static str,
281        /// The configured cap value that was hit.
282        limit: usize,
283    },
284
285    /// A publish whose append outcome is not known: the server cannot tell
286    /// whether the row was stored. Distinct from every definite publish failure
287    /// so the connection process answers it with its own reason code
288    /// (`PUBLISH_UNRESOLVED_CODE`) and a producer classifies it by type, never
289    /// by message; it is never a Reject, a Defer or a backpressure signal.
290    #[error(
291        "publish to channel {channel} is unresolved{}: {message}",
292        UnresolvedPublishDetail(.idempotency_key, .sequence)
293    )]
294    PublishUnresolved {
295        /// Channel the unresolved publish was addressed to.
296        channel: String,
297        /// Idempotency key the publish carried, when it carried one.
298        idempotency_key: Option<String>,
299        /// Sequence the append expected, when one was assigned.
300        sequence: Option<u64>,
301        /// The underlying append diagnostic, kept as evidence.
302        message: String,
303    },
304
305    /// The offline participant log migration refused.
306    #[error(transparent)]
307    ParticipantLogMigration(#[from] crate::server::participant::ParticipantLogMigrationError),
308
309    /// An agent seat refused, in the agent's own words.
310    #[error(transparent)]
311    Agent(#[from] crate::agents::error::AgentError),
312}
313
314/// Renders the optional idempotency key and sequence of
315/// [`ServerError::PublishUnresolved`], naming each only when it is present.
316struct UnresolvedPublishDetail<'a>(&'a Option<String>, &'a Option<u64>);
317
318impl std::fmt::Display for UnresolvedPublishDetail<'_> {
319    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
320        if let Some(key) = self.0 {
321            write!(formatter, " (idempotency key {key})")?;
322        }
323        if let Some(sequence) = self.1 {
324            write!(formatter, " (sequence {sequence})")?;
325        }
326        Ok(())
327    }
328}