Skip to main content

liminal_server/server/participant/
dispatch.rs

1//! Participant transport-to-semantics dispatch boundary.
2//!
3//! This module contains no lifecycle rules. The shared protocol crate gates and
4//! decodes inbound frames, while an injected semantic handler returns one typed
5//! protocol value. The server then performs only generic-frame encoding.
6
7use std::collections::BTreeSet;
8use std::sync::{Arc, Weak};
9
10use liminal::durability::DurableStore;
11use liminal::protocol::Frame;
12use liminal_protocol::lifecycle::{BindingTerminalAdmitError, ConnectionConversationTracking};
13use liminal_protocol::wire::{
14    BindingEpoch, ClientRequest, CodecError, ConnectionIncarnation, ConversationId,
15    ObserverRecoveryHandshake, ParticipantId, ServerValue, ValidatedFrameLimit,
16};
17
18use crate::auth_pass::PassPrincipal;
19use crate::server::mount::MountKind;
20
21use super::dispatch_impact::DispatchImpact;
22use super::transport::{
23    ParticipantIngress, ParticipantSession, encode_server_value, gate_generic_frame,
24    normalize_configured_frame_limit,
25};
26use super::{
27    MarkerSettledPublication, ObserverPublicationTarget, ParticipantOfferedProgress,
28    ParticipantPublication, ParticipantPublicationInbox, ParticipantPublicationRegistry,
29};
30
31/// One connection waiting on one settlement epoch, installed by its OWN refusal.
32///
33/// ⛔ This registry is the whole of §0.16 build obligation 3. The wake is
34/// delivered "exactly to connections that received the refusal in this process
35/// lifetime": a waiter can only be created from a
36/// `ServerValue::MarkerSettlementBackpressure` leaving THIS connection's own
37/// request, and the fire path walks waiters — never conversation membership,
38/// never the publication registry's incarnation map. There is deliberately no
39/// code path from a conversation id to a set of connections here, because that
40/// is exactly the settlement-timing side channel the amendment outlaws.
41///
42/// A connection refused at the ENROLLMENT wrapper cannot appear: its refusal is
43/// `EnrollmentSettlementBackpressure`, a different `ServerValue` variant with no
44/// epoch, and the registration match does not admit it.
45#[derive(Debug)]
46struct MarkerSettlementWaiter {
47    connection_incarnation: ConnectionIncarnation,
48    refused_epoch: u64,
49    target: ObserverPublicationTarget,
50}
51
52/// Told when a committed drain removes a head of one conversation's
53/// immutable-candidate lane.
54///
55/// The connection runtime installs itself here so a connection fate parked on
56/// candidate-lane `Precedence` is retried by the drain that removed the
57/// refusal, on the thread that committed it, and never by a timer or by
58/// whichever unrelated reply happens to come next. A lane drain is the only
59/// event that can turn that refusal into an admission, so it is the only
60/// event that retries.
61pub trait CandidateLaneListener: Send + Sync + std::fmt::Debug {
62    /// A drain of `conversation_id`'s candidate lane is durable and its
63    /// resulting owner installed. Runs after the conversation lock is released.
64    fn candidate_lane_drained(&self, conversation_id: ConversationId);
65}
66
67/// Connection-local semantic-conversation dispatch map (contract R-D1: the
68/// connection's binding/interest/dispatch maps are bounded by the signed
69/// `max_semantic_conversations_per_connection`).
70///
71/// One value lives in each connection process's state for the connection's
72/// lifetime and is dropped with it. A conversation enters the map exactly
73/// when a semantic operation for it COMMITS on this connection (the crate's
74/// `ConnectionConversationCapacityCommit::newly_tracked` verdict) or when an
75/// observer-recovery batch arms its refusal-only recipient; refusals and
76/// replays leave the map untouched, exactly as the crate's stage-6 selector
77/// leaves its counter unchanged. Growth is therefore bounded by the signed
78/// limit the stage-6 selector enforces.
79#[derive(Debug, Default)]
80pub struct ParticipantConnectionConversations {
81    tracked: BTreeSet<ConversationId>,
82}
83
84impl ParticipantConnectionConversations {
85    /// Stage-6 tracking fact for one conversation on this connection.
86    #[must_use]
87    pub fn tracking(&self, conversation_id: ConversationId) -> ConnectionConversationTracking {
88        if self.tracked.contains(&conversation_id) {
89            ConnectionConversationTracking::AlreadyTracked
90        } else {
91            ConnectionConversationTracking::Untracked
92        }
93    }
94
95    /// Current connection-conversation occupancy.
96    #[must_use]
97    pub fn occupied(&self) -> u64 {
98        // `usize` fits `u64` on every supported target; if that ever stopped
99        // holding, saturating at MAX fails CLOSED (capacity reads as full)
100        // rather than silently under-counting occupancy.
101        u64::try_from(self.tracked.len()).unwrap_or(u64::MAX)
102    }
103
104    /// Installs one conversation slot after a capacity-committing operation.
105    pub fn track(&mut self, conversation_id: ConversationId) {
106        self.tracked.insert(conversation_id);
107    }
108
109    /// Sorted tracked conversations (the observer-recovery preflight's
110    /// current-occupancy input).
111    #[must_use]
112    pub fn tracked_conversations(&self) -> Vec<ConversationId> {
113        self.tracked.iter().copied().collect()
114    }
115}
116
117/// Connection-scoped authority facts supplied to participant semantics.
118#[derive(Clone, Copy, Debug, PartialEq, Eq)]
119pub struct ParticipantConnectionContext {
120    connection_incarnation: ConnectionIncarnation,
121    mount: MountKind,
122}
123
124impl ParticipantConnectionContext {
125    /// Captures the durably allocated incarnation of the receiving connection
126    /// and the mount its admitting door stamped.
127    ///
128    /// Both arguments are server facts. `mount` in particular is supplied by
129    /// the spawn path from its own knowledge of which door it is (design §10);
130    /// it is a required argument rather than a defaulted field precisely so a
131    /// new transport cannot acquire a mount attestation by forgetting to say
132    /// which one it is.
133    #[must_use]
134    pub const fn new(connection_incarnation: ConnectionIncarnation, mount: MountKind) -> Self {
135        Self {
136            connection_incarnation,
137            mount,
138        }
139    }
140
141    /// Returns the durably allocated receiving-connection incarnation.
142    #[must_use]
143    pub const fn connection_incarnation(self) -> ConnectionIncarnation {
144        self.connection_incarnation
145    }
146
147    /// Returns the mount the admitting door stamped on this connection.
148    ///
149    /// This is the mount attestation the consumer's door reads before stamping
150    /// its own append. Nothing a client sends can move it: the value was fixed
151    /// by the spawn path before the connection's first inbound byte was read.
152    #[must_use]
153    pub const fn mount(self) -> MountKind {
154        self.mount
155    }
156}
157
158/// Exact terminal classification preserved from a connection's close trigger.
159#[derive(Clone, Copy, Debug, PartialEq, Eq)]
160pub enum ConnectionFateClass {
161    /// A protocol-level clean Disconnect.
162    CleanDisconnect,
163    /// An orderly server `ForceClose`.
164    ServerShutdown,
165    /// EOF or transport loss without clean protocol evidence.
166    ConnectionLost,
167    /// A terminal protocol/decode refusal after participant binding.
168    ProtocolError,
169}
170
171/// One durable bounded connection-fate intent delivered to participant semantics.
172#[derive(Clone, Debug, PartialEq, Eq)]
173pub struct ConnectionFateWorkItem {
174    /// Durable incarnation-stream Open sequence used by participant source rows.
175    pub open_sequence: u64,
176    /// Exact connection whose current Bound slots are eligible.
177    pub connection_incarnation: ConnectionIncarnation,
178    /// Preserved close classification.
179    pub class: ConnectionFateClass,
180    /// Canonical sorted tracked-conversation snapshot owned by the Open.
181    pub tracked_conversations: Vec<ConversationId>,
182}
183
184/// Process-wide terminal participant-service latch.
185#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
186pub enum ParticipantServiceFatal {
187    /// A durable Open landed but one listed conversation could not durably finish its fate.
188    #[error(
189        "connection-fate intent {open_sequence} is incomplete at conversation {conversation_id}"
190    )]
191    ConnectionFateIntentIncomplete {
192        /// Durable incarnation-stream Open sequence.
193        open_sequence: u64,
194        /// Exact conversation whose non-idempotent completion failed.
195        conversation_id: ConversationId,
196    },
197}
198
199/// Why F8B boot recovery could not empty a restored conversation's
200/// immutable-candidate lane (`docs/design/F8B-INTENT-DEADLOCK.md` §6.2
201/// R-BOOT-VERDICT).
202///
203/// The discrimination is BY TYPE, for the same reason
204/// [`ParticipantSemanticError::BindingTerminalAdmissionRefused`] carries
205/// [`BindingTerminalAdmitError`]: a consumer deciding what a refused boot
206/// means must not read it out of a formatted message.
207#[derive(Clone, Copy, Debug, PartialEq, Eq)]
208pub enum BootDrainRefusal {
209    /// The lane head is a pending binding terminal under an armed
210    /// fenced-attach recovery block. The terminal drain refuses outright while
211    /// a recovery block is armed, and the only consumer of a recovery block is
212    /// a live fenced attach — which boot cannot perform. Such a store is not
213    /// repairable by the boot drain, and this verdict is the honest answer
214    /// rather than a repair.
215    RecoveryArmed,
216    /// Any other drain refusal: the head was reachable, the drain was
217    /// attempted, and the protocol refused the transition.
218    Shape,
219}
220
221/// Non-wire semantic service failure.
222///
223/// A failure is terminal to the connection attempt. It is deliberately not
224/// convertible to [`ServerValue`], preventing the server from inventing a
225/// lifecycle response when the protocol-owned transition did not produce one.
226#[derive(Clone, Debug, thiserror::Error, PartialEq, Eq)]
227pub enum ParticipantSemanticError {
228    /// The complete semantic service is not installed.
229    #[error("participant semantic service is unavailable")]
230    Unavailable,
231    /// Durable state or a protocol invariant prevented semantic completion.
232    #[error("participant semantic service failed: {message}")]
233    Internal {
234        /// Diagnostic text for server logs; never placed on the participant wire.
235        message: String,
236    },
237    /// The request's durable write ended with an outcome the store could not
238    /// tell and the server could not settle by reading it back: it may have
239    /// been applied. The dispatch answers a token-carrying request with its
240    /// write-outcome-unknown value (`0x0128`) on an open connection.
241    #[error("participant durable write outcome unknown: {message}")]
242    WriteOutcomeUnknown {
243        /// Diagnostic text for server logs; never placed on the participant wire.
244        message: String,
245    },
246    /// A process-wide participant fatal has already latched.
247    #[error(transparent)]
248    ServiceFatal(ParticipantServiceFatal),
249    /// A keyed binding-terminal candidate was refused, carrying the protocol's
250    /// own reason rather than a formatted description of it.
251    ///
252    /// [`BindingTerminalAdmitError::Precedence`] is lane occupancy: the
253    /// conversation's immutable-candidate lane already holds a terminal
254    /// awaiting its drain. That is a designed structural boundary, and a
255    /// caller deciding whether to park or to treat the refusal as corruption
256    /// must be able to tell it from the five genuine authority defects by
257    /// type.
258    #[error("participant binding-terminal admission refused: {error:?}")]
259    BindingTerminalAdmissionRefused {
260        /// Exact protocol refusal reason.
261        error: BindingTerminalAdmitError,
262    },
263    /// F8B R-BOOT-VERDICT: boot recovery could not empty a restored
264    /// conversation's immutable-candidate lane, so the boot refuses HERE,
265    /// naming the conversation and the shape, instead of starting and dying
266    /// several collapses downstream on a retained `Open` it can never replay.
267    #[error(
268        "participant boot drain refused conversation {conversation_id} on lane head {candidate} \
269         ({refusal:?}): {reason} — docs/design/F8B-INTENT-DEADLOCK.md §6.2 R-BOOT-VERDICT"
270    )]
271    BootDrainRefused {
272        /// Conversation whose restored lane refused its drain.
273        conversation_id: ConversationId,
274        /// Typed reason, so a consumer never discriminates on a substring.
275        refusal: BootDrainRefusal,
276        /// Exact lane head that refused, rendered for the operator.
277        candidate: String,
278        /// The drain's own refusal text.
279        reason: String,
280    },
281    /// F8B R-SEAL: the conversation is Closed — a Died-flavor drain erased its
282    /// final enrollment token, so its log holds records, terminals and drain
283    /// rows but no live identity can ever be reached through it again.
284    ///
285    /// Enrollment answers with this NAMED refusal rather than falling through
286    /// to a fresh identity, which would silently re-open a conversation whose
287    /// history has already ended. On the wire it rides the existing
288    /// semantic-error framing; a protocol-native response value with its own
289    /// discriminant is deferred to a protocol-version leg (§9.8).
290    #[error(
291        "participant enrollment refused: conversation {conversation_id} is sealed — its final \
292         enrollment token was erased by a binding-terminal drain — \
293         docs/design/F8B-INTENT-DEADLOCK.md §6.6 R-SEAL"
294    )]
295    ConversationSealed {
296        /// Conversation whose closure refused the request.
297        conversation_id: ConversationId,
298    },
299    /// CONTAINMENT: this one conversation's durable state cannot be loaded, so
300    /// this one conversation is refused. The node starts, every other
301    /// conversation is served, and the refusal NAMES its subject.
302    ///
303    /// Attribution is not decoration here, it is half the property. A node
304    /// that contains an unloadable conversation without naming it boots clean
305    /// and silently serves nothing on that conversation forever, which is
306    /// worse than the crash it replaced, because the crash was the only thing
307    /// telling anyone. The underlying failure travels as `reason` rather than
308    /// as a wrapped error because it is already a rendered diagnostic by the
309    /// time replay refuses it.
310    #[error(
311        "participant conversation {conversation_id} is unloadable and is refused on its own: \
312         {reason}"
313    )]
314    ConversationUnloadable {
315        /// Conversation whose durable state could not be loaded.
316        conversation_id: ConversationId,
317        /// The load failure's own text, as the operator needs to see it.
318        reason: String,
319    },
320}
321
322impl ParticipantSemanticError {
323    /// Stable operator-facing class for this refusal.
324    ///
325    /// The rendered message is a diagnostic: it carries the subject and the
326    /// detail, and it is allowed to move. This is the discriminant an operator
327    /// surface and a log field can be read against without matching on a
328    /// substring — which is what the containment record's consumers need, since
329    /// the failure text a refused load carries ("expected value at line 1
330    /// column 1") names no class at all on its own.
331    #[must_use]
332    pub const fn class(&self) -> &'static str {
333        match self {
334            Self::Unavailable => "unavailable",
335            Self::Internal { .. } => "internal",
336            Self::WriteOutcomeUnknown { .. } => "write_outcome_unknown",
337            Self::ServiceFatal(_) => "service_fatal",
338            Self::BindingTerminalAdmissionRefused { .. } => "binding_terminal_admission_refused",
339            Self::BootDrainRefused { .. } => "boot_drain_refused",
340            Self::ConversationSealed { .. } => "conversation_sealed",
341            Self::ConversationUnloadable { .. } => "conversation_unloadable",
342        }
343    }
344}
345
346/// One semantic result paired with every dispatch effect durably installed by
347/// the request before it returned.
348///
349/// The envelope deliberately owns the `Result`: a marker-drain prefix can
350/// commit before a later retry fails, and that failure must not erase the
351/// prefix's post-commit tell.
352#[derive(Debug)]
353pub struct ParticipantSemanticOutcome<T> {
354    result: Result<T, ParticipantSemanticError>,
355    impact: DispatchImpact,
356}
357
358impl<T> ParticipantSemanticOutcome<T> {
359    /// Wraps a fixture or operation which installed no dispatch effect.
360    #[must_use]
361    pub const fn unchanged(result: Result<T, ParticipantSemanticError>) -> Self {
362        Self {
363            result,
364            impact: DispatchImpact::Unchanged,
365        }
366    }
367
368    /// Carries an operation result and its complete request accumulator.
369    #[must_use]
370    pub const fn new(result: Result<T, ParticipantSemanticError>, impact: DispatchImpact) -> Self {
371        Self { result, impact }
372    }
373
374    pub(crate) fn into_parts(self) -> (Result<T, ParticipantSemanticError>, DispatchImpact) {
375        (self.result, self.impact)
376    }
377
378    /// Returns the semantic result when an internal caller has no notification
379    /// boundary. Production request dispatch uses the complete envelope; this
380    /// projection exists for the trait's legacy direct-call entry point.
381    pub(crate) fn into_result(self) -> Result<T, ParticipantSemanticError> {
382        self.result
383    }
384}
385
386/// One connection-fate result paired with every conversation impact committed
387/// before the fate operation returned.
388#[derive(Debug)]
389pub struct ParticipantConnectionFateOutcome {
390    result: Result<(), ParticipantSemanticError>,
391    impacts: Vec<DispatchImpact>,
392}
393
394impl ParticipantConnectionFateOutcome {
395    /// Wraps a fixture fate handler which committed no dispatch impact.
396    #[must_use]
397    pub const fn unchanged(result: Result<(), ParticipantSemanticError>) -> Self {
398        Self {
399            result,
400            impacts: Vec::new(),
401        }
402    }
403
404    /// Carries a fate result and every committed per-conversation impact.
405    #[must_use]
406    pub const fn new(
407        result: Result<(), ParticipantSemanticError>,
408        impacts: Vec<DispatchImpact>,
409    ) -> Self {
410        Self { result, impacts }
411    }
412
413    pub(crate) fn into_parts(self) -> (Result<(), ParticipantSemanticError>, Vec<DispatchImpact>) {
414        (self.result, self.impacts)
415    }
416
417    pub(crate) fn into_result(self) -> Result<(), ParticipantSemanticError> {
418        self.result
419    }
420}
421
422/// Server-owned adapter from a decoded request to a protocol-owned value.
423pub trait ParticipantSemanticHandler: core::fmt::Debug + Send + Sync {
424    /// Applies one already authenticated and capability-gated request.
425    ///
426    /// `conversations` is the receiving connection's semantic-conversation
427    /// dispatch map: the handler reads it for the crate's stage-6
428    /// connection-conversation capacity facts and installs a slot exactly
429    /// when an operation's capacity commit reports `newly_tracked`.
430    ///
431    /// # Errors
432    ///
433    /// Returns [`ParticipantSemanticError`] when no protocol value can be
434    /// produced. The caller closes rather than fabricating a response.
435    ///
436    /// Production handlers override this with the signed
437    /// `max_semantic_conversations_per_connection`; semantic-only fixtures own
438    /// no publication conversations.
439    ///
440    /// Returns the latched fatal, when participant service must remain stopped.
441    fn service_fatal(&self) -> Result<Option<ParticipantServiceFatal>, ParticipantSemanticError> {
442        Ok(None)
443    }
444
445    /// Atomically latches the post-Open fatal selected by Decision B.
446    ///
447    /// Implementations must preserve the first fatal and return it on every later call.
448    /// The default exists only for semantic fixtures which own no durable intents.
449    ///
450    /// # Errors
451    ///
452    /// Returns a semantic service error when the fatal latch cannot be inspected or updated.
453    fn latch_connection_fate_intent_incomplete(
454        &self,
455        open_sequence: u64,
456        conversation_id: ConversationId,
457    ) -> Result<ParticipantServiceFatal, ParticipantSemanticError> {
458        Ok(ParticipantServiceFatal::ConnectionFateIntentIncomplete {
459            open_sequence,
460            conversation_id,
461        })
462    }
463
464    /// Applies every matching participant binding named by one durable Open.
465    ///
466    /// The incarnation-stream lock is not held while this method runs. Each
467    /// implementation serializes conversations independently and must return
468    /// only after every source and immediately executable specific fate flushes.
469    ///
470    /// # Errors
471    ///
472    /// Returns a semantic failure without consuming the Open; startup or the
473    /// live fatal path retains it for exact replay.
474    fn handle_connection_fate(
475        &self,
476        work_item: ConnectionFateWorkItem,
477    ) -> Result<(), ParticipantSemanticError> {
478        drop(work_item);
479        Err(ParticipantSemanticError::Unavailable)
480    }
481
482    /// Applies connection fate while preserving every committed conversation's
483    /// post-flush dispatch effects on both success and failure exits.
484    fn handle_connection_fate_with_impact(
485        &self,
486        work_item: ConnectionFateWorkItem,
487    ) -> ParticipantConnectionFateOutcome {
488        ParticipantConnectionFateOutcome::unchanged(self.handle_connection_fate(work_item))
489    }
490
491    /// Drains every head of one conversation's immutable-candidate lane, as
492    /// boot recovery does, and reports the drains on the outcome's impact.
493    ///
494    /// A clean stop calls this for each conversation a parked connection fate
495    /// still waits on, so the fate can complete before the process exits
496    /// instead of leaving its Open for the next boot to reconcile. The default
497    /// owns no lane and answers [`ParticipantSemanticError::Unavailable`],
498    /// which the stop reports by name.
499    fn drain_candidate_lane_with_impact(
500        &self,
501        conversation_id: ConversationId,
502    ) -> ParticipantSemanticOutcome<()> {
503        let _ = conversation_id;
504        ParticipantSemanticOutcome::unchanged(Err(ParticipantSemanticError::Unavailable))
505    }
506
507    /// Repairs every remaining binding owned by a prior server incarnation.
508    ///
509    /// Startup calls this after all retained Opens complete and before publishing
510    /// the incarnation authority, scheduler, listener, or new admission.
511    ///
512    /// The default performs NO repair and reports success, so startup proceeds as
513    /// if there were nothing left over from the prior incarnation. That is correct
514    /// only for an implementor that holds no durable bindings. Any implementor with
515    /// real restart semantics MUST override this — inheriting the default leaves
516    /// stale bindings in place and says nothing about them.
517    ///
518    /// # Errors
519    ///
520    /// Returns a semantic failure while startup still owns all publication seams.
521    fn repair_unclean_server_restart(
522        &self,
523        current_server_incarnation: u64,
524    ) -> Result<(), ParticipantSemanticError> {
525        let _ = current_server_incarnation;
526        Ok(())
527    }
528
529    /// Reports whether any listed conversation currently contains a Bound slot
530    /// owned by this exact connection. Terminal decode funnels use this query to
531    /// distinguish bound-only `ProtocolError` from pre-auth/detached/internal paths.
532    ///
533    /// The default answers "unbound" unconditionally, without inspecting anything,
534    /// so every caller is told this connection owns no Bound slot. That is correct
535    /// only for an implementor that can never hold one. Any implementor with real
536    /// binding semantics MUST override this — inheriting the default silently
537    /// routes genuinely bound connections down the unbound funnel.
538    ///
539    /// # Errors
540    ///
541    /// Returns a semantic failure when exact bound authority cannot be inspected.
542    fn connection_has_bound_participant(
543        &self,
544        connection_incarnation: ConnectionIncarnation,
545        conversations: &[ConversationId],
546    ) -> Result<bool, ParticipantSemanticError> {
547        let _ = connection_incarnation;
548        let _ = conversations;
549        Ok(false)
550    }
551
552    fn publication_conversation_limit(&self) -> u64 {
553        0
554    }
555
556    /// Resolves all live current bindings with pending durable obligations for
557    /// one conversation. Production overrides this; semantic-only fixtures have
558    /// no publication source.
559    ///
560    /// # Errors
561    ///
562    /// Returns a semantic fault when durable readiness cannot be resolved.
563    fn ready_connection_incarnations(
564        &self,
565        _conversation_id: ConversationId,
566    ) -> Result<Vec<ConnectionIncarnation>, ParticipantSemanticError> {
567        Ok(Vec::new())
568    }
569
570    /// Selects the least durable recipient obligation for this incarnation,
571    /// restarting from durable ack when `offered` names an older binding.
572    ///
573    /// # Errors
574    ///
575    /// Returns a semantic fault when the durable obligation owner is unavailable.
576    fn next_publication(
577        &self,
578        _connection_incarnation: ConnectionIncarnation,
579        _conversation_id: ConversationId,
580        _offered: Option<ParticipantOfferedProgress>,
581    ) -> Result<Option<ParticipantPublication>, ParticipantSemanticError> {
582        Ok(None)
583    }
584
585    /// Checks that a held head still belongs to the exact current binding before
586    /// it is offered after writable readiness.
587    ///
588    /// # Errors
589    ///
590    /// Returns a semantic fault when current binding authority cannot be read.
591    fn publication_binding_is_current(
592        &self,
593        _conversation_id: ConversationId,
594        _participant_id: ParticipantId,
595        _binding_epoch: BindingEpoch,
596    ) -> Result<bool, ParticipantSemanticError> {
597        Ok(false)
598    }
599
600    /// Re-selects a held publication against current binding, cursor, debt, and
601    /// outbox authority before its first offer. Semantic-only handlers retain
602    /// the binding-only default; production overrides this with the full locked
603    /// dispatch decision.
604    ///
605    /// # Errors
606    ///
607    /// Returns a semantic fault when current publication authority cannot be read.
608    fn publication_is_current(
609        &self,
610        publication: &ParticipantPublication,
611        offered: Option<ParticipantOfferedProgress>,
612    ) -> Result<bool, ParticipantSemanticError> {
613        if offered.is_some_and(|progress| progress.binding_epoch != publication.binding_epoch) {
614            return Ok(false);
615        }
616        self.publication_binding_is_current(
617            publication.conversation_id(),
618            publication.participant_id,
619            publication.binding_epoch,
620        )
621    }
622
623    /// Records exact successful marker enqueue testimony. Non-marker offers are
624    /// ignored by production after validating their current binding.
625    ///
626    /// # Errors
627    ///
628    /// Returns a semantic fault when exact offer testimony cannot be recorded.
629    fn record_publication_offer(
630        &self,
631        _publication: &ParticipantPublication,
632    ) -> Result<(), ParticipantSemanticError> {
633        Ok(())
634    }
635
636    /// Applies observer recovery with the weak exact-live-connection target
637    /// captured by the installed service. Semantic-only handlers delegate to
638    /// their ordinary request path and do not own observer publication.
639    ///
640    /// # Errors
641    ///
642    /// Returns [`ParticipantSemanticError`] under the same contract as
643    /// [`Self::handle`].
644    fn handle_observer_recovery(
645        &self,
646        context: ParticipantConnectionContext,
647        conversations: &mut ParticipantConnectionConversations,
648        request: ObserverRecoveryHandshake,
649        target: Option<ObserverPublicationTarget>,
650    ) -> Result<ServerValue, ParticipantSemanticError> {
651        drop(target);
652        self.handle(
653            context,
654            conversations,
655            ClientRequest::ObserverRecovery(request),
656        )
657    }
658
659    /// Applies one request and preserves post-commit effects on every exit.
660    ///
661    /// Semantic-only fixtures default to an empty accumulator. Production
662    /// overrides this boundary and returns operation-owned effects.
663    fn handle_with_impact(
664        &self,
665        context: ParticipantConnectionContext,
666        conversations: &mut ParticipantConnectionConversations,
667        request: ClientRequest,
668    ) -> ParticipantSemanticOutcome<ServerValue> {
669        ParticipantSemanticOutcome::unchanged(self.handle(context, conversations, request))
670    }
671
672    /// Applies one decoded participant request to protocol-owned authority.
673    ///
674    /// # Errors
675    ///
676    /// Returns [`ParticipantSemanticError`] when durable or protocol authority
677    /// cannot produce a truthful terminal value. The connection fails rather
678    /// than fabricating a response.
679    fn handle(
680        &self,
681        context: ParticipantConnectionContext,
682        conversations: &mut ParticipantConnectionConversations,
683        request: ClientRequest,
684    ) -> Result<ServerValue, ParticipantSemanticError>;
685}
686
687/// Server-sealed participant activation token installed on a connection
688/// supervisor.
689///
690/// The semantic handler and its durable store form one value so participant
691/// capability activation cannot observe one without the other. The supervisor
692/// uses the store to durably allocate connection incarnations before spawning a
693/// connection process, and the process uses the handler only after that exact
694/// incarnation has been carried into its state. The token atomically carries the
695/// pair declared by server composition; it does not independently prove storage
696/// namespace identity.
697///
698/// Construction and access are server-private. Until a complete production
699/// lifecycle handler exists, external [`ConnectionServices`](crate::server::connection::ConnectionServices)
700/// implementations cannot manufacture an activation token or advertise the
701/// participant capability.
702#[derive(Clone, Debug)]
703pub struct InstalledParticipantService {
704    handler: Arc<dyn ParticipantSemanticHandler>,
705    durable_store: Arc<dyn DurableStore>,
706    frame_limit: ValidatedFrameLimit,
707    publication_registry: Arc<ParticipantPublicationRegistry>,
708    /// Connections refused `MarkerSettlementBackpressure` in this process
709    /// lifetime, by conversation. See [`MarkerSettlementWaiter`].
710    settlement_waiters: Arc<
711        std::sync::Mutex<std::collections::BTreeMap<ConversationId, Vec<MarkerSettlementWaiter>>>,
712    >,
713    /// The connection runtime told about every candidate-lane drain. Weak so
714    /// the service never keeps the runtime that owns it alive.
715    candidate_lane_listener: Arc<std::sync::Mutex<Option<Weak<dyn CandidateLaneListener>>>>,
716}
717
718impl InstalledParticipantService {
719    /// Pairs a semantic handler, its declared durable store, and the raw
720    /// configured participant wire-frame limit.
721    ///
722    /// Production construction happens exactly once, in the server's
723    /// connection-services layer, from the deployment's `[participant]`
724    /// configuration; tests construct it directly with fixture handlers.
725    ///
726    /// # Errors
727    ///
728    /// Returns the shared codec error when the configured limit is smaller than
729    /// the protocol's minimum complete frame.
730    pub(crate) fn new(
731        handler: Arc<dyn ParticipantSemanticHandler>,
732        durable_store: Arc<dyn DurableStore>,
733        configured_wf: u64,
734    ) -> Result<Self, CodecError> {
735        Ok(Self {
736            handler,
737            durable_store,
738            frame_limit: normalize_configured_frame_limit(configured_wf)?,
739            publication_registry: Arc::new(ParticipantPublicationRegistry::default()),
740            settlement_waiters: Arc::new(std::sync::Mutex::new(std::collections::BTreeMap::new())),
741            candidate_lane_listener: Arc::new(std::sync::Mutex::new(None)),
742        })
743    }
744
745    /// Installs the runtime told about candidate-lane drains, replacing any
746    /// earlier one.
747    pub(crate) fn install_candidate_lane_listener(
748        &self,
749        listener: Weak<dyn CandidateLaneListener>,
750    ) -> Result<(), ParticipantSemanticError> {
751        let mut installed = self.candidate_lane_listener.lock().map_err(|_| {
752            ParticipantSemanticError::Internal {
753                message: "candidate-lane listener slot is poisoned".to_owned(),
754            }
755        })?;
756        *installed = Some(listener);
757        drop(installed);
758        Ok(())
759    }
760
761    /// Drains one conversation's candidate lane and tells the listener, as a
762    /// publish's drain would.
763    ///
764    /// # Errors
765    ///
766    /// Returns the handler's drain refusal after telling every drain it
767    /// committed first.
768    pub(crate) fn drain_candidate_lane(
769        &self,
770        conversation_id: ConversationId,
771    ) -> Result<(), ParticipantSemanticError> {
772        let outcome = self
773            .handler
774            .drain_candidate_lane_with_impact(conversation_id);
775        let (result, impact) = outcome.into_parts();
776        self.notify_impact(&impact)?;
777        result
778    }
779
780    /// Tells the installed listener that `conversation_id`'s lane drained.
781    ///
782    /// The listener is called with the slot lock released, because it retries
783    /// durable connection fates.
784    fn tell_candidate_lane_drained(
785        &self,
786        conversation_id: ConversationId,
787    ) -> Result<(), ParticipantSemanticError> {
788        let listener = self
789            .candidate_lane_listener
790            .lock()
791            .map_err(|_| ParticipantSemanticError::Internal {
792                message: "candidate-lane listener slot is poisoned".to_owned(),
793            })?
794            .as_ref()
795            .and_then(Weak::upgrade);
796        if let Some(listener) = listener {
797            listener.candidate_lane_drained(conversation_id);
798        }
799        Ok(())
800    }
801
802    /// Clones the durable store used by the installed participant service.
803    #[must_use]
804    pub(crate) fn durable_store(&self) -> Arc<dyn DurableStore> {
805        Arc::clone(&self.durable_store)
806    }
807
808    /// Returns the normalized configured complete-frame limit advertised by
809    /// this installed participant service.
810    #[must_use]
811    pub(crate) const fn frame_limit(&self) -> ValidatedFrameLimit {
812        self.frame_limit
813    }
814
815    /// Returns the signed semantic-conversation allowance shared by publication
816    /// readiness and connection-held encoded heads.
817    #[must_use]
818    pub(crate) fn publication_conversation_limit(&self) -> u64 {
819        self.handler.publication_conversation_limit()
820    }
821
822    /// Creates the strongly connection-owned ready inbox at process spawn.
823    #[must_use]
824    pub(crate) fn new_publication_inbox(&self) -> ParticipantPublicationInbox {
825        ParticipantPublicationInbox::new(self.handler.publication_conversation_limit())
826    }
827
828    /// Returns the shared weak publication registry.
829    #[must_use]
830    pub(crate) fn publication_registry(&self) -> &ParticipantPublicationRegistry {
831        &self.publication_registry
832    }
833
834    /// Selects one exact durable publication through the installed production
835    /// source.
836    pub(crate) fn next_publication(
837        &self,
838        connection_incarnation: ConnectionIncarnation,
839        conversation_id: ConversationId,
840        offered: Option<ParticipantOfferedProgress>,
841    ) -> Result<Option<ParticipantPublication>, ParticipantSemanticError> {
842        self.handler
843            .next_publication(connection_incarnation, conversation_id, offered)
844    }
845
846    pub(crate) fn publication_is_current(
847        &self,
848        publication: &ParticipantPublication,
849        offered: Option<ParticipantOfferedProgress>,
850    ) -> Result<bool, ParticipantSemanticError> {
851        self.handler.publication_is_current(publication, offered)
852    }
853
854    pub(crate) fn record_publication_offer(
855        &self,
856        publication: &ParticipantPublication,
857    ) -> Result<(), ParticipantSemanticError> {
858        self.handler.record_publication_offer(publication)
859    }
860
861    /// Installs the waiter a `MarkerSettlementBackpressure` refusal earns.
862    ///
863    /// The match is the scope: only that ONE `ServerValue` variant registers,
864    /// so an enrollment-wrapper refusal (which carries no epoch and no wake) and
865    /// every other refusal on the same arm install nothing. Re-refusing the same
866    /// conversation on the same connection REPLACES the waiter, because a
867    /// connection waits on its most recent refusal and never on two epochs at
868    /// once.
869    fn register_settlement_waiter(
870        &self,
871        context: ParticipantConnectionContext,
872        value: &ServerValue,
873    ) -> Result<(), ParticipantSemanticError> {
874        let ServerValue::MarkerSettlementBackpressure(refusal) = value else {
875            return Ok(());
876        };
877        let (conversation_id, refused_epoch) = match *refusal {
878            liminal_protocol::wire::MarkerSettlementBackpressure::CredentialAttach {
879                conversation_id,
880                refused_epoch,
881            }
882            | liminal_protocol::wire::MarkerSettlementBackpressure::Detach {
883                conversation_id,
884                refused_epoch,
885            } => (conversation_id, refused_epoch),
886        };
887        let incarnation = context.connection_incarnation();
888        let Some(target) = self
889            .publication_registry
890            .observer_target(incarnation)
891            .map_err(|error| ParticipantSemanticError::Internal {
892                message: format!("settlement publication target failed: {error}"),
893            })?
894        else {
895            return Ok(());
896        };
897        let mut waiters =
898            self.settlement_waiters
899                .lock()
900                .map_err(|_| ParticipantSemanticError::Internal {
901                    message: "settlement waiter registry is poisoned".to_owned(),
902                })?;
903        let entry = waiters.entry(conversation_id).or_default();
904        entry.retain(|waiter| waiter.connection_incarnation != incarnation);
905        entry.push(MarkerSettlementWaiter {
906            connection_incarnation: incarnation,
907            refused_epoch,
908            target,
909        });
910        drop(waiters);
911        Ok(())
912    }
913
914    /// Test hook onto [`Self::register_settlement_waiter`].
915    ///
916    /// The registry §0.16 obligation 3 rests on is private and is exercised in
917    /// production only as a side effect of a refusal travelling out of `handle`.
918    /// A pin that can only reach it that way measures the refusal path and the
919    /// registry at once, and cannot tell which of the two is scoping the wake.
920    /// These two hooks let the registry be measured ALONE.
921    #[cfg(test)]
922    pub(super) fn register_settlement_waiter_for_test(
923        &self,
924        context: ParticipantConnectionContext,
925        value: &ServerValue,
926    ) -> Result<(), ParticipantSemanticError> {
927        self.register_settlement_waiter(context, value)
928    }
929
930    /// Test hook onto [`Self::fire_settlements`].
931    #[cfg(test)]
932    pub(super) fn fire_settlements_for_test(
933        &self,
934        conversation_id: ConversationId,
935        settled_epochs: &[u64],
936    ) -> Result<(), ParticipantSemanticError> {
937        self.fire_settlements(conversation_id, settled_epochs)
938    }
939
940    /// Number of waiters currently installed for one conversation.
941    #[cfg(test)]
942    pub(super) fn settlement_waiter_count(&self, conversation_id: ConversationId) -> usize {
943        self.settlement_waiters.lock().map_or(0, |waiters| {
944            waiters.get(&conversation_id).map_or(0, Vec::len)
945        })
946    }
947
948    /// Fires the settlement wake for every connection whose OWN refusal named
949    /// this exact epoch, and for no one else.
950    ///
951    /// Epoch equality is load-bearing: it is what the stage-11 retry discipline
952    /// matches on, and it is also what keeps a connection waiting on a later
953    /// candidate from being told its own wait is over. Waiters are one-shot —
954    /// fired or dead, they leave the registry.
955    fn fire_settlements(
956        &self,
957        conversation_id: ConversationId,
958        settled_epochs: &[u64],
959    ) -> Result<(), ParticipantSemanticError> {
960        if settled_epochs.is_empty() {
961            return Ok(());
962        }
963        let mut waiters =
964            self.settlement_waiters
965                .lock()
966                .map_err(|_| ParticipantSemanticError::Internal {
967                    message: "settlement waiter registry is poisoned".to_owned(),
968                })?;
969        let Some(entry) = waiters.get_mut(&conversation_id) else {
970            return Ok(());
971        };
972        let mut fired = Vec::new();
973        entry.retain(|waiter| {
974            if settled_epochs.contains(&waiter.refused_epoch) {
975                fired.push((waiter.target.clone(), waiter.refused_epoch));
976                false
977            } else {
978                true
979            }
980        });
981        if entry.is_empty() {
982            waiters.remove(&conversation_id);
983        }
984        drop(waiters);
985        for (target, refused_epoch) in fired {
986            target
987                .publish_marker_settled(MarkerSettledPublication {
988                    conversation_id,
989                    refused_epoch,
990                })
991                .map_err(|error| ParticipantSemanticError::Internal {
992                    message: format!("marker settled publication failed: {error}"),
993                })?;
994        }
995        Ok(())
996    }
997
998    fn notify_impact(&self, impact: &DispatchImpact) -> Result<(), ParticipantSemanticError> {
999        let Some(conversation_id) = impact.conversation_id() else {
1000            return Ok(());
1001        };
1002        if impact.candidate_lane_drained() {
1003            self.tell_candidate_lane_drained(conversation_id)?;
1004        }
1005        self.fire_settlements(conversation_id, impact.settled_epochs())?;
1006        for target in impact.target_union() {
1007            self.publication_registry
1008                .notify(
1009                    target.binding_epoch().connection_incarnation,
1010                    conversation_id,
1011                )
1012                .map_err(|error| ParticipantSemanticError::Internal {
1013                    message: format!("participant publication wake failed: {error}"),
1014                })?;
1015        }
1016        Ok(())
1017    }
1018}
1019
1020impl ParticipantSemanticHandler for InstalledParticipantService {
1021    fn service_fatal(&self) -> Result<Option<ParticipantServiceFatal>, ParticipantSemanticError> {
1022        self.handler.service_fatal()
1023    }
1024
1025    fn latch_connection_fate_intent_incomplete(
1026        &self,
1027        open_sequence: u64,
1028        conversation_id: ConversationId,
1029    ) -> Result<ParticipantServiceFatal, ParticipantSemanticError> {
1030        self.handler
1031            .latch_connection_fate_intent_incomplete(open_sequence, conversation_id)
1032    }
1033
1034    fn publication_conversation_limit(&self) -> u64 {
1035        self.handler.publication_conversation_limit()
1036    }
1037
1038    fn handle_connection_fate(
1039        &self,
1040        work_item: ConnectionFateWorkItem,
1041    ) -> Result<(), ParticipantSemanticError> {
1042        let outcome = self.handler.handle_connection_fate_with_impact(work_item);
1043        let (result, impacts) = outcome.into_parts();
1044        for impact in &impacts {
1045            self.notify_impact(impact)?;
1046        }
1047        result
1048    }
1049
1050    fn handle_connection_fate_with_impact(
1051        &self,
1052        work_item: ConnectionFateWorkItem,
1053    ) -> ParticipantConnectionFateOutcome {
1054        let result = self.handle_connection_fate(work_item);
1055        ParticipantConnectionFateOutcome::unchanged(result)
1056    }
1057
1058    fn drain_candidate_lane_with_impact(
1059        &self,
1060        conversation_id: ConversationId,
1061    ) -> ParticipantSemanticOutcome<()> {
1062        ParticipantSemanticOutcome::unchanged(self.drain_candidate_lane(conversation_id))
1063    }
1064
1065    fn repair_unclean_server_restart(
1066        &self,
1067        current_server_incarnation: u64,
1068    ) -> Result<(), ParticipantSemanticError> {
1069        self.handler
1070            .repair_unclean_server_restart(current_server_incarnation)
1071    }
1072
1073    fn connection_has_bound_participant(
1074        &self,
1075        connection_incarnation: ConnectionIncarnation,
1076        conversations: &[ConversationId],
1077    ) -> Result<bool, ParticipantSemanticError> {
1078        self.handler
1079            .connection_has_bound_participant(connection_incarnation, conversations)
1080    }
1081
1082    fn handle(
1083        &self,
1084        context: ParticipantConnectionContext,
1085        conversations: &mut ParticipantConnectionConversations,
1086        request: ClientRequest,
1087    ) -> Result<ServerValue, ParticipantSemanticError> {
1088        if let ClientRequest::ObserverRecovery(request) = request {
1089            let target = self
1090                .publication_registry
1091                .observer_target(context.connection_incarnation())
1092                .map_err(|error| ParticipantSemanticError::Internal {
1093                    message: format!("observer publication target failed: {error}"),
1094                })?;
1095            return self
1096                .handler
1097                .handle_observer_recovery(context, conversations, request, target);
1098        }
1099        let outcome = self
1100            .handler
1101            .handle_with_impact(context, conversations, request);
1102        let (result, impact) = outcome.into_parts();
1103        // Fire before registering: a request that both drained and was refused
1104        // must not wake itself with its own drain, and within one request the
1105        // settlement it cleared is never the one it is now waiting on.
1106        self.notify_impact(&impact)?;
1107        if let Ok(value) = &result {
1108            self.register_settlement_waiter(context, value)?;
1109        }
1110        result
1111    }
1112}
1113
1114/// Result of dispatching one generic frame through participant transport.
1115#[derive(Debug)]
1116pub enum ParticipantDispatch {
1117    /// The generic frame belongs to another protocol.
1118    NotParticipant,
1119    /// Exact encoded response selected by the shared gate or semantic handler.
1120    Respond(Frame),
1121    /// Exact crate-owned pre-semantic rejection, followed by connection close.
1122    RespondThenClose(Frame),
1123    /// No truthful participant response exists; the connection must fail closed.
1124    Fatal(ParticipantDispatchError),
1125}
1126
1127/// Failure after a generic frame has entered participant dispatch.
1128#[derive(Debug, thiserror::Error)]
1129pub enum ParticipantDispatchError {
1130    /// The preserved generic frame could not represent a canonical participant frame.
1131    #[error("invalid generic participant frame")]
1132    InvalidGenericFrame,
1133    /// The semantic handler could not produce a protocol value.
1134    #[error(transparent)]
1135    Semantic(#[from] ParticipantSemanticError),
1136    /// The crate-produced value could not be encoded into the generic transport.
1137    #[error("failed to encode participant response: {0:?}")]
1138    Encode(CodecError),
1139}
1140
1141fn pass_refusal(
1142    principal: Option<&PassPrincipal>,
1143    request: &liminal_protocol::wire::ClientRequest,
1144) -> Option<liminal_protocol::wire::TransportRejectionReason> {
1145    let principal = principal?;
1146    match request {
1147        liminal_protocol::wire::ClientRequest::Enrollment(request) if !principal.may_enroll => Some(liminal_protocol::wire::TransportRejectionReason::EnrollmentNotPermitted),
1148        liminal_protocol::wire::ClientRequest::Enrollment(request) if !principal.conversations.contains(&request.conversation_id) => Some(liminal_protocol::wire::TransportRejectionReason::EnrollmentConversationOutOfScope),
1149        liminal_protocol::wire::ClientRequest::CredentialAttach(request) if !principal.conversations.contains(&request.conversation_id) => Some(liminal_protocol::wire::TransportRejectionReason::CredentialAttachConversationOutOfScope),
1150        _ => None,
1151    }
1152}
1153
1154/// The write-outcome-unknown value (`0x0128`) answering `request`, or `None`
1155/// for a request that carries no attempt token to be re-presented with.
1156const fn write_outcome_unknown(
1157    request: &liminal_protocol::wire::ClientRequest,
1158) -> Option<ServerValue> {
1159    use liminal_protocol::wire::{
1160        AttachEnvelope, ClientRequest, DetachEnvelope, EnrollmentEnvelope, LeaveEnvelope,
1161        RecordAdmissionEnvelope, WriteOutcomeUnknown,
1162    };
1163    Some(ServerValue::WriteOutcomeUnknown(match request {
1164        ClientRequest::Enrollment(request) => WriteOutcomeUnknown::Enrollment {
1165            request: EnrollmentEnvelope {
1166                conversation_id: request.conversation_id,
1167                enrollment_token: request.enrollment_token,
1168            },
1169        },
1170        ClientRequest::CredentialAttach(request) => WriteOutcomeUnknown::CredentialAttach {
1171            request: AttachEnvelope {
1172                conversation_id: request.conversation_id,
1173                participant_id: request.participant_id,
1174                capability_generation: request.capability_generation,
1175                attach_attempt_token: request.attach_attempt_token,
1176                accept_marker_delivery_seq: request.accept_marker_delivery_seq,
1177            },
1178        },
1179        ClientRequest::Detach(request) => WriteOutcomeUnknown::Detach {
1180            request: DetachEnvelope {
1181                conversation_id: request.conversation_id,
1182                participant_id: request.participant_id,
1183                capability_generation: request.capability_generation,
1184                detach_attempt_token: request.detach_attempt_token,
1185            },
1186        },
1187        ClientRequest::Leave(request) => WriteOutcomeUnknown::Leave {
1188            request: LeaveEnvelope {
1189                conversation_id: request.conversation_id,
1190                participant_id: request.participant_id,
1191                capability_generation: request.capability_generation,
1192                leave_attempt_token: request.leave_attempt_token,
1193            },
1194        },
1195        ClientRequest::RecordAdmission(request) => WriteOutcomeUnknown::RecordAdmission {
1196            request: RecordAdmissionEnvelope {
1197                conversation_id: request.conversation_id,
1198                participant_id: request.participant_id,
1199                capability_generation: request.capability_generation,
1200                record_admission_attempt_token: request.record_admission_attempt_token,
1201            },
1202        },
1203        _ => return None,
1204    }))
1205}
1206
1207/// Gates, decodes, semantically applies, and encodes one participant frame.
1208///
1209/// Transport rejection values originate in `liminal-protocol`; semantic values
1210/// originate only in `handler`. No lifecycle outcome is constructed here.
1211#[must_use]
1212pub fn dispatch_generic_frame(
1213    frame: &Frame,
1214    authenticated: bool,
1215    session: ParticipantSession,
1216    context: ParticipantConnectionContext,
1217    pass_principal: Option<&PassPrincipal>,
1218    conversations: &mut ParticipantConnectionConversations,
1219    handler: &dyn ParticipantSemanticHandler,
1220) -> ParticipantDispatch {
1221    let (value, close_after_response) = match gate_generic_frame(frame, authenticated, session) {
1222        ParticipantIngress::NotParticipant => return ParticipantDispatch::NotParticipant,
1223        ParticipantIngress::Rejected(rejection) => {
1224            (ServerValue::ParticipantTransportRejected(rejection), true)
1225        }
1226        ParticipantIngress::InvalidGenericFrame => {
1227            return ParticipantDispatch::Fatal(ParticipantDispatchError::InvalidGenericFrame);
1228        }
1229        ParticipantIngress::Request(request) => {
1230            if let Some(reason) = pass_refusal(pass_principal, &request) {
1231                (
1232                    ServerValue::ParticipantTransportRejected(
1233                        liminal_protocol::wire::ParticipantTransportRejected { reason },
1234                    ),
1235                    false,
1236                )
1237            } else {
1238                let outcome_unknown = write_outcome_unknown(&request);
1239                match handler.handle(context, conversations, request) {
1240                    Ok(value) => (value, false),
1241                    Err(error) => match (&error, outcome_unknown) {
1242                        (
1243                            ParticipantSemanticError::WriteOutcomeUnknown { message },
1244                            Some(value),
1245                        ) => {
1246                            tracing::warn!(
1247                                %message,
1248                                "a participant write's outcome is unknown; the client is told so \
1249                                 and re-presents the request with its token"
1250                            );
1251                            (value, false)
1252                        }
1253                        _ => {
1254                            return ParticipantDispatch::Fatal(ParticipantDispatchError::Semantic(
1255                                error,
1256                            ));
1257                        }
1258                    },
1259                }
1260            }
1261        }
1262    };
1263    match encode_server_value(value) {
1264        Ok(frame) if close_after_response => ParticipantDispatch::RespondThenClose(frame),
1265        Ok(frame) => ParticipantDispatch::Respond(frame),
1266        Err(error) => ParticipantDispatch::Fatal(ParticipantDispatchError::Encode(error)),
1267    }
1268}