engine.rs
cdk-rsx/crates/cdk-rsx-takt/src/engine.rs
1//! One typed engine binding; borrowed views reuse the caller's root frame.2mod commit;3#[cfg(test)]4mod save_tests;56use crate::ready::ReadyQueue;7use crate::{Error, PayloadSize, Result};8use crate::{9 memory::{cell::Cell as NyxusCell, current as Mem},10 runtime::{Runtime, RuntimeView},11 state::*,12 types::*,13};14use cdk_rsx_collections::nyxus::{15 Map as SavedMap, Queue as SavedQueue, Rc as SavedRc, SharedSlice,16};17use cdk_rsx_reactor::{WorkPriority, scheduler::Readiness};18use cdk_rsx_store::{19 Access, ModuleRef, Scope,20 binding::{Memory, MemoryView},21};22use std::{cell::RefCell, collections::BTreeMap, ops::Deref, rc::Rc};2324struct PayloadSizing<D, E> {25 data: Option<fn(&D) -> usize>,26 error: Option<fn(&E) -> usize>,27}2829pub struct Engine<D: PayloadContract, E: PayloadContract> {30 namespace: u64,31 settings: Settings,32 state: Memory<Mem::Workflow<D, E>>,33 runtime: Rc<Runtime>,34 payload_sizing: std::cell::OnceCell<PayloadSizing<D, E>>,35 // Immutable compiled input witness and its namespace-bound identity. Both36 // are transient; no per-record metadata or repeated hashing is required.37 local_definition: std::cell::Cell<Option<([u8; 32], [u8; 32])>>,38}39/// Query/update operations on one already-open actor frame.40pub struct EngineView<'a, A: Access, D: PayloadContract, E: PayloadContract> {41 engine: &'a Engine<D, E>,42 state: MemoryView<'a, A, Mem::Workflow<D, E>>,43 runtime: RuntimeView<'a, A>,44 access: &'a A,45}46impl<A: Access, D: PayloadContract, E: PayloadContract> Deref for EngineView<'_, A, D, E> {47 type Target = Engine<D, E>;48 fn deref(&self) -> &Self::Target {49 self.engine50 }51}52#[cdk_rsx::service_view(view = EngineView<'a, A, D, E>)]53impl<D, E> Engine<D, E>54where55 D: PayloadContract + PayloadSize + Clone,56 E: PayloadContract + PayloadSize + Clone,57{58 pub fn bind(59 reference: ModuleRef<Mem::Workflow<D, E>>,60 namespace: u64,61 settings: Settings,62 runtime: Rc<Runtime>,63 ) -> Result<Self> {64 if settings.max_pending == 065 || settings.max_concurrent == 066 || settings.max_nodes == 067 || settings.max_nodes > 12868 || settings.max_results == 069 || settings.result_retention_nanos == 070 || settings.max_data_bytes == 071 || settings.max_error_bytes == 072 || settings.trace_events > 409673 {74 return Err(Error::InvalidInput("invalid workflow storage bounds"));75 }76 Ok(Self {77 namespace,78 settings,79 state: Mem::Workflow::bind(reference),80 runtime,81 payload_sizing: std::cell::OnceCell::new(),82 local_definition: std::cell::Cell::new(None),83 })84 }85 pub fn view<'a, A: Access>(&'a self, access: &'a A) -> EngineView<'a, A, D, E> {86 EngineView {87 engine: self,88 state: self.state.view(access),89 runtime: self.runtime.view(access),90 access,91 }92 }93 pub fn runtime_handle(&self) -> Rc<Runtime> {94 self.runtime.clone()95 }96 /// Bind the compiled callback bounds once per actor lifetime. The shared97 /// driver does this at startup; raw hosts must also bind after reopening98 /// memory, before delivering replies or resolving saved work.99 pub fn bind_definition<F: Definition<Data = D, Error = E>>(&self) -> Result<Option<[u8; 32]>> {100 // The ordinary PayloadSize path compiles this entire branch away.101 if F::DATA_BYTES.is_some() || F::ERROR_BYTES.is_some() {102 self.payload_sizing.get_or_init(|| PayloadSizing {103 data: F::DATA_BYTES,104 error: F::ERROR_BYTES,105 });106 }107 let (signature, identity) = const { definition_signature::<F>() };108 if F::LOCAL_UPGRADE_SOURCE.is_none() {109 return Ok(signature);110 }111 if let Some((expected, bound)) = self.local_definition.get() {112 if expected != identity {113 return Err(Error::InvalidInput("bound local-work definition differs"));114 }115 return Ok(Some(bound));116 }117 let mut namespace = [0u8; 32];118 namespace[..8].copy_from_slice(&self.namespace.to_le_bytes());119 let bound = cdk_rsx_memory_abi::semantic_contract(120 "takt/namespace-bound-local-definition/v1",121 &[],122 &[identity, namespace],123 );124 self.local_definition.set(Some((identity, bound)));125 Ok(Some(bound))126 }127 pub fn namespace(&self) -> Result<u64> {128 Ok(self.namespace)129 }130}131/// Immutable prepared effect data. Retry tickets share its retained allocation.132#[derive(Clone, Debug, PartialEq, Eq)]133pub struct PreparedRequest(SavedRc<SavedRequest>);134impl PreparedRequest {135 pub fn canister(&self) -> Principal {136 self.0.canister137 }138 pub fn caller(&self) -> Principal {139 self.0.caller140 }141 pub fn route(&self) -> &str {142 self.0.route.as_str()143 }144 pub fn reader_version(&self) -> u32 {145 self.0.reader_version146 }147 pub fn args(&self) -> &[u8] {148 self.0.args.as_slice()149 }150 pub(crate) fn saved_args(&self) -> SharedSlice<u8> {151 self.0.args.clone()152 }153 pub fn expires_at(&self) -> Option<u64> {154 self.0.expires_at.into_option()155 }156 pub fn transport(&self) -> Transport {157 self.0.transport158 }159 pub fn priority(&self) -> Priority {160 self.0.priority161 }162}163impl From<Request> for PreparedRequest {164 fn from(value: Request) -> Self {165 Self(SavedRc::new(value.retain()))166 }167}168#[derive(Clone, Debug)]169pub struct CallTicket {170 pub context: Context,171 pub request: PreparedRequest,172}173#[derive(Clone, Debug)]174pub struct HandlerTicket {175 pub context: Context,176 pub node: u32,177}178#[derive(Clone, Debug)]179pub enum Run {180 Idle,181 Progress,182 Call(CallTicket),183 Handler(HandlerTicket),184}185#[derive(Clone, Debug)]186pub struct NodeSnapshot<D, E> {187 pub key: Key,188 pub operation_key: Option<Key>,189 pub parent: Option<(u32, u32)>,190 pub children: Vec<u32>,191 pub remaining: u32,192 pub failure: Option<Failure<E>>,193 pub confirmed_success: bool,194 pub step: u32,195 pub data: D,196 pub phase: Phase,197 pub attempt: u32,198 pub uncertain: bool,199 pub wake_at: Option<u64>,200 pub external: Option<ExternalAddress>,201 pub request: Option<Request>,202}203#[derive(Clone, Debug)]204pub struct Snapshot<D, E> {205 pub id: u64,206 pub version: u32,207 /// Saved executable identity; a numeric version alone cannot identify a graph.208 pub signature: Option<[u8; 32]>,209 pub input: D,210 pub status: crate::Status<D, E>,211 pub created_at: u64,212 pub finished_at: Option<u64>,213 pub expires_at: Option<u64>,214 pub nodes: Vec<NodeSnapshot<D, E>>,215}216217#[derive(Clone, Copy, Debug, Default)]218pub struct HistoryMetadata {219 pub first_sequence: u64,220 pub next_sequence: u64,221 pub retained: u64,222 pub capacity: u64,223 pub first_at: Option<u64>,224 pub last_at: Option<u64>,225}226227/// Indexed, inclusive cursor paging over this workflow's retained executions.228#[derive(Clone, Debug)]229pub struct ExecutionPage<D, E> {230 pub entries: Vec<Snapshot<D, E>>,231 pub next_from: Option<u64>,232}233234impl<235 'a,236 A: Access,237 D: PayloadContract + PayloadSize + Clone,238 E: PayloadContract + PayloadSize + Clone,239> EngineView<'a, A, D, E>240{241 fn read_state(&self) -> Result<cdk_rsx_store::Data<'_, State<D, E>>> {242 Ok(self.state.read()?)243 }244 fn execution(&self, id: u64) -> Result<Option<Execution<D, E>>> {245 Ok(self.read_state()?.executions.get(&id).cloned())246 }247 fn node_entry(&self, e: &Execution<D, E>, id: u32) -> Result<Option<Node<D, E>>> {248 Ok(e.nodes.read(self.access)?.get(&id).cloned())249 }250 /// Copy only an operation's callback inputs, never a complete saved row.251 /// This private projection must not call application code or return loans.252 fn inspect_key<R>(253 &self,254 key: Key,255 inspect: impl FnOnce(&Execution<D, E>, &Node<D, E>) -> R,256 ) -> Result<Option<R>> {257 if key.namespace != self.namespace {258 return Ok(None);259 }260 let state = self.read_state()?;261 let Some(execution) = state.executions.get(&key.execution) else {262 return Ok(None);263 };264 let nodes = execution.nodes.read(self.access)?;265 let Some(node) = nodes.get(&key.node) else {266 return Ok(None);267 };268 if node.visit != key.visit269 || (execution.version != key.version270 && !node.task.as_ref().is_some_and(|task| task.key == key))271 {272 return Ok(None);273 }274 Ok(Some(inspect(execution, node)))275 }276 fn load_failure(failure: &Failure<SavedRc<E>>) -> Failure<E> {277 match failure {278 Failure::App(e) => Failure::App((**e).clone()),279 Failure::Unknown => Failure::Unknown,280 Failure::Timeout => Failure::Timeout,281 Failure::Capacity => Failure::Capacity,282 }283 }284 fn load_status(status: &SharedStatus<D, E>) -> Status<D, E> {285 match status {286 SharedStatus::Running => Status::Running,287 SharedStatus::Succeeded(d) => Status::Succeeded((**d).clone()),288 SharedStatus::Failed(e) => Status::Failed(Self::load_failure(e)),289 }290 }291 pub fn execution_page(&self, from: Option<u64>, limit: usize) -> Result<ExecutionPage<D, E>> {292 let limit = limit.clamp(1, 128);293 let keys = self294 .read_state()?295 .executions296 .range(from.unwrap_or(0)..)297 .take(limit + 1)298 .map(|(&k, _)| k)299 .collect::<Vec<_>>();300 let next_from = keys.get(limit).copied();301 let entries = keys302 .into_iter()303 .take(limit)304 .map(|id| self.snapshot(id).map(|e| e.expect("current execution")))305 .collect::<Result<_>>()?;306 Ok(ExecutionPage { entries, next_from })307 }308 pub fn snapshot(&self, id: u64) -> Result<Option<Snapshot<D, E>>> {309 let Some(e) = self.execution(id)? else {310 return Ok(None);311 };312 let nodes = e313 .nodes314 .read(self.access)?315 .values()316 .map(|n| NodeSnapshot {317 key: Self::key(self.namespace, &e, n),318 operation_key: n.task.as_ref().map(|t| t.key),319 parent: n.parent.map(|p| (p.node, p.branch)),320 children: n321 .children322 .as_ref()323 .map_or_else(Vec::new, |children| children.as_slice().to_vec()),324 remaining: n.remaining,325 failure: n.task.as_ref().and_then(|t| match t.reply.as_ref() {326 Some(SharedOutcome::Err(e)) => Some(Self::load_failure(e)),327 _ => None,328 }),329 confirmed_success: n330 .task331 .as_ref()332 .is_some_and(|t| matches!(t.reply.as_ref(), Some(SharedOutcome::Ok(_)))),333 step: n.step,334 data: (*n.data).clone(),335 phase: n.phase,336 attempt: n.task.as_ref().map_or(0, |t| t.attempt),337 uncertain: n.task.as_ref().is_some_and(|t| t.uncertain),338 wake_at: n.wake.map(|w| w.at),339 external: n.task.as_ref().and_then(|t| t.external.into_option()),340 request: n341 .task342 .as_ref()343 .and_then(|t| t.request.as_deref())344 .map(SavedRequest::snapshot),345 })346 .collect();347 Ok(Some(Snapshot {348 id: e.id,349 version: e.version,350 signature: e.signature.into_option(),351 input: (*e.input).clone(),352 status: Self::load_status(&e.status),353 created_at: e.created_at,354 finished_at: e.finished_at.into_option(),355 expires_at: e.expiry.map(|k| k.at),356 nodes,357 }))358 }359 pub fn status(&self, id: u64, now: u64) -> Result<Option<Snapshot<D, E>>> {360 Ok(self361 .snapshot(id)?362 .filter(|e| e.expires_at.is_none_or(|at| now < at)))363 }364 pub fn tracing(&self, id: u64) -> Result<Option<(bool, u64)>> {365 Ok(self366 .execution(id)?367 .map(|e| (e.history.is_some(), e.trace_generation)))368 }369 pub fn runtime_handle(&self) -> Rc<Runtime> {370 self.engine.runtime.clone()371 }372 pub fn namespace(&self) -> Result<u64> {373 Ok(self.namespace)374 }375 pub fn pending(&self) -> Result<u32> {376 Ok(self.read_state()?.pending)377 }378 pub(crate) fn local_upgrade(&self, version: u32, signature: Option<[u8; 32]>) -> Result<u32> {379 self.pending_upgrade(version, signature, None)380 }381382 /// Only the registered lifecycle driver invokes this cold state scan.383 pub(crate) fn pending_upgrade(384 &self,385 version: u32,386 signature: Option<[u8; 32]>,387 mut replies: Option<&mut Vec<crate::driver::PendingReply>>,388 ) -> Result<u32> {389 let state = self.read_state()?;390 if (replies.is_none() && state.logical_calls != 0)391 || state.active_calls != 0392 || !state.physical.is_empty()393 {394 return Err(Error::InvalidInput("local-work KEEP has remote call state"));395 }396 let first_reply = replies.as_ref().map_or(0, |replies| replies.len());397 let mut queued = BTreeMap::new();398 for (queue, coordinated) in [(&state.calls, false), (&state.coordinated, true)] {399 for work in queue {400 if queued.insert(*work, coordinated).is_some() {401 return Err(Error::Corrupt("duplicate workflow call queue entry"));402 }403 }404 }405 let mut received = BTreeMap::new();406 let mut pending = 0u32;407 for execution in state.executions.values() {408 if !matches!(execution.status, SharedStatus::Running) {409 continue;410 }411 if signature.is_none()412 || execution.version != version413 || execution.signature.as_ref().copied() != signature414 {415 return Err(Error::InvalidInput("local-work KEEP definition differs"));416 }417 let nodes = execution.nodes.read(self.access)?;418 for node in nodes.values() {419 let eligible = match (node.phase, node.task.as_ref()) {420 (Phase::Ready | Phase::Waiting | Phase::Joining, None) => {421 node.producer.is_none()422 }423 (Phase::Calling | Phase::QueuedCall | Phase::Received, Some(task))424 if node.producer.is_none()425 && !node.visit_finished426 && !task.uncertain427 && task.key == Self::key(self.namespace, execution, node) =>428 {429 let work = Self::work(execution, node);430 if node.phase == Phase::Calling {431 let (Some(replies), Some(request), Some(address), Some(wake)) = (432 replies.as_mut(),433 task.request.as_ref(),434 task.external.into_option(),435 node.wake.as_ref(),436 ) else {437 return Err(Error::InvalidInput("queued-reply KEEP has an unowned call"));438 };439 if task.handler440 || request.transport != Transport::Reactor441 || task.attempt != 1442 || task.retries != [0; 16]443 || task.resolved_through != 0444 || task.reply.is_some()445 || node.queued446 || !matches!(state.wakes.get(wake), Some(Wake::Node(owner)) if *owner == work)447 {448 return Err(Error::InvalidInput("queued-reply KEEP has an ineligible call"));449 }450 let address = cdk_rsx_reactor::Address {451 canister: address.canister,452 id: address.id,453 };454 replies.push((455 crate::driver::Target { key: task.key, attempt: task.attempt, address },456 cdk_rsx_reactor::QueuedReply {457 address,458 producer: request.canister,459 route: request.route.as_str().into(),460 },461 ));462 continue;463 }464 if node.wake.is_some() || task.external.is_some() {465 return Err(Error::InvalidInput("local-work KEEP has an addressed task"));466 }467 let coordinated = match (task.handler, task.request.as_ref()) {468 (true, None) => Some(false),469 (false, Some(request)) => Some(request.transport == Transport::Reactor),470 _ => None,471 };472 if node.phase == Phase::QueuedCall {473 task.attempt == 0474 && task.retries == [0; 16]475 && task.resolved_through == 0476 && task.reply.is_none()477 && !node.queued478 && coordinated479 .is_some_and(|lane| queued.remove(&work) == Some(lane))480 } else {481 task.attempt > 0482 && coordinated == Some(false)483 && node.queued484 && matches!(485 task.reply.as_ref(),486 Some(487 SharedOutcome::Ok(_) | SharedOutcome::Err(Failure::App(_))488 )489 )490 && received.insert(work, false).is_none()491 }492 }493 _ => false,494 };495 if !eligible {496 return Err(Error::InvalidInput(497 "local-work KEEP has nonlocal or uncertain nodes",498 ));499 }500 }501 pending = pending.checked_add(1).ok_or(Error::Overflow)?;502 }503 if pending != state.pending {504 return Err(Error::Corrupt("local-work pending accounting"));505 }506 if replies.is_some_and(|replies| replies.len() - first_reply != state.logical_calls as usize) {507 return Err(Error::Corrupt("queued-reply workflow accounting"));508 }509 if !queued.is_empty() {510 return Err(Error::Corrupt("unmatched workflow call queue entry"));511 }512 if !received.is_empty() {513 for work in &state.ready {514 if let Some(seen) = received.get_mut(work)515 && std::mem::replace(seen, true)516 {517 return Err(Error::Corrupt("duplicate workflow reply queue entry"));518 }519 }520 if received.values().any(|&seen| !seen) {521 return Err(Error::Corrupt("missing workflow reply queue entry"));522 }523 }524 Ok(pending)525 }526 pub fn physical_calls(&self) -> Result<u32> {527 Ok(self.read_state()?.active_calls)528 }529 pub fn deadline(&self) -> Result<Option<u64>> {530 Ok(self531 .read_state()?532 .wakes533 .first_key_value()534 .map(|(k, _)| k.at))535 }536 fn has_ready_in(&self, s: &State<D, E>) -> Result<bool> {537 Ok(!s.ready.is_empty()538 || (s.logical_calls < self.settings.max_concurrent539 && ((!s.calls.is_empty()540 && s.active_calls < self.settings.max_concurrent.saturating_mul(4).min(64)541 && self.runtime.can_start(true)?)542 || (!s.coordinated.is_empty() && self.runtime.can_start(false)?))))543 }544 pub fn has_ready(&self) -> Result<bool> {545 let state = self.read_state()?;546 self.has_ready_in(&state)547 }548 pub fn readiness(&self, now: u64) -> Result<Readiness<WorkPriority>> {549 let state = self.read_state()?;550 let deadline = state.wakes.first_key_value().map(|(key, _)| key.at);551 Ok(Readiness {552 priority: if self.has_ready_in(&state)? || deadline.is_some_and(|at| at <= now) {553 Some(WorkPriority::Interactive)554 } else {555 None556 },557 deadline,558 backlog: u64::from(state.pending),559 })560 }561 pub fn history_metadata(&self, id: u64) -> Result<HistoryMetadata> {562 let Some(e) = self.execution(id)? else {563 return Ok(HistoryMetadata::default());564 };565 let Some(history) = e.history.into_option() else {566 return Ok(HistoryMetadata::default());567 };568 let history = history.read(self.access)?;569 Ok(HistoryMetadata {570 first_sequence: history.front().map_or(e.trace_sequence, |e| e.sequence),571 next_sequence: e.trace_sequence,572 retained: history.len() as u64,573 capacity: e.history_capacity as u64,574 first_at: history.front().map(|e| e.at),575 last_at: history.back().map(|e| e.at),576 })577 }578 pub fn history(&self, id: u64, from: u64, limit: usize) -> Result<Vec<TraceEvent>> {579 let Some(e) = self.execution(id)? else {580 return Ok(Vec::new());581 };582 let Some(history) = e.history.as_ref() else {583 return Ok(Vec::new());584 };585 let events = history586 .read(self.access)?587 .iter()588 .filter(|e| e.sequence >= from)589 .take(limit.min(128))590 .copied()591 .collect();592 Ok(events)593 }594595 fn key(namespace: u64, e: &Execution<D, E>, n: &Node<D, E>) -> Key {596 Key {597 namespace,598 execution: e.id,599 node: n.id,600 visit: n.visit,601 version: e.version,602 }603 }604 fn work(e: &Execution<D, E>, n: &Node<D, E>) -> Work {605 Work {606 execution: e.id,607 node: n.id,608 visit: n.visit,609 }610 }611 fn fits<T: PayloadSize>(v: &T, max: u32) -> bool {612 T::FIXED_BYTES.is_some_and(|n| n <= max as usize) || v.payload_bytes() <= max as usize613 }614 fn data_fits<F: Definition<Data = D, Error = E>>(_def: &F, v: &D, max: u32) -> bool {615 F::DATA_BYTES.map_or_else(|| Self::fits(v, max), |size| size(v) <= max as usize)616 }617 fn error_fits<F: Definition<Data = D, Error = E>>(_def: &F, v: &E, max: u32) -> bool {618 F::ERROR_BYTES.map_or_else(|| Self::fits(v, max), |size| size(v) <= max as usize)619 }620 fn callback_data_fits(&self, value: &D) -> bool {621 self.payload_sizing.get().and_then(|s| s.data).map_or_else(622 || Self::fits(value, self.settings.max_data_bytes),623 |size| size(value) <= self.settings.max_data_bytes as usize,624 )625 }626 fn callback_error_fits(&self, value: &E) -> bool {627 self.payload_sizing.get().and_then(|s| s.error).map_or_else(628 || Self::fits(value, self.settings.max_error_bytes),629 |size| size(value) <= self.settings.max_error_bytes as usize,630 )631 }632 fn node(id: u32, step: u32, data: SavedRc<D>, parent: Option<Parent>) -> Node<D, E> {633 Node {634 id,635 parent: parent.into(),636 step,637 data,638 visit: 0,639 visit_finished: false,640 phase: Phase::Ready,641 task: (None).into(),642 wake: (None).into(),643 queued: false,644 continuation: (None).into(),645 producer: (None).into(),646 children: (None).into(),647 results: (None).into(),648 remaining: 0,649 }650 }651 fn context<F: Definition<Data = D, Error = E>>(652 &self,653 e: &Execution<D, E>,654 n: &Node<D, E>,655 def: &F,656 now: u64,657 ) -> Result<Context> {658 let key = Self::key(self.namespace, e, n);659 let policy = def.policy(n.step);660 Ok(Context {661 key: n.task.as_ref().map_or(key, |t| t.key),662 attempt: n.task.as_ref().map_or(1, |t| t.attempt),663 now,664 call_timeout_millis: policy.call_timeout_millis,665 next_event: if def.next_event(n.step) {666 Some(Key {667 visit: key.visit.checked_add(1).ok_or(Error::Overflow)?,668 ..key669 })670 } else {671 None672 },673 })674 }675 fn replay_allowed(n: &Node<D, E>, now: u64) -> bool {676 n.task.as_ref().is_none_or(|t| {677 t.safety != Safety::Idempotent || t.safe_until.is_none_or(|at| now < at)678 })679 }680 fn locate_visit(&self, key: Key) -> Outcome<(Execution<D, E>, Node<D, E>)> {681 if key.namespace != self.namespace {682 return Ok(Err(Problem::StaleKey));683 }684 let Some(e) = self.execution(key.execution)? else {685 return Ok(Err(Problem::Missing));686 };687 let Some(n) = self.node_entry(&e, key.node)? else {688 return Ok(Err(Problem::Missing));689 };690 if n.visit != key.visit {691 return Ok(Err(Problem::Missing));692 }693 Ok(Ok((e, n)))694 }695 fn locate_key(&self, key: Key) -> Result<Option<(Execution<D, E>, Node<D, E>)>> {696 let (e, n) = match self.locate_visit(key)? {697 Ok(value) => value,698 Err(_) => return Ok(None),699 };700 if e.version != key.version && !n.task.as_ref().is_some_and(|t| t.key == key) {701 return Ok(None);702 }703 Ok(Some((e, n)))704 }705 fn retry_candidate(706 &self,707 e: &Execution<D, E>,708 n: &Node<D, E>,709 key: Key,710 now: u64,711 ) -> std::result::Result<(), Problem> {712 if !matches!(e.status, SharedStatus::Running) {713 return Err(Problem::StaleKey);714 }715 if !matches!(n.phase, Phase::Blocked(_)) {716 return Err(Problem::NotBlocked);717 }718 if matches!(n.phase, Phase::Blocked(BlockReason::StorageLimit)) {719 return Err(Problem::UnsafeRetry);720 }721 let Some(t) = n.task.as_ref() else {722 return Err(Problem::NotBlocked);723 };724 if t.key != key {725 return Err(Problem::StaleKey);726 }727 if t.external.is_some() {728 return Err(Problem::Pending);729 }730 if (t.uncertain && t.safety == Safety::Reconcile) || !Self::replay_allowed(n, now) {731 return Err(Problem::UnsafeRetry);732 }733 Ok(())734 }735 pub(crate) fn resolution_task(736 &self,737 key: Key,738 now: u64,739 ) -> Outcome<(Context, Option<ExternalAddress>)> {740 let (e, n) = match self.locate_visit(key)? {741 Ok(v) => v,742 Err(p) => return Ok(Err(p)),743 };744 if !matches!(e.status, SharedStatus::Running) {745 return Ok(Err(Problem::StaleKey));746 }747 if !matches!(n.phase, Phase::Blocked(_)) {748 return Ok(Err(Problem::NotBlocked));749 }750 let Some(t) = n.task.as_ref() else {751 return Ok(Err(Problem::NotBlocked));752 };753 if t.key != key {754 return Ok(Err(Problem::StaleKey));755 }756 Ok(Ok((757 Context {758 key: t.key,759 attempt: t.attempt,760 now,761 call_timeout_millis: 0,762 next_event: None,763 },764 t.external.into_option(),765 )))766 }767}768impl<'a, 's, D: PayloadContract + PayloadSize + Clone, E: PayloadContract + PayloadSize + Clone>769 EngineView<'a, Scope<'s>, D, E>770{771 fn write_state(&self) -> Result<cdk_rsx_store::DataMut<'_, State<D, E>>> {772 Ok(self.state.write()?)773 }774 fn insert_execution(&self, e: Execution<D, E>) -> Result<()> {775 self.write_state()?.executions.insert(e.id, e);776777 Ok(())778 }779 fn insert_node(&self, e: &Execution<D, E>, n: Node<D, E>) -> Result<()> {780 e.nodes.write(self.state.scope())?.insert(n);781782 Ok(())783 }784 /// Replace an existing detached row without passing it through an owned785 /// map insertion/result. The caller releases the displaced owners after786 /// this guard ends. Keep missing-row insertion semantics for reentrant code.787 fn save_execution(&self, e: &mut Execution<D, E>) -> Result<()> {788 {789 let mut state = self.write_state()?;790 if let Some(saved) = state.executions.get_mut(&e.id) {791 commit::execution(saved, e);792 return Ok(());793 }794 }795 self.insert_execution(e.clone())796 }797 fn save_node(&self, e: &Execution<D, E>, n: &mut Node<D, E>) -> Result<()> {798 {799 let mut nodes = e.nodes.write(self.state.scope())?;800 if let Some(saved) = nodes.get_mut(&n.id) {801 commit::node(saved, n);802 return Ok(());803 }804 }805 self.insert_node(e, n.clone())806 }807 /// Synchronous infrastructure only: no definition/size/runtime callback,808 /// allocation or destruction of displaced owning values inside `edit`.809 /// Row identity stays fixed. Any displaced owners leave with the result,810 /// after both row guards have been released.811 fn edit_key<R>(812 &self,813 key: Key,814 edit: impl FnOnce(&mut Execution<D, E>, &mut Node<D, E>) -> Result<R>,815 ) -> Result<Option<R>> {816 if key.namespace != self.namespace {817 return Ok(None);818 }819 let mut state = self.write_state()?;820 let Some(execution) = state.executions.get_mut(&key.execution) else {821 return Ok(None);822 };823 let saved_nodes = execution.nodes.clone();824 let mut nodes = saved_nodes.write(self.state.scope())?;825 let Some(node) = nodes.get_mut(&key.node) else {826 return Ok(None);827 };828 if node.visit != key.visit829 || (execution.version != key.version830 && !node.task.as_ref().is_some_and(|task| task.key == key))831 {832 return Ok(None);833 }834 Ok(Some(edit(execution, node)?))835 }836837 /// Record accounting before publication, as the detached-row path does.838 /// Acquire every fallible retained loan before changing either row. The839 /// remaining edit and trace append have no application callback.840 fn edit_traced_key<R>(841 &self,842 key: Key,843 kind: EventKind,844 now: u64,845 edit: impl FnOnce(&Execution<D, E>, &mut Node<D, E>) -> R,846 ) -> Result<Option<R>> {847 self.runtime.record(kind)?;848 self.edit_key(key, |execution, node| {849 let saved_history = execution.history.clone();850 let mut history = saved_history851 .as_ref()852 .map(|history| history.write(self.state.scope()))853 .transpose()?;854 let result = edit(execution, node);855 if let Some(history) = history.as_mut() {856 if history.len() == execution.history_capacity {857 history.pop_front();858 }859 history.push_back(TraceEvent {860 sequence: execution.trace_sequence,861 at: now,862 key: Self::key(self.namespace, execution, node),863 kind,864 attempt: node.task.as_ref().map_or(0, |task| task.attempt),865 });866 execution.trace_sequence += 1;867 }868 Ok(result)869 })870 }871 fn shared_failure(failure: Failure<E>) -> Failure<SavedRc<E>> {872 match failure {873 Failure::App(e) => Failure::App(SavedRc::new(e)),874 Failure::Unknown => Failure::Unknown,875 Failure::Timeout => Failure::Timeout,876 Failure::Capacity => Failure::Capacity,877 }878 }879 pub fn configure_tracing(&self, enabled: bool) -> Result<()> {880 self.runtime.configure_tracing(self.namespace, enabled)?;881 Ok(())882 }883 pub fn set_tracing(&self, id: u64, enabled: bool, now: u64) -> Outcome<()> {884 let Some(mut e) = self.execution(id)? else {885 return Ok(Err(Problem::Missing));886 };887 if e.history.is_some() == enabled {888 return Ok(Ok(()));889 }890 e.trace_generation = e.trace_generation.checked_add(1).ok_or(Error::Overflow)?;891 e.trace_sequence = 0;892 e.history_capacity = if enabled {893 self.settings.trace_events.max(128) as usize894 } else {895 0896 };897 e.history = (enabled.then(|| {898 SavedRc::new(NyxusCell::new(SavedQueue::with_capacity(899 e.history_capacity,900 )))901 }))902 .into();903 if enabled {904 let nodes = e905 .nodes906 .read(self.access)?907 .values()908 .cloned()909 .collect::<Vec<_>>();910 for n in nodes {911 self.trace(&mut e, &n, EventKind::Restored, now)?;912 }913 }914 self.save_execution(&mut e)?;915 drop(e);916 Ok(Ok(()))917 }918 fn changed(&self) {919 self.runtime.changed(self.namespace);920 }921 fn trace(922 &self,923 e: &mut Execution<D, E>,924 n: &Node<D, E>,925 kind: EventKind,926 now: u64,927 ) -> Result<()> {928 self.runtime.record(kind)?;929 if let Some(history) = e.history.as_ref() {930 let mut history = history.write(self.state.scope())?;931 if history.len() == e.history_capacity {932 history.pop_front();933 }934 history.push_back(TraceEvent {935 sequence: e.trace_sequence,936 at: now,937 key: Self::key(self.namespace, e, n),938 kind,939 attempt: n.task.as_ref().map_or(0, |t| t.attempt),940 });941 e.trace_sequence += 1;942 }943944 Ok(())945 }946 fn finish_visit(947 &self,948 e: &mut Execution<D, E>,949 n: &mut Node<D, E>,950 kind: EventKind,951 now: u64,952 ) -> Result<()> {953 if !n.visit_finished {954 n.visit_finished = true;955 self.trace(e, n, kind, now)?;956 }957958 Ok(())959 }960 fn cancel_wake(&self, n: &mut Node<D, E>) -> Result<()> {961 if let Some(k) = n.wake.take() {962 self.write_state()?.wakes.remove(&k);963 }964965 Ok(())966 }967 fn wake(&self, at: u64, wake: Wake) -> Result<WakeKey> {968 let mut s = self.write_state()?;969 let ticket = s.next_wake;970 s.next_wake = s.next_wake.checked_add(1).ok_or(Error::Overflow)?;971 let key = WakeKey { at, ticket };972 s.wakes.insert(key, wake);973 Ok(key)974 }975 fn queue(e: &Execution<D, E>, n: &mut Node<D, E>, out: &mut ReadyQueue<Work>) {976 if !n.queued {977 n.queued = true;978 out.push_back(Self::work(e, n));979 }980 }981 fn flush(&self, out: &mut ReadyQueue<Work>) -> Result<()> {982 let mut state = self.write_state()?;983 match out {984 ReadyQueue::Inline(work) => {985 if let Some(work) = work.take() {986 state.ready.push_back(work);987 }988 }989 ReadyQueue::Spilled(queue) => state.ready.extend(queue.drain(..)),990 }991992 Ok(())993 }994 fn queue_call(&self, e: &Execution<D, E>, n: &Node<D, E>) -> Result<()> {995 let t = n.task.as_ref().expect("queued task");996 let coordinated = !t.handler997 && t.request.as_ref().expect("prepared request").transport == Transport::Reactor;998 let mut s = self.write_state()?;999 if coordinated {1000 s.coordinated.push_back(Self::work(e, n));1001 } else {1002 s.calls.push_back(Self::work(e, n));1003 }10041005 Ok(())1006 }1007 fn blocked(1008 &self,1009 e: &mut Execution<D, E>,1010 n: &mut Node<D, E>,1011 reason: BlockReason,1012 now: u64,1013 ) -> Result<()> {1014 self.cancel_wake(n)?;1015 n.phase = Phase::Blocked(reason);1016 self.trace(e, n, EventKind::Blocked, now)?;10171018 Ok(())1019 }1020 fn advance<F: Definition<Data = D, Error = E>>(1021 &self,1022 def: &F,1023 e: &mut Execution<D, E>,1024 n: &mut Node<D, E>,1025 data: D,1026 next: Option<u32>,1027 now: u64,1028 out: &mut ReadyQueue<Work>,1029 ) -> Result<bool> {1030 if !Self::data_fits(def, &data, self.settings.max_data_bytes) {1031 self.blocked(e, n, BlockReason::StorageLimit, now)?;1032 return Ok(false);1033 }1034 self.advance_shared(e, n, SavedRc::new(data), next, now, out)1035 }1036 fn advance_shared(1037 &self,1038 e: &mut Execution<D, E>,1039 n: &mut Node<D, E>,1040 data: SavedRc<D>,1041 next: Option<u32>,1042 now: u64,1043 out: &mut ReadyQueue<Work>,1044 ) -> Result<bool> {1045 self.cancel_wake(n)?;1046 if let Some(step) = next {1047 self.finish_visit(e, n, EventKind::Completed, now)?;1048 n.step = step;1049 n.data = data;1050 n.visit = n.visit.checked_add(1).ok_or(Error::Overflow)?;1051 n.visit_finished = false;1052 n.task = (None).into();1053 n.phase = Phase::Ready;1054 n.queued = false;1055 n.producer = (None).into();1056 n.continuation = (None).into();1057 n.children = (None).into();1058 n.results = (None).into();1059 n.remaining = 0;1060 self.trace(e, n, EventKind::Entered, now)?;1061 Self::queue(e, n, out);1062 Ok(false)1063 } else {1064 self.complete(e, n, SharedOutcome::Ok(data), now, out)?;1065 Ok(true)1066 }1067 }1068 fn complete(1069 &self,1070 e: &mut Execution<D, E>,1071 n: &mut Node<D, E>,1072 result: SharedOutcome<D, E>,1073 now: u64,1074 out: &mut ReadyQueue<Work>,1075 ) -> Result<()> {1076 self.cancel_wake(n)?;1077 self.finish_visit(1078 e,1079 n,1080 if matches!(result, SharedOutcome::Ok(_)) {1081 EventKind::Completed1082 } else {1083 EventKind::Failed1084 },1085 now,1086 )?;1087 if let Some(link) = n.parent.into_option() {1088 let mut parent = self1089 .node_entry(e, link.node)?1090 .ok_or(Error::Corrupt("missing workflow join parent"))?;1091 if parent1092 .results1093 .as_ref()1094 .expect("joining results")1095 .read(self.access)?1096 .contains_key(&link.branch)1097 {1098 return Err(Error::Corrupt("workflow branch completed twice"));1099 }1100 parent1101 .results1102 .as_ref()1103 .expect("joining results")1104 .write(self.state.scope())?1105 .insert(link.branch, result);1106 parent.remaining = parent1107 .remaining1108 .checked_sub(1)1109 .ok_or(Error::Corrupt("completed excess branch"))?;1110 e.nodes.write(self.state.scope())?.remove(&n.id);1111 if parent.remaining == 0 {1112 Self::queue(e, &mut parent, out);1113 }1114 self.save_node(e, &mut parent)?;1115 drop(parent);1116 } else {1117 let success = matches!(result, SharedOutcome::Ok(_));1118 e.status = match result {1119 SharedOutcome::Ok(d) => SharedStatus::Succeeded(d),1120 SharedOutcome::Err(e) => SharedStatus::Failed(e),1121 };1122 e.finished_at = (Some(now)).into();1123 e.nodes.write(self.state.scope())?.remove(&n.id);1124 let mut s = self.write_state()?;1125 s.pending = s.pending.checked_sub(1).expect("balanced engine admission");1126 let evict = if s.results.len() >= self.settings.max_results as usize {1127 s.results.pop_first()1128 } else {1129 None1130 };1131 drop(s);1132 if let Some(id) = evict {1133 self.forget_inner(id)?;1134 }1135 self.runtime.finished(success)?;1136 self.write_state()?.results.insert(e.id);1137 e.expiry = (Some(self.wake(1138 now.saturating_add(self.settings.result_retention_nanos),1139 Wake::Expire(e.id),1140 )?))1141 .into();1142 }1143 Ok(())1144 }1145 fn fail<F: Definition<Data = D, Error = E>>(1146 &self,1147 e: &mut Execution<D, E>,1148 n: &mut Node<D, E>,1149 failure: Failure<E>,1150 def: &F,1151 now: u64,1152 out: &mut ReadyQueue<Work>,1153 ) -> Result<bool> {1154 self.finish_visit(e, n, EventKind::Failed, now)?;1155 if let Some((step, data)) = def.catch(n.step, &n.data, &failure) {1156 self.advance(def, e, n, data, Some(step), now, out)1157 } else {1158 self.complete(1159 e,1160 n,1161 SharedOutcome::Err(Self::shared_failure(failure)),1162 now,1163 out,1164 )?;1165 Ok(true)1166 }1167 }1168 fn consume<F: Definition<Data = D, Error = E>>(1169 &self,1170 e: &mut Execution<D, E>,1171 n: &mut Node<D, E>,1172 def: &F,1173 now: u64,1174 out: &mut ReadyQueue<Work>,1175 ) -> Result<bool> {1176 let task = n1177 .task1178 .as_ref()1179 .ok_or(Error::Corrupt("missing workflow task"))?;1180 let next = task.next.into_option();1181 let reply = task1182 .reply1183 .clone()1184 .ok_or(Error::Corrupt("missing workflow reply"))?;1185 match reply {1186 SharedOutcome::Ok(data) => {1187 if !Self::data_fits(def, &data, self.settings.max_data_bytes) {1188 self.blocked(e, n, BlockReason::StorageLimit, now)?;1189 return Ok(false);1190 }1191 self.advance_shared(e, n, data, next, now, out)1192 }1193 SharedOutcome::Err(saved_failure) => {1194 let failure = Self::load_failure(&saved_failure);1195 if let Failure::App(error) = &failure {1196 if !Self::error_fits(def, error, self.settings.max_error_bytes) {1197 self.blocked(e, n, BlockReason::StorageLimit, now)?;1198 return Ok(false);1199 }1200 }1201 let policy = def.policy(n.step);1202 let selected = def.retry_rule(n.step, &failure);1203 if let Some((index, rule)) = selected {1204 let t = n.task.as_mut().unwrap();1205 let count = t1206 .retries1207 .get_mut(usize::from(index))1208 .expect("generator limits retries to sixteen");1209 let at = now.saturating_add(rule.delay_nanos(*count));1210 if *count < rule.max_retries1211 && !(t.uncertain && t.safety == Safety::Reconcile)1212 && (t.safety != Safety::Idempotent1213 || t.safe_until.is_none_or(|until| at < until))1214 && t.external.is_none()1215 {1216 *count += 1;1217 n.phase = Phase::RetryWait;1218 n.wake = (Some(self.wake(at, Wake::Node(Self::work(e, n)))?)).into();1219 self.trace(e, n, EventKind::RetryScheduled, now)?;1220 return Ok(false);1221 }1222 }1223 let t = n.task.as_ref().unwrap();1224 if t.uncertain && t.safety != Safety::ReadOnly {1225 self.blocked(1226 e,1227 n,1228 if matches!(failure, Failure::Timeout) {1229 BlockReason::Timeout1230 } else {1231 BlockReason::Unknown1232 },1233 now,1234 )?;1235 Ok(false)1236 } else if selected.is_some() && policy.on_exhausted == Exhausted::Pause {1237 self.blocked(e, n, BlockReason::RetryExhausted, now)?;1238 Ok(false)1239 } else {1240 self.finish_visit(e, n, EventKind::Failed, now)?;1241 if let Some((step, data)) = def.catch(n.step, &n.data, &failure) {1242 self.advance(def, e, n, data, Some(step), now, out)1243 } else {1244 self.complete(e, n, SharedOutcome::Err(saved_failure), now, out)?;1245 Ok(true)1246 }1247 }1248 }1249 }1250 }1251 /// Admission and all requested inline local steps commit synchronously.1252 /// Coordinated requests may start synchronously after their exact request is1253 /// saved; other work remains queued for the shared scheduler.1254 pub fn send<F: Definition<Data = D, Error = E>>(1255 &self,1256 def: &F,1257 input: D,1258 now: u64,1259 inline_steps: usize,1260 ) -> Outcome<u64> {1261 let signature = self.engine.bind_definition::<F>()?;1262 if !Self::data_fits(def, &input, self.settings.max_data_bytes) {1263 return Ok(Err(Problem::PayloadTooLarge));1264 }1265 if self.read_state()?.pending >= self.settings.max_pending || !self.runtime.can_admit()? {1266 return Ok(Err(Problem::Busy));1267 }1268 let id = {1269 let mut s = self.write_state()?;1270 let id = s.next_id;1271 s.next_id = s.next_id.checked_add(1).ok_or(Error::Overflow)?;1272 s.pending += 1;1273 id1274 };1275 let trace_capacity =1276 self.runtime1277 .trace_capacity(self.namespace, self.settings.trace_events)? as usize;1278 let input = SavedRc::new(input);1279 let mut e = Execution {1280 id,1281 version: F::VERSION,1282 signature: signature.into(),1283 input: input.clone(),1284 created_at: now,1285 nodes: SavedRc::new(NyxusCell::new(Mem::NodeTable::new())),1286 status: SharedStatus::Running,1287 finished_at: (None).into(),1288 expiry: (None).into(),1289 next_node: 1,1290 history: ((trace_capacity > 0)1291 .then(|| SavedRc::new(NyxusCell::new(SavedQueue::with_capacity(trace_capacity)))))1292 .into(),1293 history_capacity: trace_capacity,1294 trace_sequence: 0,1295 trace_generation: 0,1296 };1297 let mut n = Self::node(0, F::START, input, None);1298 let mut ready = ReadyQueue::new();1299 self.trace(&mut e, &n, EventKind::Entered, now)?;1300 Self::queue(&e, &mut n, &mut ready);1301 self.insert_node(&e, n)?;1302 self.insert_execution(e)?;1303 self.runtime.admitted()?;1304 let ready = RefCell::new(ready);1305 let steps = std::cell::Cell::new(0usize);1306 self.runtime.scheduler().run_inline(1307 self.state.scope(),1308 cdk_rsx_reactor::Priority::Interactive,1309 || now,1310 crate::runtime::instructions,1311 || steps.get() < inline_steps && !ready.borrow().is_empty(),1312 || {1313 let work = ready.borrow_mut().pop_front().expect("inline ready work");1314 steps.set(steps.get() + 1);1315 self.process(work, def, now, &mut ready.borrow_mut())1316 },1317 )?;1318 self.flush(&mut ready.into_inner())?;1319 self.changed();1320 Ok(Ok(id))1321 }1322 fn process<F: Definition<Data = D, Error = E>>(1323 &self,1324 work: Work,1325 def: &F,1326 now: u64,1327 out: &mut ReadyQueue<Work>,1328 ) -> Result<()> {1329 let Some(mut e) = self.execution(work.execution)? else {1330 return Ok(());1331 };1332 if e.version != F::VERSION1333 || e.signature.into_option() != self.engine.bind_definition::<F>()?1334 || !matches!(e.status, SharedStatus::Running)1335 {1336 return Ok(());1337 }1338 let Some(mut n) = self.node_entry(&e, work.node)? else {1339 return Ok(());1340 };1341 if n.visit != work.visit {1342 return Ok(());1343 }1344 n.queued = false;1345 let mut new_coordinated = None;1346 let removed = match n.phase {1347 Phase::Received => self.consume(&mut e, &mut n, def, now, out)?,1348 Phase::Waiting => {1349 let data = n.data.clone();1350 let next = n.continuation.into_option();1351 self.advance_shared(&mut e, &mut n, data, next, now, out)?1352 }1353 Phase::Joining => {1354 if n.remaining != 0 {1355 false1356 } else {1357 let results = n1358 .results1359 .as_ref()1360 .expect("joining results")1361 .read(self.access)?1362 .values()1363 .cloned()1364 .collect::<Vec<_>>();1365 let error = results.iter().find_map(|x| match x {1366 SharedOutcome::Err(e) => Some(Self::load_failure(e)),1367 _ => None,1368 });1369 if let Some(error) = error {1370 self.fail(&mut e, &mut n, error, def, now, out)?1371 } else {1372 let values = results1373 .into_iter()1374 .map(|x| match x {1375 SharedOutcome::Ok(d) => (*d).clone(),1376 _ => unreachable!(),1377 })1378 .collect::<Vec<_>>();1379 let data = def.join(n.step, &n.data, &values);1380 let next = n.continuation.into_option();1381 self.advance(def, &mut e, &mut n, data, next, now, out)?1382 }1383 }1384 }1385 Phase::Ready => {1386 let kind = def.kind(n.step);1387 if matches!(kind, NodeKind::Local | NodeKind::Remote) {1388 if n.task.is_none() {1389 let policy = def.policy(n.step);1390 n.task = (Some(Task {1391 key: Self::key(self.namespace, &e, &n),1392 input: n.data.clone(),1393 safety: policy.safety,1394 safe_until: (def.safe_until(n.step, &n.data)).into(),1395 retries: [0; 16],1396 attempt: 0,1397 uncertain: false,1398 reply: (None).into(),1399 request: (None).into(),1400 handler: false,1401 external: (None).into(),1402 next: (None).into(),1403 resolved_through: 0,1404 }))1405 .into();1406 }1407 if !Self::replay_allowed(&n, now) {1408 let uncertain = n.task.as_ref().unwrap().uncertain;1409 self.blocked(1410 &mut e,1411 &mut n,1412 if uncertain {1413 BlockReason::Unknown1414 } else {1415 BlockReason::RetryExhausted1416 },1417 now,1418 )?;1419 self.save_node(&e, &mut n)?;1420 drop(n);1421 self.save_execution(&mut e)?;1422 drop(e);1423 return Ok(());1424 }1425 let t = n.task.as_ref().unwrap();1426 if kind == NodeKind::Remote && (t.request.is_some() || t.handler) {1427 n.phase = Phase::QueuedCall;1428 self.queue_call(&e, &n)?;1429 self.save_node(&e, &mut n)?;1430 drop(n);1431 self.save_execution(&mut e)?;1432 drop(e);1433 return Ok(());1434 }1435 if kind == NodeKind::Remote && t.reply.is_some() {1436 let t = n.task.as_mut().unwrap();1437 t.attempt = t.attempt.checked_add(1).ok_or(Error::Overflow)?;1438 self.trace(&mut e, &n, EventKind::AttemptStarted, now)?;1439 n.phase = Phase::Received;1440 let removed = self.consume(&mut e, &mut n, def, now, out)?;1441 if !removed {1442 self.save_node(&e, &mut n)?;1443 drop(n);1444 }1445 self.save_execution(&mut e)?;1446 drop(e);1447 return Ok(());1448 }1449 if kind == NodeKind::Local {1450 let t = n.task.as_mut().unwrap();1451 t.attempt = t.attempt.checked_add(1).ok_or(Error::Overflow)?;1452 self.trace(&mut e, &n, EventKind::AttemptStarted, now)?;1453 }1454 }1455 let context = self.context(&e, &n, def, now)?;1456 let input = n.data.clone();1457 match def.step(n.step, &input, &context) {1458 Step::Next { node, data } => {1459 self.advance(def, &mut e, &mut n, data, Some(node), now, out)?1460 }1461 Step::Succeed(data) => {1462 self.advance(def, &mut e, &mut n, data, None, now, out)?1463 }1464 Step::Fail(error) => {1465 if !Self::error_fits(def, &error, self.settings.max_error_bytes) {1466 self.blocked(&mut e, &mut n, BlockReason::StorageLimit, now)?;1467 false1468 } else {1469 self.fail(&mut e, &mut n, Failure::App(error), def, now, out)?1470 }1471 }1472 Step::Local { reply, next } => {1473 let fits = match &reply {1474 Known::Ok(d) => Self::data_fits(def, d, self.settings.max_data_bytes),1475 Known::Err(e) => {1476 Self::error_fits(def, e, self.settings.max_error_bytes)1477 }1478 };1479 if !fits {1480 if let Some(t) = n.task.as_mut() {1481 t.uncertain = true;1482 }1483 self.blocked(&mut e, &mut n, BlockReason::StorageLimit, now)?;1484 false1485 } else {1486 let t = n1487 .task1488 .as_mut()1489 .ok_or(Error::Corrupt("generated local node kind mismatch"))?;1490 t.next = (next).into();1491 t.reply = (Some(match reply {1492 Known::Ok(d) => SharedOutcome::Ok(SavedRc::new(d)),1493 Known::Err(e) => SharedOutcome::Err(Failure::App(SavedRc::new(e))),1494 }))1495 .into();1496 n.phase = Phase::Received;1497 self.consume(&mut e, &mut n, def, now, out)?1498 }1499 }1500 Step::Handler { next } => {1501 let t = n1502 .task1503 .as_mut()1504 .ok_or(Error::Corrupt("generated handler kind mismatch"))?;1505 t.handler = true;1506 t.next = (next).into();1507 n.phase = Phase::QueuedCall;1508 self.queue_call(&e, &n)?;1509 false1510 }1511 Step::Remote { request, next } => {1512 let size = F::DATA_BYTES1513 .map_or_else(|| input.payload_bytes(), |size| size(&input))1514 .saturating_add(request.payload_bytes());1515 if request.route.len() > 1281516 || request.args.len() > 655361517 || size > self.settings.max_data_bytes as usize1518 {1519 self.blocked(&mut e, &mut n, BlockReason::StorageLimit, now)?;1520 } else {1521 let coordinated = request.transport == Transport::Reactor;1522 let t = n1523 .task1524 .as_mut()1525 .ok_or(Error::Corrupt("generated remote node kind mismatch"))?;1526 t.request = (Some(SavedRc::new(request.retain()))).into();1527 t.next = (next).into();1528 n.phase = Phase::QueuedCall;1529 if coordinated {1530 new_coordinated = Some(Self::work(&e, &n));1531 } else {1532 self.queue_call(&e, &n)?;1533 }1534 }1535 false1536 }1537 Step::RemoteReply { reply, next } => {1538 let fits = match &reply {1539 Reply::Ok(d) | Reply::Resolved(Known::Ok(d)) => {1540 Self::data_fits(def, d, self.settings.max_data_bytes)1541 }1542 Reply::Err(e) | Reply::Resolved(Known::Err(e)) => {1543 Self::error_fits(def, e, self.settings.max_error_bytes)1544 }1545 Reply::Unknown => true,1546 };1547 if !fits {1548 self.blocked(&mut e, &mut n, BlockReason::StorageLimit, now)?;1549 false1550 } else {1551 let t = n1552 .task1553 .as_mut()1554 .ok_or(Error::Corrupt("generated remote node kind mismatch"))?;1555 t.attempt = t.attempt.checked_add(1).ok_or(Error::Overflow)?;1556 t.next = (next).into();1557 t.reply = (Some(match reply {1558 Reply::Ok(d) | Reply::Resolved(Known::Ok(d)) => {1559 SharedOutcome::Ok(SavedRc::new(d))1560 }1561 Reply::Err(e) | Reply::Resolved(Known::Err(e)) => {1562 SharedOutcome::Err(Failure::App(SavedRc::new(e)))1563 }1564 Reply::Unknown => {1565 t.uncertain = t.safety != Safety::ReadOnly;1566 SharedOutcome::Err(Failure::Unknown)1567 }1568 }))1569 .into();1570 self.trace(&mut e, &n, EventKind::AttemptStarted, now)?;1571 n.phase = Phase::Received;1572 self.consume(&mut e, &mut n, def, now, out)?1573 }1574 }1575 Step::Wait { until, next, data } => {1576 if !Self::data_fits(def, &data, self.settings.max_data_bytes) {1577 self.blocked(&mut e, &mut n, BlockReason::StorageLimit, now)?;1578 } else {1579 n.data = SavedRc::new(data);1580 n.continuation = (next).into();1581 n.phase = Phase::Waiting;1582 n.wake =1583 (Some(self.wake(until, Wake::Node(Self::work(&e, &n)))?)).into();1584 self.trace(&mut e, &n, EventKind::Waiting, now)?;1585 }1586 false1587 }1588 Step::Await { producer, next } => {1589 n.producer = (Some(producer)).into();1590 n.continuation = (next).into();1591 n.phase = Phase::Awaiting;1592 self.trace(&mut e, &n, EventKind::Waiting, now)?;1593 false1594 }1595 Step::Parallel { branches, next } => {1596 let count = branches.len();1597 if e.nodes.read(self.access)?.len().saturating_add(count)1598 > self.settings.max_nodes as usize1599 {1600 self.fail(&mut e, &mut n, Failure::Capacity, def, now, out)?1601 } else if branches1602 .iter()1603 .any(|(_, d)| !Self::data_fits(def, d, self.settings.max_data_bytes))1604 {1605 self.blocked(&mut e, &mut n, BlockReason::StorageLimit, now)?;1606 false1607 } else {1608 let mut children = Vec::with_capacity(count);1609 for (index, (step, data)) in branches.into_iter().enumerate() {1610 let id = e.next_node;1611 e.next_node = e.next_node.checked_add(1).ok_or(Error::Overflow)?;1612 let mut child = Self::node(1613 id,1614 step,1615 SavedRc::new(data),1616 Some(Parent {1617 node: n.id,1618 branch: index as u32,1619 }),1620 );1621 self.trace(&mut e, &child, EventKind::Entered, now)?;1622 Self::queue(&e, &mut child, out);1623 self.insert_node(&e, child)?;1624 children.push(id);1625 }1626 n.children = (Some(SharedSlice::copy_from_slice(&children))).into();1627 n.results =1628 (Some(SavedRc::new(NyxusCell::new(SavedMap::new())))).into();1629 n.remaining = count as u32;1630 n.continuation = (next).into();1631 n.phase = Phase::Joining;1632 if count == 0 {1633 Self::queue(&e, &mut n, out);1634 }1635 false1636 }1637 }1638 }1639 }1640 _ => false,1641 };1642 if !removed {1643 self.save_node(&e, &mut n)?;1644 drop(n);1645 }1646 self.save_execution(&mut e)?;1647 drop(e);1648 if let Some(work) = new_coordinated {1649 self.schedule_coordinated(work, def, now, out)?;1650 }1651 Ok(())1652 }1653 fn pop_due(state: &mut State<D, E>, now: u64) -> Option<(WakeKey, Wake)> {1654 match state.wakes.first_key_value() {1655 Some((key, _)) if key.at <= now => state.wakes.pop_first(),1656 _ => None,1657 }1658 }1659 fn run_wake(&self, key: WakeKey, wake: Wake, now: u64) -> Result<()> {1660 match wake {1661 Wake::Expire(id) => self.forget_inner(id)?,1662 Wake::Node(work) => self.wake_node(work, key, now)?,1663 }1664 Ok(())1665 }1666 /// Drain one due deadline before any addressed completion or ready task.1667 pub fn run_due(&self, now: u64) -> Result<bool> {1668 let due = {1669 let mut state = self.write_state()?;1670 Self::pop_due(&mut state, now)1671 };1672 let Some((key, wake)) = due else {1673 return Ok(false);1674 };1675 self.run_wake(key, wake, now)?;1676 Ok(true)1677 }1678 /// One bounded interpreter work item. Native launch tickets must be sent1679 /// after this method returns; no heap borrow survives a handler or await.1680 pub fn run_one<F: Definition<Data = D, Error = E>>(&self, def: &F, now: u64) -> Result<Run> {1681 self.engine.bind_definition::<F>()?;1682 // Due selection, lane choice and FIFO front/pop inspect one state1683 // borrow. Release it before running any application definition.1684 enum Turn {1685 Due(WakeKey, Wake),1686 Ready(Work),1687 Call(Work, bool),1688 Idle,1689 }1690 let turn = {1691 let mut state = self.write_state()?;1692 if let Some((key, wake)) = Self::pop_due(&mut state, now) {1693 Turn::Due(key, wake)1694 } else {1695 let logical = state.logical_calls < self.settings.max_concurrent;1696 let native = logical1697 && !state.calls.is_empty()1698 && state.active_calls < self.settings.max_concurrent.saturating_mul(4).min(64)1699 && self.runtime.can_start(true)?;1700 let coordinated =1701 logical && !state.coordinated.is_empty() && self.runtime.can_start(false)?;1702 let selected = if state.prefer_coordinated && coordinated {1703 Some(true)1704 } else if native {1705 Some(false)1706 } else if coordinated {1707 Some(true)1708 } else {1709 None1710 };1711 if let Some(coordinated) = selected {1712 let work = if coordinated {1713 state.coordinated.front().copied()1714 } else {1715 state.calls.front().copied()1716 };1717 work.map_or(Turn::Idle, |work| Turn::Call(work, coordinated))1718 } else {1719 state.ready.pop_front().map_or(Turn::Idle, Turn::Ready)1720 }1721 }1722 };1723 match turn {1724 Turn::Due(key, wake) => {1725 self.run_wake(key, wake, now)?;1726 Ok(Run::Progress)1727 }1728 Turn::Ready(work) => {1729 let mut out = ReadyQueue::new();1730 self.process(work, def, now, &mut out)?;1731 self.flush(&mut out)?;1732 Ok(Run::Progress)1733 }1734 Turn::Call(work, coordinated) => self.start_call(work, def, now, Some(coordinated)),1735 Turn::Idle => Ok(Run::Idle),1736 }1737 }1738 fn pop_call(&self, queued: Option<bool>) -> Result<()> {1739 if let Some(coordinated) = queued {1740 let mut s = self.write_state()?;1741 if coordinated {1742 s.coordinated.pop_front();1743 } else {1744 s.calls.pop_front();1745 }1746 }1747 Ok(())1748 }1749 /// Both FIFO selection and newly prepared coordinated admission use the1750 /// same replay, attempt, deadline, publication and accounting transition.1751 fn start_call<F: Definition<Data = D, Error = E>>(1752 &self,1753 work: Work,1754 def: &F,1755 now: u64,1756 queued: Option<bool>,1757 ) -> Result<Run> {1758 let Some(mut e) = self.execution(work.execution)? else {1759 self.pop_call(queued)?;1760 return Ok(Run::Progress);1761 };1762 let Some(mut n) = self.node_entry(&e, work.node)? else {1763 self.pop_call(queued)?;1764 return Ok(Run::Progress);1765 };1766 if e.version != F::VERSION1767 || e.signature.into_option() != self.engine.bind_definition::<F>()?1768 || !matches!(e.status, SharedStatus::Running)1769 || n.visit != work.visit1770 || n.phase != Phase::QueuedCall1771 {1772 self.pop_call(queued)?;1773 return Ok(Run::Progress);1774 }1775 if !Self::replay_allowed(&n, now) {1776 self.pop_call(queued)?;1777 let uncertain = n.task.as_ref().unwrap().uncertain;1778 self.blocked(1779 &mut e,1780 &mut n,1781 if uncertain {1782 BlockReason::Unknown1783 } else {1784 BlockReason::RetryExhausted1785 },1786 now,1787 )?;1788 self.save_node(&e, &mut n)?;1789 drop(n);1790 self.save_execution(&mut e)?;1791 drop(e);1792 return Ok(Run::Progress);1793 }1794 let task = n.task.as_ref().unwrap();1795 let handler = task.handler;1796 let request = task.request.clone();1797 let native =1798 handler || request.as_ref().expect("prepared request").transport != Transport::Reactor;1799 let node = n.step;1800 let available = {1801 let s = self.read_state()?;1802 s.logical_calls < self.settings.max_concurrent1803 && (!native1804 || s.active_calls < self.settings.max_concurrent.saturating_mul(4).min(64))1805 && self.runtime.can_start(native)?1806 };1807 if !available {1808 return Ok(Run::Idle);1809 }1810 self.pop_call(queued)?;1811 // Publication completes before the adapter can enqueue or watch effects.1812 let t = n.task.as_mut().unwrap();1813 t.attempt = t.attempt.checked_add(1).ok_or(Error::Overflow)?;1814 t.reply = (None).into();1815 let identity = CallIdentity {1816 key: t.key,1817 attempt: t.attempt,1818 };1819 n.phase = Phase::Calling;1820 n.wake = (Some(self.wake(1821 now.saturating_add(def.policy(n.step).timeout_millis.saturating_mul(1_000_000)),1822 Wake::Node(work),1823 )?))1824 .into();1825 let context = self.context(&e, &n, def, now)?;1826 self.trace(&mut e, &n, EventKind::AttemptStarted, now)?;1827 self.save_node(&e, &mut n)?;1828 drop(n);1829 self.save_execution(&mut e)?;1830 drop(e);1831 let mut s = self.write_state()?;1832 s.logical_calls += 1;1833 if native {1834 s.active_calls += 1;1835 s.physical.insert(identity);1836 }1837 if queued.is_some() {1838 s.prefer_coordinated = native;1839 }1840 drop(s);1841 self.runtime.started(native, identity)?;1842 Ok(if handler {1843 Run::Handler(HandlerTicket { context, node })1844 } else {1845 Run::Call(CallTicket {1846 context,1847 request: PreparedRequest(request.expect("prepared request")),1848 })1849 })1850 }1851 fn schedule_coordinated<F: Definition<Data = D, Error = E>>(1852 &self,1853 work: Work,1854 def: &F,1855 now: u64,1856 out: &mut ReadyQueue<Work>,1857 ) -> Result<()> {1858 let binding = self.runtime.coordinated::<E>(self.namespace)?;1859 let eligible = {1860 let s = self.read_state()?;1861 s.coordinated.is_empty()1862 && s.logical_calls < self.settings.max_concurrent1863 && self.runtime.can_start(false)?1864 };1865 if let Some(binding) = binding.filter(|_| eligible) {1866 match self.start_call(work, def, now, None)? {1867 Run::Call(ticket) => {1868 let key = ticket.context.key;1869 let attempt = ticket.context.attempt;1870 let wake = binding.wake.clone();1871 if let Some(error) = self.request_reactor(1872 &binding.reactor.view(self.state.scope()),1873 &ticket,1874 crate::driver::reactor_wake(wake, key, attempt),1875 now,1876 )? {1877 self.apply_reply_to::<true>(1878 &ticket.context,1879 Reply::Err((binding.send_error)(error)),1880 now,1881 Some(out),1882 )?;1883 }1884 return Ok(());1885 }1886 Run::Progress => return Ok(()),1887 Run::Idle => {}1888 Run::Handler(_) => unreachable!("new Reactor request is not a handler"),1889 }1890 }1891 self.write_state()?.coordinated.push_back(work);1892 Ok(())1893 }1894 fn wake_node(&self, work: Work, key: WakeKey, now: u64) -> Result<()> {1895 let Some(mut e) = self.execution(work.execution)? else {1896 return Ok(());1897 };1898 let Some(mut n) = self.node_entry(&e, work.node)? else {1899 return Ok(());1900 };1901 if n.visit != work.visit1902 || n.wake.into_option() != Some(key)1903 || !matches!(e.status, SharedStatus::Running)1904 {1905 return Ok(());1906 }1907 n.wake = (None).into();1908 let mut unresolved = false;1909 match n.phase {1910 Phase::Calling => {1911 self.logical_finished()?;1912 let t = n.task.as_mut().unwrap();1913 t.uncertain = t.safety != Safety::ReadOnly;1914 t.reply = (Some(SharedOutcome::Err(Failure::Timeout))).into();1915 unresolved = t.external.is_some();1916 n.phase = Phase::Received;1917 }1918 Phase::RetryWait => n.phase = Phase::Ready,1919 Phase::Waiting => {}1920 _ => return Ok(()),1921 }1922 let mut out = ReadyQueue::new();1923 self.trace(&mut e, &n, EventKind::Received, now)?;1924 if unresolved {1925 self.blocked(&mut e, &mut n, BlockReason::Unknown, now)?;1926 } else {1927 Self::queue(&e, &mut n, &mut out);1928 }1929 self.save_node(&e, &mut n)?;1930 drop(n);1931 self.save_execution(&mut e)?;1932 drop(e);1933 self.flush(&mut out)?;1934 Ok(())1935 }1936 fn logical_finished(&self) -> Result<()> {1937 let mut s = self.write_state()?;1938 s.logical_calls = s1939 .logical_calls1940 .checked_sub(1)1941 .expect("balanced engine logical call");1942 drop(s);1943 self.runtime.replied()?;19441945 Ok(())1946 }1947 pub fn physical_exit(&self, ticket: &CallTicket) -> Result<bool> {1948 self.exit_physical(&ticket.context)1949 }1950 pub fn handler_exit(&self, ticket: &HandlerTicket) -> Result<bool> {1951 self.exit_physical(&ticket.context)1952 }1953 fn exit_physical(&self, context: &Context) -> Result<bool> {1954 let identity = CallIdentity {1955 key: context.key,1956 attempt: context.attempt,1957 };1958 let mut s = self.write_state()?;1959 if !s.physical.remove(&identity) {1960 return Ok(false);1961 }1962 s.active_calls = s1963 .active_calls1964 .checked_sub(1)1965 .expect("balanced physical call");1966 drop(s);1967 self.runtime.released(identity)?;1968 self.changed();1969 Ok(true)1970 }1971 pub fn attach_address(&self, ticket: &CallTicket, address: ExternalAddress) -> Outcome<()> {1972 Ok(self1973 .edit_key(ticket.context.key, |_, node| {1974 let task = node1975 .task1976 .as_mut()1977 .ok_or(Error::Corrupt("address without task"))?;1978 Ok(1979 if task.attempt != ticket.context.attempt1980 || task.external.is_some()1981 || ticket.request.transport() != Transport::Reactor1982 {1983 Err(Problem::StaleKey)1984 } else {1985 task.external = Some(address).into();1986 Ok(())1987 },1988 )1989 })?1990 .unwrap_or(Err(Problem::StaleKey)))1991 }1992 pub fn clear_address(&self, key: Key, address: ExternalAddress) -> Result<bool> {1993 Ok(self1994 .edit_key(key, |_, node| {1995 let Some(task) = node.task.as_mut() else {1996 return Ok(false);1997 };1998 if task.external.into_option() != Some(address) {1999 return Ok(false);2000 }2001 task.external = None.into();2002 Ok(true)2003 })?2004 .unwrap_or(false))2005 }2006 pub fn reply(&self, ticket: &CallTicket, reply: Reply<D, E>, now: u64) -> Result<bool> {2007 self.apply_reply(&ticket.context, reply, now)2008 }2009 pub fn handler_reply(2010 &self,2011 ticket: &HandlerTicket,2012 reply: Reply<D, E>,2013 now: u64,2014 ) -> Result<bool> {2015 self.apply_reply(&ticket.context, reply, now)2016 }2017 pub fn prepare_handler<F: Definition<Data = D, Error = E>>(2018 &self,2019 def: &F,2020 ticket: &HandlerTicket,2021 sink: ReplySink<D, E>,2022 ) -> Result<HandlerFuture> {2023 let Some((_, n)) = self.locate_key(ticket.context.key)? else {2024 return Err(Error::Corrupt("handler launch lost its task"));2025 };2026 let task = n2027 .task2028 .as_ref()2029 .ok_or(Error::Corrupt("handler launch missing task"))?;2030 if !task.handler || task.attempt != ticket.context.attempt || n.phase != Phase::Calling {2031 return Err(Error::Corrupt("stale handler launch"));2032 }2033 def.handler(ticket.node, (*task.input).clone(), ticket.context, sink)2034 .ok_or(Error::Corrupt("generated handler missing future"))2035 }2036 fn apply_reply(&self, context: &Context, reply: Reply<D, E>, now: u64) -> Result<bool> {2037 self.apply_reply_to::<true>(context, reply, now, None)2038 }2039 fn apply_reply_to<const CHECK_SIZE: bool>(2040 &self,2041 context: &Context,2042 reply: Reply<D, E>,2043 now: u64,2044 inline: Option<&mut ReadyQueue<Work>>,2045 ) -> Result<bool> {2046 let positive = matches!(reply, Reply::Ok(_) | Reply::Resolved(Known::Ok(_)));2047 let resolved = matches!(reply, Reply::Resolved(_));2048 let Some((calling, wake, mut uncertain, safety, attempt)) = self2049 .inspect_key(context.key, |e, n| {2050 let t = n.task.as_ref()?;2051 if t.key != context.key2052 || context.attempt <= t.resolved_through2053 || !matches!(e.status, SharedStatus::Running)2054 || matches!(t.reply.as_ref(), Some(SharedOutcome::Ok(_)))2055 || (!positive2056 && (context.attempt != t.attempt2057 || (n.phase != Phase::Calling && !resolved)))2058 {2059 return None;2060 }2061 Some((2062 n.phase == Phase::Calling,2063 n.wake.into_option(),2064 t.uncertain,2065 t.safety,2066 t.attempt,2067 ))2068 })?2069 .flatten()2070 else {2071 return Ok(false);2072 };2073 if calling {2074 self.logical_finished()?;2075 }2076 if let Some(wake) = wake {2077 self.write_state()?.wakes.remove(&wake);2078 }2079 // The configured pure bound may read this engine again. Accounting2080 // has changed, but the stored Node is still old; no guard crosses it.2081 // Explicit resolution already checked once before changing accounting.2082 let fits = !CHECK_SIZE2083 || match &reply {2084 Reply::Ok(data) | Reply::Resolved(Known::Ok(data)) => self.callback_data_fits(data),2085 Reply::Err(error) | Reply::Resolved(Known::Err(error)) => {2086 self.callback_error_fits(error)2087 }2088 Reply::Unknown => true,2089 };2090 if !fits {2091 self.edit_traced_key(context.key, EventKind::Blocked, now, |_, node| {2092 node.task.as_mut().expect("validated reply task").uncertain = true;2093 node.wake = None.into();2094 node.phase = Phase::Blocked(BlockReason::StorageLimit);2095 })?2096 .ok_or(Error::Corrupt("reply task changed during pure size check"))?;2097 return Ok(true);2098 }2099 // Construct or discard application values before borrowing saved rows.2100 let outcome = match reply {2101 Reply::Ok(data) => {2102 uncertain = false;2103 SharedOutcome::Ok(SavedRc::new(data))2104 }2105 Reply::Err(error) => {2106 if uncertain {2107 SharedOutcome::Err(Failure::Unknown)2108 } else {2109 SharedOutcome::Err(Failure::App(SavedRc::new(error)))2110 }2111 }2112 Reply::Unknown => {2113 uncertain = safety != Safety::ReadOnly;2114 SharedOutcome::Err(Failure::Unknown)2115 }2116 Reply::Resolved(known) => {2117 uncertain = false;2118 match known {2119 Known::Ok(data) => SharedOutcome::Ok(SavedRc::new(data)),2120 Known::Err(error) => SharedOutcome::Err(Failure::App(SavedRc::new(error))),2121 }2122 }2123 };2124 // Keep ownership outside the edit closure too: if a history loan fails,2125 // the fresh application value must drop after the outer row guards.2126 let mut outcome = Some(outcome);2127 let mut out = ReadyQueue::new();2128 let displaced = self2129 .edit_traced_key(context.key, EventKind::Received, now, |execution, node| {2130 let task = node.task.as_mut().expect("validated reply task");2131 task.uncertain = uncertain;2132 if resolved {2133 task.resolved_through = attempt;2134 }2135 let displaced = std::mem::replace(&mut task.reply, outcome.take().into());2136 node.wake = None.into();2137 node.phase = Phase::Received;2138 Self::queue(execution, node, &mut out);2139 displaced2140 })?2141 .ok_or(Error::Corrupt("reply task changed during pure size check"))?;2142 // An application error/data destructor can reenter services. Its last2143 // owner is released only after the callback-free row edit has ended.2144 drop(displaced);2145 if let Some(inline) = inline {2146 while let Some(work) = out.pop_front() {2147 inline.push_back(work);2148 }2149 } else {2150 self.flush(&mut out)?;2151 }2152 self.changed();2153 Ok(true)2154 }2155 pub fn receive<F: Definition<Data = D, Error = E>>(2156 &self,2157 def: &F,2158 ticket: &CallTicket,2159 bytes: &[u8],2160 now: u64,2161 ) -> Result<bool> {2162 let signature = self.engine.bind_definition::<F>()?;2163 let Some((step, input)) = self2164 .inspect_key(ticket.context.key, |e, n| {2165 if e.version != F::VERSION || e.signature.into_option() != signature {2166 return None;2167 }2168 n.task.as_ref().map(|task| (n.step, task.input.clone()))2169 })?2170 .flatten()2171 else {2172 return Ok(false);2173 };2174 let reply = def.reply(step, &input, bytes, &ticket.context);2175 self.reply(ticket, reply, now)2176 }2177 pub fn receive_address<F: Definition<Data = D, Error = E>>(2178 &self,2179 def: &F,2180 reactor: &cdk_rsx_reactor::ReactorView<'_, Scope<'_>>,2181 target: crate::driver::Target,2182 now: u64,2183 ) -> Result<bool> {2184 let signature = self.engine.bind_definition::<F>()?;2185 let Some((step, input, mut context, next_key)) = self2186 .inspect_key(target.key, |e, n| {2187 if !matches!(e.status, SharedStatus::Running)2188 || e.version != F::VERSION2189 || e.signature.into_option() != signature2190 {2191 return None;2192 }2193 let task = n.task.as_ref()?;2194 if task.key != target.key2195 || task.attempt != target.attempt2196 || task.external.into_option()2197 != Some(ExternalAddress {2198 canister: target.address.canister,2199 id: target.address.id,2200 })2201 || task.request.is_none()2202 {2203 return None;2204 }2205 Some((2206 n.step,2207 task.input.clone(),2208 Context {2209 key: task.key,2210 attempt: task.attempt,2211 now,2212 call_timeout_millis: 0,2213 next_event: None,2214 },2215 Self::key(self.namespace, e, n),2216 ))2217 })?2218 .flatten()2219 else {2220 return Ok(false);2221 };2222 let Some(outcome) = reactor.shared_result(target.address)? else {2223 return Ok(false);2224 };2225 // The original mapper still sees the original mailbox and saved node.2226 // Policy, next-event and mapping all execute after releasing row loans.2227 context.call_timeout_millis = def.policy(step).call_timeout_millis;2228 if def.next_event(step) {2229 context.next_event = Some(Key {2230 visit: next_key.visit.checked_add(1).ok_or(Error::Overflow)?,2231 ..next_key2232 });2233 }2234 let reply = match outcome {2235 cdk_rsx_reactor::SharedOutcome::Reply(bytes) => {2236 def.reply(step, &input, &bytes, &context)2237 }2238 cdk_rsx_reactor::SharedOutcome::Expired => Reply::Unknown,2239 };2240 let accepted = self.apply_reply(&context, reply, now)?;2241 reactor.take_shared_result(target.address)?;2242 self.clear_address(2243 target.key,2244 ExternalAddress {2245 canister: target.address.canister,2246 id: target.address.id,2247 },2248 )?;2249 Ok(accepted)2250 }2251 pub fn signal<F: Definition<Data = D, Error = E>>(2252 &self,2253 def: &F,2254 key: Key,2255 producer: Principal,2256 bytes: &[u8],2257 now: u64,2258 ) -> Outcome<()> {2259 let (mut e, mut n) = match self.locate_visit(key)? {2260 Ok(v) => v,2261 Err(p) => return Ok(Err(p)),2262 };2263 if !matches!(e.status, SharedStatus::Running)2264 || e.version != F::VERSION2265 || e.signature.into_option() != self.engine.bind_definition::<F>()?2266 || key.version != e.version2267 {2268 return Ok(Err(Problem::StaleKey));2269 }2270 if def.kind(n.step) != NodeKind::Await {2271 return Ok(Err(Problem::InvalidEvent));2272 }2273 if def.event_source(n.step, &n.data) != Some(producer) {2274 return Ok(Err(Problem::InvalidEvent));2275 }2276 if n.phase == Phase::Ready {2277 return Ok(Err(Problem::Pending));2278 }2279 if n.phase != Phase::Awaiting {2280 return Ok(Err(Problem::StaleKey));2281 }2282 let Some(data) = def.event(n.step, &n.data, producer, bytes) else {2283 return Ok(Err(Problem::InvalidEvent));2284 };2285 if !Self::data_fits(def, &data, self.settings.max_data_bytes) {2286 return Ok(Err(Problem::PayloadTooLarge));2287 }2288 let mut out = ReadyQueue::new();2289 let next = n.continuation.into_option();2290 let removed = self.advance(def, &mut e, &mut n, data, next, now, &mut out)?;2291 if !removed {2292 self.save_node(&e, &mut n)?;2293 drop(n);2294 }2295 self.save_execution(&mut e)?;2296 drop(e);2297 self.flush(&mut out)?;2298 self.changed();2299 Ok(Ok(()))2300 }2301 fn resume_node(2302 &self,2303 e: &Execution<D, E>,2304 mut n: Node<D, E>,2305 out: &mut ReadyQueue<Work>,2306 ) -> Result<()> {2307 n.task.as_mut().unwrap().retries = [0; 16];2308 n.phase = Phase::Ready;2309 Self::queue(e, &mut n, out);2310 self.save_node(e, &mut n)?;2311 drop(n);23122313 Ok(())2314 }2315 pub fn resume(&self, key: Key, now: u64) -> Outcome<()> {2316 let (e, n) = match self.locate_visit(key)? {2317 Ok(v) => v,2318 Err(p) => return Ok(Err(p)),2319 };2320 if let Err(p) = self.retry_candidate(&e, &n, key, now) {2321 return Ok(Err(p));2322 }2323 let mut out = ReadyQueue::new();2324 self.resume_node(&e, n, &mut out)?;2325 self.flush(&mut out)?;2326 self.changed();2327 Ok(Ok(()))2328 }2329 pub fn retry_execution(&self, id: u64, now: u64) -> Outcome<()> {2330 let Some(e) = self.execution(id)? else {2331 return Ok(Err(Problem::Missing));2332 };2333 if !matches!(e.status, SharedStatus::Running) {2334 return Ok(Err(Problem::StaleKey));2335 }2336 let nodes = e2337 .nodes2338 .read(self.access)?2339 .values()2340 .filter(|n| matches!(n.phase, Phase::Blocked(_)))2341 .cloned()2342 .collect::<Vec<_>>();2343 for n in &nodes {2344 let key = n2345 .task2346 .as_ref()2347 .map_or(Self::key(self.namespace, &e, n), |t| t.key);2348 if let Err(p) = self.retry_candidate(&e, n, key, now) {2349 return Ok(Err(p));2350 }2351 }2352 if nodes.is_empty() {2353 return Ok(Err(Problem::NotBlocked));2354 }2355 let mut out = ReadyQueue::new();2356 for n in nodes {2357 self.resume_node(&e, n, &mut out)?;2358 }2359 self.flush(&mut out)?;2360 self.changed();2361 Ok(Ok(()))2362 }2363 pub fn resolve(&self, key: Key, result: Known<D, E>, now: u64) -> Outcome<()> {2364 let (context, _) = match self.resolution_task(key, now)? {2365 Ok(v) => v,2366 Err(p) => return Ok(Err(p)),2367 };2368 let fits = match &result {2369 Known::Ok(d) => self.callback_data_fits(d),2370 Known::Err(e) => self.callback_error_fits(e),2371 };2372 if !fits {2373 return Ok(Err(Problem::PayloadTooLarge));2374 }2375 Ok(2376 if self.apply_reply_to::<false>(&context, Reply::Resolved(result), now, None)? {2377 Ok(())2378 } else {2379 Err(Problem::StaleKey)2380 },2381 )2382 }2383 pub fn forget_execution(&self, id: u64) -> Outcome<()> {2384 let Some(e) = self.execution(id)? else {2385 return Ok(Err(Problem::Missing));2386 };2387 if matches!(e.status, SharedStatus::Running) {2388 return Ok(Err(Problem::Pending));2389 }2390 self.forget_inner(id)?;2391 self.changed();2392 Ok(Ok(()))2393 }2394 fn forget_inner(&self, id: u64) -> Result<()> {2395 let mut s = self.write_state()?;2396 let Some(e) = s.executions.get(&id) else {2397 return Ok(());2398 };2399 if matches!(e.status, SharedStatus::Running) {2400 return Ok(());2401 }2402 if let Some(k) = e.expiry.into_option() {2403 s.wakes.remove(&k);2404 }2405 s.executions.remove(&id);2406 s.results.remove(&id);24072408 Ok(())2409 }2410}