Skip to main content

aion_server/worker/
liminal_transport.rs

1//! Cross-node outbox dispatch over the liminal bus (LSUB push transport).
2//!
3//! # What this is (production push path)
4//!
5//! This module wires the durable outbox's fan-out dispatch over liminal to a
6//! REAL remote aion worker and returns the worker's result through the existing
7//! [`OutboxDeliveryCallback`](super::bridge::OutboxDeliveryCallback), behind the
8//! `liminal-transport` Cargo feature and the `outbox.transport = liminal`
9//! runtime flag. The aion-server HOSTS the liminal listener: a remote worker
10//! connects IN and self-describes in-band, the server registers it in the SAME
11//! connected-worker registry a gRPC worker joins, and a claimed row is PUSHED out
12//! on the worker's existing connection (the LSUB-0 server-push primitive).
13//!
14//! # Routing (NSTQ-5 / NODE-5)
15//!
16//! A worker is selected by the row's `(namespace, task_queue, activity_type,
17//! node)` pool key through the EXISTING registry `select_worker` — the same
18//! selection the gRPC path uses, so routing semantics are shared. `activity_type`
19//! is NOT a routing dimension at the wire: it rides inside the [`DispatchRequest`]
20//! payload and is matched by the worker after delivery, exactly as the gRPC
21//! registry pushes `activity_type` in the task body while selecting the worker by
22//! pool key. See `docs/NAMESPACE-TASKQUEUE-SPLIT-DESIGN.md` §4.2. The
23//! [`dispatch_channel_name`] derivation remains the single source of truth for the
24//! pool-channel string, pinned for any future channel-subscription subscriber so
25//! the two sides cannot drift.
26//!
27//! # The seams it implements
28//!
29//! - [`RegistryLiminalDispatch`] implements
30//!   [`OutboxRowDispatch`](super::outbox_dispatcher::OutboxRowDispatch): for each
31//!   claimed row it selects a worker from the connected-worker registry, pushes
32//!   the [`DispatchRequest`] to that worker's liminal connection via its
33//!   [`LiminalWorkerDelivery`], and re-enters the worker's [`DispatchResponse`]
34//!   through the SAME [`LiminalCompletionSource`] / [`OutboxDeliveryCallback`] the
35//!   gRPC completion path uses. A row that reaches no matching worker, or whose
36//!   worker is not liminal-delivered, returns an error so the outbox's unchanged
37//!   retry/backoff drives it — the same honest no-worker contract as the gRPC
38//!   path.
39//! - [`LiminalConnectionNotifier`] is the SERVER half of in-band registration:
40//!   when a worker connects with a [`WorkerRegistration`](WireWorkerRegistration)
41//!   the notifier inserts a [`WorkerDelivery::Liminal`] into the registry, and
42//!   drops it on disconnect.
43//! - [`LiminalCompletionSource`] maps a [`DispatchResponse`] onto the delivery
44//!   callback, threading `run_id` end-to-end so the existing continue-as-new run
45//!   gates apply unchanged.
46//!
47//! # The channel-subscription seam (documented, distinct from the push path)
48//!
49//! [`dispatch_channel_name`] derives the pool channel a `(namespace, task_queue)`
50//! pool addresses, optionally pinned to a `node` (NODE-2/NODE-5). The production
51//! path above does not publish to that channel — it pushes to a connected worker
52//! the server already owns — but the derivation is retained as the pinned contract
53//! any future channel-subscription transport MUST honour so the dispatcher and a
54//! subscriber cannot drift:
55//!
56//! - An UNPINNED worker pool addressed `(namespace, task_queue)` subscribes to
57//!   `dispatch_channel_name(namespace, task_queue, None)`.
58//! - A NODE-PINNED dispatch (the row carries `Some(node)`) maps to
59//!   `dispatch_channel_name(namespace, task_queue, Some(node))` — a DISTINCT
60//!   channel that a worker on that node must ALSO subscribe to in order to serve
61//!   pinned work; the unpinned channel alone never delivers a pinned dispatch.
62//!
63//! That is the single contract the seam must honour.
64
65use std::collections::HashMap;
66use std::sync::{Arc, Mutex, OnceLock};
67use std::time::Duration;
68
69use aion_core::{ActivityId, ContentType, Payload, RunId, WorkflowId};
70use aion_store::OutboxRow;
71use async_trait::async_trait;
72use liminal::protocol::WorkerRegistration as WireWorkerRegistration;
73use liminal_sdk::{SchemaMetadata, SchemaValidate};
74use liminal_server::ServerError as LiminalServerError;
75use liminal_server::server::connection::{
76    ConnectionNotifier, ConnectionSupervisor, PushReplyAwaiter,
77};
78use serde::{Deserialize, Serialize};
79
80use super::bridge::OutboxDeliveryCallback;
81use super::envelope::{CompletionFences, CompletionToken, idempotency_key};
82use super::outbox_dispatcher::{DeliveryGate, OutboxRowDispatch};
83use super::registry::{ConnectedWorkerRegistry, WorkerDelivery, WorkerHandle, WorkerRegistration};
84use crate::error::ServerError;
85
86/// Upper bound on how long a server-initiated intervention push waits for the
87/// worker's correlated control-plane acknowledgement. Activity dispatch replies
88/// use an unbounded held wait because an activity may legitimately run a while.
89const PUSH_REPLY_TIMEOUT: Duration = Duration::from_secs(30);
90
91/// Re-arm cadence for the engine-seam bridge's UNBOUNDED reply wait
92/// ([`receive_bridge_reply`]). Each elapsed poll is a benign re-arm, never a
93/// failure: the bridge dispatch contract imposes no activity timeout of its own
94/// (agent-style activities legitimately run for over an hour), exactly like the
95/// gRPC bridge's unbounded `recv`. Worker loss still terminates the wait
96/// promptly — the awaiter wakes with the typed Disconnected error the moment the
97/// connection closes.
98const BRIDGE_REPLY_POLL: Duration = Duration::from_secs(1);
99
100/// Wire request carrying one scheduled activity to a liminal worker.
101///
102/// Mirrors the dispatch half of the gRPC `ActivityTask`: the fields the worker
103/// needs to execute the activity and to correlate its result back to the exact
104/// execution (`workflow_id`, `ordinal`, `run_id`). `run_id` rides end-to-end so
105/// the existing continue-as-new run gates hold over the liminal wire (the design
106/// doc §3.3 requirement that `RunId` stays on the wire).
107#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
108pub struct DispatchRequest {
109    /// Activity type the worker must execute.
110    pub activity_type: String,
111    /// Workflow that scheduled this fan-out activity. Carried in its serde form
112    /// so no fragile id parsing happens on the wire.
113    pub workflow_id: WorkflowId,
114    /// Pinned ordinal of this activity within the workflow's fan-out range.
115    pub ordinal: u64,
116    /// Run that dispatched this ordinal, when known (continue-as-new safety).
117    pub run_id: Option<RunId>,
118    /// Opaque execution-generation proof echoed verbatim by the worker.
119    pub completion_token: String,
120    /// Stable external-effect key for this run and action site.
121    pub idempotency_key: String,
122    /// Opaque activity input bytes (JSON-tagged on the aion side).
123    pub input: Vec<u8>,
124    /// One-based delivery attempt, mirroring the gRPC `ActivityTask.attempt`.
125    /// The engine-seam bridge threads the real attempt so a retry executes with
126    /// attempt-aware handler semantics identical to the gRPC transport; the
127    /// outbox path stamps the row's stored zero-based attempt as one-based.
128    /// Serde-defaulted to `1` so a frame from a pre-attempt server (or an old
129    /// recorded frame) still decodes as a first delivery.
130    #[serde(default = "first_attempt")]
131    pub attempt: u32,
132    /// Engine-provided routing/metadata labels, mirroring the gRPC
133    /// `ActivityTask.labels`. Empty (the serde default) on the outbox path,
134    /// which has no label source.
135    #[serde(default)]
136    pub labels: std::collections::BTreeMap<String, String>,
137    /// The server's heartbeat window in milliseconds when this dispatch is
138    /// tracked by the server's per-task liveness tracker (the engine-seam
139    /// bridge path), or `0` when it is not (the outbox path, whose liveness
140    /// backstop is its own retry loop). A non-zero window tells the worker to
141    /// pump automatic liveness beats at a quarter-window cadence so the
142    /// server's heartbeat sweeper never expires a healthy long-running
143    /// activity — the exact liminal mirror of the gRPC worker's automatic
144    /// liveness pump.
145    #[serde(default)]
146    pub heartbeat_window_ms: u64,
147}
148
149/// Serde default for [`DispatchRequest::attempt`]: a frame that predates the
150/// attempt field is a first delivery.
151const fn first_attempt() -> u32 {
152    1
153}
154
155impl SchemaValidate for DispatchRequest {
156    fn schema_metadata() -> SchemaMetadata {
157        SchemaMetadata::new(
158            "aion.outbox.dispatch.request",
159            "1",
160            br#"{"type":"object"}"#.as_slice(),
161        )
162    }
163}
164
165/// Wire response carrying one worker result back to the outbox.
166///
167/// Mirrors the completion half of the gRPC `ActivityResult`: the correlation ids
168/// plus either a success result or a failure reason. `LiminalCompletionSource`
169/// maps this onto the existing [`OutboxDeliveryCallback`].
170#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
171pub struct DispatchResponse {
172    /// Workflow the completion belongs to.
173    pub workflow_id: WorkflowId,
174    /// Pinned ordinal the completion correlates against.
175    pub ordinal: u64,
176    /// Run that issued the dispatch, echoed back for the run gate.
177    pub run_id: Option<RunId>,
178    /// Opaque execution-generation proof echoed from the request.
179    pub completion_token: String,
180    /// Worker outcome: `Ok(result)` or `Err(reason)`.
181    pub outcome: Result<String, String>,
182}
183
184impl SchemaValidate for DispatchResponse {
185    fn schema_metadata() -> SchemaMetadata {
186        SchemaMetadata::new(
187            "aion.outbox.dispatch.response",
188            "1",
189            br#"{"type":"object"}"#.as_slice(),
190        )
191    }
192}
193
194/// Wire request carrying one neutral mid-run intervention command to a liminal
195/// worker (NOI-6, §6.2).
196///
197/// Rides the SAME liminal server-push channel as [`DispatchRequest`], distinguished
198/// on the wire by its unique required `intervention` field — a plain
199/// [`DispatchRequest`] has no such field, so the worker demuxes the two by which
200/// one deserializes. The whole envelope is neutral: it carries an
201/// [`InterventionCommand`], never a harness type. Field-for-field mirrored by the
202/// worker's `liminal::InterventionRequest`.
203#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
204pub struct InterventionRequest {
205    /// The neutral command to route to the worker owning the target attempt.
206    pub intervention: aion_core::InterventionCommand,
207}
208
209impl SchemaValidate for InterventionRequest {
210    fn schema_metadata() -> SchemaMetadata {
211        SchemaMetadata::new(
212            "aion.intervention.request",
213            "1",
214            br#"{"type":"object"}"#.as_slice(),
215        )
216    }
217}
218
219/// Wire response carrying the worker's neutral intervention ack back to the server
220/// (NOI-6). Field-for-field mirrored by the worker's `liminal::InterventionReply`.
221#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
222pub struct InterventionReply {
223    /// The neutral applied/gated/stale outcome the operator receives.
224    pub outcome: aion_core::InterventionOutcome,
225}
226
227impl SchemaValidate for InterventionReply {
228    fn schema_metadata() -> SchemaMetadata {
229        SchemaMetadata::new(
230            "aion.intervention.reply",
231            "1",
232            br#"{"type":"object"}"#.as_slice(),
233        )
234    }
235}
236
237/// Reserved liminal channel a worker publishes automatic liveness beats on.
238///
239/// The liminal wire has no gRPC-style heartbeat frame, so per-task liveness
240/// rides a reserved publish channel exactly as the observability transcript
241/// does: the worker's runtime pumps a [`WorkerLivenessBeat`] per in-flight
242/// tracked dispatch at a quarter-window cadence, and the server's
243/// [`LiminalConnectionNotifier`] consumes the channel and refreshes the shared
244/// [`HeartbeatTracker`] — so the #176 expiry sweeper is genuinely
245/// transport-agnostic: a healthy liminal worker running a long activity is
246/// never falsely expired, and a wedged one (which stops pumping) still is.
247/// Mirrored byte-for-byte by the worker crate's constant of the same name.
248pub const WORKER_LIVENESS_CHANNEL: &str = "aion.worker.liveness";
249
250/// Reserved liminal channel a worker announces its intervention capabilities on.
251///
252/// The in-band [`WireWorkerRegistration`] frame is a published liminal protocol
253/// type and cannot carry aion-level capability metadata, so a worker whose
254/// harness supports interventions publishes a [`WorkerCapabilitiesAnnouncement`]
255/// here immediately after registering (once per connection, so a redialed
256/// worker re-announces). The notifier consumes the channel and applies the
257/// announcement to the registered handle — the set the intervention router
258/// gates on and the ops console's live-attempts enumeration reports. Mirrored
259/// byte-for-byte by the worker crate's constant of the same name.
260pub const WORKER_CAPABILITIES_CHANNEL: &str = "aion.worker.capabilities";
261
262/// Wire announcement of a worker's advertised intervention capabilities.
263///
264/// Field-for-field mirror of the worker crate's `WorkerCapabilitiesAnnouncement`
265/// (the same cross-crate contract the dispatch/response pairs pin). The worker
266/// is identified by its CONNECTION (the publish's pid resolves the registered
267/// worker), never by wire-supplied identity, so an announcement can only ever
268/// apply to the worker that sent it.
269#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
270pub struct WorkerCapabilitiesAnnouncement {
271    /// The neutral intervention primitives the worker's harness supports.
272    pub capabilities: aion_core::InterventionCapabilities,
273}
274
275/// Wire liveness beat for one in-flight dispatch (the liminal mirror of the
276/// gRPC `Heartbeat` frame, liveness-only — progress payloads are not carried).
277///
278/// Field-for-field mirror of the worker crate's `WorkerLivenessBeat` (same
279/// serde field names + `aion-core` id types), the same cross-crate contract the
280/// dispatch/response pairs pin. The worker is identified by its CONNECTION (the
281/// publish's pid resolves the registered worker), never by wire-supplied
282/// identity, so a beat can only ever refresh tasks of the worker that sent it.
283#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
284pub struct WorkerLivenessBeat {
285    /// Workflow owning the in-flight activity being kept alive.
286    pub workflow_id: WorkflowId,
287    /// Pinned ordinal of the in-flight activity being kept alive.
288    pub ordinal: u64,
289}
290
291/// Builds the wire request for one claimed outbox row.
292///
293/// Kept free-standing (not a method) so both the dispatch path and tests build
294/// the request the same way.
295#[must_use]
296pub fn request_for_row(
297    row: &OutboxRow,
298    run_id: &RunId,
299    completion_token: &CompletionToken,
300) -> DispatchRequest {
301    let activity_id = ActivityId::from_sequence_position(row.ordinal);
302    DispatchRequest {
303        activity_type: row.activity_type.clone(),
304        workflow_id: row.workflow_id.clone(),
305        ordinal: row.ordinal,
306        run_id: Some(run_id.clone()),
307        completion_token: completion_token.as_str().to_owned(),
308        idempotency_key: idempotency_key(&row.workflow_id, run_id, &activity_id),
309        input: row.input.bytes().to_vec(),
310        // The stored zero-based attempt is stamped one-based on the wire (zero
311        // is malformed), exactly as the gRPC outbox arm's `to_scheduled` does.
312        attempt: row.attempt.saturating_add(1),
313        // Outbox rows carry no engine labels (the gRPC arm sends empty too).
314        labels: std::collections::BTreeMap::new(),
315        // Outbox dispatches are not tracked by the server's per-task liveness
316        // tracker — the outbox retry loop is their liveness backstop — so no
317        // window is assigned and the worker does not pump beats for them.
318        heartbeat_window_ms: 0,
319    }
320}
321
322/// The single reserved character that separates channel segments. Because
323/// `namespace`/`task_queue` are free-form, any occurrence of this byte INSIDE a
324/// segment must be escaped so it cannot be mistaken for the segment boundary.
325const SEGMENT_SEPARATOR: char = '.';
326
327/// The escape character used by [`encode_segment`]. It must itself be escaped so
328/// the encoding stays injective (otherwise `%2E` as a literal field value would
329/// collide with an encoded `.`).
330const SEGMENT_ESCAPE: char = '%';
331
332/// Percent-encodes the two reserved characters (`.` and `%`) inside one channel
333/// segment so distinct segment values can never collide across the join.
334///
335/// This is a minimal, deterministic, per-segment escape: a literal `.` becomes
336/// `%2E` and a literal `%` becomes `%25`; every other byte (including the empty
337/// string) passes through unchanged. Because both the separator AND the escape
338/// char are encoded, the mapping `value -> encoded` is injective: it is exactly
339/// reversible by replacing `%2E -> .` and `%25 -> %`, so two distinct values
340/// can never encode to the same string. Dot-free, percent-free inputs (the
341/// normal case, e.g. `"remote"`, `"gpu"`) are returned byte-for-byte unchanged,
342/// so existing channels are stable.
343fn encode_segment(segment: &str) -> String {
344    // Fast path: nothing reserved, return an owned copy unchanged.
345    if !segment.contains([SEGMENT_SEPARATOR, SEGMENT_ESCAPE]) {
346        return segment.to_owned();
347    }
348    let mut encoded = String::with_capacity(segment.len());
349    for ch in segment.chars() {
350        match ch {
351            // Encode the escape char FIRST so an already-present `%` cannot be
352            // confused with one we introduce for the separator.
353            SEGMENT_ESCAPE => encoded.push_str("%25"),
354            SEGMENT_SEPARATOR => encoded.push_str("%2E"),
355            other => encoded.push(other),
356        }
357    }
358    encoded
359}
360
361/// Derives the liminal dispatch channel for a worker pool addressed
362/// `(namespace, task_queue)`, optionally pinned to a specific `node`.
363///
364/// This is the **single, total source of truth** for the channel string: every
365/// site that needs the channel a `(namespace, task_queue[, node])` pool
366/// dispatches to — both this dispatcher and any future worker-pool subscription
367/// side — MUST call this function so the two sides cannot drift. The format is
368/// `"aion.dispatch.{namespace}.{task_queue}"` for an unpinned dispatch and
369/// `"aion.dispatch.{namespace}.{task_queue}.{node}"` when a `node` is pinned;
370/// each `{segment}` is independently passed through [`encode_segment`].
371///
372/// # The subscriber contract (the seam this function pins, NODE-5 / 13-x)
373///
374/// The subscriber side remains the documented seam (it does not exist yet; 13-0
375/// uses liminal's in-server echo responder). The contract both sides MUST honour:
376///
377/// - An **unpinned** worker pool addressed `(namespace, task_queue)` subscribes
378///   to `dispatch_channel_name(namespace, task_queue, None)` and receives every
379///   unpinned dispatch for that pool.
380/// - A **node-pinned** dispatch (the row carries `Some(node)`) goes to
381///   `dispatch_channel_name(namespace, task_queue, Some(node))`, a DISTINCT
382///   channel. A worker running on that node which is meant to serve pinned work
383///   for the pool MUST ALSO subscribe to that node-specific channel — the
384///   `None` channel alone will never deliver a node-pinned dispatch to it.
385///
386/// Because the `None` channel and any `Some(node)` channel are distinct strings,
387/// a node-pinned dispatch never reaches an unpinned-only subscriber and vice
388/// versa; node isolation is therefore enforced by the channel string itself.
389///
390/// # Injectivity (why the per-segment encode matters)
391///
392/// `namespace`, `task_queue` and `node` are all free-form (the design forbids
393/// preset categories), so a raw `format!` would be NON-injective: a `.` inside
394/// any field bleeds across the separator and pools the design declares disjoint
395/// collide onto one channel — e.g. `("a.b", "c", None)` and `("a", "b.c", None)`
396/// would both yield `aion.dispatch.a.b.c`, a cross-pool leak on the very
397/// isolation dimension this routing exists to keep separate. Encoding each
398/// segment independently (the separator `.` and the escape `%` are escaped within
399/// a segment) makes the map from `(namespace, task_queue, node)` to channel
400/// string injective: distinct triples always yield distinct channels, ACROSS
401/// segment counts too. The node segment is appended only for `Some(node)`, and
402/// because no encoded segment can contain a bare separator, a 2-segment channel
403/// (unpinned) can never be confused with a 3-segment channel (pinned) — e.g.
404/// `("a", "b", Some("c"))` and `("a", "b.c", None)` stay distinct, as do
405/// `("a.b", "c", None)` and `("a", "b", Some("c"))`.
406///
407/// `activity_type` is deliberately NOT part of the channel: it is *what to run*,
408/// matched by the worker after delivery (it rides inside [`DispatchRequest`]),
409/// not *which pool* — see `docs/NAMESPACE-TASKQUEUE-SPLIT-DESIGN.md` §4.2. The
410/// function is total (defined for every input) and stable (the same
411/// `(namespace, task_queue, node)` always yields the same channel).
412#[must_use]
413pub fn dispatch_channel_name(namespace: &str, task_queue: &str, node: Option<&str>) -> String {
414    let namespace = encode_segment(namespace);
415    let task_queue = encode_segment(task_queue);
416    match node {
417        Some(node) => {
418            let node = encode_segment(node);
419            format!("aion.dispatch.{namespace}.{task_queue}.{node}")
420        }
421        None => format!("aion.dispatch.{namespace}.{task_queue}"),
422    }
423}
424
425/// Derives the liminal dispatch channel for a claimed outbox row.
426///
427/// Thin wrapper over [`dispatch_channel_name`] reading the row's durable
428/// `(namespace, task_queue)` (NSTQ-2 columns) and its optional `node` (NODE-2):
429/// when `row.node` is `Some`, the row dispatches to the node-pinned sub-channel;
430/// when `None`, it derives the byte-identical unpinned channel. Kept
431/// free-standing so the dispatch path and tests derive the row's channel
432/// identically.
433#[must_use]
434pub fn channel_for_row(row: &OutboxRow) -> String {
435    dispatch_channel_name(&row.namespace, &row.task_queue, row.node.as_deref())
436}
437
438/// Wraps a reason in the existing worker-dispatch error so a non-deliverable
439/// dispatch drives the outbox's unchanged retry/backoff/dead-letter path. The
440/// row-derived `channel` is surfaced as the `activity_type` field for operator
441/// diagnostics (the field is a free-form context string on this transport's
442/// error).
443fn dispatch_error(channel: &str, reason: String) -> ServerError {
444    ServerError::WorkerDispatch {
445        namespace: "liminal".to_owned(),
446        activity_type: channel.to_owned(),
447        reason,
448    }
449}
450
451/// Receives one worker result over liminal and re-enters it into aion.
452///
453/// Holds the installed [`OutboxDeliveryCallback`] (the same prod
454/// `ServerOutboxDeliveryCallback` the gRPC completion path uses) and maps a
455/// [`DispatchResponse`] onto it, threading `run_id` so the continue-as-new run
456/// gates apply unchanged.
457pub struct LiminalCompletionSource {
458    callback: Arc<dyn OutboxDeliveryCallback>,
459    completion_fences: CompletionFences,
460}
461
462impl std::fmt::Debug for LiminalCompletionSource {
463    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
464        f.debug_struct("LiminalCompletionSource")
465            .finish_non_exhaustive()
466    }
467}
468
469impl LiminalCompletionSource {
470    /// Build a completion source over the shared outbox delivery callback.
471    #[must_use]
472    pub fn new(callback: Arc<dyn OutboxDeliveryCallback>) -> Self {
473        Self {
474            callback,
475            completion_fences: CompletionFences::default(),
476        }
477    }
478
479    /// Share the authoritative generation registry used by dispatch.
480    #[must_use]
481    pub fn with_completion_fences(mut self, completion_fences: CompletionFences) -> Self {
482        self.completion_fences = completion_fences;
483        self
484    }
485
486    /// Re-enter one worker result into aion through the delivery callback.
487    ///
488    /// Returns the callback's `bool`: `true` when delivered to a live run,
489    /// `false` when no run is live (the expected stale-completion drop that
490    /// recovery re-arms). A success outcome routes to `deliver_completion`; a
491    /// failure outcome to `deliver_failure`.
492    ///
493    /// # Errors
494    ///
495    /// Returns [`ServerError`] when the response carries an unparseable id or
496    /// the engine rejects the delivery.
497    pub fn deliver(&self, response: &DispatchResponse) -> Result<bool, ServerError> {
498        let run_id = response.run_id.as_ref().ok_or_else(|| {
499            dispatch_error(
500                "liminal completion",
501                "activity result run id is missing; refusing run-gate bypass".to_owned(),
502            )
503        })?;
504        let activity_id = ActivityId::from_sequence_position(response.ordinal);
505        let completion_token = CompletionToken::from_wire(
506            &response.workflow_id,
507            &activity_id,
508            response.completion_token.clone(),
509        )?;
510        if let Err(error) =
511            self.completion_fences
512                .accept(&response.workflow_id, &activity_id, &completion_token)
513        {
514            tracing::warn!(
515                workflow_id = %response.workflow_id,
516                %activity_id,
517                %error,
518                "liminal completion fence rejected a late or stale reply"
519            );
520            return Err(error);
521        }
522        match &response.outcome {
523            Ok(result) => self.callback.deliver_completion(
524                &response.workflow_id,
525                &activity_id,
526                Some(run_id),
527                result.clone(),
528            ),
529            Err(reason) => self.callback.deliver_failure(
530                &response.workflow_id,
531                &activity_id,
532                Some(run_id),
533                reason.clone(),
534            ),
535        }
536    }
537}
538
539/// Rebuilds the activity input payload from the wire request.
540///
541/// The aion side tags activity input as JSON; the wire carries the raw bytes, so
542/// a worker (or the test responder standing in for one) reconstructs the typed
543/// [`Payload`] with the JSON content type.
544#[must_use]
545pub fn payload_from_request(request: &DispatchRequest) -> Payload {
546    Payload::new(ContentType::Json, request.input.clone())
547}
548
549/// Delivery handle for a liminal-connected worker held in the worker registry.
550///
551/// A worker that connects over liminal is a first-class registry member selected
552/// the SAME way as a gRPC worker (`select_worker` on `(namespace, task_queue,
553/// node)`); this is the delivery leg the registry holds for it. It pairs the
554/// [`ConnectionSupervisor`] that owns the worker's connection with that
555/// connection's beamr `pid`, so [`Self::dispatch_held`] can push a
556/// [`DispatchRequest`] out on the worker's existing socket (the LSUB-0
557/// server-push primitive) and block for the correlated [`DispatchResponse`].
558#[derive(Clone)]
559pub struct LiminalWorkerDelivery {
560    supervisor: ConnectionSupervisor,
561    pid: u64,
562}
563
564impl std::fmt::Debug for LiminalWorkerDelivery {
565    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
566        f.debug_struct("LiminalWorkerDelivery")
567            .field("pid", &self.pid)
568            .finish_non_exhaustive()
569    }
570}
571
572impl LiminalWorkerDelivery {
573    /// Build a delivery handle for the worker reachable on connection `pid`
574    /// through `supervisor`.
575    #[must_use]
576    pub const fn new(supervisor: ConnectionSupervisor, pid: u64) -> Self {
577        Self { supervisor, pid }
578    }
579
580    /// The connection pid this worker is addressed on.
581    #[must_use]
582    pub const fn pid(&self) -> u64 {
583        self.pid
584    }
585
586    /// Push one outbox dispatch and wait without an activity-duration bound,
587    /// abandoning only when `keep_waiting` becomes false at a poll boundary.
588    ///
589    /// # Errors
590    ///
591    /// Returns the same typed push, receive, and decode failures as the shared
592    /// bridge wait.
593    pub fn dispatch_held(
594        &self,
595        request: &DispatchRequest,
596        keep_waiting: impl Fn() -> bool,
597    ) -> Result<Option<DispatchResponse>, ServerError> {
598        let awaiter = self.push_dispatch(request)?;
599        receive_bridge_reply(&awaiter, keep_waiting)
600    }
601
602    /// Serialize and push one dispatch out on the worker's connection, returning
603    /// the awaiter for its correlated reply — the shared push half of both
604    /// unbounded waits: [`Self::dispatch_held`] on the outbox path and the
605    /// engine-seam bridge dispatcher both use [`receive_bridge_reply`], matching
606    /// the gRPC bridge contract. One frame format, one push primitive, one held
607    /// wait policy.
608    ///
609    /// DELIBERATELY NO REPLY DEADLINE, unlike the liveness and intervention
610    /// pushes. A dispatch's reply IS the activity's completion, so its lifetime
611    /// is the activity's — `remote_gates.awl` declares legs at `timeout 45m`.
612    /// [`receive_bridge_reply`] re-arms on every poll timeout and waits
613    /// unbounded by contract, so this push NEVER abandons its slot and cannot
614    /// leak one: the slot is held for exactly as long as work is outstanding
615    /// and resolves when the reply lands. Attaching a deadline here would kill
616    /// long activities, and would be a regression, not a hardening. The leak
617    /// fixed on the other two sites came from ABANDONING a no-deadline slot,
618    /// which this site never does.
619    ///
620    /// # Errors
621    ///
622    /// Returns [`ServerError::WorkerBusy`] when liminal's typed connection cap
623    /// refuses admission, [`ServerError::WorkerConnectionLost`] for every other
624    /// push-enqueue failure, and [`ServerError::WorkerDispatch`] when the request
625    /// cannot be serialized.
626    pub(crate) fn push_dispatch(
627        &self,
628        request: &DispatchRequest,
629    ) -> Result<PushReplyAwaiter, ServerError> {
630        let payload = serde_json::to_vec(request).map_err(|error| {
631            dispatch_error("liminal-push", format!("request serialize failed: {error}"))
632        })?;
633        self.supervisor
634            .push_to_connection(self.pid, payload)
635            .map_err(|error| classify_push_error(&error))
636    }
637
638    /// Push already-encoded `payload` out on the worker's connection with an
639    /// explicit reply `deadline`, returning the awaiter for its correlated
640    /// reply.
641    ///
642    /// The raw push primitive behind the typed pushes above, used by the
643    /// connection liveness probe
644    /// ([`LivenessProbe`](super::liminal_liveness::LivenessProbe)) so the
645    /// dead-man switch rides the SAME server-push leg a dispatch does — a ping
646    /// that reaches the worker proves the exact path a dispatch would take, not
647    /// a parallel one that could be healthy while the real one is not.
648    ///
649    /// The deadline is LOAD-BEARING and is why this is not
650    /// `push_to_connection`. Riding the dispatch leg means sharing its bounded
651    /// §5 `max_pending_pushes_per_connection` admission, and a no-deadline slot
652    /// is reclaimed only by a consumed reply or a connection close — never by
653    /// the caller giving up. A probe that abandons an unanswered ping every
654    /// cadence therefore LEAKS one slot per round until the cap is exhausted,
655    /// at which point no dispatch, intervention or ping can be pushed on that
656    /// connection again. Measured live on run `dfd2117c`: 32 abandoned pings,
657    /// then permanent refusal, ≈240 s from first blocked ping. The probe built
658    /// to prove the dispatch path works is what destroyed it. With a deadline,
659    /// expiry removes the slot and RELEASES its cap admission.
660    ///
661    /// # Errors
662    ///
663    /// Returns [`ServerError::WorkerBusy`] when liminal's typed connection cap
664    /// refuses admission, and [`ServerError::WorkerConnectionLost`] for every
665    /// other push-enqueue failure.
666    pub fn push_payload_with_deadline(
667        &self,
668        payload: Vec<u8>,
669        deadline: Duration,
670    ) -> Result<PushReplyAwaiter, ServerError> {
671        self.supervisor
672            .push_to_connection_with_deadline(self.pid, payload, deadline)
673            .map_err(|error| classify_push_error(&error))
674    }
675
676    /// Push one neutral intervention command out on the worker's connection and
677    /// block for its correlated ack reply (NOI-6, §6.2).
678    ///
679    /// Uses the same connection as activity dispatch but carries an
680    /// [`InterventionRequest`] and decodes an [`InterventionReply`], so it rides the SAME server-push
681    /// channel as an activity dispatch. The push is a blocking, thread-based liminal
682    /// call; the async router runs it off the runtime.
683    ///
684    /// # Errors
685    ///
686    /// Returns [`ServerError::WorkerConnectionLost`] when the worker connection was
687    /// gone at push time or closed before replying (so the router surfaces the
688    /// too-late no-op); returns [`ServerError::WorkerDispatch`] when the request
689    /// cannot be serialized, the reply times out, or the reply cannot be decoded.
690    pub fn push_intervention(
691        &self,
692        request: &InterventionRequest,
693    ) -> Result<InterventionReply, ServerError> {
694        let payload = serde_json::to_vec(request).map_err(|error| {
695            dispatch_error(
696                "liminal-push",
697                format!("intervention serialize failed: {error}"),
698            )
699        })?;
700        // Deadline-bounded, and it must be: this wait ABANDONS on timeout (the
701        // `receive` error below is terminal, not a re-arm), so a no-deadline
702        // slot would be held until the connection closed and would count
703        // against the connection's §5 pending-push cap forever. The deadline
704        // matches the wait, so an intervention that goes unanswered releases
705        // its admission instead of leaking it. Contrast `push_dispatch`, whose
706        // wait re-arms and is unbounded by contract, and which therefore
707        // correctly takes no deadline.
708        let awaiter = self
709            .supervisor
710            .push_to_connection_with_deadline(self.pid, payload, PUSH_REPLY_TIMEOUT)
711            .map_err(|error| {
712                ServerError::worker_connection_lost(
713                    "liminal-push",
714                    format!("push intervention to worker failed: {error}"),
715                )
716            })?;
717        let reply = awaiter.receive(PUSH_REPLY_TIMEOUT).map_err(|error| {
718            if is_connection_closed_reply_error(&error) {
719                ServerError::worker_connection_lost(
720                    "liminal-push",
721                    format!("worker connection closed before intervention ack: {error}"),
722                )
723            } else {
724                dispatch_error("liminal-push", format!("intervention ack failed: {error}"))
725            }
726        })?;
727        serde_json::from_slice(&reply).map_err(|error| {
728            dispatch_error(
729                "liminal-push",
730                format!("intervention ack decode failed: {error}"),
731            )
732        })
733    }
734}
735
736/// Decodes one correlated reply payload as a [`DispatchResponse`].
737///
738/// Shared by the outbox wait ([`LiminalWorkerDelivery::dispatch_held`]) and the
739/// bridge wait ([`receive_bridge_reply`]) so the two paths can never diverge on
740/// the wire's reply shape.
741fn decode_dispatch_response(reply: &[u8]) -> Result<DispatchResponse, ServerError> {
742    serde_json::from_slice(reply).map_err(|error| {
743        dispatch_error(
744            "liminal-push",
745            format!("worker reply decode failed: {error}"),
746        )
747    })
748}
749
750/// Blocks for the correlated reply to an engine-seam BRIDGE dispatch push, with
751/// the bridge's UNBOUNDED wait contract: the engine imposes no activity timeout
752/// of its own, so an elapsed [`BRIDGE_REPLY_POLL`] merely re-arms the wait — the
753/// exact liminal mirror of the gRPC bridge's unbounded `recv`, which is released
754/// only by a completion or by stream teardown. The wait terminates on exactly:
755///
756/// - **the reply** — decoded as the worker's [`DispatchResponse`] and returned
757///   as `Ok(Some(response))`. A reply already buffered when a poll fires always
758///   wins over abandonment: the awaiter is drained before `keep_waiting` runs;
759/// - **abandonment** — `keep_waiting()` returned `false` at a poll boundary
760///   (the bridge passes "is this dispatch still tracked in-flight?"): the
761///   dispatch was resolved by another path (expiry sweep, shutdown drain, or a
762///   cleanup), so the wait returns `Ok(None)` and the router thread exits
763///   instead of parking on the connection indefinitely;
764/// - **worker loss** — the connection closed before replying: the awaiter wakes
765///   PROMPTLY with liminal's typed Disconnected error, surfaced as
766///   [`ServerError::WorkerConnectionLost`] so the bridge reports the same
767///   TRANSPORT-loss class the gRPC teardown sweep does;
768/// - **an unrecognized receive fault or a decode failure** — surfaced as
769///   [`ServerError::WorkerDispatch`].
770///
771/// Runs on a dedicated bridge reply thread, never on an async runtime worker.
772///
773/// # Errors
774///
775/// Returns [`ServerError::WorkerConnectionLost`] on worker loss and
776/// [`ServerError::WorkerDispatch`] on a receive fault or reply decode failure.
777pub(crate) fn receive_bridge_reply(
778    awaiter: &PushReplyAwaiter,
779    keep_waiting: impl Fn() -> bool,
780) -> Result<Option<DispatchResponse>, ServerError> {
781    loop {
782        match awaiter.receive(BRIDGE_REPLY_POLL) {
783            Ok(reply) => return decode_dispatch_response(&reply).map(Some),
784            // A bare poll timeout re-arms the wait while the dispatch is still
785            // outstanding (the wait is unbounded by contract; see the bridge
786            // module docs), and ends it cleanly once the dispatch was resolved
787            // elsewhere — the poll cadence bounds the router thread's lifetime
788            // to one poll past that resolution.
789            Err(LiminalServerError::PushReplyTimeout { .. }) => {
790                if !keep_waiting() {
791                    return Ok(None);
792                }
793            }
794            Err(error) if is_connection_closed_reply_error(&error) => {
795                return Err(ServerError::worker_connection_lost(
796                    "liminal-push",
797                    format!("worker connection closed before reply: {error}"),
798                ));
799            }
800            Err(error) => {
801                return Err(dispatch_error(
802                    "liminal-push",
803                    format!("worker reply failed: {error}"),
804                ));
805            }
806        }
807    }
808}
809
810/// Returns true when a liminal push-reply error is the *Disconnected* case (the
811/// worker's connection closed before it replied), as opposed to a genuine reply
812/// timeout (the worker is alive but slow).
813///
814/// Liminal returns these as distinct TYPED variants —
815/// `ServerError::PushReplyDisconnected` vs `PushReplyTimeout` (see `liminal-server`
816/// `supervisor.rs` `PushReplyAwaiter::receive`) — so this is a type match, not a
817/// message-text match: a worker that DIED (connection-lost, fast failover) is told
818/// apart from one that is merely SLOW (genuine timeout, normal backoff) by variant.
819fn is_connection_closed_reply_error(error: &LiminalServerError) -> bool {
820    matches!(error, LiminalServerError::PushReplyDisconnected { .. })
821}
822
823/// Classify a typed liminal push refusal without relying on error text.
824fn classify_push_error(error: &LiminalServerError) -> ServerError {
825    if is_connection_cap_error(error) {
826        ServerError::worker_busy(
827            "liminal-push",
828            format!("worker connection push cap reached: {error}"),
829        )
830    } else {
831        ServerError::worker_connection_lost(
832            "liminal-push",
833            format!("push to worker failed: {error}"),
834        )
835    }
836}
837
838/// Liminal's typed admission refusal when a connection has too many held pushes.
839fn is_connection_cap_error(error: &LiminalServerError) -> bool {
840    matches!(error, LiminalServerError::ConnectionCapReached { .. })
841}
842
843/// Cross-node [`OutboxRowDispatch`] that selects a liminal worker from the
844/// connected-worker registry and pushes the row to it.
845///
846/// This is the LSUB-1 server-side composition: for each claimed row it selects a
847/// worker by the row's `(namespace, task_queue, activity_type, node)` via the
848/// EXISTING registry `select_worker` (the same selection the gRPC path uses, so
849/// routing semantics are shared), pushes the [`DispatchRequest`] to that worker's
850/// liminal connection via its [`LiminalWorkerDelivery`], and re-enters the
851/// worker's [`DispatchResponse`] through the SAME [`LiminalCompletionSource`] /
852/// [`OutboxDeliveryCallback`] the existing completion path uses. A row that
853/// reaches no matching worker, or whose worker is not liminal-delivered, returns
854/// an error so the outbox's unchanged retry/backoff drives it — the same honest
855/// no-worker contract as the gRPC path.
856pub struct RegistryLiminalDispatch {
857    registry: ConnectedWorkerRegistry,
858    completion: LiminalCompletionSource,
859    delivery_gate: DeliveryGate,
860    /// Optional short-TTL per-namespace placement cache (Control-Plane Phase 2,
861    /// P2-P3), the SAME cache the gRPC
862    /// [`WorkerOutboxDispatch`](crate::worker::WorkerOutboxDispatch) is given. When
863    /// present, an UNPINNED row (`row.node == None`) whose namespace placement is
864    /// `Prefer{L}` selects an L-labelled worker and spills to any live worker when
865    /// none is up, via the SHARED
866    /// [`preferred_node_order`](crate::worker::preferred_node_order). When absent
867    /// (the default, every pre-Phase-2 construction and test) selection is
868    /// byte-identical to before: one `select_worker` off the row's own node.
869    /// Placement is NEVER stamped back onto the row — it is consulted only here,
870    /// in this non-replayed dispatcher, for worker selection.
871    placement_cache: Option<crate::worker::PlacementCache>,
872    /// Optional NOI-6 `attempt -> owning-worker` back-index. When installed via
873    /// [`Self::with_attempt_owners`], each dispatched agent attempt binds its
874    /// `(workflow, activity, attempt)` to the selected worker here BEFORE the push and
875    /// releases it after the reply, so the server's intervention router resolves the
876    /// CURRENT owner of a live attempt. `None` (the default, and every non-agent
877    /// deployment) skips the binding — intervention is simply never offered.
878    attempt_owners: Option<super::intervention::AttemptOwnerIndex>,
879}
880
881impl std::fmt::Debug for RegistryLiminalDispatch {
882    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
883        f.debug_struct("RegistryLiminalDispatch")
884            .field("placement_cache", &self.placement_cache.is_some())
885            .finish_non_exhaustive()
886    }
887}
888
889impl RegistryLiminalDispatch {
890    /// Build a registry-backed liminal dispatch that re-enters worker results
891    /// through `callback` (the shared `ServerOutboxDeliveryCallback`).
892    #[must_use]
893    pub fn new(
894        registry: ConnectedWorkerRegistry,
895        callback: Arc<dyn OutboxDeliveryCallback>,
896        delivery_gate: DeliveryGate,
897    ) -> Self {
898        Self {
899            registry,
900            completion: LiminalCompletionSource::new(callback),
901            delivery_gate,
902            placement_cache: None,
903            attempt_owners: None,
904        }
905    }
906
907    /// Share completion-generation authority with result ingestion.
908    #[must_use]
909    pub fn with_completion_fences(mut self, completion_fences: CompletionFences) -> Self {
910        self.completion = self.completion.with_completion_fences(completion_fences);
911        self
912    }
913
914    /// Install the NOI-6 attempt-owner back-index so each dispatched attempt binds
915    /// its owning worker for the intervention router to resolve (NOI-6).
916    ///
917    /// The SAME index the server's [`InterventionRouter`](super::intervention::InterventionRouter)
918    /// resolves through (from `ServerState::attempt_owners`), so a pushed command
919    /// reaches the worker this dispatcher sent the attempt to. Pure builder addition:
920    /// without it, no ownership is recorded and the router finds no owner (the
921    /// too-late no-op), exactly as before.
922    #[must_use]
923    pub fn with_attempt_owners(
924        mut self,
925        attempt_owners: super::intervention::AttemptOwnerIndex,
926    ) -> Self {
927        self.attempt_owners = Some(attempt_owners);
928        self
929    }
930
931    /// Attach the per-namespace placement cache so an unpinned row consults its
932    /// namespace's `Prefer` directive at selection time (Control-Plane Phase 2,
933    /// P2-P3) — the liminal mirror of
934    /// [`WorkerOutboxDispatch::with_placement_cache`](crate::worker::WorkerOutboxDispatch::with_placement_cache).
935    /// Pure builder addition: without it, selection is byte-identical to the
936    /// pre-Phase-2 behaviour.
937    #[must_use]
938    pub fn with_placement_cache(mut self, cache: crate::worker::PlacementCache) -> Self {
939        self.placement_cache = Some(cache);
940        self
941    }
942
943    /// Select the liminal worker for `row`, applying the SHARED placement decision
944    /// for an UNPINNED row when a placement cache is attached — the exact gRPC
945    /// semantics ([`worker_selection_for`](crate::worker::worker_selection_for)):
946    /// `Prefer{L}` spills to any live worker, `Pinned{L}` requires an L-labelled
947    /// worker and NEVER spills to a node=None any-worker.
948    ///
949    /// A per-activity authored pin (`row.node == Some(N)`) ALWAYS wins and is
950    /// selected off the row's own node, untouched by placement — exactly the gRPC
951    /// composition rule. Without a cache (or with a pinned row) this collapses to
952    /// the single `select_worker` off the row's own node — the pre-Phase-2
953    /// behaviour.
954    ///
955    /// For `Pinned{L}`, when no L-labelled worker is live this returns `Ok(None)` —
956    /// NOT a spill to a node=None worker — so the [`OutboxRowDispatch`] surfaces the
957    /// honest no-worker error and the outbox retries/stalls until an L-labelled
958    /// worker returns, mirroring the gRPC wait-for-worker path exactly (both
959    /// transports agree via [`WorkerSelection`](crate::worker::WorkerSelection)).
960    async fn select_liminal_worker(
961        &self,
962        row: &OutboxRow,
963    ) -> Result<Option<WorkerHandle>, ServerError> {
964        // A pinned row or an absent cache: one selection off the row's own node.
965        let (Some(cache), None) = (&self.placement_cache, &row.node) else {
966            return self.registry.select_worker(
967                &row.namespace,
968                &row.task_queue,
969                &row.activity_type,
970                row.node.as_deref(),
971            );
972        };
973        // Unpinned + placement-aware: resolve the shared selection decision, so this
974        // liminal path and the gRPC path can never diverge on Prefer-vs-Pinned. The
975        // row's `node` is never mutated — selection is a pure dispatch-time input.
976        let placement = cache.placement(&row.namespace).await;
977        match crate::worker::worker_selection_for(&placement) {
978            // Prefer/Unplaced: walk the prefer-then-spill tiers (the `None` spill is
979            // always last), stopping at the first tier with a live worker.
980            crate::worker::WorkerSelection::PreferTiers(tiers) => {
981                self.select_over_tiers(row, tiers.iter().map(Option::as_deref))
982            }
983            // Pinned{L}: try ONLY the required labels — no `None` spill. When none is
984            // live, return None so the caller retries/stalls (never any-node).
985            crate::worker::WorkerSelection::Required(required) => self.select_over_tiers(
986                row,
987                required.iter().map(|label| Some(String::as_str(label))),
988            ),
989        }
990    }
991
992    /// Select the first live worker over an ordered sequence of node filters,
993    /// returning `Ok(None)` when no filter matches a live worker. Shared by the
994    /// `Prefer` (tiers end in a `None` spill) and `Pinned` (required labels only,
995    /// no spill) selection arms so both walk the registry identically.
996    fn select_over_tiers<'a>(
997        &self,
998        row: &OutboxRow,
999        tiers: impl Iterator<Item = Option<&'a str>>,
1000    ) -> Result<Option<WorkerHandle>, ServerError> {
1001        for tier in tiers {
1002            let selected = self.registry.select_worker(
1003                &row.namespace,
1004                &row.task_queue,
1005                &row.activity_type,
1006                tier,
1007            )?;
1008            if selected.is_some() {
1009                return Ok(selected);
1010            }
1011        }
1012        Ok(None)
1013    }
1014
1015    fn revoke_completion(
1016        &self,
1017        row: &OutboxRow,
1018        activity_id: &ActivityId,
1019        completion_token: &CompletionToken,
1020    ) -> Result<(), ServerError> {
1021        self.completion
1022            .completion_fences
1023            .revoke(&row.workflow_id, activity_id, completion_token)
1024    }
1025}
1026
1027#[async_trait]
1028impl OutboxRowDispatch for RegistryLiminalDispatch {
1029    async fn dispatch(&self, row: &OutboxRow) -> Result<(), ServerError> {
1030        // Select the worker the SAME way the gRPC path does: by the row's
1031        // (namespace, task_queue, activity_type) pool key with the row's optional
1032        // node affinity, applying the SHARED `Prefer` two-tier spill for an
1033        // unpinned row when a placement cache is attached. No worker for the pool
1034        // => honest no-worker error => the outbox retries (never a false `done`).
1035        let worker = self.select_liminal_worker(row).await?.ok_or_else(|| {
1036            dispatch_error(
1037                &channel_for_row(row),
1038                "no liminal worker registered for the row's pool".to_owned(),
1039            )
1040        })?;
1041
1042        let delivery = match worker.delivery() {
1043            WorkerDelivery::Liminal(delivery) => delivery.clone(),
1044            WorkerDelivery::Grpc(_) => {
1045                return Err(dispatch_error(
1046                    &channel_for_row(row),
1047                    "selected worker is not delivered over liminal".to_owned(),
1048                ));
1049            }
1050        };
1051
1052        // NOI-6: bind this attempt's owner BEFORE the push, so an intervention that
1053        // races the dispatch resolves the worker. The guard releases on every exit
1054        // path (reply, error, panic) so the index never keeps a finished attempt.
1055        // The key mirrors the worker's execute-path stamp exactly: activity_id from
1056        // the ordinal, attempt = the wire's one-based delivery attempt (the same
1057        // `request_for_row` stamp the worker echoes into its session key). See
1058        // `LiminalActivityWorker::execute` / `run_agent_dispatch`.
1059        let _owner_guard = self.attempt_owners.as_ref().map(|owners| {
1060            AttemptOwnerGuard::bind(
1061                owners.clone(),
1062                super::intervention::AttemptKey::new(
1063                    row.workflow_id.clone(),
1064                    ActivityId::from_sequence_position(row.ordinal),
1065                    row.attempt.saturating_add(1),
1066                ),
1067                worker.id(),
1068            )
1069        });
1070
1071        // Push the dispatch to the worker and block for its correlated reply. The
1072        // push is a blocking, thread-based liminal call; run it off the async
1073        // runtime so a long-running activity cannot starve a runtime worker.
1074        let activity_id = ActivityId::from_sequence_position(row.ordinal);
1075        let run_id = row.run_id.as_ref().ok_or_else(|| {
1076            dispatch_error(
1077                &channel_for_row(row),
1078                "activity run id is missing; refusing unfenced external effect".to_owned(),
1079            )
1080        })?;
1081        let completion_token = self
1082            .completion
1083            .completion_fences
1084            .issue(&row.workflow_id, &activity_id)?;
1085        let request = request_for_row(row, run_id, &completion_token);
1086        let gate = self.delivery_gate.clone();
1087        let dispatch_key = row.dispatch_key.clone();
1088        let registry = self.registry.clone();
1089        let worker_id = worker.id();
1090        let dispatched = tokio::task::spawn_blocking(move || {
1091            delivery.dispatch_held(&request, || {
1092                if gate.is_draining() || !gate.holds(&dispatch_key) {
1093                    return false;
1094                }
1095                match registry.worker_by_id(worker_id) {
1096                    Ok(Some(_)) => true,
1097                    Ok(None) => false,
1098                    Err(error) => {
1099                        tracing::warn!(
1100                            %error,
1101                            %dispatch_key,
1102                            "delivery wait could not verify worker registration; abandoning"
1103                        );
1104                        false
1105                    }
1106                }
1107            })
1108        })
1109        .await
1110        .map_err(|error| {
1111            dispatch_error(
1112                &channel_for_row(row),
1113                format!("dispatch task join failed: {error}"),
1114            )
1115        });
1116        let response = match dispatched {
1117            Ok(Ok(Some(response))) => response,
1118            Ok(Ok(None)) => {
1119                tracing::warn!(
1120                    dispatch_key = %row.dispatch_key,
1121                    workflow_id = %row.workflow_id,
1122                    %activity_id,
1123                    "delivery wait abandoned; late reply will be discarded"
1124                );
1125                self.revoke_completion(row, &activity_id, &completion_token)?;
1126                return Err(dispatch_error(
1127                    &channel_for_row(row),
1128                    "delivery wait abandoned before worker reply".to_owned(),
1129                ));
1130            }
1131            Ok(Err(error)) | Err(error) => {
1132                self.revoke_completion(row, &activity_id, &completion_token)?;
1133                return Err(error);
1134            }
1135        };
1136
1137        // Re-enter the worker's result through the SAME completion path the gRPC
1138        // transport uses (terminal dedup in `record_fan_out_completion` applies
1139        // unchanged). The dispatch itself succeeded — the row's terminal state is
1140        // recorded by the completion callback, exactly as in the gRPC path.
1141        if let Err(error) = self.completion.deliver(&response) {
1142            self.revoke_completion(row, &activity_id, &completion_token)?;
1143            return Err(error);
1144        }
1145        Ok(())
1146    }
1147}
1148
1149/// RAII guard that releases an [`AttemptOwnerIndex`](super::intervention::AttemptOwnerIndex)
1150/// binding when the dispatch resolves — on the reply, an error, or a panic — so
1151/// the back-index tracks exactly the attempts currently in flight (NOI-6).
1152///
1153/// Shared by both liminal dispatch arms: the outbox row wait holds it across
1154/// its blocking `dispatch` call, and the engine-seam bridge hands it to the
1155/// dispatch's reply-router thread, which drops it on every exit path.
1156pub(crate) struct AttemptOwnerGuard {
1157    owners: super::intervention::AttemptOwnerIndex,
1158    key: super::intervention::AttemptKey,
1159}
1160
1161impl AttemptOwnerGuard {
1162    /// Bind `key` to `worker` in `owners` and return the guard that releases
1163    /// the binding on drop.
1164    pub(crate) fn bind(
1165        owners: super::intervention::AttemptOwnerIndex,
1166        key: super::intervention::AttemptKey,
1167        worker: super::registry::WorkerId,
1168    ) -> Self {
1169        owners.bind(key.clone(), worker);
1170        Self { owners, key }
1171    }
1172}
1173
1174impl Drop for AttemptOwnerGuard {
1175    fn drop(&mut self) {
1176        self.owners.release(&self.key);
1177    }
1178}
1179
1180/// Normalize a wire `node` (`Option<String>`) onto the registry's optional
1181/// locality affinity, applying the SAME none-convention the gRPC registration
1182/// path uses (`registry::optional_node`): an empty string carries no node, so it
1183/// collapses to `None`; any non-empty value is the worker's advertised node.
1184///
1185/// The wire already models `node` as `Option<String>`, but a worker that joins
1186/// `Some("")` (the empty-string node) must not register a distinct empty-node
1187/// affinity that no pinned dispatch could ever match — it is semantically
1188/// unpinned, exactly as the gRPC proto3 empty default is. Folding it to `None`
1189/// here keeps the two registration paths byte-for-byte equivalent.
1190fn normalize_wire_node(node: Option<&str>) -> Option<String> {
1191    node.filter(|value| !value.is_empty())
1192        .map(ToOwned::to_owned)
1193}
1194
1195/// Connection-keyed [`ConnectionNotifier`] that turns liminal's in-band worker
1196/// registration into a first-class [`ConnectedWorkerRegistry`] membership.
1197///
1198/// This is the SERVER half of LSUB-L2: when a worker connects with a
1199/// [`WireWorkerRegistration`] (the SDK's `connect_with_registration`), liminal's
1200/// connection process invokes [`on_worker_registered`](Self::on_worker_registered)
1201/// with the connection's beamr `pid` and the worker's declared
1202/// `(namespaces, task_queue, node, activity_types)`. The notifier builds a
1203/// [`WorkerDelivery::Liminal`] over the connection and inserts it into the
1204/// registry — the SAME registry entry, selected the SAME way, as a gRPC worker —
1205/// retiring the LSUB-1 out-of-band `active_connection_pids()` + hard-coded
1206/// registration hack.
1207///
1208/// # Lifetime of the registration guard
1209///
1210/// [`ConnectedWorkerRegistry::register_delivery`] returns a
1211/// [`WorkerRegistration`] guard whose drop deregisters the worker. The notifier
1212/// OWNS that guard keyed by `pid` (`Mutex<HashMap<u64, WorkerRegistration>>`), so
1213/// the registration lives exactly as long as the connection: it is inserted on
1214/// register and removed (dropped) on
1215/// [`on_worker_unregistered`](Self::on_worker_unregistered), which liminal fires
1216/// on connection close.
1217///
1218/// # Construction-order cycle (notifier <-> supervisor)
1219///
1220/// [`LiminalWorkerDelivery`] needs a [`ConnectionSupervisor`] handle to push to
1221/// the worker's connection, but the supervisor is itself constructed WITH this
1222/// notifier ([`ConnectionSupervisor::with_services_and_notifier`]) — a cycle. The
1223/// notifier therefore holds the supervisor behind a [`OnceLock`], populated
1224/// IMMEDIATELY after the supervisor is built via [`Self::bind_supervisor`]. The
1225/// `OnceLock` is never read before it is set in correct wiring (a worker can only
1226/// register after the listener — built after the supervisor and after
1227/// `bind_supervisor` — accepts its connection); if it somehow were, registration
1228/// is REJECTED with a typed error rather than panicking, so there is no
1229/// production `unwrap`/`expect` and no second always-`None` code path.
1230pub struct LiminalConnectionNotifier {
1231    registry: ConnectedWorkerRegistry,
1232    contract_catalog: Option<Arc<aion::Engine>>,
1233    supervisor: OnceLock<ConnectionSupervisor>,
1234    guards: Mutex<HashMap<u64, WorkerRegistration>>,
1235    /// The neutral intervention primitives a liminal-connected agent worker
1236    /// advertises (NOI-6, item 4). The liminal `WorkerRegistration` wire has a fixed
1237    /// shape that cannot carry this, so it is configured on the notifier at the
1238    /// composition root from the harness's advertised `AgentSession::capabilities()`
1239    /// and recorded on every registered worker's handle, where the intervention
1240    /// router gates on it. Default empty = observability-only (a plain activity
1241    /// worker), so the router offers no controls for it.
1242    intervention_capabilities: aion_core::InterventionCapabilities,
1243    /// The transcript sequencer a worker's observability publishes drain into
1244    /// (NOI-5b), plus the Tokio [`Handle`](tokio::runtime::Handle) to bridge the
1245    /// synchronous connection-process callback onto the async publish. `None` (the
1246    /// default, and every non-agent boot) makes the observability tap a no-op, so a
1247    /// worker publish to the reserved channel is simply ignored by the notifier.
1248    transcript: Option<TranscriptTap>,
1249    /// The SAME per-task liveness tracker the bridge dispatcher tracks into and
1250    /// the #176 expiry sweeper expires from. A worker's automatic
1251    /// [`WorkerLivenessBeat`] publishes on [`WORKER_LIVENESS_CHANNEL`] refresh
1252    /// their task stamps here, keeping the sweeper honest for liminal-delivered
1253    /// dispatches. `None` (a wiring that never bridges dispatches, e.g. isolated
1254    /// tests) consumes and drops the beats.
1255    heartbeat_tracker: Option<super::heartbeat::HeartbeatTracker>,
1256}
1257
1258/// The observability-drain leg of the notifier: a bounded, ORDERED queue into
1259/// the one drain task that publishes transcript events sequentially.
1260///
1261/// One consumer is load-bearing, not an implementation detail: a spawned task
1262/// per event (the pre-2026-07-23 shape) made every in-flight frame a
1263/// concurrent writer racing the same stream head, turning the sequencer's
1264/// optimistic-append loop into an O(N²) conflict stampede under load — and
1265/// destroyed `worker_seq` order on the durable transcript. Sequential
1266/// draining preserves arrival order and leaves the conflict-retry loop to
1267/// handle only genuine cross-process races (failover adoption).
1268#[derive(Clone)]
1269struct TranscriptTap {
1270    queue: tokio::sync::mpsc::Sender<aion_core::ActivityEvent>,
1271}
1272
1273/// Bound on the transcript drain queue: events a slow durable append cannot
1274/// keep up with are dropped (with a warning) rather than buffered without
1275/// limit. Live streaming is best-effort; the bound protects server memory.
1276const TRANSCRIPT_QUEUE_CAPACITY: usize = 4096;
1277
1278impl std::fmt::Debug for LiminalConnectionNotifier {
1279    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1280        f.debug_struct("LiminalConnectionNotifier")
1281            .field("supervisor_bound", &self.supervisor.get().is_some())
1282            .finish_non_exhaustive()
1283    }
1284}
1285
1286impl LiminalConnectionNotifier {
1287    /// Build a notifier that registers connecting workers into `registry`.
1288    ///
1289    /// The supervisor handle is bound separately via [`Self::bind_supervisor`]
1290    /// immediately after the supervisor is constructed, resolving the
1291    /// notifier <-> supervisor construction cycle (see the type docs).
1292    #[must_use]
1293    pub fn new(registry: ConnectedWorkerRegistry) -> Self {
1294        Self {
1295            registry,
1296            contract_catalog: None,
1297            supervisor: OnceLock::new(),
1298            guards: Mutex::new(HashMap::new()),
1299            intervention_capabilities: aion_core::InterventionCapabilities::none(),
1300            transcript: None,
1301            heartbeat_tracker: None,
1302        }
1303    }
1304
1305    /// Install the live package catalog used to refuse incompatible workers
1306    /// before liminal acknowledges or publishes their registration.
1307    #[must_use]
1308    pub fn with_contract_catalog(mut self, engine: Arc<aion::Engine>) -> Self {
1309        self.contract_catalog = Some(engine);
1310        self
1311    }
1312
1313    /// Install the shared per-task liveness tracker so a worker's automatic
1314    /// [`WorkerLivenessBeat`] publishes refresh the SAME in-flight entries the
1315    /// bridge dispatcher tracks and the #176 sweeper expires.
1316    ///
1317    /// MUST be wired on every boot that hosts the engine-seam bridge (the
1318    /// production composition does), or the sweeper would expire healthy
1319    /// liminal workers running activities longer than the heartbeat window.
1320    /// Without it (isolated tests that never bridge-dispatch) beats are
1321    /// consumed and dropped.
1322    #[must_use]
1323    pub fn with_heartbeat_tracker(mut self, tracker: super::heartbeat::HeartbeatTracker) -> Self {
1324        self.heartbeat_tracker = Some(tracker);
1325        self
1326    }
1327
1328    /// Install the transcript sequencer a worker's observability publishes drain into
1329    /// (NOI-5b), capturing the CURRENT Tokio runtime handle to bridge the synchronous
1330    /// connection-process callback onto the async publish.
1331    ///
1332    /// MUST be called from within a Tokio runtime (the server boot path is), so the
1333    /// captured [`Handle`](tokio::runtime::Handle) can spawn the append+fan-out when a
1334    /// worker publishes a transcript event over the reserved channel. Without this
1335    /// builder the observability tap is a no-op (a plain, non-agent deployment).
1336    ///
1337    /// # Panics
1338    ///
1339    /// Panics if called outside a Tokio runtime — a construction-time wiring error in
1340    /// the server boot, never a runtime condition (the boot path always builds the
1341    /// notifier inside the server runtime).
1342    #[must_use]
1343    pub fn with_transcript_publisher(
1344        mut self,
1345        publisher: crate::activity_publisher::ActivityEventPublisher,
1346    ) -> Self {
1347        let (queue, mut events) =
1348            tokio::sync::mpsc::channel::<aion_core::ActivityEvent>(TRANSCRIPT_QUEUE_CAPACITY);
1349        // The ONE drain task: transcript events publish sequentially in
1350        // arrival order (see the `TranscriptTap` docs for why one consumer is
1351        // load-bearing). It lives as long as any queue sender does.
1352        tokio::runtime::Handle::current().spawn(async move {
1353            while let Some(event) = events.recv().await {
1354                if let Err(error) = publisher.publish(&event).await {
1355                    tracing::warn!(%error, "observability tap: transcript publish failed");
1356                }
1357            }
1358        });
1359        self.transcript = Some(TranscriptTap { queue });
1360        self
1361    }
1362
1363    /// Set the neutral intervention capability set every worker registering through
1364    /// this notifier advertises (NOI-6, item 4).
1365    ///
1366    /// The composition root wires this from the harness's advertised
1367    /// `AgentSession::capabilities()` so a liminal-connected agent worker's handle
1368    /// carries the primitives its harness supports, which the intervention router
1369    /// gates on. Without this builder the set is empty (observability-only), so a
1370    /// plain activity worker advertises no controls. Pure builder addition, mirroring
1371    /// the registry's capability-carrying registration façade.
1372    #[must_use]
1373    pub fn with_intervention_capabilities(
1374        mut self,
1375        capabilities: aion_core::InterventionCapabilities,
1376    ) -> Self {
1377        self.intervention_capabilities = capabilities;
1378        self
1379    }
1380
1381    /// Bind the connection supervisor the notifier pushes through, immediately
1382    /// after it is constructed with this notifier.
1383    ///
1384    /// Returns `true` when the supervisor was stored, `false` when it was already
1385    /// bound (a second bind is a wiring bug and is ignored, never overwriting the
1386    /// live handle). Call this exactly once, right after
1387    /// [`ConnectionSupervisor::with_services_and_notifier`].
1388    pub fn bind_supervisor(&self, supervisor: ConnectionSupervisor) -> bool {
1389        self.supervisor.set(supervisor).is_ok()
1390    }
1391
1392    /// Snapshot of every live liminal connection the dead-man switch must ping:
1393    /// its pid, the worker it registered, and the push leg to reach it.
1394    ///
1395    /// Built from the SAME guard map that owns each connection's registration,
1396    /// so a connection that has closed (its guard removed) is structurally
1397    /// absent from the snapshot and is never pinged. A poisoned guard map is
1398    /// recovered rather than skipped: silently returning no targets would turn
1399    /// the dead-man switch off exactly when the server is already unhealthy.
1400    #[must_use]
1401    pub fn liveness_targets(&self) -> Vec<super::liminal_liveness::LivenessTarget> {
1402        let Some(supervisor) = self.supervisor.get() else {
1403            return Vec::new();
1404        };
1405        let guards = match self.guards.lock() {
1406            Ok(guards) => guards,
1407            Err(poisoned) => poisoned.into_inner(),
1408        };
1409        guards
1410            .iter()
1411            .filter_map(|(pid, guard)| {
1412                guard
1413                    .worker_id()
1414                    .map(|worker_id| super::liminal_liveness::LivenessTarget {
1415                        pid: *pid,
1416                        worker_id,
1417                        delivery: LiminalWorkerDelivery::new(supervisor.clone(), *pid),
1418                    })
1419            })
1420            .collect()
1421    }
1422
1423    /// Refresh one worker's in-flight task stamp from a [`WorkerLivenessBeat`]
1424    /// published on [`WORKER_LIVENESS_CHANNEL`].
1425    ///
1426    /// The worker is resolved by the publishing CONNECTION (`pid` -> the
1427    /// registration guard this notifier owns), never by wire identity, so a
1428    /// beat can only refresh tasks assigned to the worker that sent it. An
1429    /// untracked task is benign (an outbox dispatch the tracker never held, or
1430    /// a beat racing its completion) and is dropped silently; a malformed
1431    /// payload or unregistered connection is logged and dropped — a bad beat
1432    /// must never tear down the connection callback.
1433    fn record_liveness_beat(&self, pid: u64, payload: &[u8]) {
1434        let Some(tracker) = &self.heartbeat_tracker else {
1435            return;
1436        };
1437        let beat: WorkerLivenessBeat = match serde_json::from_slice(payload) {
1438            Ok(beat) => beat,
1439            Err(error) => {
1440                tracing::warn!(%error, "liveness tap: malformed WorkerLivenessBeat payload");
1441                return;
1442            }
1443        };
1444        let worker_id = match self.guards.lock() {
1445            Ok(guards) => guards.get(&pid).and_then(WorkerRegistration::worker_id),
1446            Err(poisoned) => poisoned
1447                .into_inner()
1448                .get(&pid)
1449                .and_then(WorkerRegistration::worker_id),
1450        };
1451        let Some(worker_id) = worker_id else {
1452            tracing::warn!(
1453                connection_pid = pid,
1454                "liveness tap: beat from a connection with no registered worker"
1455            );
1456            return;
1457        };
1458        let activity_id = ActivityId::from_sequence_position(beat.ordinal);
1459        if let Err(error) = tracker.record_liveness(
1460            worker_id,
1461            &beat.workflow_id,
1462            &activity_id,
1463            std::time::Instant::now(),
1464        ) {
1465            tracing::error!(
1466                %error,
1467                connection_pid = pid,
1468                "liveness tap: heartbeat tracker refresh failed"
1469            );
1470        }
1471    }
1472
1473    /// Apply one worker's [`WorkerCapabilitiesAnnouncement`] published on
1474    /// [`WORKER_CAPABILITIES_CHANNEL`] to its registered handle.
1475    ///
1476    /// The worker is resolved by the publishing CONNECTION (`pid` -> the
1477    /// registration guard this notifier owns), never by wire identity, so an
1478    /// announcement can only ever update the worker that sent it. A malformed
1479    /// payload or unregistered connection is logged and dropped — a bad
1480    /// announcement must never tear down the connection callback.
1481    fn record_capabilities_announcement(&self, pid: u64, payload: &[u8]) {
1482        let announcement: WorkerCapabilitiesAnnouncement = match serde_json::from_slice(payload) {
1483            Ok(announcement) => announcement,
1484            Err(error) => {
1485                tracing::warn!(
1486                    %error,
1487                    "capabilities tap: malformed WorkerCapabilitiesAnnouncement payload"
1488                );
1489                return;
1490            }
1491        };
1492        let worker_id = match self.guards.lock() {
1493            Ok(guards) => guards.get(&pid).and_then(WorkerRegistration::worker_id),
1494            Err(poisoned) => poisoned
1495                .into_inner()
1496                .get(&pid)
1497                .and_then(WorkerRegistration::worker_id),
1498        };
1499        let Some(worker_id) = worker_id else {
1500            tracing::warn!(
1501                connection_pid = pid,
1502                "capabilities tap: announcement from a connection with no registered worker"
1503            );
1504            return;
1505        };
1506        match self
1507            .registry
1508            .set_intervention_capabilities(worker_id, &announcement.capabilities)
1509        {
1510            Ok(true) => {}
1511            Ok(false) => tracing::warn!(
1512                connection_pid = pid,
1513                worker_id = ?worker_id,
1514                "capabilities tap: announcement raced the worker's deregistration"
1515            ),
1516            Err(error) => tracing::error!(
1517                %error,
1518                connection_pid = pid,
1519                "capabilities tap: registry capability update failed"
1520            ),
1521        }
1522    }
1523
1524    fn validate_registration_contract(
1525        &self,
1526        registration: &WireWorkerRegistration,
1527    ) -> Result<(), LiminalServerError> {
1528        let Some(engine) = &self.contract_catalog else {
1529            return Ok(());
1530        };
1531        let advertised =
1532            registration
1533                .activities
1534                .iter()
1535                .map(|activity| {
1536                    let input_schema =
1537                        serde_json::from_str(&activity.input_schema_json).map_err(|error| {
1538                            LiminalServerError::ListenerAccept {
1539                                message: format!(
1540                                    "liminal worker activity `{}` input schema is invalid: {error}",
1541                                    activity.name
1542                                ),
1543                            }
1544                        })?;
1545                    let output_schema = serde_json::from_str(&activity.output_schema_json)
1546                        .map_err(|error| LiminalServerError::ListenerAccept {
1547                            message: format!(
1548                                "liminal worker activity `{}` output schema is invalid: {error}",
1549                                activity.name
1550                            ),
1551                        })?;
1552                    Ok(aion_package::ActivityDescriptor {
1553                        name: activity.name.clone(),
1554                        input_schema,
1555                        output_schema,
1556                    })
1557                })
1558                .collect::<Result<Vec<_>, LiminalServerError>>()?;
1559        // Both advertised forms travel into the gate together: the NAME set the
1560        // dispatcher selects on and the CONTRACT set admission compares. A
1561        // refusal computed from one while the record printed the other is what
1562        // produced the 2026-07-30 self-contradicting log.
1563        let activity_types = registration
1564            .activity_types
1565            .iter()
1566            .cloned()
1567            .collect::<std::collections::BTreeSet<_>>();
1568        super::contracts::validate_worker_contracts(
1569            engine,
1570            &registration.task_queue,
1571            registration.node.as_deref(),
1572            &registration.identity,
1573            super::contracts::WorkerAdvertisement {
1574                activity_types: &activity_types,
1575                contracts: &advertised,
1576            },
1577        )
1578        .map_err(|error| LiminalServerError::ListenerAccept {
1579            message: error.to_string(),
1580        })
1581    }
1582
1583    /// Admit one connecting worker, or refuse it with a structured reason.
1584    ///
1585    /// Split out of [`ConnectionNotifier::on_worker_registered`] so EVERY
1586    /// refusal — contract mismatch, unbound supervisor, registry error, lease
1587    /// failure — funnels through exactly one place that logs it. Before this
1588    /// split the rejection reason was carried in the `Rejected` ack and logged
1589    /// NOWHERE: on 2026-07-29 a worker whose `.v4` contract field-mismatched was
1590    /// refused on every single dial with the server silent on all of them, and
1591    /// the refused process looked merely asleep.
1592    fn admit_registration(
1593        &self,
1594        pid: u64,
1595        registration: &WireWorkerRegistration,
1596    ) -> Result<(), LiminalServerError> {
1597        self.validate_registration_contract(registration)?;
1598        // The delivery leg needs the supervisor to push to this connection. In
1599        // correct wiring it is bound before any connection is accepted; a missing
1600        // binding is a rejected registration, never a panic.
1601        let supervisor =
1602            self.supervisor
1603                .get()
1604                .ok_or_else(|| LiminalServerError::ListenerAccept {
1605                    message: format!(
1606                        "liminal worker registration for connection {pid} rejected: \
1607                     notifier supervisor handle not yet bound"
1608                    ),
1609                })?;
1610
1611        let delivery = WorkerDelivery::Liminal(LiminalWorkerDelivery::new(supervisor.clone(), pid));
1612        let node = normalize_wire_node(registration.node.as_deref());
1613        // Insert into the SAME registry, selected the SAME way, as a gRPC worker.
1614        // A registry error (poisoned lock) becomes a Rejected ack so the worker
1615        // never believes it is registered when it is not.
1616        let guard = self
1617            .registry
1618            .register_delivery_with_capabilities(
1619                registration.namespaces.iter().cloned(),
1620                registration.task_queue.clone(),
1621                node,
1622                registration.activity_types.iter(),
1623                delivery,
1624                self.intervention_capabilities.clone(),
1625            )
1626            .map_err(|error| LiminalServerError::ListenerAccept {
1627                message: format!(
1628                    "liminal worker registration for connection {pid} rejected: {error}"
1629                ),
1630            })?;
1631        let worker_id = guard
1632            .worker_id()
1633            .ok_or_else(|| LiminalServerError::ListenerAccept {
1634                message: format!(
1635                    "liminal worker registration for connection {pid} has no worker id"
1636                ),
1637            })?;
1638
1639        // OWN the guard for the connection's lifetime, keyed by pid. Dropping it
1640        // (on unregister) deregisters the worker, so the registration lives
1641        // exactly as long as the connection.
1642        let mut guards = self.guards.lock().map_err(|_| {
1643            // The accepted registry entry cannot be tracked for deregistration, so
1644            // reject (and drop the just-created guard, deregistering it) rather
1645            // than leak a never-deregistered association.
1646            LiminalServerError::ListenerAccept {
1647                message: format!(
1648                    "liminal worker registration for connection {pid} rejected: \
1649                     notifier guard map poisoned"
1650                ),
1651            }
1652        })?;
1653        guards.insert(pid, guard);
1654        drop(guards);
1655        if let Some(tracker) = &self.heartbeat_tracker {
1656            if let Err(error) = tracker.register_connection(worker_id, std::time::Instant::now()) {
1657                let removed = match self.guards.lock() {
1658                    Ok(mut guards) => guards.remove(&pid),
1659                    Err(poisoned) => poisoned.into_inner().remove(&pid),
1660                };
1661                drop(removed);
1662                return Err(LiminalServerError::ListenerAccept {
1663                    message: format!(
1664                        "liminal worker registration for connection {pid} rejected: {error}"
1665                    ),
1666                });
1667            }
1668        }
1669        tracing::info!(
1670            connection_pid = pid,
1671            identity = %registration.identity,
1672            task_queue = %registration.task_queue,
1673            "registered liminal worker in-band"
1674        );
1675        Ok(())
1676    }
1677}
1678
1679impl ConnectionNotifier for LiminalConnectionNotifier {
1680    fn on_worker_registered(
1681        &self,
1682        pid: u64,
1683        registration: &WireWorkerRegistration,
1684    ) -> Result<(), LiminalServerError> {
1685        // Every refusal is NAMED on the server, at WARN, with the queue, the
1686        // worker build identity, and the structured reason — the same reason
1687        // that rides back in the `Rejected` ack, so both sides' logs carry
1688        // identical text and a refused worker can be diagnosed from either end.
1689        self.admit_registration(pid, registration)
1690            .inspect_err(|error| {
1691                // The two advertised sets are logged SEPARATELY and named for
1692                // what each one is. Logging `activity_types` alone beside a
1693                // contract-mismatch reason produced a record that listed an
1694                // action as advertised in the same line that reported it
1695                // `<missing>` — true of two different sets, and unresolvable by
1696                // the operator it exists to help.
1697                let advertised_contracts = registration
1698                    .activities
1699                    .iter()
1700                    .map(|activity| activity.name.as_str())
1701                    .collect::<Vec<_>>();
1702                tracing::warn!(
1703                    connection_pid = pid,
1704                    identity = %registration.identity,
1705                    task_queue = %registration.task_queue,
1706                    namespaces = ?registration.namespaces,
1707                    advertised_activity_types = ?registration.activity_types,
1708                    advertised_contracts = ?advertised_contracts,
1709                    reason = %error,
1710                    "REFUSED liminal worker registration"
1711                );
1712            })
1713    }
1714
1715    fn on_worker_unregistered(&self, pid: u64) {
1716        // Remove + drop the guard for pid, deregistering the worker. A poisoned
1717        // lock on the close path has no peer to report to; recover the guard map
1718        // and still drop the guard so the registry does not keep routing to a
1719        // gone connection.
1720        let removed = match self.guards.lock() {
1721            Ok(mut guards) => guards.remove(&pid),
1722            Err(poisoned) => poisoned.into_inner().remove(&pid),
1723        };
1724        let worker_id = removed.as_ref().and_then(WorkerRegistration::worker_id);
1725        if let (Some(tracker), Some(worker_id)) = (&self.heartbeat_tracker, worker_id) {
1726            if let Err(error) = tracker.unregister_connection(worker_id) {
1727                tracing::error!(
1728                    %error,
1729                    connection_pid = pid,
1730                    worker_id = worker_id.value(),
1731                    "failed to clear liminal worker connection lease"
1732                );
1733            }
1734        }
1735        if removed.is_some() {
1736            tracing::info!(
1737                connection_pid = pid,
1738                "deregistered liminal worker on disconnect"
1739            );
1740        }
1741    }
1742
1743    fn on_channel_publish(&self, pid: u64, channel: &str, payload: &[u8]) -> bool {
1744        if let Some(tracker) = &self.heartbeat_tracker {
1745            let worker_id = match self.guards.lock() {
1746                Ok(guards) => guards.get(&pid).and_then(WorkerRegistration::worker_id),
1747                Err(poisoned) => poisoned
1748                    .into_inner()
1749                    .get(&pid)
1750                    .and_then(WorkerRegistration::worker_id),
1751            };
1752            if let Some(worker_id) = worker_id {
1753                if let Err(error) =
1754                    tracker.record_connection_activity(worker_id, std::time::Instant::now())
1755                {
1756                    tracing::error!(
1757                        %error,
1758                        connection_pid = pid,
1759                        worker_id = worker_id.value(),
1760                        "failed to advance liminal worker connection lease"
1761                    );
1762                }
1763            }
1764        }
1765        // Reserved liveness channel: refresh the beat's in-flight task stamp in
1766        // the shared heartbeat tracker (always consumed, never fanned out).
1767        if channel == WORKER_LIVENESS_CHANNEL {
1768            self.record_liveness_beat(pid, payload);
1769            return true;
1770        }
1771        // Reserved capabilities channel: apply the worker's advertised
1772        // intervention capabilities to its registered handle (always consumed).
1773        if channel == WORKER_CAPABILITIES_CHANNEL {
1774            self.record_capabilities_announcement(pid, payload);
1775            return true;
1776        }
1777        // Only consume the reserved observability channel; any other channel falls
1778        // through to liminal's normal fan-out (this returns false).
1779        if channel != liminal_sdk::OBSERVABILITY_CHANNEL {
1780            return false;
1781        }
1782        let Some(tap) = &self.transcript else {
1783            // No transcript sequencer installed (a non-agent deployment): still
1784            // CONSUME the reserved channel so it never leaks into the fan-out, but
1785            // drop the event — there is nothing to persist it into.
1786            return true;
1787        };
1788        let event: aion_core::ActivityEvent = match serde_json::from_slice(payload) {
1789            Ok(event) => event,
1790            Err(error) => {
1791                tracing::warn!(%error, "observability tap: malformed ActivityEvent payload");
1792                return true;
1793            }
1794        };
1795        // Hand the event to the ordered drain queue (the synchronous
1796        // connection-process callback never blocks). A full queue means the
1797        // durable append cannot keep up: the event is dropped with a warning,
1798        // never buffered without bound.
1799        if let Err(error) = tap.queue.try_send(event) {
1800            tracing::warn!(%error, "observability tap: transcript queue rejected event");
1801        }
1802        true
1803    }
1804}
1805
1806/// The production [`InterventionTransport`](super::intervention::InterventionTransport):
1807/// pushes a routed command to the owning worker over its liminal server-push
1808/// connection (NOI-6, §6.2).
1809///
1810/// It reads the worker handle's [`WorkerDelivery::Liminal`] leg and pushes the
1811/// neutral [`InterventionRequest`] via [`LiminalWorkerDelivery::push_intervention`],
1812/// running the blocking push off the async runtime. A worker delivered over gRPC
1813/// (no liminal leg) surfaces the stale-target no-op via a connection-lost error, so
1814/// the router NACKs the operator rather than routing to a leg it cannot reach.
1815#[derive(Clone, Debug, Default)]
1816pub struct LiminalInterventionTransport;
1817
1818#[async_trait]
1819impl super::intervention::InterventionTransport for LiminalInterventionTransport {
1820    async fn push(
1821        &self,
1822        worker: &super::registry::WorkerHandle,
1823        command: aion_core::InterventionCommand,
1824    ) -> Result<aion_core::InterventionOutcome, ServerError> {
1825        let delivery = match worker.delivery() {
1826            WorkerDelivery::Liminal(delivery) => delivery.clone(),
1827            WorkerDelivery::Grpc(_) => {
1828                // No liminal leg to push to: the intervention transport rides the
1829                // liminal push channel only, so this is unreachable for the target.
1830                return Err(ServerError::worker_connection_lost(
1831                    "liminal-push",
1832                    "owning worker is not delivered over liminal".to_owned(),
1833                ));
1834            }
1835        };
1836        let request = InterventionRequest {
1837            intervention: command,
1838        };
1839        let reply = tokio::task::spawn_blocking(move || delivery.push_intervention(&request))
1840            .await
1841            .map_err(|error| {
1842                dispatch_error(
1843                    "liminal-push",
1844                    format!("intervention task join failed: {error}"),
1845                )
1846            })??;
1847        Ok(reply.outcome)
1848    }
1849}
1850
1851#[cfg(test)]
1852#[path = "liminal_contract_tests.rs"]
1853mod contract_tests;
1854
1855#[cfg(test)]
1856mod tests {
1857    use super::{channel_for_row, dispatch_channel_name, normalize_wire_node};
1858    use aion_core::{ActivityId, ContentType, Payload, WorkflowId};
1859    use aion_store::{OutboxRow, OutboxStatus};
1860    use chrono::Utc;
1861    use uuid::Uuid;
1862
1863    /// The NOI-6 dispatch owner guard RELEASES its binding on drop, on EVERY exit path
1864    /// (reply, error, panic) — so the attempt-owner back-index tracks exactly the
1865    /// attempts currently in flight. This is the invariant the dispatch path relies on
1866    /// to never leak a finished attempt's owner.
1867    #[tokio::test]
1868    async fn attempt_owner_guard_releases_on_drop() -> Result<(), Box<dyn std::error::Error>> {
1869        use super::super::intervention::{AttemptKey, AttemptOwnerIndex};
1870        use super::super::registry::{ConnectedWorkerRegistry, WorkerDelivery};
1871        use super::AttemptOwnerGuard;
1872
1873        // A real registration yields a real WorkerId (there is no fabricated id).
1874        let registry = ConnectedWorkerRegistry::default();
1875        let (tx, _rx) = tokio::sync::mpsc::channel(1);
1876        let types = [String::from("agent")];
1877        let registration = registry.register_delivery_with_capabilities(
1878            [String::from("default")],
1879            String::from("default"),
1880            None,
1881            types.iter(),
1882            WorkerDelivery::Grpc(tx),
1883            aion_core::InterventionCapabilities::none(),
1884        )?;
1885        let worker = registration
1886            .worker_id()
1887            .ok_or("registration must assign a worker id")?;
1888
1889        let owners = AttemptOwnerIndex::new();
1890        let key = AttemptKey::new(
1891            WorkflowId::new(Uuid::nil()),
1892            ActivityId::from_sequence_position(3),
1893            1,
1894        );
1895        owners.bind(key.clone(), worker);
1896        assert_eq!(
1897            owners.owner(&key),
1898            Some(worker),
1899            "owner bound before the guard"
1900        );
1901        {
1902            let _guard = AttemptOwnerGuard {
1903                owners: owners.clone(),
1904                key: key.clone(),
1905            };
1906            assert_eq!(
1907                owners.owner(&key),
1908                Some(worker),
1909                "still bound while in flight"
1910            );
1911        }
1912        // The guard dropped at the end of the block: the binding is released, so a
1913        // later intervention resolves no owner (the too-late no-op).
1914        assert_eq!(
1915            owners.owner(&key),
1916            None,
1917            "owner released when the dispatch returns"
1918        );
1919        Ok(())
1920    }
1921
1922    /// The channel format is pinned EXACTLY: any change is a wire-compatibility
1923    /// break (the dispatcher and any worker subscription must agree byte-for-byte).
1924    /// The UNPINNED (`None`) channel MUST stay byte-identical to the pre-NODE-5
1925    /// format so existing pool subscriptions are stable.
1926    #[test]
1927    fn channel_format_is_pinned() {
1928        assert_eq!(
1929            dispatch_channel_name("remote", "gpu", None),
1930            "aion.dispatch.remote.gpu"
1931        );
1932        assert_eq!(
1933            dispatch_channel_name("local", "norn", None),
1934            "aion.dispatch.local.norn"
1935        );
1936    }
1937
1938    /// A node-pinned dispatch appends the node as an injectively-encoded
1939    /// sub-segment: `f(ns, tq, Some(node))` == `aion.dispatch.{ns}.{tq}.{node}`.
1940    #[test]
1941    fn node_pinned_channel_appends_node_subsegment() {
1942        assert_eq!(
1943            dispatch_channel_name("remote", "gpu", Some("box-7")),
1944            "aion.dispatch.remote.gpu.box-7"
1945        );
1946    }
1947
1948    /// Same input always yields the same channel (the function is stable/total),
1949    /// for both the unpinned and node-pinned cases.
1950    #[test]
1951    fn channel_derivation_is_stable() {
1952        assert_eq!(
1953            dispatch_channel_name("default", "default", None),
1954            dispatch_channel_name("default", "default", None)
1955        );
1956        assert_eq!(
1957            dispatch_channel_name("default", "default", Some("box-1")),
1958            dispatch_channel_name("default", "default", Some("box-1"))
1959        );
1960    }
1961
1962    /// Distinct `(namespace, task_queue)` pools derive distinct channels — the
1963    /// whole point of NSTQ-5: `(remote, gpu)` and `(local, norn)` never collide.
1964    #[test]
1965    fn distinct_pools_get_distinct_channels() {
1966        assert_ne!(
1967            dispatch_channel_name("remote", "gpu", None),
1968            dispatch_channel_name("local", "norn", None)
1969        );
1970    }
1971
1972    /// A node-pinned dispatch and the unpinned dispatch for the SAME pool derive
1973    /// DISTINCT channels, and two distinct nodes for the same pool also differ —
1974    /// the property node isolation rests on (the subscriber contract).
1975    #[test]
1976    fn node_pin_separates_channels() {
1977        let unpinned = dispatch_channel_name("remote", "gpu", None);
1978        let box7 = dispatch_channel_name("remote", "gpu", Some("box-7"));
1979        let box8 = dispatch_channel_name("remote", "gpu", Some("box-8"));
1980        assert_ne!(
1981            unpinned, box7,
1982            "pinned dispatch must not reach unpinned pool"
1983        );
1984        assert_ne!(box7, box8, "distinct nodes must not collide");
1985    }
1986
1987    /// The core injectivity property: free-form fields containing the segment
1988    /// separator `.` must NOT bleed across the join. With the raw `format!` the
1989    /// disjoint pools `("a.b", "c")` and `("a", "b.c")` both collapsed onto
1990    /// `aion.dispatch.a.b.c` — a cross-pool/cross-namespace leak. The per-segment
1991    /// encode keeps them distinct.
1992    #[test]
1993    fn dotted_fields_do_not_collide_across_segments() {
1994        assert_ne!(
1995            dispatch_channel_name("a.b", "c", None),
1996            dispatch_channel_name("a", "b.c", None),
1997            "a '.' in a field must not bleed across the segment separator"
1998        );
1999    }
2000
2001    /// Injectivity holds ACROSS segment counts: a 2-segment (unpinned) channel
2002    /// can never be confused with a 3-segment (node-pinned) channel even when a
2003    /// `.` in a field would otherwise make the raw strings line up. Both
2004    /// directions of the brief's collision cases must stay distinct.
2005    #[test]
2006    fn node_subsegment_does_not_collide_with_dotted_fields() {
2007        // A node sub-segment vs the same dot living inside task_queue.
2008        assert_ne!(
2009            dispatch_channel_name("a", "b", Some("c")),
2010            dispatch_channel_name("a", "b.c", None),
2011            "a node sub-segment must not collide with a dotted task_queue"
2012        );
2013        // The dot living inside namespace vs a node sub-segment.
2014        assert_ne!(
2015            dispatch_channel_name("a.b", "c", None),
2016            dispatch_channel_name("a", "b", Some("c")),
2017            "a dotted namespace must not collide with a node-pinned channel"
2018        );
2019    }
2020
2021    /// More reserved-char shifts that the raw `format!` collapsed but the encode
2022    /// must keep distinct — the dot can sit on either side of the boundary.
2023    #[test]
2024    fn reserved_char_shifts_stay_distinct() {
2025        // Dot at the end of namespace vs start of task_queue.
2026        assert_ne!(
2027            dispatch_channel_name("ns.", "tq", None),
2028            dispatch_channel_name("ns", ".tq", None)
2029        );
2030        // Empty field vs the dot living in the other field.
2031        assert_ne!(
2032            dispatch_channel_name("", "a.b", None),
2033            dispatch_channel_name(".a", "b", None)
2034        );
2035        // The escape char itself must not let a literal `%2E` impersonate an
2036        // encoded `.`: `("%2E", "x")` (literal percent-two-E) must differ from
2037        // `(".", "x")` (an actual dot, which encodes to `%2E`).
2038        assert_ne!(
2039            dispatch_channel_name("%2E", "x", None),
2040            dispatch_channel_name(".", "x", None)
2041        );
2042    }
2043
2044    /// Encoding is injective in ALL THREE segments independently and is exactly
2045    /// reversible (the property the channel relies on), so a small exhaustive
2046    /// sweep of reserved-char arrangements — INCLUDING the optional node taking
2047    /// `None` and every reserved-char value — yields all-distinct channels. This
2048    /// covers cross-segment-count collisions (the `None` vs `Some` boundary) too.
2049    #[test]
2050    fn encoding_is_injective_over_reserved_char_triples() {
2051        let fields = ["a", "a.b", "a.", ".a", ".", "", "%", "%2E", "a%b", "%2."];
2052        let nodes = [
2053            None,
2054            Some("a"),
2055            Some("a.b"),
2056            Some("."),
2057            Some(""),
2058            Some("%2E"),
2059        ];
2060        let mut channels = std::collections::HashSet::new();
2061        for ns in fields {
2062            for tq in fields {
2063                for node in nodes {
2064                    let channel = dispatch_channel_name(ns, tq, node);
2065                    assert!(
2066                        channels.insert(channel.clone()),
2067                        "collision on ({ns:?}, {tq:?}, {node:?}) -> {channel}"
2068                    );
2069                }
2070            }
2071        }
2072    }
2073
2074    fn row(namespace: &str, task_queue: &str) -> OutboxRow {
2075        let workflow_id = WorkflowId::new(Uuid::new_v4());
2076        OutboxRow {
2077            dispatch_key: format!("{workflow_id}:0"),
2078            workflow_id,
2079            ordinal: 0,
2080            run_id: Some(aion_core::RunId::new_v4()),
2081            namespace: namespace.to_owned(),
2082            task_queue: task_queue.to_owned(),
2083            node: None,
2084            activity_type: "charge-card".to_owned(),
2085            input: Payload::new(ContentType::Json, Vec::new()),
2086            status: OutboxStatus::Pending,
2087            attempt: 0,
2088            visible_after: Utc::now(),
2089            claimed_at: None,
2090            failure_delivered: false,
2091        }
2092    }
2093
2094    /// A row's channel is derived from its durable `(namespace, task_queue)`
2095    /// columns (NSTQ-2), through the same single derivation function — and
2096    /// `activity_type` does NOT enter the channel. With `node = None` the channel
2097    /// is byte-identical to the pre-NODE-5 2-segment form.
2098    #[test]
2099    fn channel_for_row_uses_namespace_and_task_queue_only() {
2100        let remote_gpu = row("remote", "gpu");
2101        let local_norn = row("local", "norn");
2102        assert_eq!(channel_for_row(&remote_gpu), "aion.dispatch.remote.gpu");
2103        assert_eq!(channel_for_row(&local_norn), "aion.dispatch.local.norn");
2104        assert_ne!(channel_for_row(&remote_gpu), channel_for_row(&local_norn));
2105
2106        // Two rows that differ ONLY in activity_type derive the SAME channel:
2107        // activity_type is matched after delivery, not used to select the pool.
2108        let mut other_activity = row("remote", "gpu");
2109        other_activity.activity_type = "refund".to_owned();
2110        assert_eq!(
2111            channel_for_row(&remote_gpu),
2112            channel_for_row(&other_activity),
2113            "activity_type must not affect the channel"
2114        );
2115    }
2116
2117    /// A row carrying `Some(node)` (NODE-2) derives the node-pinned sub-channel,
2118    /// distinct from the same pool's unpinned channel; a row with `None` derives
2119    /// the 2-segment channel. `channel_for_row` threads `row.node` through the
2120    /// single derivation function.
2121    #[test]
2122    fn channel_for_row_derives_node_subchannel_when_pinned() {
2123        let mut pinned = row("remote", "gpu");
2124        pinned.node = Some("box-7".to_owned());
2125        assert_eq!(channel_for_row(&pinned), "aion.dispatch.remote.gpu.box-7");
2126
2127        let unpinned = row("remote", "gpu");
2128        assert_eq!(channel_for_row(&unpinned), "aion.dispatch.remote.gpu");
2129        assert_ne!(channel_for_row(&pinned), channel_for_row(&unpinned));
2130    }
2131
2132    /// The outbox wire request stamps the row's stored ZERO-based attempt as a
2133    /// ONE-based delivery attempt (zero is malformed on the wire) — the exact
2134    /// stamp the gRPC outbox arm's `to_scheduled` applies — carries no labels,
2135    /// and assigns no liveness window (outbox rows are not tracker-tracked; the
2136    /// outbox retry loop is their liveness backstop).
2137    #[test]
2138    fn request_for_row_stamps_one_based_attempt_and_no_window() -> Result<(), crate::ServerError> {
2139        let mut retried = row("remote", "gpu");
2140        retried.attempt = 2;
2141        let run_id = retried
2142            .run_id
2143            .as_ref()
2144            .ok_or_else(|| crate::ServerError::worker_dispatch("", "", "test row missing run"))?;
2145        let token = super::CompletionToken::for_test();
2146        let request = super::request_for_row(&retried, run_id, &token);
2147        assert_eq!(
2148            request.attempt, 3,
2149            "zero-based row attempt goes one-based on the wire"
2150        );
2151        assert!(request.labels.is_empty());
2152        assert_eq!(request.heartbeat_window_ms, 0);
2153
2154        let fresh = row("remote", "gpu");
2155        let fresh_run = fresh
2156            .run_id
2157            .as_ref()
2158            .ok_or_else(|| crate::ServerError::worker_dispatch("", "", "test row missing run"))?;
2159        assert_eq!(super::request_for_row(&fresh, fresh_run, &token).attempt, 1);
2160        Ok(())
2161    }
2162
2163    /// The wire `node` is normalized onto the registry's optional affinity with
2164    /// the SAME none-convention the gRPC registration path uses: `None` and the
2165    /// empty-string node both collapse to unpinned (`None`), a non-empty value is
2166    /// the advertised node. An empty-string node must NOT register a distinct
2167    /// empty affinity no pinned dispatch could match.
2168    #[test]
2169    fn wire_node_normalizes_empty_to_none() {
2170        assert_eq!(normalize_wire_node(None), None);
2171        assert_eq!(normalize_wire_node(Some("")), None);
2172        assert_eq!(normalize_wire_node(Some("box-7")), Some("box-7".to_owned()));
2173    }
2174
2175    // --- #163: the Prefer two-tier spill on the LIMINAL selection path ---------
2176    //
2177    // These exercise `RegistryLiminalDispatch::select_liminal_worker` — the
2178    // liminal transport's worker selection — proving it consults the SAME shared
2179    // `preferred_node_order` two-tier spill the gRPC path uses (the cross-node
2180    // demo behaviour), and that placement NEVER mutates the recorded row's node.
2181    // Selection is delivery-agnostic (`select_worker` filters by node regardless
2182    // of transport), so a worker registered with any delivery drives the same
2183    // selection the production liminal-delivered worker would; the tests assert on
2184    // the SELECTED handle's node, which is exactly what #163 changed.
2185    mod placement_selection {
2186        use std::collections::BTreeSet;
2187        use std::sync::Arc;
2188        use std::time::Duration;
2189
2190        use aion_core::{ActivityId, Payload, RunId, WorkflowId};
2191        use aion_store::{
2192            InMemoryStore, NamespaceOrigin, NamespacePlacement, NamespaceStore, OutboxRow,
2193        };
2194
2195        use crate::error::ServerError;
2196        use crate::worker::bridge::OutboxDeliveryCallback;
2197        use crate::worker::registry::{ConnectedWorkerRegistry, WorkerMessage, WorkerRegistration};
2198        use crate::worker::{DeliveryGate, PlacementCache};
2199
2200        use super::super::RegistryLiminalDispatch;
2201
2202        /// No-op delivery callback: the selection tests never deliver a result, so
2203        /// the completion sink is never invoked. Both methods are unreachable in
2204        /// these tests and simply report "no live run" if ever called.
2205        struct NoopCallback;
2206
2207        impl OutboxDeliveryCallback for NoopCallback {
2208            fn deliver_completion(
2209                &self,
2210                _workflow_id: &WorkflowId,
2211                _activity_id: &ActivityId,
2212                _run_id: Option<&RunId>,
2213                _result: String,
2214            ) -> Result<bool, ServerError> {
2215                Ok(false)
2216            }
2217            fn deliver_failure(
2218                &self,
2219                _workflow_id: &WorkflowId,
2220                _activity_id: &ActivityId,
2221                _run_id: Option<&RunId>,
2222                _reason: String,
2223            ) -> Result<bool, ServerError> {
2224                Ok(false)
2225            }
2226        }
2227
2228        fn labels(values: &[&str]) -> BTreeSet<String> {
2229            values.iter().map(|v| (*v).to_owned()).collect()
2230        }
2231
2232        /// Register a worker advertising `node` for `charge` in `namespace`,
2233        /// returning the registration guard (held to keep it connected).
2234        fn register_node_worker(
2235            registry: &ConnectedWorkerRegistry,
2236            namespace: &str,
2237            node: &str,
2238        ) -> Result<WorkerRegistration, ServerError> {
2239            let (tx, _rx) = tokio::sync::mpsc::channel::<WorkerMessage>(1);
2240            let types = [String::from("charge")];
2241            registry.register_namespaces(
2242                [namespace.to_owned()],
2243                String::from("default"),
2244                Some(node.to_owned()),
2245                types.iter(),
2246                tx,
2247            )
2248        }
2249
2250        /// Build an UNPINNED outbox row (`node == None`) in `namespace` for `charge`.
2251        fn unpinned_row(namespace: &str) -> OutboxRow {
2252            OutboxRow::pending(
2253                WorkflowId::new_v4(),
2254                0,
2255                String::from("charge"),
2256                Payload::from_json(&serde_json::json!({}))
2257                    .unwrap_or_else(|_| Payload::new(aion_core::ContentType::Json, Vec::new())),
2258                chrono::Utc::now(),
2259            )
2260            .with_namespace(namespace)
2261            .with_task_queue("default")
2262        }
2263
2264        /// A namespace store with `namespace` set to `Prefer{nodes}`.
2265        async fn prefer_store(
2266            namespace: &str,
2267            nodes: &[&str],
2268        ) -> Result<Arc<dyn NamespaceStore>, ServerError> {
2269            let store: Arc<dyn NamespaceStore> = Arc::new(InMemoryStore::default());
2270            store
2271                .register_namespace(namespace, NamespaceOrigin::Explicit)
2272                .await?;
2273            store
2274                .set_namespace_placement(
2275                    namespace,
2276                    NamespacePlacement::Prefer {
2277                        nodes: labels(nodes),
2278                    },
2279                )
2280                .await?;
2281            Ok(store)
2282        }
2283
2284        /// A namespace store with `namespace` set to `Pinned{nodes}` (P2-I1).
2285        async fn pinned_store(
2286            namespace: &str,
2287            nodes: &[&str],
2288        ) -> Result<Arc<dyn NamespaceStore>, ServerError> {
2289            let store: Arc<dyn NamespaceStore> = Arc::new(InMemoryStore::default());
2290            store
2291                .register_namespace(namespace, NamespaceOrigin::Explicit)
2292                .await?;
2293            store
2294                .set_namespace_placement(
2295                    namespace,
2296                    NamespacePlacement::Pinned {
2297                        nodes: labels(nodes),
2298                    },
2299                )
2300                .await?;
2301            Ok(store)
2302        }
2303
2304        /// Build a `RegistryLiminalDispatch` over `registry` whose placement cache
2305        /// reads `ns_store` (zero TTL so each selection sees the latest placement).
2306        fn liminal_dispatch(
2307            registry: &ConnectedWorkerRegistry,
2308            ns_store: Arc<dyn NamespaceStore>,
2309        ) -> RegistryLiminalDispatch {
2310            let cache = PlacementCache::new(ns_store, Duration::ZERO);
2311            RegistryLiminalDispatch::new(
2312                registry.clone(),
2313                Arc::new(NoopCallback),
2314                DeliveryGate::default(),
2315            )
2316            .with_placement_cache(cache)
2317        }
2318
2319        /// #163 (prefer): an unpinned row in a `Prefer{n1}` namespace selects the
2320        /// n1 worker on the liminal path when one is live, even with an n2 worker
2321        /// also connected.
2322        #[tokio::test]
2323        async fn prefer_selects_preferred_node_worker_on_liminal_path()
2324        -> Result<(), Box<dyn std::error::Error>> {
2325            let ns_store = prefer_store("t", &["n1"]).await?;
2326            let registry = ConnectedWorkerRegistry::default();
2327            let _n1 = register_node_worker(&registry, "t", "n1")?;
2328            let _n2 = register_node_worker(&registry, "t", "n2")?;
2329            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2330
2331            let row = unpinned_row("t");
2332            let selected = dispatch
2333                .select_liminal_worker(&row)
2334                .await?
2335                .ok_or("a worker must be selected")?;
2336            assert_eq!(
2337                selected.node(),
2338                Some("n1"),
2339                "the liminal path prefers the n1 worker while it is live"
2340            );
2341            // Determinism gate: preference never mutates the recorded row's node.
2342            assert_eq!(row.node, None, "placement must never mutate the row's node");
2343            Ok(())
2344        }
2345
2346        /// #163 (spill): an unpinned row in a `Prefer{n1}` namespace SPILLS to the
2347        /// only live worker (n2) on the liminal path when no n1 worker is
2348        /// connected — the cross-node node-loss failover behaviour.
2349        #[tokio::test]
2350        async fn prefer_spills_to_any_live_worker_on_liminal_path()
2351        -> Result<(), Box<dyn std::error::Error>> {
2352            let ns_store = prefer_store("t", &["n1"]).await?;
2353            // Only an n2 worker is live: no n1-labelled worker exists at all.
2354            let registry = ConnectedWorkerRegistry::default();
2355            let _n2 = register_node_worker(&registry, "t", "n2")?;
2356            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2357
2358            let row = unpinned_row("t");
2359            let selected = dispatch
2360                .select_liminal_worker(&row)
2361                .await?
2362                .ok_or("the spill must select the live n2 worker")?;
2363            assert_eq!(
2364                selected.node(),
2365                Some("n2"),
2366                "with no n1 worker live, the liminal selection spills to the live n2 worker"
2367            );
2368            assert_eq!(row.node, None, "spill must never mutate the row's node");
2369            Ok(())
2370        }
2371
2372        /// #163 (determinism, mirrors the gRPC `placement_never_mutates_recorded_row_node`
2373        /// test): under `Prefer{n1}` the SAME unpinned row selected once to the n1
2374        /// worker and once (after n1 leaves) spilled to n2 keeps `node == None`
2375        /// BOTH times — selection reads the row's node, never the placement, so
2376        /// replay sees an identical command stream irrespective of the target.
2377        #[tokio::test]
2378        async fn placement_never_mutates_recorded_row_node_on_liminal_path()
2379        -> Result<(), Box<dyn std::error::Error>> {
2380            let ns_store = prefer_store("t", &["n1"]).await?;
2381            let registry = ConnectedWorkerRegistry::default();
2382            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2383
2384            // Routing A: n1 present -> preferred selection.
2385            let n1 = register_node_worker(&registry, "t", "n1")?;
2386            let row_a = unpinned_row("t");
2387            let selected_a = dispatch
2388                .select_liminal_worker(&row_a)
2389                .await?
2390                .ok_or("routing A must select a worker")?;
2391            assert_eq!(selected_a.node(), Some("n1"));
2392
2393            // n1 leaves; only n2 remains.
2394            n1.deregister()?;
2395            let _n2 = register_node_worker(&registry, "t", "n2")?;
2396
2397            // Routing B: same shape of unpinned row -> spills to n2.
2398            let row_b = unpinned_row("t");
2399            let selected_b = dispatch
2400                .select_liminal_worker(&row_b)
2401                .await?
2402                .ok_or("routing B must spill to a worker")?;
2403            assert_eq!(selected_b.node(), Some("n2"));
2404
2405            // The recorded row node is None in BOTH routings: the dispatch target
2406            // (n1 vs n2) did not perturb it.
2407            assert_eq!(row_a.node, None);
2408            assert_eq!(row_b.node, None);
2409            assert_eq!(
2410                row_a.node, row_b.node,
2411                "the recorded row node is identical regardless of which worker was selected"
2412            );
2413            Ok(())
2414        }
2415
2416        /// #164 (P2-I1 hard pin): an unpinned row in a `Pinned{n1}` namespace
2417        /// selects the n1 worker on the liminal path when live — exactly like
2418        /// Prefer's happy path.
2419        #[tokio::test]
2420        async fn pinned_selects_required_node_worker_on_liminal_path()
2421        -> Result<(), Box<dyn std::error::Error>> {
2422            let ns_store = pinned_store("t", &["n1"]).await?;
2423            let registry = ConnectedWorkerRegistry::default();
2424            let _n1 = register_node_worker(&registry, "t", "n1")?;
2425            let _n2 = register_node_worker(&registry, "t", "n2")?;
2426            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2427
2428            let row = unpinned_row("t");
2429            let selected = dispatch
2430                .select_liminal_worker(&row)
2431                .await?
2432                .ok_or("the required n1 worker must be selected")?;
2433            assert_eq!(selected.node(), Some("n1"));
2434            assert_eq!(row.node, None, "placement must never mutate the row's node");
2435            Ok(())
2436        }
2437
2438        /// #164 (P2-I1 no spill — the load-bearing test): an unpinned row in a
2439        /// `Pinned{n1}` namespace with ONLY a live n2 worker selects NOTHING — it
2440        /// must NEVER spill to the wrong-node worker. This is the exact opposite of
2441        /// the `prefer_spills_to_any_live_worker_on_liminal_path` behaviour and would
2442        /// FAIL under the old fall-through (which selected any worker for Pinned).
2443        /// The `Ok(None)` drives the outbox no-worker retry/stall, mirroring the
2444        /// gRPC wait.
2445        #[tokio::test]
2446        async fn pinned_never_spills_to_a_wrong_node_worker_on_liminal_path()
2447        -> Result<(), Box<dyn std::error::Error>> {
2448            let ns_store = pinned_store("t", &["n1"]).await?;
2449            // Only an n2 worker is live: no n1-labelled worker exists at all.
2450            let registry = ConnectedWorkerRegistry::default();
2451            let _n2 = register_node_worker(&registry, "t", "n2")?;
2452            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2453
2454            let row = unpinned_row("t");
2455            let selected = dispatch.select_liminal_worker(&row).await?;
2456            assert!(
2457                selected.is_none(),
2458                "Pinned{{n1}} must NOT spill to the live n2 worker — it selects nothing \
2459                 so the outbox retries/stalls until an n1 worker returns"
2460            );
2461            assert_eq!(row.node, None, "placement must never mutate the row's node");
2462            Ok(())
2463        }
2464
2465        /// #163 (authored pin wins): a row authored-pinned to `Some(n2)` STILL
2466        /// selects an n2 worker on the liminal path regardless of the namespace's
2467        /// `Prefer{n1}` — the per-activity pin is authoritative and placement never
2468        /// overrides it.
2469        #[tokio::test]
2470        async fn authored_node_pin_wins_over_namespace_prefer_on_liminal_path()
2471        -> Result<(), Box<dyn std::error::Error>> {
2472            let ns_store = prefer_store("t", &["n1"]).await?;
2473            let registry = ConnectedWorkerRegistry::default();
2474            let _n1 = register_node_worker(&registry, "t", "n1")?;
2475            let _n2 = register_node_worker(&registry, "t", "n2")?;
2476            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2477
2478            // Authored pin: node = Some("n2").
2479            let row = unpinned_row("t").with_node(Some(String::from("n2")));
2480            let selected = dispatch
2481                .select_liminal_worker(&row)
2482                .await?
2483                .ok_or("the authored pin must select the n2 worker")?;
2484            assert_eq!(
2485                selected.node(),
2486                Some("n2"),
2487                "the authored Some(n2) pin is honoured regardless of the namespace Prefer{{n1}}"
2488            );
2489            // The authored node is preserved exactly (determinism gate).
2490            assert_eq!(row.node.as_deref(), Some("n2"));
2491            Ok(())
2492        }
2493
2494        /// #163 (byte-identical default): an `Unplaced` namespace selects any live
2495        /// worker on the liminal path exactly as the pre-Phase-2 single
2496        /// `select_worker` would — the ceiling/placement never engages.
2497        #[tokio::test]
2498        async fn unplaced_namespace_selects_any_worker_on_liminal_path()
2499        -> Result<(), Box<dyn std::error::Error>> {
2500            let ns_store: Arc<dyn NamespaceStore> = Arc::new(InMemoryStore::default());
2501            // Registered but left Unplaced (the default placement).
2502            ns_store
2503                .register_namespace("t", NamespaceOrigin::Explicit)
2504                .await?;
2505            let registry = ConnectedWorkerRegistry::default();
2506            let _n2 = register_node_worker(&registry, "t", "n2")?;
2507            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2508
2509            let selected = dispatch
2510                .select_liminal_worker(&unpinned_row("t"))
2511                .await?
2512                .ok_or("an Unplaced namespace still selects a live worker")?;
2513            assert_eq!(
2514                selected.node(),
2515                Some("n2"),
2516                "an Unplaced namespace reaches any live worker, exactly as before"
2517            );
2518            Ok(())
2519        }
2520
2521        /// #163 (byte-identical, no cache): with NO placement cache attached, the
2522        /// liminal selection is the single `select_worker` off the row's own node —
2523        /// byte-identical to the pre-#163 construction. An unpinned row reaches any
2524        /// live worker; the namespace's `Prefer` is not even consulted.
2525        #[tokio::test]
2526        async fn no_cache_selection_is_byte_identical_to_pre_163()
2527        -> Result<(), Box<dyn std::error::Error>> {
2528            // The namespace prefers n1, but with no cache the preference is ignored.
2529            let _ns_store = prefer_store("t", &["n1"]).await?;
2530            let registry = ConnectedWorkerRegistry::default();
2531            let _n2 = register_node_worker(&registry, "t", "n2")?;
2532            // No `.with_placement_cache(...)`: the pre-#163 construction.
2533            let dispatch = RegistryLiminalDispatch::new(
2534                registry.clone(),
2535                Arc::new(NoopCallback),
2536                DeliveryGate::default(),
2537            );
2538
2539            let selected = dispatch
2540                .select_liminal_worker(&unpinned_row("t"))
2541                .await?
2542                .ok_or("without a cache the unpinned row still selects any worker")?;
2543            assert_eq!(
2544                selected.node(),
2545                Some("n2"),
2546                "with no placement cache the selection is the unchanged any-worker path"
2547            );
2548            Ok(())
2549        }
2550    }
2551}