Skip to main content

aion_client/transport/
embedded.rs

1//! Transport backed by an in-process [`aion::Engine`].
2//!
3//! Event subscriptions honour the same resume/replay-splice contract as the
4//! server's `/events/stream` endpoint, built directly on [`aion::Engine`]
5//! seams (`Engine::subscribe` for the live broadcast, `engine.store()` for
6//! the history snapshot — never a client-held stream over engine internals):
7//!
8//! 1. attach the live broadcast subscription FIRST (time T0);
9//! 2. snapshot recorded history via `engine.store().read_history` (T1 > T0);
10//! 3. validate the cursor against the snapshot head;
11//! 4. splice: replay `[resume_from_seq ..= head]` from the snapshot, then the
12//!    live tail filtered to `seq > head`.
13//!
14//! Gap-free: publish strictly follows durable commit, so every event with
15//! `seq > head` was committed — and therefore broadcast — after T0.
16//! Duplicate-free: the live filter drops every `seq <= head`, so an event
17//! present in both the snapshot and the broadcast is emitted exactly once,
18//! from the snapshot. Engine-side lag is never silent: each
19//! `Err(EventStreamLagged)` item surfaces as `Err(ClientError::Unavailable)`
20//! so the resume loop reconnects with its cursor.
21
22use std::sync::Arc;
23
24use aion_core::Event;
25use async_trait::async_trait;
26use futures::stream::BoxStream;
27use futures::{StreamExt, stream};
28
29use crate::error::ClientError;
30use crate::transport::contract::{SubscriptionAttempt, WorkflowTransport};
31
32/// Transport backed by an in-process [`aion::Engine`].
33pub struct EmbeddedWorkflowTransport {
34    engine: Arc<aion::Engine>,
35}
36
37impl EmbeddedWorkflowTransport {
38    /// Creates an embedded transport for `engine`.
39    #[must_use]
40    pub fn new(engine: Arc<aion::Engine>) -> Self {
41        Self { engine }
42    }
43
44    /// Resolve the target run id: the supplied one, or the latest run from the
45    /// workflow's run chain when omitted (mirrors the server's `resolve_run_id`).
46    async fn resolve_run_id(
47        &self,
48        workflow_id: &aion_core::WorkflowId,
49        run_id: Option<aion_proto::ProtoRunId>,
50    ) -> Result<aion_core::RunId, ClientError> {
51        if let Some(run_id) = run_id {
52            return run_id.try_into().map_err(ClientError::from_wire_error);
53        }
54        let chain = self
55            .engine
56            .store()
57            .read_run_chain(workflow_id)
58            .await
59            .map_err(|error| store_error_class(&error, error.to_string()))?;
60        chain
61            .last()
62            .map(|summary| summary.run_id.clone())
63            .ok_or_else(|| ClientError::not_found(format!("workflow {workflow_id} not found")))
64    }
65}
66
67#[async_trait]
68impl WorkflowTransport for EmbeddedWorkflowTransport {
69    async fn start_workflow(
70        &self,
71        request: aion_proto::ProtoStartWorkflowRequest,
72    ) -> Result<aion_proto::ProtoStartWorkflowResponse, ClientError> {
73        let input = request
74            .input
75            .ok_or_else(|| ClientError::invalid_argument("start request input payload is missing"))
76            .and_then(|payload| {
77                aion_core::Payload::try_from(payload).map_err(ClientError::from_wire_error)
78            })?;
79        // The embedded engine is single-tenant and in-process: there is no
80        // namespace authority stamping visibility attributes, so the start
81        // carries no search attributes.
82        let handle = self
83            .engine
84            .start_workflow(
85                &request.workflow_type,
86                input,
87                std::collections::HashMap::new(),
88                String::from("default"),
89            )
90            .await
91            .map_err(|error| map_engine_error(&error))?;
92        Ok(aion_proto::ProtoStartWorkflowResponse {
93            workflow_id: Some(aion_proto::ProtoWorkflowId::from(
94                handle.workflow_id().clone(),
95            )),
96            run_id: Some(aion_proto::ProtoRunId::from(handle.run_id().clone())),
97        })
98    }
99
100    async fn signal(
101        &self,
102        request: aion_proto::ProtoSignalRequest,
103    ) -> Result<aion_proto::ProtoSignalResponse, ClientError> {
104        let workflow_id = decode_required_workflow_id(request.workflow_id)?;
105        let run_id = decode_required_run_id(request.run_id)?;
106        let payload = request
107            .payload
108            .ok_or_else(|| ClientError::invalid_argument("signal request payload is missing"))
109            .and_then(|payload| {
110                aion_core::Payload::try_from(payload).map_err(ClientError::from_wire_error)
111            })?;
112        self.engine
113            .signal(&workflow_id, &run_id, request.signal_name, payload)
114            .await
115            .map_err(|error| map_engine_error(&error))?;
116        Ok(aion_proto::ProtoSignalResponse {})
117    }
118
119    async fn query(
120        &self,
121        request: aion_proto::ProtoQueryRequest,
122    ) -> Result<aion_proto::ProtoQueryResponse, ClientError> {
123        let workflow_id = decode_required_workflow_id(request.workflow_id)?;
124        let run_id = decode_required_run_id(request.run_id)?;
125        // Absent arguments mean the caller supplied none; the handler still
126        // receives one well-formed document.
127        let arguments = request.arguments.map_or_else(
128            || Ok(aion_core::Payload::json_null()),
129            |arguments| {
130                aion_core::Payload::try_from(arguments).map_err(ClientError::from_wire_error)
131            },
132        )?;
133        let payload = self
134            .engine
135            .query(&workflow_id, &run_id, request.query_name, arguments)
136            .await
137            .map_err(|error| map_engine_error(&error))?;
138        Ok(aion_proto::ProtoQueryResponse {
139            outcome: Some(aion_proto::proto_query_response::Outcome::Result(
140                aion_proto::ProtoPayload::from(payload),
141            )),
142        })
143    }
144
145    async fn cancel(
146        &self,
147        request: aion_proto::ProtoCancelRequest,
148    ) -> Result<aion_proto::ProtoCancelResponse, ClientError> {
149        let workflow_id = decode_required_workflow_id(request.workflow_id)?;
150        let run_id = decode_required_run_id(request.run_id)?;
151        self.engine
152            .cancel(&workflow_id, &run_id, request.reason)
153            .await
154            .map_err(|error| map_engine_error(&error))?;
155        Ok(aion_proto::ProtoCancelResponse {})
156    }
157
158    async fn retire_workloop(
159        &self,
160        request: aion_proto::ProtoRetireWorkloopRequest,
161    ) -> Result<aion_proto::ProtoRetireWorkloopResponse, ClientError> {
162        let workflow_id = decode_required_workflow_id(request.workflow_id)?;
163        self.engine
164            .retire_declared_workloop(
165                &workflow_id,
166                request.reason.clone(),
167                // The retirement RESULT is the operator's, never the retire
168                // body's return value.
169                aion_core::Payload::new(aion_core::ContentType::Json, b"null".to_vec()),
170            )
171            .await
172            .map_err(|error| map_engine_error(&error))?;
173        Ok(aion_proto::ProtoRetireWorkloopResponse {
174            reason: request.reason,
175        })
176    }
177
178    async fn reopen(
179        &self,
180        request: aion_proto::ProtoReopenRequest,
181    ) -> Result<aion_proto::ProtoReopenResponse, ClientError> {
182        let workflow_id = decode_required_workflow_id(request.workflow_id)?;
183        let run_id = self.resolve_run_id(&workflow_id, request.run_id).await?;
184        let handle = self
185            .engine
186            .reopen_workflow(&workflow_id, &run_id)
187            .await
188            .map_err(|error| map_engine_error(&error))?;
189        Ok(aion_proto::ProtoReopenResponse {
190            run_id: Some(handle.run_id().clone().into()),
191            status: aion_proto::ProtoWorkflowStatus::from(handle.cached_status()) as i32,
192        })
193    }
194
195    async fn pause(
196        &self,
197        request: aion_proto::ProtoPauseRequest,
198    ) -> Result<aion_proto::ProtoPauseResponse, ClientError> {
199        let workflow_id = decode_required_workflow_id(request.workflow_id)?;
200        let run_id = self.resolve_run_id(&workflow_id, request.run_id).await?;
201        let reason = if request.reason.is_empty() {
202            None
203        } else {
204            Some(request.reason)
205        };
206        let handle = self
207            .engine
208            .pause_workflow(&workflow_id, &run_id, reason, None)
209            .await
210            .map_err(|error| map_engine_error(&error))?;
211        Ok(aion_proto::ProtoPauseResponse {
212            run_id: Some(handle.run_id().clone().into()),
213            status: aion_proto::ProtoWorkflowStatus::Paused as i32,
214        })
215    }
216
217    async fn resume(
218        &self,
219        request: aion_proto::ProtoResumeRequest,
220    ) -> Result<aion_proto::ProtoResumeResponse, ClientError> {
221        let workflow_id = decode_required_workflow_id(request.workflow_id)?;
222        let run_id = self.resolve_run_id(&workflow_id, request.run_id).await?;
223        let handle = self
224            .engine
225            .resume_paused_workflow(&workflow_id, &run_id, None)
226            .await
227            .map_err(|error| map_engine_error(&error))?;
228        Ok(aion_proto::ProtoResumeResponse {
229            run_id: Some(handle.run_id().clone().into()),
230            status: aion_proto::ProtoWorkflowStatus::Running as i32,
231        })
232    }
233
234    async fn list_workflows(
235        &self,
236        request: aion_proto::ProtoListWorkflowsRequest,
237    ) -> Result<aion_proto::ProtoListWorkflowsResponse, ClientError> {
238        let filter = match request.filter.as_ref() {
239            Some(filter) => {
240                aion_proto::decode_workflow_filter(filter).map_err(ClientError::from_wire_error)?
241            }
242            None => aion_core::WorkflowFilter::default(),
243        };
244        let summaries = self
245            .engine
246            .list_workflows(filter)
247            .await
248            .map_err(|error| map_engine_error(&error))?
249            .iter()
250            .map(|summary| {
251                aion_proto::encode_workflow_summary(request.namespace.clone(), None, summary)
252            })
253            .map(|result| result.map_err(ClientError::from_wire_error))
254            .collect::<Result<Vec<_>, _>>()?;
255        Ok(aion_proto::ProtoListWorkflowsResponse { summaries })
256    }
257
258    async fn describe_workflow(
259        &self,
260        request: aion_proto::ProtoDescribeWorkflowRequest,
261    ) -> Result<aion_proto::ProtoDescribeWorkflowResponse, ClientError> {
262        let workflow_id = decode_required_workflow_id(request.workflow_id)?;
263        let run_id = self.resolve_run_id(&workflow_id, request.run_id).await?;
264        let history = self
265            .engine
266            .store()
267            .read_history(&workflow_id)
268            .await
269            // This read goes straight to the store, so the refusal arrives with
270            // no `EngineError` around it — but it is the same refusal, and a
271            // `NotOwner` here means exactly what it means everywhere else: ask a
272            // different owner. Collapsing it into `server` told the caller its
273            // request was unanswerable when a re-route would have served it.
274            .map_err(|error| store_error_class(&error, error.to_string()))?;
275        let Some(summary) = aion_core::WorkflowSummary::from_history(&history) else {
276            return Err(ClientError::not_found(format!(
277                "workflow {workflow_id} has no recorded history"
278            )));
279        };
280        let summary = Some(
281            aion_proto::encode_workflow_summary(request.namespace.clone(), None, &summary)
282                .map_err(ClientError::from_wire_error)?,
283        );
284        let history_head_seq = history.last().map_or(0, aion_core::Event::seq);
285        let terminal_event = aion_core::current_lease_terminal(&history)
286            .map(|event| aion_proto::encode_event(request.namespace.clone(), None, event))
287            .transpose()
288            .map_err(ClientError::from_wire_error)?;
289        let history = if request.include_history {
290            history
291                .iter()
292                .map(|event| aion_proto::encode_event(request.namespace.clone(), None, event))
293                .map(|result| result.map_err(ClientError::from_wire_error))
294                .collect::<Result<Vec<_>, _>>()?
295        } else {
296            Vec::new()
297        };
298        Ok(aion_proto::ProtoDescribeWorkflowResponse {
299            summary,
300            history,
301            run_id: Some(run_id.into()),
302            history_head_seq,
303            terminal_event,
304        })
305    }
306
307    async fn read_history(
308        &self,
309        request: aion_proto::ProtoReadHistoryRequest,
310    ) -> Result<aion_proto::ProtoReadHistoryResponse, ClientError> {
311        let workflow_id = decode_required_workflow_id(request.workflow_id)?;
312        let from_seq = request.from_seq.unwrap_or(0);
313        let mut events = self
314            .engine
315            .store()
316            .read_history_from(&workflow_id, from_seq)
317            .await
318            .map_err(|error| store_error_class(&error, error.to_string()))?;
319        let head_seq = events.last().map_or(0, aion_core::Event::seq);
320        let next_from_seq = request
321            .limit
322            .and_then(|limit| events.get(limit as usize).map(aion_core::Event::seq));
323        if let Some(limit) = request.limit {
324            events.truncate(limit as usize);
325        }
326        let events = events
327            .iter()
328            .map(|event| aion_proto::encode_event(request.namespace.clone(), None, event))
329            .map(|result| result.map_err(ClientError::from_wire_error))
330            .collect::<Result<Vec<_>, _>>()?;
331        Ok(aion_proto::ProtoReadHistoryResponse {
332            events,
333            next_from_seq,
334            head_seq,
335        })
336    }
337
338    async fn subscribe(
339        &self,
340        request: aion_proto::SubscriptionRequest,
341        resume_from_sequence: Option<u64>,
342    ) -> Result<SubscriptionAttempt, ClientError> {
343        let (workflow_target, filter) = embedded_subscription_target(request)?;
344        // T0: attach to the live broadcast BEFORE any history snapshot — one
345        // half of the gap-free splice proof (mirrors the server's
346        // subscribe-then-snapshot ordering).
347        let live = self.engine.subscribe(filter);
348        let events = match (&workflow_target, resume_from_sequence) {
349            (Some(workflow_id), Some(resume_from_seq)) => {
350                // T1 (> T0): snapshot recorded history, then validate the
351                // cursor against its head and build the dedupe splice.
352                let history = self
353                    .engine
354                    .store()
355                    .read_history(workflow_id)
356                    .await
357                    .map_err(|error| store_error_class(&error, error.to_string()))?;
358                splice_resume(live, history, resume_from_seq)?
359            }
360            (None, Some(_)) => {
361                return Err(ClientError::invalid_argument(
362                    "filtered and firehose event streams are live-only by design; resume \
363                     cursors are valid for per-workflow subscriptions only",
364                ));
365            }
366            (_, None) => map_lag(live),
367        };
368        // Per-workflow streams end at the run's terminal event, exactly like
369        // the server socket; callers walk continue-as-new chains by
370        // resubscribing with their cursor.
371        Ok(SubscriptionAttempt::new(match workflow_target {
372            Some(_) => close_after_terminal(events),
373            None => events,
374        }))
375    }
376}
377
378/// Validates a resume cursor against a history snapshot and builds the
379/// replay/live splice (see the module docs for the gap/duplicate proof).
380fn splice_resume(
381    live: BoxStream<'static, Result<Event, aion::EventStreamLagged>>,
382    history: Vec<Event>,
383    resume_from_seq: u64,
384) -> Result<BoxStream<'static, Result<Event, ClientError>>, ClientError> {
385    if resume_from_seq == 0 {
386        return Err(ClientError::invalid_argument(
387            "resume_from_seq must be >= 1 (the first sequence number wanted)",
388        ));
389    }
390    let head = history.last().map_or(0, Event::seq);
391    if resume_from_seq > head.saturating_add(1) {
392        return Err(ClientError::invalid_argument(format!(
393            "resume_from_seq {resume_from_seq} is ahead of recorded history (head seq {head}); \
394             the largest valid cursor is {}",
395            head.saturating_add(1)
396        )));
397    }
398
399    let mut history = history;
400    let replay_start = history.partition_point(|event| event.seq() < resume_from_seq);
401    let replay = history.split_off(replay_start);
402    let tail = live.filter(move |item| {
403        let keep = match item {
404            Ok(event) => event.seq() > head,
405            // Lag is information, never filtered away.
406            Err(aion::EventStreamLagged { .. }) => true,
407        };
408        futures::future::ready(keep)
409    });
410
411    Ok(stream::iter(replay.into_iter().map(Ok))
412        .chain(map_lag(tail.boxed()))
413        .boxed())
414}
415
416/// Maps engine-side lag items to retryable [`ClientError::Unavailable`] so
417/// the resume loop reconnects with its cursor instead of silently gapping.
418fn map_lag(
419    live: BoxStream<'static, Result<Event, aion::EventStreamLagged>>,
420) -> BoxStream<'static, Result<Event, ClientError>> {
421    live.map(|item| {
422        item.map_err(|lagged| {
423            ClientError::from_wire_error(aion_proto::WireError::lagged(lagged.to_string()))
424        })
425    })
426    .boxed()
427}
428
429/// Ends the stream after the first terminal workflow event, mirroring the
430/// server socket's per-workflow run-boundary close.
431fn close_after_terminal(
432    events: BoxStream<'static, Result<Event, ClientError>>,
433) -> BoxStream<'static, Result<Event, ClientError>> {
434    stream::unfold(Some(events), |state| async move {
435        let mut events = state?;
436        let item = events.next().await?;
437        // The terminal event is delivered and the inner stream is dropped
438        // immediately afterwards (releasing the broadcast receiver), so the
439        // close is eager — it never waits for a further event to be polled.
440        let closed = matches!(&item, Ok(event) if is_terminal_workflow_event(event));
441        Some((item, if closed { None } else { Some(events) }))
442    })
443    .boxed()
444}
445
446fn is_terminal_workflow_event(event: &Event) -> bool {
447    matches!(
448        event,
449        Event::WorkflowCompleted { .. }
450            | Event::WorkflowFailed { .. }
451            | Event::WorkflowCancelled { .. }
452            | Event::WorkflowTimedOut { .. }
453            | Event::WorkflowContinuedAsNew { .. }
454    )
455}
456
457fn decode_required_workflow_id(
458    value: Option<aion_proto::ProtoWorkflowId>,
459) -> Result<aion_core::WorkflowId, ClientError> {
460    value
461        .ok_or_else(|| ClientError::invalid_argument("request workflow id is missing"))?
462        .try_into()
463        .map_err(ClientError::from_wire_error)
464}
465
466fn decode_required_run_id(
467    value: Option<aion_proto::ProtoRunId>,
468) -> Result<aion_core::RunId, ClientError> {
469    value
470        .ok_or_else(|| ClientError::invalid_argument("request run id is missing"))?
471        .try_into()
472        .map_err(ClientError::from_wire_error)
473}
474
475/// Maps a wire subscription request onto the engine filter surface plus the
476/// per-workflow target the splice and run-boundary close key on.
477fn embedded_subscription_target(
478    request: aion_proto::SubscriptionRequest,
479) -> Result<(Option<aion_core::WorkflowId>, aion::EventFilter), ClientError> {
480    match request.subscription {
481        Some(aion_proto::subscription_request::Subscription::PerWorkflow(subscription)) => {
482            let workflow_id = subscription
483                .workflow_id
484                .ok_or_else(|| {
485                    ClientError::invalid_argument(
486                        "per-workflow subscription requires a workflow id",
487                    )
488                })?
489                .try_into()
490                .map_err(ClientError::from_wire_error)?;
491            Ok((
492                Some(aion_core::WorkflowId::clone(&workflow_id)),
493                aion::EventFilter {
494                    workflow_id: Some(workflow_id),
495                    run: None,
496                    family: None,
497                },
498            ))
499        }
500        Some(
501            aion_proto::subscription_request::Subscription::Filtered(_)
502            | aion_proto::subscription_request::Subscription::Firehose(_),
503        ) => Ok((None, aion::EventFilter::default())),
504        Some(aion_proto::subscription_request::Subscription::Cluster(_)) => {
505            // The WS3 cluster topology/ownership channel is a server-side
506            // projection of distributed cluster state. The embedded in-process
507            // transport drives a single local engine with no cluster topology to
508            // project, so a cluster subscription is not serviceable here; reject it
509            // cleanly rather than silently degrading to a workflow event stream.
510            Err(ClientError::invalid_argument(
511                "cluster topology subscriptions are not supported by the embedded in-process \
512                 transport; connect to an aion-server over gRPC/WebSocket to subscribe to the \
513                 cluster channel",
514            ))
515        }
516        Some(aion_proto::subscription_request::Subscription::Transcript(_)) => {
517            // The NOI-5b agent-observability transcript channel is a server-side
518            // projection over the durable `O` keyspace + the server's transcript
519            // sequencer. The embedded in-process transport has no such server
520            // bridge, so a transcript subscription is not serviceable here; reject
521            // it cleanly rather than degrading to a workflow event stream.
522            Err(ClientError::invalid_argument(
523                "agent-observability transcript subscriptions are not supported by the embedded \
524                 in-process transport; connect to an aion-server over gRPC/WebSocket to subscribe \
525                 to the transcript channel",
526            ))
527        }
528        None => Err(ClientError::invalid_argument(
529            "subscription request is missing its subscription variant",
530        )),
531    }
532}
533
534/// Translate an engine failure into the client-facing error class.
535///
536/// # The `_` arm is a family default, and it is not free
537///
538/// `EngineError` has 51 variants and is not `#[non_exhaustive]`, so an
539/// exhaustive match here *would* compile-fail on every new variant. That is
540/// deliberately not what this does: a 51-arm list in a transport adapter is a
541/// list nothing reads, and it would go stale as silently as the wildcard does.
542/// The wildcard is chosen, with its cost stated — **a new variant lands in the
543/// generic server bucket and the compiler will not say so.**
544///
545/// What makes that acceptable is the direction it fails in. `server` is the
546/// "something went wrong, this is not your request's fault and not a wait"
547/// class; landing there is uninformative, never *wrong* in a way that makes a
548/// caller retry something unretryable or give up on something transient. Every
549/// arm above it exists because its variant would be actively mis-served by that
550/// default — a not-found retried forever, a shutdown reported as an engine bug.
551///
552/// So the rule for adding an arm is not "is this variant new" but "would the
553/// generic bucket mislead a caller about what to DO". Only those get named.
554fn map_engine_error(error: &aion::EngineError) -> ClientError {
555    match error {
556        aion::EngineError::WorkflowNotFound { .. } => ClientError::not_found(error.to_string()),
557        // Reopen precondition failure (AD-012): distinct typed variant, never
558        // conflated with not-found or the generic server bucket.
559        aion::EngineError::InvalidState { .. } => ClientError::invalid_state(error.to_string()),
560        // The caller's own payload did not satisfy the contract the target
561        // package declares. Both are raised BEFORE anything is recorded, so
562        // there is nothing to clean up and nothing to retry — the remedy is to
563        // send different bytes. `server` would say the opposite: "not your
564        // fault, try again", which is how a caller ends up retrying a payload
565        // that can never be accepted. `aion-server` classifies these two
566        // through `declared_contract_wire` for the same reason; this is the
567        // embedded surface reaching the same verdict, not a second opinion.
568        aion::EngineError::StartInputRefused { .. } | aion::EngineError::SignalRefused { .. } => {
569            ClientError::invalid_argument(error.to_string())
570        }
571        // Six refusals about the state of a run, or of the package a run would
572        // start from, rather than the health of the engine — all reachable
573        // through the embedded surface, all classified `invalid_state` by
574        // `aion-server`, and all erased into "engine bug" by the generic
575        // bucket, which is the wrong thing to say about any of them.
576        //
577        // Two are transient by construction (`TerminalWriterUnavailable`,
578        // `TerminalWriterHeld`): a writer reservation lives across one terminal
579        // transition. Two name a precondition the caller can act on: redeploy
580        // and cancel through the ordinary path (`RunIsRecoverable`), or address
581        // this engine's missing startup verdict (`NoResidencyVerdict`). The
582        // last two are admission refusals raised before the run starts — the
583        // package's declared contract does not identify what the request names
584        // (`ContractIdentity`), or it declares no task queue to serve from
585        // (`NoQueueDeclaration`) — and the remedy for both is a redeploy.
586        aion::EngineError::TerminalWriterUnavailable { .. }
587        | aion::EngineError::TerminalWriterHeld { .. }
588        | aion::EngineError::RunIsRecoverable { .. }
589        | aion::EngineError::NoResidencyVerdict { .. }
590        | aion::EngineError::ContractIdentity { .. }
591        | aion::EngineError::NoQueueDeclaration { .. } => {
592            ClientError::invalid_state(error.to_string())
593        }
594        // 🔴 BOTH SHAPES A STORE REFUSAL ARRIVES IN, CLASSIFIED IN ONE PLACE.
595        //
596        // An earlier revision matched only the bare `Store(..)` shape and its
597        // test hand-built that shape, so the arm looked covered and fired on
598        // nothing a caller could provoke: every durable write these operations
599        // trigger goes through the `Recorder`, which returns `DurabilityError`,
600        // and the engine wraps that as `EngineError::Durability` — so the
601        // production shape of a lost-ownership refusal is
602        // `Durability(Store(NotOwner))`. Both shapes now route through
603        // `store_error_class`, which is the only place the rule is written.
604        aion::EngineError::Store(store)
605        | aion::EngineError::Durability(aion::durability::DurabilityError::Store(store)) => {
606            store_error_class(store, error.to_string())
607        }
608        // Live-query dispatch. `aion-server` gives this family five distinct
609        // wire codes and the caller taxonomy has a class for each; collapsing
610        // them into `server` left `unknown_query`, `query_timeout`,
611        // `query_failed` and the query half of `not_running` unreachable
612        // in-process — four classes that exist solely for this operation. The
613        // same caller code branches correctly over the wire and could not
614        // branch at all here.
615        aion::EngineError::Query(query) => query_error_class(query, error),
616        // This engine has stopped serving. `aion-server`'s `wire_from_engine`
617        // (`error.rs:645`) answers `not_running`, and an over-the-wire caller of
618        // these operations therefore sees `ClientError::NotRunning`; an earlier
619        // revision of this arm said `unavailable`, which is the transport-level
620        // class the SDK also raises for a dial failure. That told an in-process
621        // caller its ENDPOINT was unreachable when what had happened was that
622        // the engine it holds is shutting down.
623        //
624        // ⚠️ "Mirror the server" is not one answer — the server gives two, and
625        // saying otherwise would hide a real divergence. `wire_from_engine` is
626        // the mapping that governs the eight engine operations THIS transport
627        // exposes, and it is the one mirrored here. Two control-plane handlers
628        // answer `Unavailable` for the same variant —
629        // `aion-server/src/authoring/handlers.rs:404-406` and
630        // `api/handlers/deploy.rs:415` — and both serve deploy/authoring
631        // operations that this transport does not expose, so neither is
632        // reachable through a caller holding an `EmbeddedWorkflowTransport`.
633        // Recorded rather than reconciled: a shared classifier is what would
634        // actually force the two into agreement, and that needs a crate both
635        // sides can depend on.
636        //
637        // `EngineTaskEpochClosed` deliberately has no arm. It is constructed at
638        // exactly one site — the terminal-append boundary in the engine's
639        // process-exit path — which is reached by the completion monitor, never
640        // by any of the operations this transport exposes. An arm for it would
641        // be a classification nobody can observe, and a wrong claim about what
642        // this surface can return.
643        // 🔴 CARRY THE DISCRIMINATOR, because the class alone is a false hint.
644        // `not_running` is the right CLASS and mirrors `wire_from_engine` — but
645        // the operator-facing hint for a bare `not_running` says the run is no
646        // longer running and points at `aion list --status running`, which is
647        // false twice here: the run is fine, it is the ENGINE that stopped
648        // serving, and `aion list` would fail identically. That is the same
649        // defect this lane's F4 fix cited when it moved `EngineTaskEpochClosed`
650        // OFF `not_running`; leaving the discriminator behind would have this
651        // lane arguing both sides of one rule.
652        //
653        // The wire surface already carries it — `wire_from_engine` builds
654        // `not_running_with_type("ShuttingDown", …)` — so attaching it here
655        // makes the embedded and wire surfaces agree rather than diverge, and
656        // gives `render.rs` the one fact it needs to say something true.
657        aion::EngineError::ShuttingDown => ClientError::NotRunning {
658            detail: crate::ErrorDetail::with_type(error.to_string(), "ShuttingDown"),
659        },
660        _ => ClientError::server(error.to_string()),
661    }
662}
663
664/// The class a store-layer refusal carries, whichever shape it reached
665/// [`map_engine_error`] in.
666///
667/// Mirrors `aion-server`'s `wire_from_store` composed with
668/// [`ClientError::from_wire_error`], so the same underlying refusal names the
669/// same class whether the caller is in-process or across the wire.
670///
671/// `not_owner` is the one class that names a ROUTING failure — the endpoint
672/// answered, it simply does not own this target's shard, so the remedy is a
673/// DIFFERENT owner rather than a retry against this one. Collapsing it into
674/// `server` costs the caller that distinction entirely: `server` says the
675/// request is unanswerable, and a caller that believes it abandons work a
676/// re-route would have served.
677///
678/// ⚠️ Nothing in this crate retries it AUTOMATICALLY, and an earlier revision of
679/// this comment claimed otherwise. `aion-client`'s only retry classifier is
680/// `stream.rs`'s `is_retryable`, which is `matches!(error, ClientError::
681/// Unavailable { .. })` — `NotOwner` is not in it, so `ResumingEventStream`
682/// terminates the stream on one. The distinction this arm preserves is
683/// therefore one the CALLER acts on, and the surface that already does is the
684/// CLI's operator hint (`aion-cli/src/render.rs:175-178`), which tells the
685/// operator to retry or point `--endpoint` at another node instead of sending
686/// them hunting a network fault that does not exist.
687///
688/// Takes the caller-facing `message` separately rather than deriving it, because
689/// a store refusal reaches this transport in three shapes and only two of them
690/// have an `EngineError` to render: wrapped as `EngineError::Store`, wrapped as
691/// `EngineError::Durability(Store(..))`, and — at the three call sites that read
692/// the store directly rather than through an engine API — as a bare
693/// [`aion_store::StoreError`] with no wrapper at all. The rule is written once
694/// and all three shapes are held to it.
695fn store_error_class(error: &aion_store::StoreError, message: String) -> ClientError {
696    match error {
697        aion_store::StoreError::NotOwner { .. } => ClientError::not_owner(message),
698        aion_store::StoreError::NotFound { .. } => ClientError::not_found(message),
699        // A `SequenceConflict` is this codebase's single-writer invariant
700        // violation — a double-writer bug, not a caller mistake and not an
701        // idempotency conflict — and `Backend`/`Serialization` are
702        // infrastructure faults. All three are the engine's to answer for, and
703        // `from_wire_error` puts all three in the generic bucket for a caller
704        // arriving over the wire.
705        aion_store::StoreError::SequenceConflict { .. }
706        | aion_store::StoreError::Backend(_)
707        | aion_store::StoreError::Serialization(_) => ClientError::server(message),
708    }
709}
710
711/// The class a live-query dispatch failure carries.
712///
713/// Mirrors `aion-server`'s `query_wire` composed with
714/// [`ClientError::from_wire_error`]. Every arm is a distinct remedy: name a
715/// query the workflow declares, wait or retry, address a run that is not
716/// answering, look up a workflow that does not exist, or fix the handler.
717fn query_error_class(error: &aion::QueryError, source: &aion::EngineError) -> ClientError {
718    match error {
719        aion::QueryError::UnknownQuery(_) => ClientError::unknown_query(source.to_string()),
720        aion::QueryError::Timeout => ClientError::query_timeout(source.to_string()),
721        // A run that cannot answer and a reply channel that closed are the same
722        // fact to a caller: the workflow is not there to answer right now.
723        aion::QueryError::NotRunning(_) | aion::QueryError::ReplyDropped => {
724            ClientError::not_running(source.to_string())
725        }
726        aion::QueryError::Unknown(_) => ClientError::not_found(source.to_string()),
727        // The handler ran and reported an application-level failure — the
728        // workflow author's to fix, and distinct from the engine failing to
729        // deliver the query at all.
730        aion::QueryError::HandlerFailed { .. } => ClientError::query_failed(source.to_string()),
731        // The caller sent arguments the engine cannot carry to a handler: the
732        // caller's request to fix, never the workflow's or the server's.
733        aion::QueryError::InvalidArguments { .. } => {
734            ClientError::invalid_argument(source.to_string())
735        }
736        aion::QueryError::Engine(_) => ClientError::server(source.to_string()),
737    }
738}
739
740#[cfg(test)]
741mod tests {
742    use std::num::NonZeroUsize;
743    use std::time::Duration;
744
745    use aion::EventStreamLagged;
746    use aion_core::{Event, EventEnvelope, Payload, RunId, WorkflowId};
747    use chrono::Utc;
748    use futures::{StreamExt, stream};
749
750    use super::{close_after_terminal, map_lag, splice_resume};
751    use crate::error::ClientError;
752
753    fn workflow_id() -> WorkflowId {
754        WorkflowId::new(uuid::Uuid::from_u128(1))
755    }
756
757    fn envelope(seq: u64) -> EventEnvelope {
758        EventEnvelope {
759            seq,
760            recorded_at: Utc::now(),
761            workflow_id: workflow_id(),
762        }
763    }
764
765    fn signal(seq: u64) -> Result<Event, aion_core::PayloadError> {
766        Ok(Event::SignalReceived {
767            envelope: envelope(seq),
768            name: format!("signal-{seq}"),
769            payload: Payload::from_json(&serde_json::json!({ "seq": seq }))?,
770        })
771    }
772
773    fn completed(seq: u64) -> Result<Event, aion_core::PayloadError> {
774        Ok(Event::WorkflowCompleted {
775            envelope: envelope(seq),
776            result: Payload::from_json(&serde_json::json!({ "seq": seq }))?,
777        })
778    }
779
780    fn history(seqs: std::ops::RangeInclusive<u64>) -> Result<Vec<Event>, aion_core::PayloadError> {
781        seqs.map(signal).collect()
782    }
783
784    fn live(
785        items: Vec<Result<Event, EventStreamLagged>>,
786    ) -> futures::stream::BoxStream<'static, Result<Event, EventStreamLagged>> {
787        stream::iter(items).boxed()
788    }
789
790    async fn delivered_seqs(
791        events: futures::stream::BoxStream<'static, Result<Event, ClientError>>,
792    ) -> Result<Vec<u64>, ClientError> {
793        events
794            .map(|item| item.map(|event| event.seq()))
795            .collect::<Vec<_>>()
796            .await
797            .into_iter()
798            .collect()
799    }
800
801    #[tokio::test]
802    async fn cursor_zero_is_invalid_argument() -> Result<(), Box<dyn std::error::Error>> {
803        let error = splice_resume(live(Vec::new()), history(1..=3)?, 0).err();
804
805        let Some(ClientError::InvalidArgument { detail }) = error else {
806            return Err(format!("cursor 0 must be InvalidArgument, got {error:?}").into());
807        };
808        assert!(detail.message.contains(">= 1"), "detail: {detail}");
809        Ok(())
810    }
811
812    #[tokio::test]
813    async fn cursor_ahead_of_history_is_invalid_argument() -> Result<(), Box<dyn std::error::Error>>
814    {
815        let error = splice_resume(live(Vec::new()), history(1..=5)?, 7).err();
816
817        let Some(ClientError::InvalidArgument { detail }) = error else {
818            return Err(format!("cursor head+2 must be InvalidArgument, got {error:?}").into());
819        };
820        assert!(
821            detail.message.contains("ahead of recorded history"),
822            "{detail}"
823        );
824
825        let empty = splice_resume(live(Vec::new()), Vec::new(), 2).err();
826        assert!(
827            matches!(empty, Some(ClientError::InvalidArgument { .. })),
828            "cursor 2 over empty history must be rejected, got {empty:?}"
829        );
830        Ok(())
831    }
832
833    #[tokio::test]
834    async fn overlap_between_snapshot_and_live_is_deduplicated_contiguous_unique()
835    -> Result<(), Box<dyn std::error::Error>> {
836        // Snapshot holds 1..=5; the live broadcast re-emits 4 and 5 (arrived
837        // between attach and snapshot) before the genuinely new 6.
838        let events = splice_resume(
839            live(vec![Ok(signal(4)?), Ok(signal(5)?), Ok(signal(6)?)]),
840            history(1..=5)?,
841            1,
842        )?;
843
844        assert_eq!(delivered_seqs(events).await?, vec![1, 2, 3, 4, 5, 6]);
845        Ok(())
846    }
847
848    #[tokio::test]
849    async fn mid_history_cursor_replays_suffix_only() -> Result<(), Box<dyn std::error::Error>> {
850        let events = splice_resume(live(vec![Ok(signal(6)?)]), history(1..=5)?, 3)?;
851
852        assert_eq!(delivered_seqs(events).await?, vec![3, 4, 5, 6]);
853        Ok(())
854    }
855
856    #[tokio::test]
857    async fn cursor_at_head_plus_one_yields_empty_replay_and_live_tail_only()
858    -> Result<(), Box<dyn std::error::Error>> {
859        let events = splice_resume(
860            live(vec![Ok(signal(6)?), Ok(signal(7)?)]),
861            history(1..=5)?,
862            6,
863        )?;
864
865        assert_eq!(delivered_seqs(events).await?, vec![6, 7]);
866        Ok(())
867    }
868
869    #[tokio::test]
870    async fn lag_mid_splice_surfaces_unavailable_after_the_replay()
871    -> Result<(), Box<dyn std::error::Error>> {
872        let events = splice_resume(
873            live(vec![Err(EventStreamLagged { skipped: 3 })]),
874            history(1..=2)?,
875            1,
876        )?;
877        let collected: Vec<_> = events.collect().await;
878
879        assert_eq!(collected.len(), 3, "two replay events then the lag item");
880        assert!(collected[0].is_ok() && collected[1].is_ok());
881        assert!(
882            matches!(
883                collected[2].as_ref().err(),
884                Some(ClientError::Unavailable { .. })
885            ),
886            "lag must surface as retryable Unavailable, never a silent gap, got {:?}",
887            collected[2]
888        );
889        Ok(())
890    }
891
892    #[tokio::test]
893    async fn per_workflow_stream_closes_after_terminal_event()
894    -> Result<(), Box<dyn std::error::Error>> {
895        // Terminal at seq 3 mid-replay: deliver 1..=3 and close without
896        // draining the live tail (continue-as-new/terminal run boundary).
897        let mut history = history(1..=2)?;
898        history.push(completed(3)?);
899        history.push(signal(4)?);
900        let events = splice_resume(live(vec![Ok(signal(5)?)]), history, 1)?;
901
902        assert_eq!(
903            delivered_seqs(close_after_terminal(events)).await?,
904            vec![1, 2, 3],
905            "the stream must close after the terminal event"
906        );
907        Ok(())
908    }
909
910    #[tokio::test]
911    async fn live_lag_maps_to_unavailable() -> Result<(), Box<dyn std::error::Error>> {
912        let events = map_lag(live(vec![
913            Ok(signal(1)?),
914            Err(EventStreamLagged { skipped: 9 }),
915        ]));
916        let collected: Vec<_> = events.collect().await;
917
918        assert_eq!(collected.len(), 2);
919        assert!(
920            matches!(
921                collected[1].as_ref().err(),
922                Some(ClientError::Unavailable { .. })
923            ),
924            "got {:?}",
925            collected[1]
926        );
927        Ok(())
928    }
929
930    /// End-to-end through a real engine: the embedded resume splice delivers
931    /// recorded history and live appends gap-free and duplicate-free, built
932    /// on `Engine::subscribe` + `engine.store()` (the pin-note seams).
933    #[tokio::test]
934    async fn embedded_resume_splices_recorded_history_with_live_appends()
935    -> Result<(), Box<dyn std::error::Error>> {
936        use crate::stream::SubscribeTarget;
937        use crate::transport::{EmbeddedWorkflowTransport, WorkflowTransport};
938
939        let capacity = NonZeroUsize::new(16).ok_or("capacity must be non-zero")?;
940        let engine = std::sync::Arc::new(
941            aion::EngineBuilder::new()
942                .store(aion_store::InMemoryStore::default())
943                .in_memory_visibility()
944                .event_streaming(capacity)
945                .build()
946                .await?,
947        );
948        let workflow_id = WorkflowId::new_v4();
949        let mut recorder = aion::durability::Recorder::new(workflow_id.clone(), engine.store());
950        recorder
951            .record_workflow_started(
952                Utc::now(),
953                aion::durability::WorkflowStartRecord {
954                    workflow_type: String::from("checkout"),
955                    input: Payload::from_json(&serde_json::json!({ "cart": [] }))?,
956                    run_id: RunId::new(uuid::Uuid::from_u128(7)),
957                    parent_run_id: None,
958                    parent_workflow_id: None,
959                    package_version: aion_core::PackageVersion::new("a".repeat(64)),
960                },
961            )
962            .await?;
963        for seq in 2..=3 {
964            recorder
965                .record_signal_received(
966                    Utc::now(),
967                    format!("signal-{seq}"),
968                    Payload::from_json(&serde_json::json!({ "seq": seq }))?,
969                )
970                .await?;
971        }
972
973        // Resume from seq 2: replay [2, 3] from the snapshot, then splice the
974        // live append (4) with no gaps and no duplicates.
975        let transport = EmbeddedWorkflowTransport::new(std::sync::Arc::clone(&engine));
976        let request = SubscribeTarget::Workflow {
977            workflow_id: workflow_id.clone(),
978        }
979        .request("default");
980        let attempt = transport.subscribe(request, Some(2)).await?;
981        let mut events = attempt.events;
982
983        let mut delivered = Vec::new();
984        for _ in 0..2 {
985            let item = tokio::time::timeout(Duration::from_secs(2), events.next())
986                .await
987                .map_err(|_| "timed out waiting for a replay event")?
988                .ok_or("stream ended before the replay completed")?;
989            delivered.push(item?.seq());
990        }
991        recorder
992            .record_workflow_completed(
993                Utc::now(),
994                Payload::from_json(&serde_json::json!({ "done": true }))?,
995            )
996            .await?;
997        let item = tokio::time::timeout(Duration::from_secs(2), events.next())
998            .await
999            .map_err(|_| "timed out waiting for the live spliced event")?
1000            .ok_or("stream ended before the live event arrived")?;
1001        delivered.push(item?.seq());
1002        assert_eq!(delivered, vec![2, 3, 4]);
1003
1004        // Seq 4 is terminal: the per-workflow stream must now close.
1005        let end = tokio::time::timeout(Duration::from_secs(2), events.next())
1006            .await
1007            .map_err(|_| "timed out waiting for the post-terminal close")?;
1008        assert!(
1009            end.is_none(),
1010            "per-workflow stream must close after the terminal event, got {end:?}"
1011        );
1012
1013        // A cursor beyond head + 1 is rejected against the same engine.
1014        let ahead = transport
1015            .subscribe(
1016                SubscribeTarget::Workflow { workflow_id }.request("default"),
1017                Some(9),
1018            )
1019            .await
1020            .err();
1021        assert!(
1022            matches!(ahead, Some(ClientError::InvalidArgument { .. })),
1023            "cursor ahead of history must be InvalidArgument, got {ahead:?}"
1024        );
1025
1026        engine.shutdown()?;
1027        Ok(())
1028    }
1029
1030    /// 🔴 THE THREE CALL SITES THAT READ THE STORE DIRECTLY CARRY A ROUTABLE
1031    /// REFUSAL THROUGH — THEY DO NOT FLATTEN IT INTO "ENGINE BUG".
1032    ///
1033    /// [`map_engine_error`] is only reached by the eight operations that go
1034    /// through an engine API. Three do not: `resolve_run_id` reads the run
1035    /// chain, and `describe_workflow` and the resuming half of `subscribe` read
1036    /// history, all straight off `engine.store()`. Each of those refusals
1037    /// arrives as a bare [`aion_store::StoreError`] with no `EngineError` around
1038    /// it, and each was mapped by hand to `ClientError::server`.
1039    ///
1040    /// `not_owner` is the one store class that names a ROUTING failure — try a
1041    /// different owner, never this one. It is a distinction the CALLER acts on,
1042    /// not one this crate retries for it: `stream.rs`'s `is_retryable` matches
1043    /// only `ClientError::Unavailable`. Flattened to `server` the caller is told
1044    /// its request is unanswerable and gives up on work a re-route would have
1045    /// served, and no test could see the difference:
1046    /// [`aion_store::InMemoryStore`] owns every shard and so can never produce
1047    /// `NotOwner` at all. [`FencedHistoryStore`] is the instrument that can.
1048    ///
1049    /// The unarmed pass is the control. Without it an armed `not_owner` would be
1050    /// consistent with a fixture that never worked — the wrong workflow id, an
1051    /// engine that never built — and the test would be measuring its own setup.
1052    #[tokio::test]
1053    async fn a_directly_read_store_refusal_keeps_its_routing_class()
1054    -> Result<(), Box<dyn std::error::Error>> {
1055        use aion_store::testing::FencedHistoryStore;
1056
1057        use crate::stream::SubscribeTarget;
1058        use crate::transport::{EmbeddedWorkflowTransport, WorkflowTransport};
1059
1060        let capacity = NonZeroUsize::new(16).ok_or("capacity must be non-zero")?;
1061        let store = std::sync::Arc::new(FencedHistoryStore::new());
1062        let engine = std::sync::Arc::new(
1063            aion::EngineBuilder::new()
1064                .store_arc(
1065                    std::sync::Arc::clone(&store) as std::sync::Arc<dyn aion_store::EventStore>
1066                )
1067                .in_memory_visibility()
1068                .event_streaming(capacity)
1069                .build()
1070                .await?,
1071        );
1072        let workflow_id = WorkflowId::new_v4();
1073        let mut recorder = aion::durability::Recorder::new(workflow_id.clone(), engine.store());
1074        recorder
1075            .record_workflow_started(
1076                Utc::now(),
1077                aion::durability::WorkflowStartRecord {
1078                    workflow_type: String::from("checkout"),
1079                    input: Payload::from_json(&serde_json::json!({ "cart": [] }))?,
1080                    run_id: RunId::new(uuid::Uuid::from_u128(11)),
1081                    parent_run_id: None,
1082                    parent_workflow_id: None,
1083                    package_version: aion_core::PackageVersion::new("b".repeat(64)),
1084                },
1085            )
1086            .await?;
1087
1088        let transport = EmbeddedWorkflowTransport::new(std::sync::Arc::clone(&engine));
1089        let describe = |include_history: bool| aion_proto::ProtoDescribeWorkflowRequest {
1090            namespace: String::from("default"),
1091            workflow_id: Some(aion_proto::ProtoWorkflowId::from(workflow_id.clone())),
1092            run_id: None,
1093            include_history,
1094        };
1095
1096        // CONTROL, one per operation, so an armed `not_owner` below is
1097        // attributable to the fence rather than to a fixture that never reached
1098        // the read at all.
1099        //
1100        // 🔴 An earlier revision of this comment claimed "with the fence
1101        // disarmed every one of these succeeds" and ran a control for
1102        // `describe_workflow` only. That claim was not merely unproven, it was
1103        // impossible: this fixture records `WorkflowStarted` and nothing else,
1104        // so the run is NON-TERMINAL and `reopen_workflow` answers the AD-012
1105        // `invalid_state` this file names at `:486-487`. `reopen`'s control is
1106        // therefore the sharper one available — disarmed it must fail with some
1107        // class OTHER than `not_owner`, which still separates "the fence did
1108        // it" from "this call always fails".
1109        transport.describe_workflow(describe(true)).await?;
1110        transport
1111            .subscribe(
1112                SubscribeTarget::Workflow {
1113                    workflow_id: workflow_id.clone(),
1114                }
1115                .request("default"),
1116                Some(1),
1117            )
1118            .await?;
1119        let reopen_request = || aion_proto::ProtoReopenRequest {
1120            namespace: String::from("default"),
1121            workflow_id: Some(aion_proto::ProtoWorkflowId::from(workflow_id.clone())),
1122            run_id: None,
1123        };
1124        let reopen_control = transport.reopen(reopen_request()).await;
1125        assert_ne!(
1126            reopen_control.as_ref().err().map(ClientError::class),
1127            Some("not_owner"),
1128            "the reopen control answered `not_owner` with the fence DISARMED, so the armed \
1129             assertion below would prove nothing: {reopen_control:?}"
1130        );
1131
1132        store.arm_fence();
1133
1134        let described = transport.describe_workflow(describe(false)).await;
1135        assert_eq!(
1136            described.as_ref().err().map(ClientError::class),
1137            Some("not_owner"),
1138            "describe_workflow flattened a shard-ownership refusal into an unroutable class: \
1139             {described:?}"
1140        );
1141
1142        let subscribed = transport
1143            .subscribe(
1144                SubscribeTarget::Workflow {
1145                    workflow_id: workflow_id.clone(),
1146                }
1147                .request("default"),
1148                Some(1),
1149            )
1150            .await;
1151        assert_eq!(
1152            subscribed.as_ref().err().map(ClientError::class),
1153            Some("not_owner"),
1154            "the resuming half of subscribe flattened a shard-ownership refusal into an \
1155             unroutable class"
1156        );
1157
1158        // `resolve_run_id` reads the RUN CHAIN rather than history, and it is
1159        // reached only when the caller omits the run id — which is why
1160        // `reopen_request` carries `run_id: None`.
1161        let reopened = transport.reopen(reopen_request()).await;
1162        assert_eq!(
1163            reopened.as_ref().err().map(ClientError::class),
1164            Some("not_owner"),
1165            "resolve_run_id flattened a shard-ownership refusal into an unroutable class: \
1166             {reopened:?}"
1167        );
1168
1169        // Teardown, and the fence comes down FIRST. Every other engine-backed
1170        // test in this file shuts its engine down; this one left the engine to
1171        // `Drop`, which gates the epoch but cannot await, so teardown work that
1172        // must finish was left racing the test's exit. Disarming before the
1173        // shutdown means the shutdown is measured against an honest store — a
1174        // shutdown error arriving through `?` here would then be a real fault
1175        // and not the fixture fencing its own teardown's history access.
1176        store.disarm_fence();
1177        engine.shutdown()?;
1178        Ok(())
1179    }
1180
1181    /// Every arm this map NAMES must reach its own class, and the wildcard must
1182    /// still catch what it is for.
1183    ///
1184    /// 🔴 Structured as a table with a NEGATIVE control (`Runtime`), because the
1185    /// assertion that matters is not "these map somewhere" but "these map
1186    /// somewhere OTHER than the generic bucket". Without the control, deleting
1187    /// every named arm and returning `ClientError::server` for everything would
1188    /// still fail — but a test that only listed the named variants could not
1189    /// tell a correct map from one that had accidentally started naming
1190    /// everything.
1191    ///
1192    /// 🔴 EACH ERROR IS BUILT IN THE SHAPE PRODUCTION PRODUCES IT, NOT THE
1193    /// SHAPE THAT MAKES THE ARM LOOK COVERED.
1194    ///
1195    /// An earlier revision of this table listed a bare
1196    /// `Store(StoreError::NotOwner)` and passed — and the arm it exercised
1197    /// never fired on the shape a caller actually provokes. A fenced APPEND
1198    /// goes through the `Recorder`, which returns `DurabilityError`, so that
1199    /// path's caller-reachable shape is `Durability(Store(NotOwner))` — and
1200    /// against THAT shape the same table failed with `left: "backend"`.
1201    ///
1202    /// The bare shape is reachable too, and an earlier revision of THIS comment
1203    /// wrongly said it was not. `EngineError` carries `Store(#[from]
1204    /// StoreError)`, so every `?` on a store call inside an engine API that
1205    /// returns `EngineError` produces it: `list_workflows`
1206    /// (`api_workflow_ops.rs`, both `store.query` and `store.read_history`),
1207    /// `cancel` (`lifecycle/terminate.rs`) and `signal`
1208    /// (`engine/delegated.rs`) are three of the eight engine operations this
1209    /// transport calls, and all three are store READS rather than appends —
1210    /// which is precisely why no `Recorder` is involved and no `Durability`
1211    /// wrapper appears. Both shapes are listed below because both happen.
1212    ///
1213    /// ⚠️ WHAT THIS TEST DOES NOT DO. The classes are the same ones
1214    /// `aion-server`'s `error.rs` assigns, but this test cannot check that: the
1215    /// dependency runs server → client, so the server's table is not visible
1216    /// from here and these expectations are a TRANSCRIPTION of it. A rule
1217    /// written in two places with nothing forcing agreement has already
1218    /// drifted or will. What holds them together today is that a change to
1219    /// either side must be made deliberately on both; the durable fix is a
1220    /// shared classifier, which needs a crate both can depend on and is not in
1221    /// this change's scope. Naming it here rather than letting the doc comment
1222    /// imply a guarantee the test does not provide.
1223    #[test]
1224    fn every_named_engine_error_reaches_its_own_class() {
1225        use super::map_engine_error;
1226
1227        for (error, expected) in engine_error_class_table() {
1228            assert_eq!(
1229                map_engine_error(&error).class(),
1230                expected,
1231                "wrong class for {error}"
1232            );
1233        }
1234    }
1235
1236    /// F3: the CLASS is not the whole answer — `ShuttingDown` must also carry
1237    /// its discriminator, because the operator-facing hint keyed off a bare
1238    /// `not_running` tells them the run ended and points at `aion list`, which
1239    /// is false twice (the run is fine; that command fails the same way).
1240    ///
1241    /// The class-table test above is invariant to this: it asserts
1242    /// `"not_running"` and would stay green with the discriminator dropped.
1243    /// That is exactly why this assertion is separate.
1244    ///
1245    /// Killing mutation: revert the arm to `ClientError::not_running(...)`.
1246    /// `error_type` becomes `None` and the first assertion fails.
1247    #[test]
1248    fn shutting_down_carries_its_discriminator_not_only_its_class()
1249    -> Result<(), Box<dyn std::error::Error>> {
1250        let mapped = super::map_engine_error(&aion::EngineError::ShuttingDown);
1251        let ClientError::NotRunning { detail } = &mapped else {
1252            return Err(format!("ShuttingDown must keep the not_running CLASS: {mapped}").into());
1253        };
1254        assert_eq!(
1255            detail.error_type.as_deref(),
1256            Some("ShuttingDown"),
1257            "the wire surface builds `not_running_with_type(\"ShuttingDown\", …)`; an embedded \
1258             caller that loses the discriminator cannot be told anything true about why"
1259        );
1260        // CONTROL: a different error in the same class must NOT claim this
1261        // discriminator, or the assertion above would pass for anything.
1262        let other = super::map_engine_error(&aion::EngineError::Runtime {
1263            reason: "beamr scheduler refused".to_owned(),
1264        });
1265        assert_ne!(
1266            other.class(),
1267            "not_running",
1268            "control: the negative case must not share the class under test"
1269        );
1270        Ok(())
1271    }
1272
1273    /// The table itself, lifted out of the test body so the case list can grow
1274    /// with the taxonomy without the assertion loop growing at all, and split
1275    /// by family so each half stays readable.
1276    fn engine_error_class_table() -> Vec<(aion::EngineError, &'static str)> {
1277        let mut cases = admission_and_run_state_cases();
1278        cases.extend(store_and_query_cases());
1279        cases
1280    }
1281
1282    /// Refusals about the request, the run's state, or the engine's own
1283    /// availability — plus the negative control.
1284    fn admission_and_run_state_cases() -> Vec<(aion::EngineError, &'static str)> {
1285        use aion_core::{RunId, WorkflowId};
1286
1287        let version = aion::ContentHash::from_bytes([7u8; 32]);
1288        vec![
1289            // The two oldest named arms, and until this revision the only two
1290            // with no row: the table asserted every arm reached its own class
1291            // while silently omitting them, so either could have been deleted
1292            // and every assertion here would still have passed.
1293            (
1294                aion::EngineError::WorkflowNotFound {
1295                    workflow_type: "orders".to_owned(),
1296                },
1297                "not_found",
1298            ),
1299            (
1300                aion::EngineError::InvalidState {
1301                    reason: "workflow w run r is Running, not terminal".to_owned(),
1302                },
1303                "invalid_state",
1304            ),
1305            (
1306                aion::EngineError::StartInputRefused {
1307                    workflow_type: "orders".to_owned(),
1308                    version: version.clone(),
1309                    reason: "field `total` is missing".to_owned(),
1310                },
1311                "invalid_input",
1312            ),
1313            (
1314                aion::EngineError::SignalRefused {
1315                    workflow_id: WorkflowId::new_v4(),
1316                    run_id: RunId::new_v4(),
1317                    signal_name: "approve".to_owned(),
1318                    version,
1319                    reason: "undeclared signal".to_owned(),
1320                },
1321                "invalid_input",
1322            ),
1323            (
1324                aion::EngineError::TerminalWriterUnavailable {
1325                    workflow_id: "w".to_owned(),
1326                    run_id: "r".to_owned(),
1327                    holder: "another reservation".to_owned(),
1328                },
1329                "invalid_state",
1330            ),
1331            (
1332                aion::EngineError::TerminalWriterHeld {
1333                    workflow_id: "w".to_owned(),
1334                    run_id: "r".to_owned(),
1335                },
1336                "invalid_state",
1337            ),
1338            (
1339                aion::EngineError::RunIsRecoverable {
1340                    workflow_id: "w".to_owned(),
1341                    run_id: "r".to_owned(),
1342                    version: "abc".to_owned(),
1343                },
1344                "invalid_state",
1345            ),
1346            (
1347                aion::EngineError::NoResidencyVerdict {
1348                    workflow_id: "w".to_owned(),
1349                    run_id: "r".to_owned(),
1350                },
1351                "invalid_state",
1352            ),
1353            (
1354                aion::EngineError::ContractIdentity {
1355                    workflow_type: "orders".to_owned(),
1356                    source: aion::ContractIdentityError::RedeployRequired {
1357                        stored_version: "orders$deadbeef".to_owned(),
1358                    },
1359                },
1360                "invalid_state",
1361            ),
1362            (
1363                aion::EngineError::NoQueueDeclaration {
1364                    workflow_type: "orders".to_owned(),
1365                    version: aion::ContentHash::from_bytes([5u8; 32]),
1366                    activities: "charge_card,send_receipt".to_owned(),
1367                },
1368                "invalid_state",
1369            ),
1370            (aion::EngineError::ShuttingDown, "not_running"),
1371            // The control: a variant this map does NOT name must still land in
1372            // the generic bucket. If it stops doing so, the wildcard has been
1373            // replaced by something that names everything, and the assertions
1374            // above would have passed for the wrong reason.
1375            (
1376                aion::EngineError::Runtime {
1377                    reason: "beamr scheduler refused".to_owned(),
1378                },
1379                "backend",
1380            ),
1381        ]
1382    }
1383
1384    /// The two nested families, each of which reaches this map wrapped in an
1385    /// outer `EngineError` variant rather than as itself.
1386    fn store_and_query_cases() -> Vec<(aion::EngineError, &'static str)> {
1387        use aion_core::WorkflowId;
1388
1389        vec![
1390            (
1391                aion::EngineError::Store(aion_store::StoreError::NotOwner { shard: 3 }),
1392                "not_owner",
1393            ),
1394            // 🔴 The shape a caller actually gets: the fence is raised inside a
1395            // recorded append, so it arrives wrapped in `Durability`.
1396            (
1397                aion::EngineError::Durability(aion::durability::DurabilityError::Store(
1398                    aion_store::StoreError::NotOwner { shard: 3 },
1399                )),
1400                "not_owner",
1401            ),
1402            (
1403                aion::EngineError::Durability(aion::durability::DurabilityError::Store(
1404                    aion_store::StoreError::NotFound {
1405                        workflow_id: WorkflowId::new_v4(),
1406                    },
1407                )),
1408                "not_found",
1409            ),
1410            // The store family's own control: a store fault that is genuinely
1411            // the engine's problem must NOT acquire a caller-facing class just
1412            // because it arrived through the same helper.
1413            (
1414                aion::EngineError::Durability(aion::durability::DurabilityError::Store(
1415                    aion_store::StoreError::SequenceConflict {
1416                        expected: 4,
1417                        found: 7,
1418                    },
1419                )),
1420                "backend",
1421            ),
1422            (
1423                aion::EngineError::Query(aion::QueryError::UnknownQuery("balance".to_owned())),
1424                "unknown_query",
1425            ),
1426            (
1427                aion::EngineError::Query(aion::QueryError::Timeout),
1428                "query_timeout",
1429            ),
1430            (
1431                aion::EngineError::Query(aion::QueryError::NotRunning(WorkflowId::new_v4())),
1432                "not_running",
1433            ),
1434            (
1435                aion::EngineError::Query(aion::QueryError::ReplyDropped),
1436                "not_running",
1437            ),
1438            (
1439                aion::EngineError::Query(aion::QueryError::Unknown(WorkflowId::new_v4())),
1440                "not_found",
1441            ),
1442            (
1443                aion::EngineError::Query(aion::QueryError::HandlerFailed {
1444                    message: "handler panicked".to_owned(),
1445                }),
1446                "query_failed",
1447            ),
1448            // The caller's own arguments were malformed: the request is the
1449            // thing to fix, so this is `invalid_argument` — not the handler's
1450            // failure and not the engine's.
1451            (
1452                aion::EngineError::Query(aion::QueryError::InvalidArguments {
1453                    reason: "arguments payload is not a well-formed JSON document".to_owned(),
1454                }),
1455                "invalid_input",
1456            ),
1457            // The query family's own control, and the eighth of eight arms —
1458            // an earlier revision of this table listed six and left this one
1459            // unmeasured, so a change re-classifying an engine-seam failure as
1460            // a caller-facing one survived green. A seam that could not deliver
1461            // the query is the ENGINE's failure, not the caller's, and must
1462            // land in the generic bucket rather than acquire a remedy the
1463            // caller cannot act on.
1464            (
1465                aion::EngineError::Query(aion::QueryError::Engine(
1466                    aion::engine_seam::EngineSeamError::Delivery {
1467                        reason: "mailbox send failed".to_owned(),
1468                    },
1469                )),
1470                "backend",
1471            ),
1472        ]
1473    }
1474}