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