Skip to main content

aion_server/worker/
liminal_task_delivery.rs

1//! The liminal arm of the delivery seam: push the dispatch out on the worker's
2//! existing connection and block for its correlated reply.
3//!
4//! # Why this arm is the one that needed a seam
5//!
6//! Before #52 there was no way to reach it from the worker dispatcher at all: a
7//! worker with no gRPC stream sender was deregistered on the premise that its
8//! presence could only be a leak. This module is the same delivery sequence the
9//! outbox arm has always run, lifted so both callers reach one implementation.
10//!
11//! # What it does NOT own any more
12//!
13//! Two responsibilities deliberately stayed with the caller, and moving them
14//! here would break the invariants they exist to keep:
15//!
16//! - **The completion token.** One per pass, minted before the candidate walk
17//!   and revoked once when the pass places nothing. Minting per delivery would
18//!   put a second authorization beside the one a worker may still be holding for
19//!   the same attempt.
20//! - **The abandonment condition.** See
21//!   [`DeliveryIntent`](super::delivery_intent::DeliveryIntent): one of its terms
22//!   is unanswerable from inside a transport.
23
24use std::sync::Arc;
25
26use async_trait::async_trait;
27
28use aion_core::{ActivityId, RunId, WorkflowId};
29use aion_proto::ProtoActivityTask;
30
31use super::delivery_intent::SharedDeliveryIntent;
32use super::intervention::{AttemptKey, AttemptOwnerIndex};
33use super::liminal_transport::{AttemptOwnerGuard, DispatchRequest, LiminalCompletionSource};
34use super::registry::{WorkerDelivery, WorkerHandle};
35use super::task_delivery::{LivenessTracking, TaskDelivery, WorkerTaskDelivery};
36
37/// Delivers by pushing the dispatch out on the worker's liminal connection and
38/// blocking for the correlated reply.
39///
40/// The reply **is** the activity's completion, so this arm re-enters it through
41/// the same completion path the gRPC transport's out-of-band completion uses.
42pub struct LiminalTaskDelivery {
43    completion: Arc<LiminalCompletionSource>,
44    /// NOI-6 `attempt -> owning-worker` back-index. `None` (every non-agent
45    /// deployment) skips the binding, exactly as the outbox arm does —
46    /// intervention is then simply never offered.
47    attempt_owners: Option<AttemptOwnerIndex>,
48}
49
50impl std::fmt::Debug for LiminalTaskDelivery {
51    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        formatter
53            .debug_struct("LiminalTaskDelivery")
54            .field("attempt_owners", &self.attempt_owners.is_some())
55            .finish_non_exhaustive()
56    }
57}
58
59impl LiminalTaskDelivery {
60    /// Build the liminal delivery arm over the completion sink both transports
61    /// share.
62    #[must_use]
63    pub fn new(completion: Arc<LiminalCompletionSource>) -> Self {
64        Self {
65            completion,
66            attempt_owners: None,
67        }
68    }
69
70    /// Install the NOI-6 attempt-owner back-index, so a dispatched attempt binds
71    /// its owning worker before the push and the intervention router can resolve
72    /// the current owner of a live attempt.
73    #[must_use]
74    pub fn with_attempt_owners(mut self, attempt_owners: AttemptOwnerIndex) -> Self {
75        self.attempt_owners = Some(attempt_owners);
76        self
77    }
78}
79
80/// The identity a delivery needs, resolved from the wire task **before** any
81/// owner binding is taken.
82///
83/// 🔴 This type exists to make the ordering structural rather than positional.
84/// The owner binding is keyed on the run, so a binding taken before the run is
85/// resolved would let an intervention aimed at one continue-as-new generation
86/// resolve another generation's worker.
87///
88/// # Exactly how strong this is, measured rather than asserted
89///
90/// The binding is taken by [`Resolved::bind_owner`], a method **on the resolved
91/// identity**, so it cannot be called before that identity exists: moving the
92/// call above the resolution does not compile. That is the mutation this guards
93/// against, and it has been run.
94///
95/// It is **not** proof against a deliberate bypass. [`AttemptKey::new`] is a
96/// public constructor over four plain components, so an edit that calls
97/// [`AttemptOwnerGuard::bind`] directly with a placeholder run compiles and
98/// binds. An earlier version of this comment claimed the key "can only be built
99/// from a `Resolved`", which was false — the mutation that proved it survived
100/// both this structure and the test below.
101///
102/// The bypass is also, for the same reason, invisible at runtime: the guard
103/// releases on drop, so a binding taken before a refusal is gone again before
104/// any caller can look. What defends the property is that the natural edit does
105/// not compile and the deliberate one is a different API call, which review can
106/// see.
107struct Resolved {
108    workflow_id: WorkflowId,
109    run_id: RunId,
110    activity_id: ActivityId,
111    attempt: u32,
112}
113
114impl Resolved {
115    /// Resolve the task's identity, refusing a task with no run.
116    ///
117    /// The refusal is the pre-existing one — an activity without a run cannot be
118    /// dispatched at all, because an unfenced external effect has no generation
119    /// to belong to.
120    fn from_task(task: &ProtoActivityTask) -> Result<Self, &'static str> {
121        let workflow_id = task
122            .workflow_id
123            .clone()
124            .ok_or("task carries no workflow id")?
125            .try_into()
126            .map_err(|_| "task carries a malformed workflow id")?;
127        let run_id: RunId = task
128            .run_id
129            .clone()
130            .ok_or("activity run id is missing; refusing unfenced external effect")?
131            .try_into()
132            .map_err(|_| "task carries a malformed run id")?;
133        // Infallible: `ProtoActivityId` is the sequence position, and
134        // `ActivityId` is a newtype over it. Only its ABSENCE can be refused.
135        let activity_id: ActivityId = task
136            .activity_id
137            .ok_or("task carries no activity id")?
138            .into();
139        Ok(Self {
140            workflow_id,
141            run_id,
142            activity_id,
143            attempt: task.attempt,
144        })
145    }
146
147    /// The intervention key for this attempt, carrying the **resolved** run.
148    fn attempt_key(&self) -> AttemptKey {
149        AttemptKey::new(
150            self.workflow_id.clone(),
151            self.run_id.clone(),
152            self.activity_id.clone(),
153            self.attempt,
154        )
155    }
156
157    /// Bind this attempt's owner, returning the guard that releases it.
158    ///
159    /// 🔴 A method on the **resolved** identity on purpose. The binding is keyed
160    /// on the run, so taking it before the run is resolved is the defect; making
161    /// it a method on `Resolved` means the call cannot be moved above the
162    /// resolution — there is no receiver for it there, and the lift does not
163    /// compile. See this type's docs for what that does and does not prove.
164    fn bind_owner(
165        &self,
166        owners: Option<&AttemptOwnerIndex>,
167        worker: super::registry::WorkerId,
168    ) -> Option<AttemptOwnerGuard> {
169        owners.map(|owners| AttemptOwnerGuard::bind(owners.clone(), self.attempt_key(), worker))
170    }
171
172    /// The outbox ordinal this activity id was derived from.
173    ///
174    /// [`ActivityId`] is a newtype over the scheduling sequence position, so
175    /// `from_sequence_position` is exactly invertible and the ordinal the wire
176    /// needs round-trips without the row being present.
177    fn ordinal(&self) -> u64 {
178        self.activity_id.sequence_position()
179    }
180}
181
182/// Build the liminal wire request from the already-built task.
183///
184/// Every field is carried from the task except `heartbeat_window_ms`, which the
185/// task does not have — see [`LivenessTracking`] for why that assignment is a named
186/// value rather than a bare zero.
187fn request_for_task(task: &ProtoActivityTask, resolved: &Resolved) -> DispatchRequest {
188    DispatchRequest {
189        activity_type: task.activity_type.clone(),
190        workflow_id: resolved.workflow_id.clone(),
191        ordinal: resolved.ordinal(),
192        run_id: Some(resolved.run_id.clone()),
193        completion_token: task.completion_token.clone(),
194        idempotency_key: task.idempotency_key.clone(),
195        input: task
196            .input
197            .as_ref()
198            .map(|payload| payload.bytes.clone())
199            .unwrap_or_default(),
200        attempt: resolved.attempt,
201        labels: task
202            .labels
203            .iter()
204            .map(|(k, v)| (k.clone(), v.clone()))
205            .collect(),
206        heartbeat_window_ms: LivenessTracking::NotTrackedPerTask.heartbeat_window_ms(),
207    }
208}
209
210#[async_trait]
211impl WorkerTaskDelivery for LiminalTaskDelivery {
212    async fn deliver(
213        &self,
214        worker: &WorkerHandle,
215        task: &ProtoActivityTask,
216        intent: &SharedDeliveryIntent,
217    ) -> TaskDelivery {
218        // Identity is resolved FIRST — before the transport is even consulted —
219        // and the binding below is a method on what this produces, so it cannot
220        // be moved above this line.
221        //
222        // Ahead of the transport check deliberately. A task with no run is
223        // malformed **regardless of which worker it was aimed at**, so refusing
224        // it with "not delivered over liminal" would name the wrong defect and
225        // send an operator after the wrong remedy.
226        let resolved = match Resolved::from_task(task) {
227            Ok(resolved) => resolved,
228            Err(reason) => return TaskDelivery::failed(reason),
229        };
230
231        let delivery = match worker.delivery() {
232            WorkerDelivery::Liminal(delivery) => delivery.clone(),
233            WorkerDelivery::Grpc(_) => {
234                // A caller chose the wrong transport for the worker it selected.
235                // The worker is alive and correctly registered, so its
236                // registration stands — this is #52's defect refused at its
237                // mirror site.
238                return TaskDelivery::failed(
239                    "selected worker is not delivered over liminal; the liminal transport cannot \
240                     reach it",
241                );
242            }
243        };
244
245        // NOI-6: bind this attempt's owner BEFORE the push, so an intervention
246        // that races the dispatch resolves the worker. The guard releases on
247        // every exit path (reply, error, panic) so the index never keeps a
248        // finished attempt.
249        let _owner_guard = resolved.bind_owner(self.attempt_owners.as_ref(), worker.id());
250
251        let request = request_for_task(task, &resolved);
252        // The push is a blocking, thread-based liminal call; run it off the
253        // async runtime so a long-running activity cannot starve a runtime
254        // worker. The caller's intent is re-asked at every poll boundary of the
255        // wait, which is why it arrives behind an `Arc`.
256        let waiting_intent = Arc::clone(intent);
257        let dispatched = tokio::task::spawn_blocking(move || {
258            delivery.dispatch_held(&request, || waiting_intent.still_wanted())
259        })
260        .await;
261
262        let response = match dispatched {
263            Ok(Ok(Some(response))) => response,
264            Ok(Ok(None)) => {
265                // The caller withdrew while the delivery waited. The worker is
266                // alive and correctly registered; only this pass gave up, and a
267                // late reply is discarded by the fences.
268                return TaskDelivery::failed("delivery wait abandoned before worker reply");
269            }
270            Ok(Err(error)) => {
271                return TaskDelivery::failed(format!("liminal dispatch failed: {error}"));
272            }
273            Err(error) => {
274                return TaskDelivery::failed(format!("dispatch task join failed: {error}"));
275            }
276        };
277
278        // Re-enter the worker's result through the SAME completion path the gRPC
279        // transport uses; terminal dedup applies unchanged.
280        //
281        // 🔴 A failure HERE is the one outcome whose name reads narrower than its
282        // meaning: the worker took the task, executed it, and replied — and the
283        // reply did not record. `Delivered` would be wrong (the caller would
284        // settle the work without its result) and `WorkerUnreachable` would be
285        // wrong twice over (the worker is demonstrably alive, and deregistering
286        // it would destroy a healthy registration). `DeliveryFailed` carries the
287        // right obligations — registration stands, the caller withdraws its
288        // token — which is what the type encodes and what the outbox arm has
289        // always done here.
290        if let Err(error) = self.completion.deliver(&response) {
291            return TaskDelivery::failed(format!(
292                "worker replied but the completion could not be recorded: {error}"
293            ));
294        }
295        TaskDelivery::Delivered
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use std::sync::Arc;
302
303    use aion_core::{ActivityId, InterventionCapabilities, RunId, WorkflowId};
304    use aion_proto::{ProtoActivityId, ProtoActivityTask, ProtoWorkflowId};
305    use uuid::Uuid;
306
307    use crate::error::ServerError;
308    use crate::worker::bridge::OutboxDeliveryCallback;
309    use crate::worker::delivery_intent::{AlwaysWanted, SharedDeliveryIntent};
310    use crate::worker::intervention::AttemptOwnerIndex;
311    use crate::worker::liminal_transport::LiminalCompletionSource;
312    use crate::worker::registry::{ConnectedWorkerRegistry, WorkerDelivery};
313    use crate::worker::task_delivery::{TaskDelivery, WorkerTaskDelivery};
314
315    use super::{LiminalTaskDelivery, Resolved};
316
317    /// The completion sink is never reached by these tests — every one of them
318    /// refuses before a worker is pushed to — so both methods report "no live
319    /// run" if they are ever called, rather than pretending to succeed.
320    struct NoopCallback;
321
322    impl OutboxDeliveryCallback for NoopCallback {
323        fn deliver_completion(
324            &self,
325            _workflow_id: &WorkflowId,
326            _activity_id: &ActivityId,
327            _run_id: Option<&RunId>,
328            _result: String,
329        ) -> Result<bool, ServerError> {
330            Ok(false)
331        }
332        fn deliver_failure(
333            &self,
334            _workflow_id: &WorkflowId,
335            _activity_id: &ActivityId,
336            _run_id: Option<&RunId>,
337            _reason: String,
338        ) -> Result<bool, ServerError> {
339            Ok(false)
340        }
341    }
342
343    const WORKFLOW: u128 = 0x51;
344
345    /// A task carrying everything a delivery needs EXCEPT a run id.
346    fn task_without_a_run() -> ProtoActivityTask {
347        ProtoActivityTask {
348            workflow_id: Some(ProtoWorkflowId::from(WorkflowId::new(Uuid::from_u128(
349                WORKFLOW,
350            )))),
351            activity_id: Some(ProtoActivityId::from(ActivityId::from_sequence_position(3))),
352            activity_type: String::from("agent"),
353            input: None,
354            attempt: 1,
355            labels: std::collections::HashMap::new(),
356            // The whole point of this fixture.
357            run_id: None,
358            completion_token: String::from("token"),
359            idempotency_key: String::from("key"),
360        }
361    }
362
363    fn liminal_delivery(owners: &AttemptOwnerIndex) -> LiminalTaskDelivery {
364        LiminalTaskDelivery::new(Arc::new(LiminalCompletionSource::new(Arc::new(
365            NoopCallback,
366        ))))
367        .with_attempt_owners(owners.clone())
368    }
369
370    /// 🔴 NAMED PROPERTY: the run is resolved BEFORE any attempt owner is bound.
371    ///
372    /// # What breaks without it
373    ///
374    /// The owner binding is keyed on the run. A binding taken before the run is
375    /// resolved would let an intervention aimed at one continue-as-new
376    /// generation resolve a DIFFERENT generation's worker — an operator
377    /// stopping run A reaching the worker executing run B.
378    ///
379    /// # 🔴 What this test does and does NOT witness — measured by mutation
380    ///
381    /// It witnesses the **refusal**: a run-less task is rejected, is diagnosed
382    /// by its missing run rather than by the transport, does not deregister the
383    /// worker, and leaves no owner binding behind.
384    ///
385    /// It does **not** witness the ordering, and an earlier version of this
386    /// comment claimed it did. The mutation — lifting the bind above the
387    /// resolution with a placeholder run — was run, and **this test stayed
388    /// green**, because [`AttemptOwnerGuard`] releases on drop: a binding taken
389    /// before a refusal is already gone by the time any caller can look. There
390    /// is no observation window on this path, and there cannot be one.
391    ///
392    /// The ordering is defended structurally instead: the bind is a method on
393    /// [`Resolved`], so the natural lift does not compile. That claim was also
394    /// checked by mutation rather than asserted — see [`Resolved`] for exactly
395    /// how far it goes, including the bypass it does not stop.
396    #[tokio::test]
397    async fn run_resolution_precedes_attempt_owner_binding()
398    -> Result<(), Box<dyn std::error::Error>> {
399        let owners = AttemptOwnerIndex::new();
400        let delivery = liminal_delivery(&owners);
401
402        // A real registration yields a real WorkerId; no id here is fabricated.
403        let registry = ConnectedWorkerRegistry::default();
404        let (sender, _receiver) = tokio::sync::mpsc::channel(1);
405        let types = [String::from("agent")];
406        let registration = registry.register_delivery_with_capabilities(
407            [String::from("default")],
408            String::from("default"),
409            None,
410            types.iter(),
411            WorkerDelivery::Grpc(sender),
412            InterventionCapabilities::none(),
413        )?;
414        let worker_id = registration
415            .worker_id()
416            .ok_or("a registration must assign a worker id")?;
417        let worker = registry
418            .worker_by_id(worker_id)?
419            .ok_or("the worker just registered must be readable")?;
420
421        let intent: SharedDeliveryIntent = Arc::new(AlwaysWanted);
422        let outcome = delivery
423            .deliver(&worker, &task_without_a_run(), &intent)
424            .await;
425
426        match outcome {
427            TaskDelivery::Delivered => {
428                return Err("a task with no run must never be delivered".into());
429            }
430            TaskDelivery::Undeliverable(undeliverable) => {
431                // The refusal names the RUN, not the transport: identity is
432                // resolved before the transport is consulted, so a run-less task
433                // is diagnosed as run-less whichever worker it was aimed at.
434                assert!(
435                    undeliverable.reason().contains("run id is missing"),
436                    "a run-less task must be refused BY ITS MISSING RUN, not by the transport; \
437                     got: {}",
438                    undeliverable.reason()
439                );
440                assert!(
441                    !undeliverable.deregisters_worker(),
442                    "a malformed task is not evidence that the worker is gone"
443                );
444            }
445        }
446
447        // 🔴 THE PROPERTY, as far as this test can witness it: nothing is bound
448        // when the run refuses. Note what this does NOT say — an earlier
449        // version of this comment claimed nothing COULD be bound because an
450        // `AttemptKey` is only constructible from a resolved identity, and that
451        // was false. `AttemptKey::new` is public over four plain components.
452        // See this test's docs and [`Resolved`] for what actually holds.
453        let bound = owners.attempts_for_workflow(&WorkflowId::new(Uuid::from_u128(WORKFLOW)));
454        assert!(
455            bound.is_empty(),
456            "the attempt-owner index must be untouched when the run refused; a binding here \
457             means the bind was lifted above the run resolution, and an intervention could \
458             resolve the wrong generation's worker. Found: {bound:?}"
459        );
460        Ok(())
461    }
462
463    /// The property's SECOND witness, and the one that outlives a refactor of
464    /// the call site: identity resolution refuses a run-less task, so no
465    /// `Resolved` is produced — and [`Resolved::bind_owner`], the only binding
466    /// path the delivery takes, is a method on it.
467    ///
468    /// 🔴 That is a claim about the CALL SITE, not about the key type. An
469    /// earlier version said an `AttemptKey` "cannot be built without" a
470    /// `Resolved`; it can, and the mutation that proved it survived. What this
471    /// witnesses is that resolution refuses first.
472    ///
473    /// Kept beside the behavioural test deliberately. The refusal and the
474    /// structure are different claims, and a change that removes one should
475    /// still meet the other.
476    #[test]
477    fn identity_resolution_refuses_a_task_with_no_run() -> Result<(), Box<dyn std::error::Error>> {
478        let Err(refusal) = Resolved::from_task(&task_without_a_run()) else {
479            return Err("a task with no run must not resolve".into());
480        };
481        assert!(
482            refusal.contains("run id is missing"),
483            "the refusal must name the run so an operator is sent to the right remedy: {refusal}"
484        );
485        Ok(())
486    }
487}