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        // The run is resolved BEFORE the owner binding, because the binding is
1053        // keyed on it: a run-blind key would let an intervention aimed at one
1054        // continue-as-new generation resolve another's worker. The refusal is
1055        // the pre-existing one — a row without a run cannot be dispatched at all
1056        // — simply moved ahead of the bind it now feeds.
1057        let activity_id = ActivityId::from_sequence_position(row.ordinal);
1058        let run_id = row.run_id.as_ref().ok_or_else(|| {
1059            dispatch_error(
1060                &channel_for_row(row),
1061                "activity run id is missing; refusing unfenced external effect".to_owned(),
1062            )
1063        })?;
1064
1065        // NOI-6: bind this attempt's owner BEFORE the push, so an intervention that
1066        // races the dispatch resolves the worker. The guard releases on every exit
1067        // path (reply, error, panic) so the index never keeps a finished attempt.
1068        // The key mirrors the worker's execute-path stamp exactly: activity_id from
1069        // the ordinal, run_id from the row, attempt = the wire's one-based delivery
1070        // attempt (the same `request_for_row` stamp the worker echoes into its
1071        // session key). See `LiminalActivityWorker::execute` / `run_agent_dispatch`.
1072        let _owner_guard = self.attempt_owners.as_ref().map(|owners| {
1073            AttemptOwnerGuard::bind(
1074                owners.clone(),
1075                super::intervention::AttemptKey::new(
1076                    row.workflow_id.clone(),
1077                    run_id.clone(),
1078                    activity_id.clone(),
1079                    row.attempt.saturating_add(1),
1080                ),
1081                worker.id(),
1082            )
1083        });
1084
1085        // Push the dispatch to the worker and block for its correlated reply. The
1086        // push is a blocking, thread-based liminal call; run it off the async
1087        // runtime so a long-running activity cannot starve a runtime worker.
1088        let completion_token = self
1089            .completion
1090            .completion_fences
1091            .issue(&row.workflow_id, &activity_id)?;
1092        let request = request_for_row(row, run_id, &completion_token);
1093        let gate = self.delivery_gate.clone();
1094        let dispatch_key = row.dispatch_key.clone();
1095        let registry = self.registry.clone();
1096        let worker_id = worker.id();
1097        let dispatched = tokio::task::spawn_blocking(move || {
1098            delivery.dispatch_held(&request, || {
1099                if gate.is_draining() || !gate.holds(&dispatch_key) {
1100                    return false;
1101                }
1102                match registry.worker_by_id(worker_id) {
1103                    Ok(Some(_)) => true,
1104                    Ok(None) => false,
1105                    Err(error) => {
1106                        tracing::warn!(
1107                            %error,
1108                            %dispatch_key,
1109                            "delivery wait could not verify worker registration; abandoning"
1110                        );
1111                        false
1112                    }
1113                }
1114            })
1115        })
1116        .await
1117        .map_err(|error| {
1118            dispatch_error(
1119                &channel_for_row(row),
1120                format!("dispatch task join failed: {error}"),
1121            )
1122        });
1123        let response = match dispatched {
1124            Ok(Ok(Some(response))) => response,
1125            Ok(Ok(None)) => {
1126                tracing::warn!(
1127                    dispatch_key = %row.dispatch_key,
1128                    workflow_id = %row.workflow_id,
1129                    %activity_id,
1130                    "delivery wait abandoned; late reply will be discarded"
1131                );
1132                self.revoke_completion(row, &activity_id, &completion_token)?;
1133                return Err(dispatch_error(
1134                    &channel_for_row(row),
1135                    "delivery wait abandoned before worker reply".to_owned(),
1136                ));
1137            }
1138            Ok(Err(error)) | Err(error) => {
1139                self.revoke_completion(row, &activity_id, &completion_token)?;
1140                return Err(error);
1141            }
1142        };
1143
1144        // Re-enter the worker's result through the SAME completion path the gRPC
1145        // transport uses (terminal dedup in `record_fan_out_completion` applies
1146        // unchanged). The dispatch itself succeeded — the row's terminal state is
1147        // recorded by the completion callback, exactly as in the gRPC path.
1148        if let Err(error) = self.completion.deliver(&response) {
1149            self.revoke_completion(row, &activity_id, &completion_token)?;
1150            return Err(error);
1151        }
1152        Ok(())
1153    }
1154}
1155
1156/// RAII guard that releases an [`AttemptOwnerIndex`](super::intervention::AttemptOwnerIndex)
1157/// binding when the dispatch resolves — on the reply, an error, or a panic — so
1158/// the back-index tracks exactly the attempts currently in flight (NOI-6).
1159///
1160/// Shared by both liminal dispatch arms: the outbox row wait holds it across
1161/// its blocking `dispatch` call, and the engine-seam bridge hands it to the
1162/// dispatch's reply-router thread, which drops it on every exit path.
1163pub(crate) struct AttemptOwnerGuard {
1164    owners: super::intervention::AttemptOwnerIndex,
1165    key: super::intervention::AttemptKey,
1166}
1167
1168impl AttemptOwnerGuard {
1169    /// Bind `key` to `worker` in `owners` and return the guard that releases
1170    /// the binding on drop.
1171    pub(crate) fn bind(
1172        owners: super::intervention::AttemptOwnerIndex,
1173        key: super::intervention::AttemptKey,
1174        worker: super::registry::WorkerId,
1175    ) -> Self {
1176        owners.bind(key.clone(), worker);
1177        Self { owners, key }
1178    }
1179}
1180
1181impl Drop for AttemptOwnerGuard {
1182    fn drop(&mut self) {
1183        self.owners.release(&self.key);
1184    }
1185}
1186
1187/// Normalize a wire `node` (`Option<String>`) onto the registry's optional
1188/// locality affinity, applying the SAME none-convention the gRPC registration
1189/// path uses (`registry::optional_node`): an empty string carries no node, so it
1190/// collapses to `None`; any non-empty value is the worker's advertised node.
1191///
1192/// The wire already models `node` as `Option<String>`, but a worker that joins
1193/// `Some("")` (the empty-string node) must not register a distinct empty-node
1194/// affinity that no pinned dispatch could ever match — it is semantically
1195/// unpinned, exactly as the gRPC proto3 empty default is. Folding it to `None`
1196/// here keeps the two registration paths byte-for-byte equivalent.
1197fn normalize_wire_node(node: Option<&str>) -> Option<String> {
1198    node.filter(|value| !value.is_empty())
1199        .map(ToOwned::to_owned)
1200}
1201
1202/// Connection-keyed [`ConnectionNotifier`] that turns liminal's in-band worker
1203/// registration into a first-class [`ConnectedWorkerRegistry`] membership.
1204///
1205/// This is the SERVER half of LSUB-L2: when a worker connects with a
1206/// [`WireWorkerRegistration`] (the SDK's `connect_with_registration`), liminal's
1207/// connection process invokes [`on_worker_registered`](Self::on_worker_registered)
1208/// with the connection's beamr `pid` and the worker's declared
1209/// `(namespaces, task_queue, node, activity_types)`. The notifier builds a
1210/// [`WorkerDelivery::Liminal`] over the connection and inserts it into the
1211/// registry — the SAME registry entry, selected the SAME way, as a gRPC worker —
1212/// retiring the LSUB-1 out-of-band `active_connection_pids()` + hard-coded
1213/// registration hack.
1214///
1215/// # Lifetime of the registration guard
1216///
1217/// [`ConnectedWorkerRegistry::register_delivery`] returns a
1218/// [`WorkerRegistration`] guard whose drop deregisters the worker. The notifier
1219/// OWNS that guard keyed by `pid` (`Mutex<HashMap<u64, WorkerRegistration>>`), so
1220/// the registration lives exactly as long as the connection: it is inserted on
1221/// register and removed (dropped) on
1222/// [`on_worker_unregistered`](Self::on_worker_unregistered), which liminal fires
1223/// on connection close.
1224///
1225/// # Construction-order cycle (notifier <-> supervisor)
1226///
1227/// [`LiminalWorkerDelivery`] needs a [`ConnectionSupervisor`] handle to push to
1228/// the worker's connection, but the supervisor is itself constructed WITH this
1229/// notifier ([`ConnectionSupervisor::with_services_and_notifier`]) — a cycle. The
1230/// notifier therefore holds the supervisor behind a [`OnceLock`], populated
1231/// IMMEDIATELY after the supervisor is built via [`Self::bind_supervisor`]. The
1232/// `OnceLock` is never read before it is set in correct wiring (a worker can only
1233/// register after the listener — built after the supervisor and after
1234/// `bind_supervisor` — accepts its connection); if it somehow were, registration
1235/// is REJECTED with a typed error rather than panicking, so there is no
1236/// production `unwrap`/`expect` and no second always-`None` code path.
1237pub struct LiminalConnectionNotifier {
1238    registry: ConnectedWorkerRegistry,
1239    contract_catalog: Option<Arc<aion::Engine>>,
1240    supervisor: OnceLock<ConnectionSupervisor>,
1241    guards: Mutex<HashMap<u64, WorkerRegistration>>,
1242    /// The neutral intervention primitives a liminal-connected agent worker
1243    /// advertises (NOI-6, item 4). The liminal `WorkerRegistration` wire has a fixed
1244    /// shape that cannot carry this, so it is configured on the notifier at the
1245    /// composition root from the harness's advertised `AgentSession::capabilities()`
1246    /// and recorded on every registered worker's handle, where the intervention
1247    /// router gates on it. Default empty = observability-only (a plain activity
1248    /// worker), so the router offers no controls for it.
1249    intervention_capabilities: aion_core::InterventionCapabilities,
1250    /// The transcript sequencer a worker's observability publishes drain into
1251    /// (NOI-5b), plus the Tokio [`Handle`](tokio::runtime::Handle) to bridge the
1252    /// synchronous connection-process callback onto the async publish. `None` (the
1253    /// default, and every non-agent boot) makes the observability tap a no-op, so a
1254    /// worker publish to the reserved channel is simply ignored by the notifier.
1255    transcript: Option<TranscriptTap>,
1256    /// The SAME per-task liveness tracker the bridge dispatcher tracks into and
1257    /// the #176 expiry sweeper expires from. A worker's automatic
1258    /// [`WorkerLivenessBeat`] publishes on [`WORKER_LIVENESS_CHANNEL`] refresh
1259    /// their task stamps here, keeping the sweeper honest for liminal-delivered
1260    /// dispatches. `None` (a wiring that never bridges dispatches, e.g. isolated
1261    /// tests) consumes and drops the beats.
1262    heartbeat_tracker: Option<super::heartbeat::HeartbeatTracker>,
1263}
1264
1265/// The observability-drain leg of the notifier: a bounded, ORDERED queue into
1266/// the one drain task that publishes transcript events sequentially.
1267///
1268/// One consumer is load-bearing, not an implementation detail: a spawned task
1269/// per event (the pre-2026-07-23 shape) made every in-flight frame a
1270/// concurrent writer racing the same stream head, turning the sequencer's
1271/// optimistic-append loop into an O(N²) conflict stampede under load — and
1272/// destroyed `worker_seq` order on the durable transcript. Sequential
1273/// draining preserves arrival order and leaves the conflict-retry loop to
1274/// handle only genuine cross-process races (failover adoption).
1275#[derive(Clone)]
1276struct TranscriptTap {
1277    queue: tokio::sync::mpsc::Sender<aion_core::ActivityEvent>,
1278}
1279
1280/// Bound on the transcript drain queue: events a slow durable append cannot
1281/// keep up with are dropped (with a warning) rather than buffered without
1282/// limit. Live streaming is best-effort; the bound protects server memory.
1283const TRANSCRIPT_QUEUE_CAPACITY: usize = 4096;
1284
1285impl std::fmt::Debug for LiminalConnectionNotifier {
1286    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1287        f.debug_struct("LiminalConnectionNotifier")
1288            .field("supervisor_bound", &self.supervisor.get().is_some())
1289            .finish_non_exhaustive()
1290    }
1291}
1292
1293impl LiminalConnectionNotifier {
1294    /// Build a notifier that registers connecting workers into `registry`.
1295    ///
1296    /// The supervisor handle is bound separately via [`Self::bind_supervisor`]
1297    /// immediately after the supervisor is constructed, resolving the
1298    /// notifier <-> supervisor construction cycle (see the type docs).
1299    #[must_use]
1300    pub fn new(registry: ConnectedWorkerRegistry) -> Self {
1301        Self {
1302            registry,
1303            contract_catalog: None,
1304            supervisor: OnceLock::new(),
1305            guards: Mutex::new(HashMap::new()),
1306            intervention_capabilities: aion_core::InterventionCapabilities::none(),
1307            transcript: None,
1308            heartbeat_tracker: None,
1309        }
1310    }
1311
1312    /// Install the live package catalog used to refuse incompatible workers
1313    /// before liminal acknowledges or publishes their registration.
1314    #[must_use]
1315    pub fn with_contract_catalog(mut self, engine: Arc<aion::Engine>) -> Self {
1316        self.contract_catalog = Some(engine);
1317        self
1318    }
1319
1320    /// Install the shared per-task liveness tracker so a worker's automatic
1321    /// [`WorkerLivenessBeat`] publishes refresh the SAME in-flight entries the
1322    /// bridge dispatcher tracks and the #176 sweeper expires.
1323    ///
1324    /// MUST be wired on every boot that hosts the engine-seam bridge (the
1325    /// production composition does), or the sweeper would expire healthy
1326    /// liminal workers running activities longer than the heartbeat window.
1327    /// Without it (isolated tests that never bridge-dispatch) beats are
1328    /// consumed and dropped.
1329    #[must_use]
1330    pub fn with_heartbeat_tracker(mut self, tracker: super::heartbeat::HeartbeatTracker) -> Self {
1331        self.heartbeat_tracker = Some(tracker);
1332        self
1333    }
1334
1335    /// Install the transcript sequencer a worker's observability publishes drain into
1336    /// (NOI-5b), capturing the CURRENT Tokio runtime handle to bridge the synchronous
1337    /// connection-process callback onto the async publish.
1338    ///
1339    /// MUST be called from within a Tokio runtime (the server boot path is), so the
1340    /// captured [`Handle`](tokio::runtime::Handle) can spawn the append+fan-out when a
1341    /// worker publishes a transcript event over the reserved channel. Without this
1342    /// builder the observability tap is a no-op (a plain, non-agent deployment).
1343    ///
1344    /// # Panics
1345    ///
1346    /// Panics if called outside a Tokio runtime — a construction-time wiring error in
1347    /// the server boot, never a runtime condition (the boot path always builds the
1348    /// notifier inside the server runtime).
1349    #[must_use]
1350    pub fn with_transcript_publisher(
1351        mut self,
1352        publisher: crate::activity_publisher::ActivityEventPublisher,
1353    ) -> Self {
1354        let (queue, mut events) =
1355            tokio::sync::mpsc::channel::<aion_core::ActivityEvent>(TRANSCRIPT_QUEUE_CAPACITY);
1356        // The ONE drain task: transcript events publish sequentially in
1357        // arrival order (see the `TranscriptTap` docs for why one consumer is
1358        // load-bearing). It lives as long as any queue sender does.
1359        tokio::runtime::Handle::current().spawn(async move {
1360            while let Some(event) = events.recv().await {
1361                if let Err(error) = publisher.publish(&event).await {
1362                    tracing::warn!(%error, "observability tap: transcript publish failed");
1363                }
1364            }
1365        });
1366        self.transcript = Some(TranscriptTap { queue });
1367        self
1368    }
1369
1370    /// Set the neutral intervention capability set every worker registering through
1371    /// this notifier advertises (NOI-6, item 4).
1372    ///
1373    /// The composition root wires this from the harness's advertised
1374    /// `AgentSession::capabilities()` so a liminal-connected agent worker's handle
1375    /// carries the primitives its harness supports, which the intervention router
1376    /// gates on. Without this builder the set is empty (observability-only), so a
1377    /// plain activity worker advertises no controls. Pure builder addition, mirroring
1378    /// the registry's capability-carrying registration façade.
1379    #[must_use]
1380    pub fn with_intervention_capabilities(
1381        mut self,
1382        capabilities: aion_core::InterventionCapabilities,
1383    ) -> Self {
1384        self.intervention_capabilities = capabilities;
1385        self
1386    }
1387
1388    /// Bind the connection supervisor the notifier pushes through, immediately
1389    /// after it is constructed with this notifier.
1390    ///
1391    /// Returns `true` when the supervisor was stored, `false` when it was already
1392    /// bound (a second bind is a wiring bug and is ignored, never overwriting the
1393    /// live handle). Call this exactly once, right after
1394    /// [`ConnectionSupervisor::with_services_and_notifier`].
1395    pub fn bind_supervisor(&self, supervisor: ConnectionSupervisor) -> bool {
1396        self.supervisor.set(supervisor).is_ok()
1397    }
1398
1399    /// Snapshot of every live liminal connection the dead-man switch must ping:
1400    /// its pid, the worker it registered, and the push leg to reach it.
1401    ///
1402    /// Built from the SAME guard map that owns each connection's registration,
1403    /// so a connection that has closed (its guard removed) is structurally
1404    /// absent from the snapshot and is never pinged. A poisoned guard map is
1405    /// recovered rather than skipped: silently returning no targets would turn
1406    /// the dead-man switch off exactly when the server is already unhealthy.
1407    #[must_use]
1408    pub fn liveness_targets(&self) -> Vec<super::liminal_liveness::LivenessTarget> {
1409        let Some(supervisor) = self.supervisor.get() else {
1410            return Vec::new();
1411        };
1412        let guards = match self.guards.lock() {
1413            Ok(guards) => guards,
1414            Err(poisoned) => poisoned.into_inner(),
1415        };
1416        guards
1417            .iter()
1418            .filter_map(|(pid, guard)| {
1419                guard
1420                    .worker_id()
1421                    .map(|worker_id| super::liminal_liveness::LivenessTarget {
1422                        pid: *pid,
1423                        worker_id,
1424                        delivery: LiminalWorkerDelivery::new(supervisor.clone(), *pid),
1425                    })
1426            })
1427            .collect()
1428    }
1429
1430    /// Refresh one worker's in-flight task stamp from a [`WorkerLivenessBeat`]
1431    /// published on [`WORKER_LIVENESS_CHANNEL`].
1432    ///
1433    /// The worker is resolved by the publishing CONNECTION (`pid` -> the
1434    /// registration guard this notifier owns), never by wire identity, so a
1435    /// beat can only refresh tasks assigned to the worker that sent it. An
1436    /// untracked task is benign (an outbox dispatch the tracker never held, or
1437    /// a beat racing its completion) and is dropped silently; a malformed
1438    /// payload or unregistered connection is logged and dropped — a bad beat
1439    /// must never tear down the connection callback.
1440    fn record_liveness_beat(&self, pid: u64, payload: &[u8]) {
1441        let Some(tracker) = &self.heartbeat_tracker else {
1442            return;
1443        };
1444        let beat: WorkerLivenessBeat = match serde_json::from_slice(payload) {
1445            Ok(beat) => beat,
1446            Err(error) => {
1447                tracing::warn!(%error, "liveness tap: malformed WorkerLivenessBeat payload");
1448                return;
1449            }
1450        };
1451        let worker_id = match self.guards.lock() {
1452            Ok(guards) => guards.get(&pid).and_then(WorkerRegistration::worker_id),
1453            Err(poisoned) => poisoned
1454                .into_inner()
1455                .get(&pid)
1456                .and_then(WorkerRegistration::worker_id),
1457        };
1458        let Some(worker_id) = worker_id else {
1459            tracing::warn!(
1460                connection_pid = pid,
1461                "liveness tap: beat from a connection with no registered worker"
1462            );
1463            return;
1464        };
1465        let activity_id = ActivityId::from_sequence_position(beat.ordinal);
1466        if let Err(error) = tracker.record_liveness(
1467            worker_id,
1468            &beat.workflow_id,
1469            &activity_id,
1470            std::time::Instant::now(),
1471        ) {
1472            tracing::error!(
1473                %error,
1474                connection_pid = pid,
1475                "liveness tap: heartbeat tracker refresh failed"
1476            );
1477        }
1478    }
1479
1480    /// Apply one worker's [`WorkerCapabilitiesAnnouncement`] published on
1481    /// [`WORKER_CAPABILITIES_CHANNEL`] to its registered handle.
1482    ///
1483    /// The worker is resolved by the publishing CONNECTION (`pid` -> the
1484    /// registration guard this notifier owns), never by wire identity, so an
1485    /// announcement can only ever update the worker that sent it. A malformed
1486    /// payload or unregistered connection is logged and dropped — a bad
1487    /// announcement must never tear down the connection callback.
1488    fn record_capabilities_announcement(&self, pid: u64, payload: &[u8]) {
1489        let announcement: WorkerCapabilitiesAnnouncement = match serde_json::from_slice(payload) {
1490            Ok(announcement) => announcement,
1491            Err(error) => {
1492                tracing::warn!(
1493                    %error,
1494                    "capabilities tap: malformed WorkerCapabilitiesAnnouncement payload"
1495                );
1496                return;
1497            }
1498        };
1499        let worker_id = match self.guards.lock() {
1500            Ok(guards) => guards.get(&pid).and_then(WorkerRegistration::worker_id),
1501            Err(poisoned) => poisoned
1502                .into_inner()
1503                .get(&pid)
1504                .and_then(WorkerRegistration::worker_id),
1505        };
1506        let Some(worker_id) = worker_id else {
1507            tracing::warn!(
1508                connection_pid = pid,
1509                "capabilities tap: announcement from a connection with no registered worker"
1510            );
1511            return;
1512        };
1513        match self
1514            .registry
1515            .set_intervention_capabilities(worker_id, &announcement.capabilities)
1516        {
1517            Ok(true) => {}
1518            Ok(false) => tracing::warn!(
1519                connection_pid = pid,
1520                worker_id = ?worker_id,
1521                "capabilities tap: announcement raced the worker's deregistration"
1522            ),
1523            Err(error) => tracing::error!(
1524                %error,
1525                connection_pid = pid,
1526                "capabilities tap: registry capability update failed"
1527            ),
1528        }
1529    }
1530
1531    fn validate_registration_contract(
1532        &self,
1533        registration: &WireWorkerRegistration,
1534    ) -> Result<(), LiminalServerError> {
1535        let Some(engine) = &self.contract_catalog else {
1536            return Ok(());
1537        };
1538        let advertised =
1539            registration
1540                .activities
1541                .iter()
1542                .map(|activity| {
1543                    let input_schema =
1544                        serde_json::from_str(&activity.input_schema_json).map_err(|error| {
1545                            LiminalServerError::ListenerAccept {
1546                                message: format!(
1547                                    "liminal worker activity `{}` input schema is invalid: {error}",
1548                                    activity.name
1549                                ),
1550                            }
1551                        })?;
1552                    let output_schema = serde_json::from_str(&activity.output_schema_json)
1553                        .map_err(|error| LiminalServerError::ListenerAccept {
1554                            message: format!(
1555                                "liminal worker activity `{}` output schema is invalid: {error}",
1556                                activity.name
1557                            ),
1558                        })?;
1559                    Ok(aion_package::ActivityDescriptor {
1560                        name: activity.name.clone(),
1561                        input_schema,
1562                        output_schema,
1563                    })
1564                })
1565                .collect::<Result<Vec<_>, LiminalServerError>>()?;
1566        // Both advertised forms travel into the gate together: the NAME set the
1567        // dispatcher selects on and the CONTRACT set admission compares. A
1568        // refusal computed from one while the record printed the other is what
1569        // produced the 2026-07-30 self-contradicting log.
1570        let activity_types = registration
1571            .activity_types
1572            .iter()
1573            .cloned()
1574            .collect::<std::collections::BTreeSet<_>>();
1575        super::contracts::validate_worker_contracts(
1576            engine,
1577            self.registry.admission_audit(),
1578            &registration.task_queue,
1579            registration.node.as_deref(),
1580            &registration.identity,
1581            super::contracts::WorkerAdvertisement {
1582                activity_types: &activity_types,
1583                contracts: &advertised,
1584            },
1585        )
1586        .map_err(|error| LiminalServerError::ListenerAccept {
1587            message: error.to_string(),
1588        })
1589    }
1590
1591    /// Admit one connecting worker past the TRANSPORT's own refusals, or refuse
1592    /// it with a structured reason.
1593    ///
1594    /// Split out of [`ConnectionNotifier::on_worker_registered`] so every
1595    /// refusal this transport owns — unbound supervisor, registry error, lease
1596    /// failure — funnels through exactly one place that logs it. Before that
1597    /// split the rejection reason was carried in the `Rejected` ack and logged
1598    /// NOWHERE: on 2026-07-29 a worker whose `.v4` contract field-mismatched was
1599    /// refused on every single dial with the server silent on all of them, and
1600    /// the refused process looked merely asleep.
1601    ///
1602    /// **The contract check is deliberately NOT here.** That 2026-07-29 fix was
1603    /// made in this caller rather than at the shared gate, and within a week the
1604    /// gRPC transport re-manifested the identical silent refusal with nothing in
1605    /// the tree able to notice (#147). The gate now names its own refusal for
1606    /// every transport, so the contract check runs BEFORE this function and its
1607    /// error propagates from here already spoken for.
1608    fn admit_registration(
1609        &self,
1610        pid: u64,
1611        registration: &WireWorkerRegistration,
1612    ) -> Result<(), LiminalServerError> {
1613        // The delivery leg needs the supervisor to push to this connection. In
1614        // correct wiring it is bound before any connection is accepted; a missing
1615        // binding is a rejected registration, never a panic.
1616        let supervisor =
1617            self.supervisor
1618                .get()
1619                .ok_or_else(|| LiminalServerError::ListenerAccept {
1620                    message: format!(
1621                        "liminal worker registration for connection {pid} rejected: \
1622                     notifier supervisor handle not yet bound"
1623                    ),
1624                })?;
1625
1626        let delivery = WorkerDelivery::Liminal(LiminalWorkerDelivery::new(supervisor.clone(), pid));
1627        let node = normalize_wire_node(registration.node.as_deref());
1628        // Insert into the SAME registry, selected the SAME way, as a gRPC worker.
1629        // A registry error (poisoned lock) becomes a Rejected ack so the worker
1630        // never believes it is registered when it is not.
1631        let guard = self
1632            .registry
1633            .register_delivery_with_capabilities(
1634                registration.namespaces.iter().cloned(),
1635                registration.task_queue.clone(),
1636                node,
1637                registration.activity_types.iter(),
1638                delivery,
1639                self.intervention_capabilities.clone(),
1640            )
1641            .map_err(|error| LiminalServerError::ListenerAccept {
1642                message: format!(
1643                    "liminal worker registration for connection {pid} rejected: {error}"
1644                ),
1645            })?;
1646        let worker_id = guard
1647            .worker_id()
1648            .ok_or_else(|| LiminalServerError::ListenerAccept {
1649                message: format!(
1650                    "liminal worker registration for connection {pid} has no worker id"
1651                ),
1652            })?;
1653
1654        // OWN the guard for the connection's lifetime, keyed by pid. Dropping it
1655        // (on unregister) deregisters the worker, so the registration lives
1656        // exactly as long as the connection.
1657        let mut guards = self.guards.lock().map_err(|_| {
1658            // The accepted registry entry cannot be tracked for deregistration, so
1659            // reject (and drop the just-created guard, deregistering it) rather
1660            // than leak a never-deregistered association.
1661            LiminalServerError::ListenerAccept {
1662                message: format!(
1663                    "liminal worker registration for connection {pid} rejected: \
1664                     notifier guard map poisoned"
1665                ),
1666            }
1667        })?;
1668        guards.insert(pid, guard);
1669        drop(guards);
1670        if let Some(tracker) = &self.heartbeat_tracker {
1671            if let Err(error) = tracker.register_connection(worker_id, std::time::Instant::now()) {
1672                let removed = match self.guards.lock() {
1673                    Ok(mut guards) => guards.remove(&pid),
1674                    Err(poisoned) => poisoned.into_inner().remove(&pid),
1675                };
1676                drop(removed);
1677                return Err(LiminalServerError::ListenerAccept {
1678                    message: format!(
1679                        "liminal worker registration for connection {pid} rejected: {error}"
1680                    ),
1681                });
1682            }
1683        }
1684        tracing::info!(
1685            connection_pid = pid,
1686            identity = %registration.identity,
1687            task_queue = %registration.task_queue,
1688            "registered liminal worker in-band"
1689        );
1690        Ok(())
1691    }
1692}
1693
1694impl ConnectionNotifier for LiminalConnectionNotifier {
1695    fn on_worker_registered(
1696        &self,
1697        pid: u64,
1698        registration: &WireWorkerRegistration,
1699    ) -> Result<(), LiminalServerError> {
1700        // The contract gate NAMES its own refusal, for every transport, with the
1701        // queue, the node, the worker build identity and the structured reason.
1702        // So this path propagates that refusal SILENTLY rather than restating
1703        // it: a second copy of the same log is how #147 happened, and a log
1704        // written twice per refusal is #94's 12 MB/hour with a second author.
1705        self.validate_registration_contract(registration)?;
1706        // Every refusal this TRANSPORT owns is named here instead, at WARN, with
1707        // the same reason that rides back in the `Rejected` ack, so both sides'
1708        // logs carry identical text and a refused worker can be diagnosed from
1709        // either end.
1710        self.admit_registration(pid, registration)
1711            .inspect_err(|error| {
1712                // The two advertised sets are logged SEPARATELY and named for
1713                // what each one is. Logging `activity_types` alone beside a
1714                // contract-mismatch reason produced a record that listed an
1715                // action as advertised in the same line that reported it
1716                // `<missing>` — true of two different sets, and unresolvable by
1717                // the operator it exists to help.
1718                let advertised_contracts = registration
1719                    .activities
1720                    .iter()
1721                    .map(|activity| activity.name.as_str())
1722                    .collect::<Vec<_>>();
1723                tracing::warn!(
1724                    connection_pid = pid,
1725                    identity = %registration.identity,
1726                    task_queue = %registration.task_queue,
1727                    namespaces = ?registration.namespaces,
1728                    advertised_activity_types = ?registration.activity_types,
1729                    advertised_contracts = ?advertised_contracts,
1730                    reason = %error,
1731                    "REFUSED liminal worker registration"
1732                );
1733            })
1734    }
1735
1736    fn on_worker_unregistered(&self, pid: u64) {
1737        // Remove + drop the guard for pid, deregistering the worker. A poisoned
1738        // lock on the close path has no peer to report to; recover the guard map
1739        // and still drop the guard so the registry does not keep routing to a
1740        // gone connection.
1741        let removed = match self.guards.lock() {
1742            Ok(mut guards) => guards.remove(&pid),
1743            Err(poisoned) => poisoned.into_inner().remove(&pid),
1744        };
1745        let worker_id = removed.as_ref().and_then(WorkerRegistration::worker_id);
1746        if let (Some(tracker), Some(worker_id)) = (&self.heartbeat_tracker, worker_id) {
1747            if let Err(error) = tracker.unregister_connection(worker_id) {
1748                tracing::error!(
1749                    %error,
1750                    connection_pid = pid,
1751                    worker_id = worker_id.value(),
1752                    "failed to clear liminal worker connection lease"
1753                );
1754            }
1755        }
1756        if removed.is_some() {
1757            tracing::info!(
1758                connection_pid = pid,
1759                "deregistered liminal worker on disconnect"
1760            );
1761        }
1762    }
1763
1764    fn on_channel_publish(&self, pid: u64, channel: &str, payload: &[u8]) -> bool {
1765        if let Some(tracker) = &self.heartbeat_tracker {
1766            let worker_id = match self.guards.lock() {
1767                Ok(guards) => guards.get(&pid).and_then(WorkerRegistration::worker_id),
1768                Err(poisoned) => poisoned
1769                    .into_inner()
1770                    .get(&pid)
1771                    .and_then(WorkerRegistration::worker_id),
1772            };
1773            if let Some(worker_id) = worker_id {
1774                if let Err(error) =
1775                    tracker.record_connection_activity(worker_id, std::time::Instant::now())
1776                {
1777                    tracing::error!(
1778                        %error,
1779                        connection_pid = pid,
1780                        worker_id = worker_id.value(),
1781                        "failed to advance liminal worker connection lease"
1782                    );
1783                }
1784            }
1785        }
1786        // Reserved liveness channel: refresh the beat's in-flight task stamp in
1787        // the shared heartbeat tracker (always consumed, never fanned out).
1788        if channel == WORKER_LIVENESS_CHANNEL {
1789            self.record_liveness_beat(pid, payload);
1790            return true;
1791        }
1792        // Reserved capabilities channel: apply the worker's advertised
1793        // intervention capabilities to its registered handle (always consumed).
1794        if channel == WORKER_CAPABILITIES_CHANNEL {
1795            self.record_capabilities_announcement(pid, payload);
1796            return true;
1797        }
1798        // Only consume the reserved observability channel; any other channel falls
1799        // through to liminal's normal fan-out (this returns false).
1800        if channel != liminal_sdk::OBSERVABILITY_CHANNEL {
1801            return false;
1802        }
1803        let Some(tap) = &self.transcript else {
1804            // No transcript sequencer installed (a non-agent deployment): still
1805            // CONSUME the reserved channel so it never leaks into the fan-out, but
1806            // drop the event — there is nothing to persist it into.
1807            return true;
1808        };
1809        let event: aion_core::ActivityEvent = match serde_json::from_slice(payload) {
1810            Ok(event) => event,
1811            Err(error) => {
1812                tracing::warn!(%error, "observability tap: malformed ActivityEvent payload");
1813                return true;
1814            }
1815        };
1816        // Hand the event to the ordered drain queue (the synchronous
1817        // connection-process callback never blocks). A full queue means the
1818        // durable append cannot keep up: the event is dropped with a warning,
1819        // never buffered without bound.
1820        if let Err(error) = tap.queue.try_send(event) {
1821            tracing::warn!(%error, "observability tap: transcript queue rejected event");
1822        }
1823        true
1824    }
1825}
1826
1827/// The production [`InterventionTransport`](super::intervention::InterventionTransport):
1828/// pushes a routed command to the owning worker over its liminal server-push
1829/// connection (NOI-6, §6.2).
1830///
1831/// It reads the worker handle's [`WorkerDelivery::Liminal`] leg and pushes the
1832/// neutral [`InterventionRequest`] via [`LiminalWorkerDelivery::push_intervention`],
1833/// running the blocking push off the async runtime. A worker delivered over gRPC
1834/// (no liminal leg) surfaces the stale-target no-op via a connection-lost error, so
1835/// the router NACKs the operator rather than routing to a leg it cannot reach.
1836#[derive(Clone, Debug, Default)]
1837pub struct LiminalInterventionTransport;
1838
1839#[async_trait]
1840impl super::intervention::InterventionTransport for LiminalInterventionTransport {
1841    async fn push(
1842        &self,
1843        worker: &super::registry::WorkerHandle,
1844        command: aion_core::InterventionCommand,
1845    ) -> Result<aion_core::InterventionOutcome, ServerError> {
1846        let delivery = match worker.delivery() {
1847            WorkerDelivery::Liminal(delivery) => delivery.clone(),
1848            WorkerDelivery::Grpc(_) => {
1849                // No liminal leg to push to: the intervention transport rides the
1850                // liminal push channel only, so this is unreachable for the target.
1851                return Err(ServerError::worker_connection_lost(
1852                    "liminal-push",
1853                    "owning worker is not delivered over liminal".to_owned(),
1854                ));
1855            }
1856        };
1857        let request = InterventionRequest {
1858            intervention: command,
1859        };
1860        let reply = tokio::task::spawn_blocking(move || delivery.push_intervention(&request))
1861            .await
1862            .map_err(|error| {
1863                dispatch_error(
1864                    "liminal-push",
1865                    format!("intervention task join failed: {error}"),
1866                )
1867            })??;
1868        Ok(reply.outcome)
1869    }
1870}
1871
1872#[cfg(test)]
1873#[path = "liminal_contract_tests.rs"]
1874mod contract_tests;
1875
1876#[cfg(test)]
1877mod tests {
1878    use super::{channel_for_row, dispatch_channel_name, normalize_wire_node};
1879    use aion_core::{ActivityId, ContentType, Payload, WorkflowId};
1880    use aion_store::{OutboxRow, OutboxStatus};
1881    use chrono::Utc;
1882    use uuid::Uuid;
1883
1884    /// The NOI-6 dispatch owner guard RELEASES its binding on drop, on EVERY exit path
1885    /// (reply, error, panic) — so the attempt-owner back-index tracks exactly the
1886    /// attempts currently in flight. This is the invariant the dispatch path relies on
1887    /// to never leak a finished attempt's owner.
1888    #[tokio::test]
1889    async fn attempt_owner_guard_releases_on_drop() -> Result<(), Box<dyn std::error::Error>> {
1890        use super::super::intervention::{AttemptKey, AttemptOwnerIndex};
1891        use super::super::registry::{ConnectedWorkerRegistry, WorkerDelivery};
1892        use super::AttemptOwnerGuard;
1893
1894        // A real registration yields a real WorkerId (there is no fabricated id).
1895        let registry = ConnectedWorkerRegistry::default();
1896        let (tx, _rx) = tokio::sync::mpsc::channel(1);
1897        let types = [String::from("agent")];
1898        let registration = registry.register_delivery_with_capabilities(
1899            [String::from("default")],
1900            String::from("default"),
1901            None,
1902            types.iter(),
1903            WorkerDelivery::Grpc(tx),
1904            aion_core::InterventionCapabilities::none(),
1905        )?;
1906        let worker = registration
1907            .worker_id()
1908            .ok_or("registration must assign a worker id")?;
1909
1910        let owners = AttemptOwnerIndex::new();
1911        let key = AttemptKey::new(
1912            WorkflowId::new(Uuid::nil()),
1913            aion_core::RunId::new(Uuid::from_u128(0x11)),
1914            ActivityId::from_sequence_position(3),
1915            1,
1916        );
1917        owners.bind(key.clone(), worker);
1918        assert_eq!(
1919            owners.owner(&key),
1920            Some(worker),
1921            "owner bound before the guard"
1922        );
1923        {
1924            let _guard = AttemptOwnerGuard {
1925                owners: owners.clone(),
1926                key: key.clone(),
1927            };
1928            assert_eq!(
1929                owners.owner(&key),
1930                Some(worker),
1931                "still bound while in flight"
1932            );
1933        }
1934        // The guard dropped at the end of the block: the binding is released, so a
1935        // later intervention resolves no owner (the too-late no-op).
1936        assert_eq!(
1937            owners.owner(&key),
1938            None,
1939            "owner released when the dispatch returns"
1940        );
1941        Ok(())
1942    }
1943
1944    /// The channel format is pinned EXACTLY: any change is a wire-compatibility
1945    /// break (the dispatcher and any worker subscription must agree byte-for-byte).
1946    /// The UNPINNED (`None`) channel MUST stay byte-identical to the pre-NODE-5
1947    /// format so existing pool subscriptions are stable.
1948    #[test]
1949    fn channel_format_is_pinned() {
1950        assert_eq!(
1951            dispatch_channel_name("remote", "gpu", None),
1952            "aion.dispatch.remote.gpu"
1953        );
1954        assert_eq!(
1955            dispatch_channel_name("local", "norn", None),
1956            "aion.dispatch.local.norn"
1957        );
1958    }
1959
1960    /// A node-pinned dispatch appends the node as an injectively-encoded
1961    /// sub-segment: `f(ns, tq, Some(node))` == `aion.dispatch.{ns}.{tq}.{node}`.
1962    #[test]
1963    fn node_pinned_channel_appends_node_subsegment() {
1964        assert_eq!(
1965            dispatch_channel_name("remote", "gpu", Some("box-7")),
1966            "aion.dispatch.remote.gpu.box-7"
1967        );
1968    }
1969
1970    /// Same input always yields the same channel (the function is stable/total),
1971    /// for both the unpinned and node-pinned cases.
1972    #[test]
1973    fn channel_derivation_is_stable() {
1974        assert_eq!(
1975            dispatch_channel_name("default", "default", None),
1976            dispatch_channel_name("default", "default", None)
1977        );
1978        assert_eq!(
1979            dispatch_channel_name("default", "default", Some("box-1")),
1980            dispatch_channel_name("default", "default", Some("box-1"))
1981        );
1982    }
1983
1984    /// Distinct `(namespace, task_queue)` pools derive distinct channels — the
1985    /// whole point of NSTQ-5: `(remote, gpu)` and `(local, norn)` never collide.
1986    #[test]
1987    fn distinct_pools_get_distinct_channels() {
1988        assert_ne!(
1989            dispatch_channel_name("remote", "gpu", None),
1990            dispatch_channel_name("local", "norn", None)
1991        );
1992    }
1993
1994    /// A node-pinned dispatch and the unpinned dispatch for the SAME pool derive
1995    /// DISTINCT channels, and two distinct nodes for the same pool also differ —
1996    /// the property node isolation rests on (the subscriber contract).
1997    #[test]
1998    fn node_pin_separates_channels() {
1999        let unpinned = dispatch_channel_name("remote", "gpu", None);
2000        let box7 = dispatch_channel_name("remote", "gpu", Some("box-7"));
2001        let box8 = dispatch_channel_name("remote", "gpu", Some("box-8"));
2002        assert_ne!(
2003            unpinned, box7,
2004            "pinned dispatch must not reach unpinned pool"
2005        );
2006        assert_ne!(box7, box8, "distinct nodes must not collide");
2007    }
2008
2009    /// The core injectivity property: free-form fields containing the segment
2010    /// separator `.` must NOT bleed across the join. With the raw `format!` the
2011    /// disjoint pools `("a.b", "c")` and `("a", "b.c")` both collapsed onto
2012    /// `aion.dispatch.a.b.c` — a cross-pool/cross-namespace leak. The per-segment
2013    /// encode keeps them distinct.
2014    #[test]
2015    fn dotted_fields_do_not_collide_across_segments() {
2016        assert_ne!(
2017            dispatch_channel_name("a.b", "c", None),
2018            dispatch_channel_name("a", "b.c", None),
2019            "a '.' in a field must not bleed across the segment separator"
2020        );
2021    }
2022
2023    /// Injectivity holds ACROSS segment counts: a 2-segment (unpinned) channel
2024    /// can never be confused with a 3-segment (node-pinned) channel even when a
2025    /// `.` in a field would otherwise make the raw strings line up. Both
2026    /// directions of the brief's collision cases must stay distinct.
2027    #[test]
2028    fn node_subsegment_does_not_collide_with_dotted_fields() {
2029        // A node sub-segment vs the same dot living inside task_queue.
2030        assert_ne!(
2031            dispatch_channel_name("a", "b", Some("c")),
2032            dispatch_channel_name("a", "b.c", None),
2033            "a node sub-segment must not collide with a dotted task_queue"
2034        );
2035        // The dot living inside namespace vs a node sub-segment.
2036        assert_ne!(
2037            dispatch_channel_name("a.b", "c", None),
2038            dispatch_channel_name("a", "b", Some("c")),
2039            "a dotted namespace must not collide with a node-pinned channel"
2040        );
2041    }
2042
2043    /// More reserved-char shifts that the raw `format!` collapsed but the encode
2044    /// must keep distinct — the dot can sit on either side of the boundary.
2045    #[test]
2046    fn reserved_char_shifts_stay_distinct() {
2047        // Dot at the end of namespace vs start of task_queue.
2048        assert_ne!(
2049            dispatch_channel_name("ns.", "tq", None),
2050            dispatch_channel_name("ns", ".tq", None)
2051        );
2052        // Empty field vs the dot living in the other field.
2053        assert_ne!(
2054            dispatch_channel_name("", "a.b", None),
2055            dispatch_channel_name(".a", "b", None)
2056        );
2057        // The escape char itself must not let a literal `%2E` impersonate an
2058        // encoded `.`: `("%2E", "x")` (literal percent-two-E) must differ from
2059        // `(".", "x")` (an actual dot, which encodes to `%2E`).
2060        assert_ne!(
2061            dispatch_channel_name("%2E", "x", None),
2062            dispatch_channel_name(".", "x", None)
2063        );
2064    }
2065
2066    /// Encoding is injective in ALL THREE segments independently and is exactly
2067    /// reversible (the property the channel relies on), so a small exhaustive
2068    /// sweep of reserved-char arrangements — INCLUDING the optional node taking
2069    /// `None` and every reserved-char value — yields all-distinct channels. This
2070    /// covers cross-segment-count collisions (the `None` vs `Some` boundary) too.
2071    #[test]
2072    fn encoding_is_injective_over_reserved_char_triples() {
2073        let fields = ["a", "a.b", "a.", ".a", ".", "", "%", "%2E", "a%b", "%2."];
2074        let nodes = [
2075            None,
2076            Some("a"),
2077            Some("a.b"),
2078            Some("."),
2079            Some(""),
2080            Some("%2E"),
2081        ];
2082        let mut channels = std::collections::HashSet::new();
2083        for ns in fields {
2084            for tq in fields {
2085                for node in nodes {
2086                    let channel = dispatch_channel_name(ns, tq, node);
2087                    assert!(
2088                        channels.insert(channel.clone()),
2089                        "collision on ({ns:?}, {tq:?}, {node:?}) -> {channel}"
2090                    );
2091                }
2092            }
2093        }
2094    }
2095
2096    fn row(namespace: &str, task_queue: &str) -> OutboxRow {
2097        let workflow_id = WorkflowId::new(Uuid::new_v4());
2098        OutboxRow {
2099            dispatch_key: format!("{workflow_id}:0"),
2100            workflow_id,
2101            ordinal: 0,
2102            run_id: Some(aion_core::RunId::new_v4()),
2103            namespace: namespace.to_owned(),
2104            task_queue: task_queue.to_owned(),
2105            node: None,
2106            activity_type: "charge-card".to_owned(),
2107            input: Payload::new(ContentType::Json, Vec::new()),
2108            status: OutboxStatus::Pending,
2109            attempt: 0,
2110            visible_after: Utc::now(),
2111            claimed_at: None,
2112            failure_delivered: false,
2113        }
2114    }
2115
2116    /// A row's channel is derived from its durable `(namespace, task_queue)`
2117    /// columns (NSTQ-2), through the same single derivation function — and
2118    /// `activity_type` does NOT enter the channel. With `node = None` the channel
2119    /// is byte-identical to the pre-NODE-5 2-segment form.
2120    #[test]
2121    fn channel_for_row_uses_namespace_and_task_queue_only() {
2122        let remote_gpu = row("remote", "gpu");
2123        let local_norn = row("local", "norn");
2124        assert_eq!(channel_for_row(&remote_gpu), "aion.dispatch.remote.gpu");
2125        assert_eq!(channel_for_row(&local_norn), "aion.dispatch.local.norn");
2126        assert_ne!(channel_for_row(&remote_gpu), channel_for_row(&local_norn));
2127
2128        // Two rows that differ ONLY in activity_type derive the SAME channel:
2129        // activity_type is matched after delivery, not used to select the pool.
2130        let mut other_activity = row("remote", "gpu");
2131        other_activity.activity_type = "refund".to_owned();
2132        assert_eq!(
2133            channel_for_row(&remote_gpu),
2134            channel_for_row(&other_activity),
2135            "activity_type must not affect the channel"
2136        );
2137    }
2138
2139    /// A row carrying `Some(node)` (NODE-2) derives the node-pinned sub-channel,
2140    /// distinct from the same pool's unpinned channel; a row with `None` derives
2141    /// the 2-segment channel. `channel_for_row` threads `row.node` through the
2142    /// single derivation function.
2143    #[test]
2144    fn channel_for_row_derives_node_subchannel_when_pinned() {
2145        let mut pinned = row("remote", "gpu");
2146        pinned.node = Some("box-7".to_owned());
2147        assert_eq!(channel_for_row(&pinned), "aion.dispatch.remote.gpu.box-7");
2148
2149        let unpinned = row("remote", "gpu");
2150        assert_eq!(channel_for_row(&unpinned), "aion.dispatch.remote.gpu");
2151        assert_ne!(channel_for_row(&pinned), channel_for_row(&unpinned));
2152    }
2153
2154    /// The outbox wire request stamps the row's stored ZERO-based attempt as a
2155    /// ONE-based delivery attempt (zero is malformed on the wire) — the exact
2156    /// stamp the gRPC outbox arm's `to_scheduled` applies — carries no labels,
2157    /// and assigns no liveness window (outbox rows are not tracker-tracked; the
2158    /// outbox retry loop is their liveness backstop).
2159    #[test]
2160    fn request_for_row_stamps_one_based_attempt_and_no_window() -> Result<(), crate::ServerError> {
2161        let mut retried = row("remote", "gpu");
2162        retried.attempt = 2;
2163        let run_id = retried
2164            .run_id
2165            .as_ref()
2166            .ok_or_else(|| crate::ServerError::worker_dispatch("", "", "test row missing run"))?;
2167        let token = super::CompletionToken::for_test();
2168        let request = super::request_for_row(&retried, run_id, &token);
2169        assert_eq!(
2170            request.attempt, 3,
2171            "zero-based row attempt goes one-based on the wire"
2172        );
2173        assert!(request.labels.is_empty());
2174        assert_eq!(request.heartbeat_window_ms, 0);
2175
2176        let fresh = row("remote", "gpu");
2177        let fresh_run = fresh
2178            .run_id
2179            .as_ref()
2180            .ok_or_else(|| crate::ServerError::worker_dispatch("", "", "test row missing run"))?;
2181        assert_eq!(super::request_for_row(&fresh, fresh_run, &token).attempt, 1);
2182        Ok(())
2183    }
2184
2185    /// The wire `node` is normalized onto the registry's optional affinity with
2186    /// the SAME none-convention the gRPC registration path uses: `None` and the
2187    /// empty-string node both collapse to unpinned (`None`), a non-empty value is
2188    /// the advertised node. An empty-string node must NOT register a distinct
2189    /// empty affinity no pinned dispatch could match.
2190    #[test]
2191    fn wire_node_normalizes_empty_to_none() {
2192        assert_eq!(normalize_wire_node(None), None);
2193        assert_eq!(normalize_wire_node(Some("")), None);
2194        assert_eq!(normalize_wire_node(Some("box-7")), Some("box-7".to_owned()));
2195    }
2196
2197    // --- #163: the Prefer two-tier spill on the LIMINAL selection path ---------
2198    //
2199    // These exercise `RegistryLiminalDispatch::select_liminal_worker` — the
2200    // liminal transport's worker selection — proving it consults the SAME shared
2201    // `preferred_node_order` two-tier spill the gRPC path uses (the cross-node
2202    // demo behaviour), and that placement NEVER mutates the recorded row's node.
2203    // Selection is delivery-agnostic (`select_worker` filters by node regardless
2204    // of transport), so a worker registered with any delivery drives the same
2205    // selection the production liminal-delivered worker would; the tests assert on
2206    // the SELECTED handle's node, which is exactly what #163 changed.
2207    mod placement_selection {
2208        use std::collections::BTreeSet;
2209        use std::sync::Arc;
2210        use std::time::Duration;
2211
2212        use aion_core::{ActivityId, Payload, RunId, WorkflowId};
2213        use aion_store::{
2214            InMemoryStore, NamespaceOrigin, NamespacePlacement, NamespaceStore, OutboxRow,
2215        };
2216
2217        use crate::error::ServerError;
2218        use crate::worker::bridge::OutboxDeliveryCallback;
2219        use crate::worker::registry::{ConnectedWorkerRegistry, WorkerMessage, WorkerRegistration};
2220        use crate::worker::{DeliveryGate, PlacementCache};
2221
2222        use super::super::RegistryLiminalDispatch;
2223
2224        /// No-op delivery callback: the selection tests never deliver a result, so
2225        /// the completion sink is never invoked. Both methods are unreachable in
2226        /// these tests and simply report "no live run" if ever called.
2227        struct NoopCallback;
2228
2229        impl OutboxDeliveryCallback for NoopCallback {
2230            fn deliver_completion(
2231                &self,
2232                _workflow_id: &WorkflowId,
2233                _activity_id: &ActivityId,
2234                _run_id: Option<&RunId>,
2235                _result: String,
2236            ) -> Result<bool, ServerError> {
2237                Ok(false)
2238            }
2239            fn deliver_failure(
2240                &self,
2241                _workflow_id: &WorkflowId,
2242                _activity_id: &ActivityId,
2243                _run_id: Option<&RunId>,
2244                _reason: String,
2245            ) -> Result<bool, ServerError> {
2246                Ok(false)
2247            }
2248        }
2249
2250        fn labels(values: &[&str]) -> BTreeSet<String> {
2251            values.iter().map(|v| (*v).to_owned()).collect()
2252        }
2253
2254        /// Register a worker advertising `node` for `charge` in `namespace`,
2255        /// returning the registration guard (held to keep it connected).
2256        fn register_node_worker(
2257            registry: &ConnectedWorkerRegistry,
2258            namespace: &str,
2259            node: &str,
2260        ) -> Result<WorkerRegistration, ServerError> {
2261            let (tx, _rx) = tokio::sync::mpsc::channel::<WorkerMessage>(1);
2262            let types = [String::from("charge")];
2263            registry.register_namespaces(
2264                [namespace.to_owned()],
2265                String::from("default"),
2266                Some(node.to_owned()),
2267                types.iter(),
2268                tx,
2269            )
2270        }
2271
2272        /// Build an UNPINNED outbox row (`node == None`) in `namespace` for `charge`.
2273        fn unpinned_row(namespace: &str) -> OutboxRow {
2274            OutboxRow::pending(
2275                WorkflowId::new_v4(),
2276                0,
2277                String::from("charge"),
2278                Payload::from_json(&serde_json::json!({}))
2279                    .unwrap_or_else(|_| Payload::new(aion_core::ContentType::Json, Vec::new())),
2280                chrono::Utc::now(),
2281            )
2282            .with_namespace(namespace)
2283            .with_task_queue("default")
2284        }
2285
2286        /// A namespace store with `namespace` set to `Prefer{nodes}`.
2287        async fn prefer_store(
2288            namespace: &str,
2289            nodes: &[&str],
2290        ) -> Result<Arc<dyn NamespaceStore>, ServerError> {
2291            let store: Arc<dyn NamespaceStore> = Arc::new(InMemoryStore::default());
2292            store
2293                .register_namespace(namespace, NamespaceOrigin::Explicit)
2294                .await?;
2295            store
2296                .set_namespace_placement(
2297                    namespace,
2298                    NamespacePlacement::Prefer {
2299                        nodes: labels(nodes),
2300                    },
2301                )
2302                .await?;
2303            Ok(store)
2304        }
2305
2306        /// A namespace store with `namespace` set to `Pinned{nodes}` (P2-I1).
2307        async fn pinned_store(
2308            namespace: &str,
2309            nodes: &[&str],
2310        ) -> Result<Arc<dyn NamespaceStore>, ServerError> {
2311            let store: Arc<dyn NamespaceStore> = Arc::new(InMemoryStore::default());
2312            store
2313                .register_namespace(namespace, NamespaceOrigin::Explicit)
2314                .await?;
2315            store
2316                .set_namespace_placement(
2317                    namespace,
2318                    NamespacePlacement::Pinned {
2319                        nodes: labels(nodes),
2320                    },
2321                )
2322                .await?;
2323            Ok(store)
2324        }
2325
2326        /// Build a `RegistryLiminalDispatch` over `registry` whose placement cache
2327        /// reads `ns_store` (zero TTL so each selection sees the latest placement).
2328        fn liminal_dispatch(
2329            registry: &ConnectedWorkerRegistry,
2330            ns_store: Arc<dyn NamespaceStore>,
2331        ) -> RegistryLiminalDispatch {
2332            let cache = PlacementCache::new(ns_store, Duration::ZERO);
2333            RegistryLiminalDispatch::new(
2334                registry.clone(),
2335                Arc::new(NoopCallback),
2336                DeliveryGate::default(),
2337            )
2338            .with_placement_cache(cache)
2339        }
2340
2341        /// #163 (prefer): an unpinned row in a `Prefer{n1}` namespace selects the
2342        /// n1 worker on the liminal path when one is live, even with an n2 worker
2343        /// also connected.
2344        #[tokio::test]
2345        async fn prefer_selects_preferred_node_worker_on_liminal_path()
2346        -> Result<(), Box<dyn std::error::Error>> {
2347            let ns_store = prefer_store("t", &["n1"]).await?;
2348            let registry = ConnectedWorkerRegistry::default();
2349            let _n1 = register_node_worker(&registry, "t", "n1")?;
2350            let _n2 = register_node_worker(&registry, "t", "n2")?;
2351            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2352
2353            let row = unpinned_row("t");
2354            let selected = dispatch
2355                .select_liminal_worker(&row)
2356                .await?
2357                .ok_or("a worker must be selected")?;
2358            assert_eq!(
2359                selected.node(),
2360                Some("n1"),
2361                "the liminal path prefers the n1 worker while it is live"
2362            );
2363            // Determinism gate: preference never mutates the recorded row's node.
2364            assert_eq!(row.node, None, "placement must never mutate the row's node");
2365            Ok(())
2366        }
2367
2368        /// #163 (spill): an unpinned row in a `Prefer{n1}` namespace SPILLS to the
2369        /// only live worker (n2) on the liminal path when no n1 worker is
2370        /// connected — the cross-node node-loss failover behaviour.
2371        #[tokio::test]
2372        async fn prefer_spills_to_any_live_worker_on_liminal_path()
2373        -> Result<(), Box<dyn std::error::Error>> {
2374            let ns_store = prefer_store("t", &["n1"]).await?;
2375            // Only an n2 worker is live: no n1-labelled worker exists at all.
2376            let registry = ConnectedWorkerRegistry::default();
2377            let _n2 = register_node_worker(&registry, "t", "n2")?;
2378            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2379
2380            let row = unpinned_row("t");
2381            let selected = dispatch
2382                .select_liminal_worker(&row)
2383                .await?
2384                .ok_or("the spill must select the live n2 worker")?;
2385            assert_eq!(
2386                selected.node(),
2387                Some("n2"),
2388                "with no n1 worker live, the liminal selection spills to the live n2 worker"
2389            );
2390            assert_eq!(row.node, None, "spill must never mutate the row's node");
2391            Ok(())
2392        }
2393
2394        /// #163 (determinism, mirrors the gRPC `placement_never_mutates_recorded_row_node`
2395        /// test): under `Prefer{n1}` the SAME unpinned row selected once to the n1
2396        /// worker and once (after n1 leaves) spilled to n2 keeps `node == None`
2397        /// BOTH times — selection reads the row's node, never the placement, so
2398        /// replay sees an identical command stream irrespective of the target.
2399        #[tokio::test]
2400        async fn placement_never_mutates_recorded_row_node_on_liminal_path()
2401        -> Result<(), Box<dyn std::error::Error>> {
2402            let ns_store = prefer_store("t", &["n1"]).await?;
2403            let registry = ConnectedWorkerRegistry::default();
2404            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2405
2406            // Routing A: n1 present -> preferred selection.
2407            let n1 = register_node_worker(&registry, "t", "n1")?;
2408            let row_a = unpinned_row("t");
2409            let selected_a = dispatch
2410                .select_liminal_worker(&row_a)
2411                .await?
2412                .ok_or("routing A must select a worker")?;
2413            assert_eq!(selected_a.node(), Some("n1"));
2414
2415            // n1 leaves; only n2 remains.
2416            n1.deregister()?;
2417            let _n2 = register_node_worker(&registry, "t", "n2")?;
2418
2419            // Routing B: same shape of unpinned row -> spills to n2.
2420            let row_b = unpinned_row("t");
2421            let selected_b = dispatch
2422                .select_liminal_worker(&row_b)
2423                .await?
2424                .ok_or("routing B must spill to a worker")?;
2425            assert_eq!(selected_b.node(), Some("n2"));
2426
2427            // The recorded row node is None in BOTH routings: the dispatch target
2428            // (n1 vs n2) did not perturb it.
2429            assert_eq!(row_a.node, None);
2430            assert_eq!(row_b.node, None);
2431            assert_eq!(
2432                row_a.node, row_b.node,
2433                "the recorded row node is identical regardless of which worker was selected"
2434            );
2435            Ok(())
2436        }
2437
2438        /// #164 (P2-I1 hard pin): an unpinned row in a `Pinned{n1}` namespace
2439        /// selects the n1 worker on the liminal path when live — exactly like
2440        /// Prefer's happy path.
2441        #[tokio::test]
2442        async fn pinned_selects_required_node_worker_on_liminal_path()
2443        -> Result<(), Box<dyn std::error::Error>> {
2444            let ns_store = pinned_store("t", &["n1"]).await?;
2445            let registry = ConnectedWorkerRegistry::default();
2446            let _n1 = register_node_worker(&registry, "t", "n1")?;
2447            let _n2 = register_node_worker(&registry, "t", "n2")?;
2448            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2449
2450            let row = unpinned_row("t");
2451            let selected = dispatch
2452                .select_liminal_worker(&row)
2453                .await?
2454                .ok_or("the required n1 worker must be selected")?;
2455            assert_eq!(selected.node(), Some("n1"));
2456            assert_eq!(row.node, None, "placement must never mutate the row's node");
2457            Ok(())
2458        }
2459
2460        /// #164 (P2-I1 no spill — the load-bearing test): an unpinned row in a
2461        /// `Pinned{n1}` namespace with ONLY a live n2 worker selects NOTHING — it
2462        /// must NEVER spill to the wrong-node worker. This is the exact opposite of
2463        /// the `prefer_spills_to_any_live_worker_on_liminal_path` behaviour and would
2464        /// FAIL under the old fall-through (which selected any worker for Pinned).
2465        /// The `Ok(None)` drives the outbox no-worker retry/stall, mirroring the
2466        /// gRPC wait.
2467        #[tokio::test]
2468        async fn pinned_never_spills_to_a_wrong_node_worker_on_liminal_path()
2469        -> Result<(), Box<dyn std::error::Error>> {
2470            let ns_store = pinned_store("t", &["n1"]).await?;
2471            // Only an n2 worker is live: no n1-labelled worker exists at all.
2472            let registry = ConnectedWorkerRegistry::default();
2473            let _n2 = register_node_worker(&registry, "t", "n2")?;
2474            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2475
2476            let row = unpinned_row("t");
2477            let selected = dispatch.select_liminal_worker(&row).await?;
2478            assert!(
2479                selected.is_none(),
2480                "Pinned{{n1}} must NOT spill to the live n2 worker — it selects nothing \
2481                 so the outbox retries/stalls until an n1 worker returns"
2482            );
2483            assert_eq!(row.node, None, "placement must never mutate the row's node");
2484            Ok(())
2485        }
2486
2487        /// #163 (authored pin wins): a row authored-pinned to `Some(n2)` STILL
2488        /// selects an n2 worker on the liminal path regardless of the namespace's
2489        /// `Prefer{n1}` — the per-activity pin is authoritative and placement never
2490        /// overrides it.
2491        #[tokio::test]
2492        async fn authored_node_pin_wins_over_namespace_prefer_on_liminal_path()
2493        -> Result<(), Box<dyn std::error::Error>> {
2494            let ns_store = prefer_store("t", &["n1"]).await?;
2495            let registry = ConnectedWorkerRegistry::default();
2496            let _n1 = register_node_worker(&registry, "t", "n1")?;
2497            let _n2 = register_node_worker(&registry, "t", "n2")?;
2498            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2499
2500            // Authored pin: node = Some("n2").
2501            let row = unpinned_row("t").with_node(Some(String::from("n2")));
2502            let selected = dispatch
2503                .select_liminal_worker(&row)
2504                .await?
2505                .ok_or("the authored pin must select the n2 worker")?;
2506            assert_eq!(
2507                selected.node(),
2508                Some("n2"),
2509                "the authored Some(n2) pin is honoured regardless of the namespace Prefer{{n1}}"
2510            );
2511            // The authored node is preserved exactly (determinism gate).
2512            assert_eq!(row.node.as_deref(), Some("n2"));
2513            Ok(())
2514        }
2515
2516        /// #163 (byte-identical default): an `Unplaced` namespace selects any live
2517        /// worker on the liminal path exactly as the pre-Phase-2 single
2518        /// `select_worker` would — the ceiling/placement never engages.
2519        #[tokio::test]
2520        async fn unplaced_namespace_selects_any_worker_on_liminal_path()
2521        -> Result<(), Box<dyn std::error::Error>> {
2522            let ns_store: Arc<dyn NamespaceStore> = Arc::new(InMemoryStore::default());
2523            // Registered but left Unplaced (the default placement).
2524            ns_store
2525                .register_namespace("t", NamespaceOrigin::Explicit)
2526                .await?;
2527            let registry = ConnectedWorkerRegistry::default();
2528            let _n2 = register_node_worker(&registry, "t", "n2")?;
2529            let dispatch = liminal_dispatch(&registry, Arc::clone(&ns_store));
2530
2531            let selected = dispatch
2532                .select_liminal_worker(&unpinned_row("t"))
2533                .await?
2534                .ok_or("an Unplaced namespace still selects a live worker")?;
2535            assert_eq!(
2536                selected.node(),
2537                Some("n2"),
2538                "an Unplaced namespace reaches any live worker, exactly as before"
2539            );
2540            Ok(())
2541        }
2542
2543        /// #163 (byte-identical, no cache): with NO placement cache attached, the
2544        /// liminal selection is the single `select_worker` off the row's own node —
2545        /// byte-identical to the pre-#163 construction. An unpinned row reaches any
2546        /// live worker; the namespace's `Prefer` is not even consulted.
2547        #[tokio::test]
2548        async fn no_cache_selection_is_byte_identical_to_pre_163()
2549        -> Result<(), Box<dyn std::error::Error>> {
2550            // The namespace prefers n1, but with no cache the preference is ignored.
2551            let _ns_store = prefer_store("t", &["n1"]).await?;
2552            let registry = ConnectedWorkerRegistry::default();
2553            let _n2 = register_node_worker(&registry, "t", "n2")?;
2554            // No `.with_placement_cache(...)`: the pre-#163 construction.
2555            let dispatch = RegistryLiminalDispatch::new(
2556                registry.clone(),
2557                Arc::new(NoopCallback),
2558                DeliveryGate::default(),
2559            );
2560
2561            let selected = dispatch
2562                .select_liminal_worker(&unpinned_row("t"))
2563                .await?
2564                .ok_or("without a cache the unpinned row still selects any worker")?;
2565            assert_eq!(
2566                selected.node(),
2567                Some("n2"),
2568                "with no placement cache the selection is the unchanged any-worker path"
2569            );
2570            Ok(())
2571        }
2572    }
2573}