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