admissions.rs
benches/rrt/canister/src/admissions.rs
1//! Deferred FIFO admission with Nyxus receipts. Same limits and clocks2//! as RRT's 8836ac6e admission owner; only storage/access is replaced.3use crate::{api, flows::Workflow, workflows::Seed};4use cdk_rsx::Principal;5use cdk_rsx_reactor::{Error, Result};6use cdk_rsx_reactor::{7 WorkPriority,8 scheduler::{Lease, Readiness, Scheduler, Step, WorkDriver},9};10pub mod memory;11use cdk_rsx_store::{12 Access, ModuleRef, ReadScope, Scope,13 binding::{Memory as Binding, MemoryView},14};15use cdk_rsx_takt::{Outcome, Problem};16use memory::v1::{Entry, Status};17use std::{cell::RefCell, rc::Rc};18const MAX_RECEIPTS: usize = 16_384;19const MAX_PENDING: u64 = 4096;2021/// Transient admission input after protocol validation. A canonical natural22/// outside u64 remains `None` until this owner returns its ordinary Busy result.23#[derive(Clone, Copy, Debug, PartialEq, Eq)]24pub struct Input {25 pub run: Option<u64>,26 pub job: Option<u64>,27 pub left: Principal,28 pub right: Principal,29 pub child: Principal,30 pub units: Option<u64>,31 pub delay_millis: Option<u64>,32}33impl From<api::Start> for Input {34 fn from(args: api::Start) -> Self {35 Self {36 run: args.run.try_to_u64(),37 job: args.job.try_to_u64(),38 left: args.left.0,39 right: args.right.0,40 child: args.child.0,41 units: args.units.try_to_u64(),42 delay_millis: args.delay_millis.try_to_u64(),43 }44 }45}4647pub struct Admissions {48 memory: Binding<memory::Memory>,49 owner: Principal,50 lease: RefCell<Option<Lease<WorkPriority>>>,51}52pub struct View<'a, A: Access> {53 owner: &'a Admissions,54 memory: MemoryView<'a, A, memory::Memory>,55}56impl Admissions {57 pub fn bind(58 access: &impl Access,59 reference: ModuleRef<memory::Memory>,60 owner: Principal,61 ) -> Result<Rc<Self>> {62 let memory = memory::bind(reference);63 {64 let view = memory.view(access);65 if view.read()?.owner != owner {66 return Err(Error::InvalidInput(67 "admission owner differs from saved contract",68 ));69 }70 }71 Ok(Rc::new(Self {72 memory,73 owner,74 lease: RefCell::new(None),75 }))76 }77 pub fn view<'a, A: Access>(&'a self, access: &'a A) -> View<'a, A> {78 View {79 owner: self,80 memory: self.memory.view(access),81 }82 }83 pub fn shutdown(&self) {84 drop(self.lease.borrow_mut().take());85 }86 pub fn start(87 self: &Rc<Self>,88 scheduler: Scheduler,89 process: impl Fn(&Scope<'_>, u64) -> Result<()> + 'static,90 ) {91 assert!(92 self.lease.borrow().is_none(),93 "one admission driver per root"94 );95 let driver = Rc::new(AdmissionDriver {96 admissions: self.clone(),97 process: Box::new(process),98 });99 *self.lease.borrow_mut() = Some(scheduler.register_work(driver, false));100 }101}102impl<A: Access> View<'_, A> {103 pub fn queued(&self) -> Result<u64> {104 let state = self.memory.read()?;105 Ok((state.entries.len() - state.next_to_start) as u64)106 }107 pub fn status(&self, caller: Principal, id: u64) -> Result<Option<api::RequestStatus>> {108 if caller != self.owner.owner || id == 0 {109 return Ok(None);110 }111 let state = self.memory.read()?;112 Ok(usize::try_from(id - 1)113 .ok()114 .and_then(|index| state.entries.get(index))115 .map(|entry| match entry.status {116 Status::Pending => api::RequestStatus::Pending,117 Status::Started {118 workflow,119 execution,120 received_at,121 } => api::RequestStatus::Started {122 workflow: workflow.into(),123 execution: execution.into(),124 received_at,125 },126 Status::Rejected(problem) => api::RequestStatus::Rejected(problem.into()),127 }))128 }129 fn readiness(&self) -> Result<Readiness<WorkPriority>> {130 let pending = self.queued()?;131 Ok(Readiness {132 priority: (pending != 0).then_some(WorkPriority::Interactive),133 deadline: None,134 backlog: pending,135 })136 }137}138impl View<'_, Scope<'_>> {139 pub fn enqueue(140 &self,141 caller: Principal,142 workflow: Workflow,143 args: Input,144 received_at: u64,145 ) -> Outcome<u64> {146 let (Some(run), Some(job), Some(units), Some(delay_millis)) =147 (args.run, args.job, args.units, args.delay_millis)148 else {149 return Ok(Err(Problem::Busy));150 };151 if caller != self.owner.owner152 || run > 1_000_000153 || job > 1_000_000154 || delay_millis > 60_000155 || self.queued()? >= MAX_PENDING156 {157 return Ok(Err(Problem::Busy));158 }159 let id = {160 let mut state = self.memory.write()?;161 if state.entries.len() == MAX_RECEIPTS {162 return Ok(Err(Problem::Busy));163 }164 state.entries.push(Entry {165 caller,166 left: args.left,167 right: args.right,168 child: args.child,169 run,170 job,171 units,172 received_at,173 delay_millis,174 workflow: workflow.into(),175 status: Status::Pending,176 });177 state.entries.len() as u64178 };179 if let Some(lease) = self.owner.lease.borrow().as_ref() {180 lease.changed();181 }182 Ok(Ok(id))183 }184 pub fn process_one(185 &self,186 now: u64,187 start: impl FnOnce(Workflow, Seed, u64) -> Outcome<u64>,188 ) -> Result<Option<bool>> {189 let (index, entry) = {190 let state = self.memory.read()?;191 let Some(entry) = state.entries.get(state.next_to_start) else {192 return Ok(None);193 };194 (state.next_to_start, entry.clone())195 };196 if !matches!(entry.status, Status::Pending) {197 return Err(Error::Corrupt(198 "admission cursor points to resolved request",199 ));200 }201 let result = match (202 now.checked_add(entry.delay_millis * 1_000_000),203 now.checked_add(23 * 60 * 60 * 1_000_000_000),204 ) {205 (Some(wake_at), Some(expires_at)) => start(206 entry.workflow.into(),207 Seed {208 caller: entry.caller,209 run: entry.run,210 job: entry.job,211 left: entry.left,212 right: entry.right,213 child: entry.child,214 units: entry.units,215 created_at: now,216 wake_at,217 expires_at,218 topic: Vec::new(),219 },220 now,221 )?,222 _ => Err(Problem::Busy),223 };224 let admitted = result.is_ok();225 let status = match result {226 Ok(id) => Status::Started {227 workflow: entry.workflow,228 execution: id,229 received_at: entry.received_at,230 },231 Err(problem) => Status::Rejected(problem.into()),232 };233 let mut state = self.memory.write()?;234 state.entries[index].status = status;235 state.next_to_start = index + 1;236 Ok(Some(admitted))237 }238}239struct AdmissionDriver {240 admissions: Rc<Admissions>,241 process: Box<dyn Fn(&Scope<'_>, u64) -> Result<()>>,242}243impl WorkDriver for AdmissionDriver {244 fn readiness(&self, scope: &ReadScope<'_>, _: u64) -> Readiness<WorkPriority> {245 self.admissions246 .view(scope)247 .readiness()248 .expect("admission readiness storage")249 }250 fn step(&self, scope: &Scope<'_>, _: WorkPriority, now: u64) -> Result<Step<WorkPriority>> {251 (self.process)(scope, now)?;252 Ok(Step::done(self.admissions.view(scope).readiness()?))253 }254}255256#[cfg(test)]257mod tests {258 use super::*;259 const KEY: cdk_rsx_store::MemoryKey<memory::Memory> =260 unsafe { cdk_rsx_store::MemoryKey::new() };261 struct Harness {262 actor: cdk_rsx_store::Actor<memory::Memory>,263 service: Rc<Admissions>,264 }265 impl Harness {266 fn install(store: &cdk_rsx_store::Store, owner: Principal) -> Self {267 let actor = store268 .install(&KEY, |cx| Ok(memory::new(cx, owner).unwrap()))269 .unwrap();270 Self::bind(actor, owner)271 }272 fn reopen(store: &cdk_rsx_store::Store, owner: Principal) -> Self {273 Self::bind(store.open(&KEY).unwrap(), owner)274 }275 fn bind(actor: cdk_rsx_store::Actor<memory::Memory>, owner: Principal) -> Self {276 let service = actor277 .read(|cx, root| Ok(Admissions::bind(cx, root, owner).unwrap()))278 .unwrap();279 Self { actor, service }280 }281 fn queued(&self) -> u64 {282 self.actor283 .read(|cx, _| Ok(self.service.view(cx).queued().unwrap()))284 .unwrap()285 }286 fn enqueue(287 &self,288 caller: Principal,289 workflow: Workflow,290 args: Input,291 at: u64,292 ) -> Outcome<u64> {293 self.actor294 .with(|cx, _| Ok(self.service.view(cx).enqueue(caller, workflow, args, at)))?295 }296 fn process_one(297 &self,298 now: u64,299 start: impl FnOnce(Workflow, Seed, u64) -> Outcome<u64>,300 ) -> Result<Option<bool>> {301 self.actor302 .with(|cx, _| Ok(self.service.view(cx).process_one(now, start)))?303 }304 fn status(&self, caller: Principal, id: u64) -> Result<Option<api::RequestStatus>> {305 self.actor306 .read(|cx, _| Ok(self.service.view(cx).status(caller, id)))?307 }308 }309 fn args(job: u64) -> Input {310 Input {311 run: Some(1),312 job: Some(job),313 left: Principal::anonymous(),314 right: Principal::anonymous(),315 child: Principal::anonymous(),316 units: Some(1),317 delay_millis: Some(17),318 }319 }320 #[test]321 fn delayed_admission_reopen_preserves_fifo_receipt_and_starts_clocks_at_admission() {322 let store = cdk_rsx_store::Store::default();323 let owner = Principal::anonymous();324 let admissions = Harness::install(&store, owner);325 assert_eq!(326 admissions327 .enqueue(owner, Workflow::Local, args(2), 7)328 .unwrap(),329 Ok(1)330 );331 assert_eq!(332 admissions333 .enqueue(owner, Workflow::Relay, args(3), 8)334 .unwrap(),335 Ok(2)336 );337 drop(admissions);338 let admissions = Harness::reopen(&store, owner);339 assert_eq!(admissions.queued(), 2);340 let now = 25 * 60 * 60 * 1_000_000_000;341 assert_eq!(342 admissions343 .process_one(now, |kind, seed, at| {344 assert_eq!(kind, Workflow::Local);345 assert_eq!(seed.job, 2);346 assert_eq!(seed.created_at, now);347 assert_eq!(seed.wake_at, now + 17_000_000);348 assert_eq!(seed.expires_at, now + 23 * 60 * 60 * 1_000_000_000);349 assert_eq!(at, now);350 Ok(Ok(71))351 })352 .unwrap(),353 Some(true)354 );355 assert!(matches!(356 admissions.status(owner, 1).unwrap(),357 Some(api::RequestStatus::Started { received_at: 7, .. })358 ));359 admissions360 .process_one(now, |kind, seed, _| {361 assert_eq!(kind, Workflow::Relay);362 assert_eq!(seed.job, 3);363 Ok(Err(Problem::Busy))364 })365 .unwrap();366 assert_eq!(admissions.queued(), 0);367 assert!(matches!(368 admissions.status(owner, 2).unwrap(),369 Some(api::RequestStatus::Rejected(Problem::Busy))370 ));371 }372 #[test]373 fn bounds_overflow_and_pending_capacity_reject_before_effects() {374 let owner = Principal::anonymous();375 let store = cdk_rsx_store::Store::default();376 let admissions = Harness::install(&store, owner);377 let mut bad = args(0);378 bad.delay_millis = Some(60_001);379 assert_eq!(380 admissions.enqueue(owner, Workflow::Local, bad, 0).unwrap(),381 Err(Problem::Busy)382 );383 for _ in 0..MAX_PENDING {384 assert!(385 admissions386 .enqueue(owner, Workflow::Local, args(1), 0)387 .unwrap()388 .is_ok()389 );390 }391 assert_eq!(392 admissions393 .enqueue(owner, Workflow::Local, args(1), 0)394 .unwrap(),395 Err(Problem::Busy)396 );397 assert_eq!(398 admissions399 .process_one(u64::MAX, |_, _, _| panic!(400 "overflow must reject before effect"401 ))402 .unwrap(),403 Some(false)404 );405 assert!(406 admissions407 .enqueue(owner, Workflow::Local, args(1), 0)408 .unwrap()409 .is_ok()410 );411 }412413 #[test]414 fn wire_normalization_keeps_overflow_and_owner_rejection_inside_admission() {415 use cdk_rsx::wire::{Nat, evolve::Fixed};416 let owner = Principal::anonymous();417 let store = cdk_rsx_store::Store::default();418 let admissions = Harness::install(&store, owner);419 for field in 0..4 {420 let mut input = api::Start {421 run: 1u64.into(),422 job: 2u64.into(),423 left: Fixed(owner),424 right: Fixed(owner),425 child: Fixed(owner),426 units: 3u64.into(),427 delay_millis: 4u64.into(),428 };429 let overflow = Nat::from_le_bytes(vec![255; 9]).unwrap();430 match field {431 0 => input.run = overflow,432 1 => input.job = overflow,433 2 => input.units = overflow,434 3 => input.delay_millis = overflow,435 _ => unreachable!(),436 }437 assert_eq!(438 admissions439 .enqueue(owner, Workflow::Local, input.into(), 0)440 .unwrap(),441 Err(Problem::Busy)442 );443 assert_eq!(admissions.queued(), 0);444 assert_eq!(admissions.status(owner, 1).unwrap(), None);445 }446 let foreign = Principal::from_slice(&[1]);447 assert_eq!(448 admissions449 .enqueue(foreign, Workflow::Local, args(1), 0)450 .unwrap(),451 Err(Problem::Busy)452 );453 assert_eq!(admissions.queued(), 0);454 let mut largest = args(1);455 largest.units = Some(u64::MAX);456 assert_eq!(457 admissions458 .enqueue(owner, Workflow::Local, largest, 0)459 .unwrap(),460 Ok(1)461 );462 admissions463 .process_one(1, |_, seed, _| {464 assert_eq!(seed.units, u64::MAX);465 Ok(Ok(1))466 })467 .unwrap();468 }469470 #[cfg(feature = "tripwire-workload")]471 #[test]472 fn tripwire_overflow_is_validated_then_rejected_without_a_receipt() {473 use crate::ingress::{StartPacket, StartPacketArgs, request};474 use cdk_rsx_reactor::tripwire_codec::principal;475 let owner = Principal::anonymous();476 let store = cdk_rsx_store::Store::default();477 let admissions = Harness::install(&store, owner);478 for field in 0..4 {479 let mut magnitudes = [&[1][..], &[2][..], &[3][..], &[4][..]];480 magnitudes[field] = &[255; 9];481 let args = StartPacketArgs {482 workflow: 0,483 run: magnitudes[0],484 job: magnitudes[1],485 left: principal(owner),486 right: principal(owner),487 child: principal(owner),488 units: magnitudes[2],489 delay_millis: magnitudes[3],490 }491 .encode()492 .unwrap();493 let (kind, input) = StartPacket::with_slice(&args, 2097152, request)494 .unwrap()495 .unwrap();496 assert_eq!(497 admissions.enqueue(owner, kind, input, 0).unwrap(),498 Err(Problem::Busy)499 );500 assert_eq!(admissions.queued(), 0);501 assert_eq!(admissions.status(owner, 1).unwrap(), None);502 }503 assert_eq!(504 admissions505 .enqueue(owner, Workflow::Local, args(1), 0)506 .unwrap(),507 Ok(1)508 );509 }510}