1use crate::time::{Duration, Instant};
16use std::collections::{BTreeMap, BTreeSet};
17use std::error::Error;
18use std::fmt::Debug;
19use std::fmt::{self, Display, Formatter};
20use std::future::Future;
21use std::num::NonZeroUsize;
22use std::pin::Pin;
23use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};
24use std::sync::{Arc, Mutex, Weak};
25use std::task::{Context, Poll, Waker};
26
27const NOT_CANCELLED: u8 = 0;
28const CANCELLED: u8 = 1;
29const RESOURCE_EXHAUSTED: u8 = 2;
30
31#[derive(Debug, Clone)]
32pub struct RuntimeCancellationToken {
33 state: Arc<RuntimeCancellationState>,
34}
35
36#[derive(Debug)]
37struct RuntimeCancellationState {
38 cancellation_reason: AtomicU8,
39 parents: [Option<RuntimeCancellationToken>; 2],
42 next_waiter_id: AtomicU64,
43 waiters: Mutex<BTreeMap<u64, Waker>>,
44}
45
46impl Default for RuntimeCancellationToken {
47 fn default() -> Self {
48 Self {
49 state: Arc::new(RuntimeCancellationState {
50 cancellation_reason: AtomicU8::new(NOT_CANCELLED),
51 parents: [None, None],
52 next_waiter_id: AtomicU64::new(1),
53 waiters: Mutex::new(BTreeMap::new()),
54 }),
55 }
56 }
57}
58
59impl RuntimeCancellationToken {
60 pub fn new() -> Self {
61 Self::default()
62 }
63
64 pub fn cancel(&self) -> bool {
65 self.cancel_with_code(CANCELLED)
66 }
67
68 pub fn cancel_for_resource_exhaustion(&self) -> bool {
72 self.cancel_with_code(RESOURCE_EXHAUSTED)
73 }
74
75 fn cancel_with_code(&self, reason: u8) -> bool {
76 if self
77 .state
78 .cancellation_reason
79 .compare_exchange(NOT_CANCELLED, reason, Ordering::AcqRel, Ordering::Acquire)
80 .is_err()
81 {
82 return false;
83 }
84 let waiters = {
85 let mut waiters = self
86 .state
87 .waiters
88 .lock()
89 .unwrap_or_else(|poisoned| poisoned.into_inner());
90 std::mem::take(&mut *waiters)
91 };
92 for (_, waiter) in waiters {
93 waiter.wake();
94 }
95 true
96 }
97
98 #[inline]
99 pub fn is_cancelled(&self) -> bool {
100 self.reason().is_some()
101 }
102
103 #[inline]
108 fn reason(&self) -> Option<RuntimeCancellationReason> {
109 let code = self.state.cancellation_reason.load(Ordering::Acquire);
110 if code == NOT_CANCELLED && self.state.parents[0].is_none() {
111 return None;
112 }
113 Self::reason_of(&self.state, code)
114 }
115
116 #[cold]
117 #[inline(never)]
118 fn reason_of(state: &RuntimeCancellationState, code: u8) -> Option<RuntimeCancellationReason> {
119 match code {
120 CANCELLED => Some(RuntimeCancellationReason::Cancelled),
121 RESOURCE_EXHAUSTED => Some(RuntimeCancellationReason::ResourceExhausted),
122 _ => state
123 .parents
124 .iter()
125 .flatten()
126 .find_map(RuntimeCancellationToken::reason),
127 }
128 }
129
130 pub fn child(&self) -> Self {
131 Self {
132 state: Arc::new(RuntimeCancellationState {
133 cancellation_reason: AtomicU8::new(NOT_CANCELLED),
134 parents: [Some(self.clone()), None],
135 next_waiter_id: AtomicU64::new(1),
136 waiters: Mutex::new(BTreeMap::new()),
137 }),
138 }
139 }
140
141 fn linked(&self, other: &Self) -> Self {
142 if Arc::ptr_eq(&self.state, &other.state) {
143 return self.child();
144 }
145 Self {
146 state: Arc::new(RuntimeCancellationState {
147 cancellation_reason: AtomicU8::new(NOT_CANCELLED),
148 parents: [Some(self.clone()), Some(other.clone())],
149 next_waiter_id: AtomicU64::new(1),
150 waiters: Mutex::new(BTreeMap::new()),
151 }),
152 }
153 }
154
155 pub fn cancelled(&self) -> RuntimeCancellationFuture<'_> {
157 RuntimeCancellationFuture {
158 token: self,
159 registrations: Vec::new(),
160 }
161 }
162}
163
164struct RuntimeCancellationRegistration {
165 state: Weak<RuntimeCancellationState>,
166 waiter_id: u64,
167}
168
169pub struct RuntimeCancellationFuture<'a> {
171 token: &'a RuntimeCancellationToken,
172 registrations: Vec<RuntimeCancellationRegistration>,
173}
174
175impl Future for RuntimeCancellationFuture<'_> {
176 type Output = ();
177
178 fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
179 if self.token.is_cancelled() {
180 return Poll::Ready(());
181 }
182
183 if self.registrations.is_empty() {
184 let mut pending = vec![self.token];
185 let mut visited = BTreeSet::new();
186 while let Some(current) = pending.pop() {
187 if !visited.insert(Arc::as_ptr(¤t.state)) {
188 continue;
189 }
190 let waiter_id = current.state.next_waiter_id.fetch_add(1, Ordering::Relaxed);
191 current
192 .state
193 .waiters
194 .lock()
195 .unwrap_or_else(|poisoned| poisoned.into_inner())
196 .insert(waiter_id, context.waker().clone());
197 self.registrations.push(RuntimeCancellationRegistration {
198 state: Arc::downgrade(¤t.state),
199 waiter_id,
200 });
201 pending.extend(current.state.parents.iter().flatten());
202 }
203 } else {
204 for registration in &self.registrations {
205 if let Some(state) = registration.state.upgrade()
206 && let Some(waiter) = state
207 .waiters
208 .lock()
209 .unwrap_or_else(|poisoned| poisoned.into_inner())
210 .get_mut(®istration.waiter_id)
211 && !waiter.will_wake(context.waker())
212 {
213 *waiter = context.waker().clone();
214 }
215 }
216 }
217
218 if self.token.is_cancelled() {
219 Poll::Ready(())
220 } else {
221 Poll::Pending
222 }
223 }
224}
225
226impl Drop for RuntimeCancellationFuture<'_> {
227 fn drop(&mut self) {
228 for registration in &self.registrations {
229 if let Some(state) = registration.state.upgrade() {
230 state
231 .waiters
232 .lock()
233 .unwrap_or_else(|poisoned| poisoned.into_inner())
234 .remove(®istration.waiter_id);
235 }
236 }
237 }
238}
239
240pub trait RuntimeIoWavePermit: Debug + Send {}
242
243impl<T: Debug + Send> RuntimeIoWavePermit for T {}
244
245pub trait RuntimeIoWaveController: Debug + Send + Sync {
247 fn try_acquire(
252 &self,
253 slots: NonZeroUsize,
254 context: &RuntimeTaskContext,
255 ) -> Result<Option<Box<dyn RuntimeIoWavePermit>>, RuntimeIoWaveError>;
256
257 fn acquire(
258 &self,
259 slots: NonZeroUsize,
260 context: &RuntimeTaskContext,
261 ) -> Result<Box<dyn RuntimeIoWavePermit>, RuntimeIoWaveError>;
262}
263
264#[derive(Debug, Clone, Copy, PartialEq, Eq)]
265pub enum RuntimeIoWaveError {
266 Stopped(RuntimeCancellationReason),
267 ReservationExceeded {
268 requested_slots: usize,
269 reserved_slots: usize,
270 },
271}
272
273#[derive(Debug)]
274pub enum RuntimeIoWaveTryAcquire {
275 Acquired(Option<Box<dyn RuntimeIoWavePermit>>),
277 Pending,
279}
280
281impl Display for RuntimeIoWaveError {
282 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
283 match self {
284 Self::Stopped(reason) => write!(formatter, "runtime I/O wave stopped: {reason}"),
285 Self::ReservationExceeded {
286 requested_slots,
287 reserved_slots,
288 } => write!(
289 formatter,
290 "runtime I/O wave requested {requested_slots} slots, exceeding the {reserved_slots}-slot reservation"
291 ),
292 }
293 }
294}
295
296impl Error for RuntimeIoWaveError {
297 fn source(&self) -> Option<&(dyn Error + 'static)> {
298 match self {
299 Self::Stopped(reason) => Some(reason),
300 Self::ReservationExceeded { .. } => None,
301 }
302 }
303}
304
305mod admission;
306mod memory;
307mod work;
308pub use admission::{RuntimeAdmissionTrace, RuntimeAdmissionWait, RuntimeWorkPriority};
309pub use memory::{
310 RuntimeMemoryController, RuntimeMemoryError, RuntimeMemoryPermit, RuntimeMemoryTarget,
311};
312
313#[derive(Debug, Clone)]
314pub struct RuntimeTaskContext {
315 cancellation: RuntimeCancellationToken,
316 deadline: Option<Instant>,
317 admitted_parallelism: NonZeroUsize,
318 executor_thread_limit: Option<NonZeroUsize>,
319 memory_reservation: Option<RuntimeMemoryReservation>,
320 memory_controller: Option<Arc<dyn RuntimeMemoryController>>,
321 memory_target: Option<Arc<dyn RuntimeMemoryTarget>>,
322 io_wave_controller: Option<Arc<dyn RuntimeIoWaveController>>,
323 work_budget: Option<Arc<work::RuntimeWorkBudget>>,
324 admission_priority: RuntimeWorkPriority,
325 admission_queue_priority: RuntimeWorkPriority,
326 admission_wait: RuntimeAdmissionWait,
327 admission_trace: Option<RuntimeAdmissionTrace>,
328}
329
330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
332pub struct RuntimeMemoryReservation {
333 memory_bytes: u64,
334 result_bytes: u64,
335}
336
337impl RuntimeMemoryReservation {
338 pub const fn new(memory_bytes: u64, result_bytes: u64) -> Self {
339 Self {
340 memory_bytes,
341 result_bytes,
342 }
343 }
344
345 pub const fn memory_bytes(self) -> u64 {
346 self.memory_bytes
347 }
348
349 pub const fn result_bytes(self) -> u64 {
350 self.result_bytes
351 }
352
353 pub const fn intersect(self, other: Self) -> Self {
354 Self {
355 memory_bytes: if self.memory_bytes < other.memory_bytes {
356 self.memory_bytes
357 } else {
358 other.memory_bytes
359 },
360 result_bytes: if self.result_bytes < other.result_bytes {
361 self.result_bytes
362 } else {
363 other.result_bytes
364 },
365 }
366 }
367}
368
369impl RuntimeTaskContext {
370 pub fn new(cancellation: RuntimeCancellationToken, deadline: Option<Instant>) -> Self {
371 Self {
372 cancellation,
373 deadline,
374 admitted_parallelism: NonZeroUsize::MIN,
375 executor_thread_limit: None,
376 memory_reservation: None,
377 memory_controller: None,
378 memory_target: None,
379 io_wave_controller: None,
380 work_budget: None,
381 admission_priority: RuntimeWorkPriority::Foreground,
382 admission_queue_priority: RuntimeWorkPriority::Foreground,
383 admission_wait: RuntimeAdmissionWait::Refuse,
384 admission_trace: None,
385 }
386 }
387
388 pub fn without_deadline(cancellation: RuntimeCancellationToken) -> Self {
389 Self::new(cancellation, None)
390 }
391
392 pub fn with_timeout(timeout: Duration) -> Self {
393 Self::new(
394 RuntimeCancellationToken::new(),
395 Instant::now().checked_add(timeout),
396 )
397 }
398
399 pub fn cancellation(&self) -> &RuntimeCancellationToken {
400 &self.cancellation
401 }
402
403 pub fn child(&self) -> Self {
404 Self {
405 cancellation: self.cancellation.child(),
406 deadline: self.deadline,
407 admitted_parallelism: self.admitted_parallelism,
408 executor_thread_limit: self.executor_thread_limit,
409 memory_reservation: self.memory_reservation,
410 memory_controller: self.memory_controller.clone(),
411 memory_target: self.memory_target.clone(),
412 io_wave_controller: self.io_wave_controller.clone(),
413 work_budget: self.work_budget.clone(),
414 admission_priority: self.admission_priority,
415 admission_queue_priority: self.admission_queue_priority,
416 admission_wait: self.admission_wait,
417 admission_trace: self.admission_trace.clone(),
418 }
419 }
420
421 pub fn constrained_by(&self, request: &Self) -> crate::Result<Self> {
426 fn controller<T: ?Sized>(
427 parent: &Option<Arc<T>>,
428 request: &Option<Arc<T>>,
429 resource: &str,
430 ) -> crate::Result<Option<Arc<T>>> {
431 match (parent, request) {
432 (Some(parent), Some(request)) if !Arc::ptr_eq(parent, request) => {
433 Err(crate::HawDBError::Execution(format!(
434 "request task context carries a different {resource} admission"
435 )))
436 }
437 (Some(parent), _) => Ok(Some(parent.clone())),
438 (_, request) => Ok(request.clone()),
439 }
440 }
441 fn minimum<T: Ord + Copy>(left: Option<T>, right: Option<T>) -> Option<T> {
442 match (left, right) {
443 (Some(left), Some(right)) => Some(left.min(right)),
444 (left, right) => left.or(right),
445 }
446 }
447 Ok(Self {
448 cancellation: self.cancellation.linked(&request.cancellation),
449 deadline: minimum(self.deadline, request.deadline),
450 admitted_parallelism: self.admitted_parallelism.min(request.admitted_parallelism),
451 executor_thread_limit: minimum(
452 self.executor_thread_limit,
453 request.executor_thread_limit,
454 ),
455 memory_reservation: match (self.memory_reservation, request.memory_reservation) {
456 (Some(parent), Some(request)) => Some(parent.intersect(request)),
457 (parent, request) => parent.or(request),
458 },
459 memory_controller: controller(
460 &self.memory_controller,
461 &request.memory_controller,
462 "memory",
463 )?,
464 memory_target: controller(
465 &self.memory_target,
466 &request.memory_target,
467 "memory target",
468 )?,
469 io_wave_controller: controller(
470 &self.io_wave_controller,
471 &request.io_wave_controller,
472 "I/O",
473 )?,
474 work_budget: work::RuntimeWorkBudget::intersect(
475 &self.work_budget,
476 &request.work_budget,
477 ),
478 admission_priority: self
481 .admission_priority
482 .lowered_by(request.admission_priority),
483 admission_queue_priority: self
484 .admission_queue_priority
485 .lowered_by(request.admission_queue_priority),
486 admission_wait: match self.admission_wait {
487 RuntimeAdmissionWait::Refuse => request.admission_wait,
488 wait => wait,
489 },
490 admission_trace: self
491 .admission_trace
492 .clone()
493 .or_else(|| request.admission_trace.clone()),
494 })
495 }
496
497 pub fn with_admission_priority(mut self, priority: RuntimeWorkPriority) -> Self {
516 self.admission_priority = priority;
517 self
518 }
519
520 pub fn admission_priority(&self) -> RuntimeWorkPriority {
521 self.admission_priority
522 }
523
524 pub fn with_admission_queue_priority(mut self, priority: RuntimeWorkPriority) -> Self {
534 self.admission_queue_priority = priority;
535 self
536 }
537
538 pub fn admission_queue_priority(&self) -> RuntimeWorkPriority {
539 self.admission_queue_priority
540 }
541
542 pub fn with_admission_wait(self, timeout: crate::time::Duration) -> Self {
571 let wait = Instant::now()
572 .checked_add(timeout)
573 .map_or(RuntimeAdmissionWait::Unbounded, RuntimeAdmissionWait::Until);
574 self.with_admission_wait_policy(wait)
575 }
576
577 pub fn with_admission_wait_policy(mut self, wait: RuntimeAdmissionWait) -> Self {
580 self.admission_wait = wait;
581 self
582 }
583
584 pub fn admission_wait(&self) -> RuntimeAdmissionWait {
585 self.admission_wait
586 }
587
588 pub fn with_admission_trace(mut self, trace: RuntimeAdmissionTrace) -> Self {
591 self.admission_trace = Some(trace);
592 self
593 }
594
595 pub fn admission_trace(&self) -> Option<&RuntimeAdmissionTrace> {
596 self.admission_trace.as_ref()
597 }
598
599 pub fn record_admission(&self, queued_for: crate::time::Duration) {
601 if let Some(trace) = &self.admission_trace {
602 trace.record(queued_for);
603 }
604 }
605
606 pub fn with_admitted_parallelism(mut self, admitted_parallelism: NonZeroUsize) -> Self {
611 self.admitted_parallelism = admitted_parallelism;
612 self
613 }
614
615 pub fn admitted_parallelism(&self) -> NonZeroUsize {
616 self.admitted_parallelism
617 }
618
619 pub fn with_executor_thread_limit(mut self, limit: NonZeroUsize) -> Self {
624 self.executor_thread_limit = Some(
625 self.executor_thread_limit
626 .map_or(limit, |current| current.min(limit)),
627 );
628 self
629 }
630
631 pub fn executor_thread_limit(&self) -> Option<NonZeroUsize> {
632 self.executor_thread_limit
633 }
634
635 pub fn with_memory_reservation(mut self, reservation: RuntimeMemoryReservation) -> Self {
641 self.memory_reservation = Some(reservation);
642 self
643 }
644
645 pub fn memory_reservation(&self) -> Option<RuntimeMemoryReservation> {
646 self.memory_reservation
647 }
648
649 pub fn has_resource_controllers(&self) -> bool {
653 self.memory_controller.is_some()
654 || self.memory_target.is_some()
655 || self.io_wave_controller.is_some()
656 }
657
658 pub fn with_memory_target(mut self, target: Arc<dyn RuntimeMemoryTarget>) -> Self {
660 self.memory_target = Some(target);
661 self
662 }
663
664 pub fn working_memory_target(&self, hard_limit: u64) -> u64 {
667 self.memory_target.as_ref().map_or(hard_limit, |target| {
668 target.target_bytes(hard_limit).min(hard_limit)
669 })
670 }
671
672 pub fn with_memory_controller(mut self, controller: Arc<dyn RuntimeMemoryController>) -> Self {
674 self.memory_controller = Some(controller);
675 self
676 }
677
678 pub fn reserve_working_memory(
682 &self,
683 bytes: u64,
684 ) -> Result<Option<Box<dyn RuntimeMemoryPermit>>, RuntimeMemoryError> {
685 self.checkpoint().map_err(RuntimeMemoryError::Stopped)?;
686 if let Some(reservation) = self.memory_reservation
687 && bytes > reservation.memory_bytes()
688 {
689 return Err(RuntimeMemoryError::ReservationExceeded {
690 requested_bytes: bytes,
691 available_bytes: reservation.memory_bytes(),
692 });
693 }
694 self.memory_controller
695 .as_ref()
696 .map(|controller| {
697 controller.reserve(
698 bytes,
699 self.memory_reservation
700 .map_or(u64::MAX, RuntimeMemoryReservation::memory_bytes),
701 )
702 })
703 .transpose()
704 }
705
706 pub fn with_io_wave_controller(mut self, controller: Arc<dyn RuntimeIoWaveController>) -> Self {
708 self.io_wave_controller = Some(controller);
709 self
710 }
711
712 pub fn acquire_io_wave(
717 &self,
718 slots: NonZeroUsize,
719 ) -> Result<Option<Box<dyn RuntimeIoWavePermit>>, RuntimeIoWaveError> {
720 self.checkpoint().map_err(RuntimeIoWaveError::Stopped)?;
721 self.io_wave_controller
722 .as_ref()
723 .map(|controller| controller.acquire(slots, self))
724 .transpose()
725 }
726
727 pub fn try_acquire_io_wave(
732 &self,
733 slots: NonZeroUsize,
734 ) -> Result<RuntimeIoWaveTryAcquire, RuntimeIoWaveError> {
735 self.checkpoint().map_err(RuntimeIoWaveError::Stopped)?;
736 let Some(controller) = &self.io_wave_controller else {
737 return Ok(RuntimeIoWaveTryAcquire::Acquired(None));
738 };
739 controller.try_acquire(slots, self).map(|permit| {
740 permit.map_or(RuntimeIoWaveTryAcquire::Pending, |permit| {
741 RuntimeIoWaveTryAcquire::Acquired(Some(permit))
742 })
743 })
744 }
745
746 pub fn with_work_limit(mut self, limit: usize) -> Self {
749 self.work_budget = Some(Arc::new(work::RuntimeWorkBudget::new(
750 limit,
751 self.work_budget.take(),
752 )));
753 self
754 }
755
756 pub fn has_work_limit(&self) -> bool {
757 self.work_budget.is_some()
758 }
759
760 pub fn work_units(&self) -> usize {
761 self.work_budget.as_ref().map_or(0, |budget| budget.used())
762 }
763
764 pub fn remaining_work(&self) -> Option<usize> {
766 self.work_budget.as_ref().map(|budget| budget.remaining())
767 }
768
769 pub fn check_work_limit(&self) -> crate::Result<()> {
771 match self
772 .work_budget
773 .as_ref()
774 .and_then(|budget| budget.refusal())
775 {
776 Some(error) => Err(error.into()),
777 None => Ok(()),
778 }
779 }
780
781 pub fn charge_work(&self, units: usize) -> crate::Result<()> {
784 let Some(budget) = &self.work_budget else {
785 return Ok(());
786 };
787 self.checkpoint()
788 .map_err(crate::HawDBError::RuntimeTaskStopped)?;
789 budget.charge(units)
790 }
791
792 pub fn deadline(&self) -> Option<Instant> {
793 self.deadline
794 }
795
796 pub fn remaining(&self) -> Option<Duration> {
797 self.deadline
798 .map(|deadline| deadline.saturating_duration_since(Instant::now()))
799 }
800
801 #[inline]
802 pub fn checkpoint(&self) -> Result<(), RuntimeCancellationReason> {
803 self.check_cancellation()?;
804 if self.deadline.is_some() {
805 self.check_deadline_at(Instant::now())?;
806 }
807 Ok(())
808 }
809
810 #[inline]
814 pub fn check_cancellation(&self) -> Result<(), RuntimeCancellationReason> {
815 match self.cancellation.reason() {
816 Some(reason) => Err(reason),
817 None => Ok(()),
818 }
819 }
820
821 #[inline]
823 pub fn check_deadline_at(&self, now: Instant) -> Result<(), RuntimeCancellationReason> {
824 if self.deadline.is_some_and(|deadline| now >= deadline) {
825 return Err(RuntimeCancellationReason::DeadlineExceeded);
826 }
827 Ok(())
828 }
829}
830
831impl Default for RuntimeTaskContext {
832 fn default() -> Self {
833 Self::without_deadline(RuntimeCancellationToken::new())
834 }
835}
836
837#[derive(Debug, Clone, Copy, PartialEq, Eq)]
838pub enum RuntimeCancellationReason {
839 Cancelled,
840 DeadlineExceeded,
841 ResourceExhausted,
842}
843
844impl RuntimeCancellationReason {
845 pub const fn as_str(self) -> &'static str {
846 match self {
847 Self::Cancelled => "cancelled",
848 Self::DeadlineExceeded => "deadline_exceeded",
849 Self::ResourceExhausted => "resource_exhausted",
850 }
851 }
852}
853
854impl Display for RuntimeCancellationReason {
855 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
856 formatter.write_str(self.as_str())
857 }
858}
859
860impl Error for RuntimeCancellationReason {}
861
862#[cfg(test)]
863mod tests {
864 use super::*;
865 use std::sync::atomic::AtomicUsize;
866 use std::sync::atomic::Ordering;
867 use std::task::Wake;
868
869 #[derive(Debug)]
870 struct RecordingIoController {
871 active_slots: Arc<AtomicUsize>,
872 }
873
874 #[derive(Debug)]
875 struct RecordingIoPermit {
876 active_slots: Arc<AtomicUsize>,
877 slots: usize,
878 }
879
880 impl Drop for RecordingIoPermit {
881 fn drop(&mut self) {
882 self.active_slots.fetch_sub(self.slots, Ordering::AcqRel);
883 }
884 }
885
886 impl RuntimeIoWaveController for RecordingIoController {
887 fn try_acquire(
888 &self,
889 slots: NonZeroUsize,
890 context: &RuntimeTaskContext,
891 ) -> Result<Option<Box<dyn RuntimeIoWavePermit>>, RuntimeIoWaveError> {
892 self.acquire(slots, context).map(Some)
893 }
894
895 fn acquire(
896 &self,
897 slots: NonZeroUsize,
898 context: &RuntimeTaskContext,
899 ) -> Result<Box<dyn RuntimeIoWavePermit>, RuntimeIoWaveError> {
900 context.checkpoint().map_err(RuntimeIoWaveError::Stopped)?;
901 self.active_slots.fetch_add(slots.get(), Ordering::AcqRel);
902 Ok(Box::new(RecordingIoPermit {
903 active_slots: Arc::clone(&self.active_slots),
904 slots: slots.get(),
905 }))
906 }
907 }
908
909 #[test]
910 fn cancellation_is_shared_across_context_clones() {
911 let token = RuntimeCancellationToken::new();
912 let context = RuntimeTaskContext::without_deadline(token.clone());
913 assert!(context.checkpoint().is_ok());
914 assert!(token.cancel());
915 assert!(!token.cancel());
916 assert_eq!(
917 context.checkpoint(),
918 Err(RuntimeCancellationReason::Cancelled)
919 );
920 }
921
922 #[test]
923 fn expired_deadline_fails_at_a_cooperative_checkpoint() {
924 let context = RuntimeTaskContext::new(
925 RuntimeCancellationToken::new(),
926 Some(Instant::now() - Duration::from_millis(1)),
927 );
928 assert_eq!(
929 context.checkpoint(),
930 Err(RuntimeCancellationReason::DeadlineExceeded)
931 );
932 }
933
934 #[test]
935 fn child_cancellation_is_local_and_parent_cancellation_propagates() {
936 let parent_token = RuntimeCancellationToken::new();
937 let parent = RuntimeTaskContext::without_deadline(parent_token.clone());
938 let child = parent.child();
939
940 assert!(child.cancellation().cancel());
941 assert!(child.checkpoint().is_err());
942 assert!(parent.checkpoint().is_ok());
943
944 let sibling = parent.child();
945 assert!(parent_token.cancel());
946 assert!(parent.checkpoint().is_err());
947 assert!(sibling.checkpoint().is_err());
948 }
949
950 #[test]
951 fn resource_exhaustion_keeps_its_cause_and_is_local_to_the_child() {
952 let parent = RuntimeTaskContext::default();
953 let child = parent.child();
954 let clone = child.clone();
955 let grandchild = child.child();
956 assert!(child.cancellation().cancel_for_resource_exhaustion());
957 assert!(!clone.cancellation().cancel());
958 assert!(!clone.cancellation().cancel_for_resource_exhaustion());
959 for context in [&child, &clone, &grandchild] {
960 assert_eq!(
961 context.checkpoint(),
962 Err(RuntimeCancellationReason::ResourceExhausted)
963 );
964 }
965 assert_eq!(parent.checkpoint(), Ok(()));
966 assert_eq!(parent.child().checkpoint(), Ok(()));
967
968 let cancelled = parent.child();
969 assert!(cancelled.cancellation().cancel());
970 assert!(!cancelled.cancellation().cancel_for_resource_exhaustion());
971 assert_eq!(
972 cancelled.checkpoint(),
973 Err(RuntimeCancellationReason::Cancelled)
974 );
975 }
976
977 #[test]
978 fn reason_fast_path_and_ancestor_walk_select_the_same_first_cause() {
979 let root = RuntimeCancellationToken::new();
982 assert!(root.state.parents[0].is_none());
983 assert_eq!(root.reason(), None);
984 let first = RuntimeCancellationToken::new();
985 let second = RuntimeCancellationToken::new();
986 let linked = first.linked(&second);
987 let grandchild = linked.child();
988 assert_eq!(linked.reason(), None);
989 assert_eq!(grandchild.reason(), None);
990 assert!(second.cancel_for_resource_exhaustion());
991 assert_eq!(
992 grandchild.reason(),
993 Some(RuntimeCancellationReason::ResourceExhausted)
994 );
995 assert!(first.cancel());
996 for token in [&linked, &grandchild] {
997 assert_eq!(token.reason(), Some(RuntimeCancellationReason::Cancelled));
998 }
999 assert!(grandchild.cancel_for_resource_exhaustion());
1000 assert_eq!(
1001 grandchild.reason(),
1002 Some(RuntimeCancellationReason::ResourceExhausted)
1003 );
1004 assert_eq!(linked.reason(), Some(RuntimeCancellationReason::Cancelled));
1005 assert_eq!(root.reason(), None);
1006 assert!(root.cancel());
1007 assert!(root.is_cancelled());
1008 }
1009
1010 #[derive(Default)]
1011 struct WakeCounter(AtomicUsize);
1012
1013 impl Wake for WakeCounter {
1014 fn wake(self: Arc<Self>) {
1015 self.0.fetch_add(1, Ordering::AcqRel);
1016 }
1017 }
1018
1019 #[test]
1020 fn admission_policy_defaults_to_refusing_foreground_work_and_survives_scoping() {
1021 let default = RuntimeTaskContext::default();
1022 assert_eq!(
1023 default.admission_priority(),
1024 RuntimeWorkPriority::Foreground
1025 );
1026 assert_eq!(default.admission_wait(), RuntimeAdmissionWait::Refuse);
1027
1028 let unbounded = default
1029 .clone()
1030 .with_admission_wait(crate::time::Duration::MAX);
1031 assert_eq!(unbounded.admission_wait(), RuntimeAdmissionWait::Unbounded);
1032 let shadow = RuntimeTaskContext::default()
1033 .with_admission_priority(RuntimeWorkPriority::Background)
1034 .with_admission_wait(crate::time::Duration::from_secs(1));
1035 assert!(matches!(
1036 shadow.admission_wait(),
1037 RuntimeAdmissionWait::Until(_)
1038 ));
1039 let trace = RuntimeAdmissionTrace::new();
1040 let traced = shadow.clone().with_admission_trace(trace.clone());
1041 traced
1042 .child()
1043 .record_admission(crate::time::Duration::from_millis(3));
1044 default
1045 .constrained_by(&traced)
1046 .unwrap()
1047 .record_admission(crate::time::Duration::ZERO);
1048 assert_eq!(trace.admissions(), 2);
1049 assert_eq!(trace.queued_for(), crate::time::Duration::from_millis(3));
1050 default.record_admission(crate::time::Duration::from_secs(1));
1051 let child = shadow.child();
1052 assert_eq!(child.admission_priority(), RuntimeWorkPriority::Background);
1053 assert_eq!(child.admission_wait(), shadow.admission_wait());
1054
1055 let combined = default.constrained_by(&shadow).unwrap();
1058 assert_eq!(
1059 combined.admission_priority(),
1060 RuntimeWorkPriority::Background
1061 );
1062 assert_eq!(combined.admission_wait(), shadow.admission_wait());
1063 let combined = shadow.constrained_by(&unbounded).unwrap();
1064 assert_eq!(
1065 combined.admission_priority(),
1066 RuntimeWorkPriority::Background
1067 );
1068 assert_eq!(combined.admission_wait(), shadow.admission_wait());
1069 assert_eq!(
1070 shadow
1071 .with_admission_wait_policy(RuntimeAdmissionWait::Refuse)
1072 .admission_wait(),
1073 RuntimeAdmissionWait::Refuse
1074 );
1075 }
1076
1077 #[test]
1078 fn constrained_context_observes_both_cancellations_without_cancelling_parents() {
1079 for cancel_parent in [false, true] {
1080 let parent = RuntimeTaskContext::default();
1081 let request = RuntimeTaskContext::default();
1082 let combined = parent.constrained_by(&request).unwrap();
1083 let counter = Arc::new(WakeCounter::default());
1084 let waker = Waker::from(counter.clone());
1085 let mut context = Context::from_waker(&waker);
1086 let mut cancelled = Box::pin(combined.cancellation().cancelled());
1087 assert!(cancelled.as_mut().poll(&mut context).is_pending());
1088 if cancel_parent {
1089 parent.cancellation().cancel();
1090 } else {
1091 request.cancellation().cancel();
1092 }
1093 assert_eq!(counter.0.load(Ordering::Acquire), 1);
1094 assert!(cancelled.as_mut().poll(&mut context).is_ready());
1095 assert_eq!(
1096 combined.checkpoint(),
1097 Err(RuntimeCancellationReason::Cancelled)
1098 );
1099 }
1100 let parent = RuntimeTaskContext::default();
1101 let request = RuntimeTaskContext::default();
1102 let combined = parent.constrained_by(&request).unwrap();
1103 combined.cancellation().cancel();
1104 assert!(parent.checkpoint().is_ok());
1105 assert!(request.checkpoint().is_ok());
1106 }
1107
1108 #[test]
1109 fn constrained_descendants_register_shared_ancestors_once_and_unregister_on_drop() {
1110 let parent = RuntimeTaskContext::default();
1111 let request = parent.child();
1112 let combined = parent.constrained_by(&request).unwrap();
1113 let waker = Waker::from(Arc::new(WakeCounter::default()));
1114 let mut context = Context::from_waker(&waker);
1115 let mut cancelled = Box::pin(combined.cancellation().cancelled());
1116 assert!(cancelled.as_mut().poll(&mut context).is_pending());
1117 assert_eq!(parent.cancellation.state.waiters.lock().unwrap().len(), 1);
1118 assert_eq!(request.cancellation.state.waiters.lock().unwrap().len(), 1);
1119 drop(cancelled);
1120 assert!(parent.cancellation.state.waiters.lock().unwrap().is_empty());
1121 assert!(request
1122 .cancellation
1123 .state
1124 .waiters
1125 .lock()
1126 .unwrap()
1127 .is_empty());
1128 }
1129
1130 #[test]
1131 fn constrained_context_tightens_limits_and_keeps_the_original_io_controller() {
1132 let active_slots = Arc::new(AtomicUsize::new(0));
1133 let parent = RuntimeTaskContext::with_timeout(Duration::from_secs(5))
1134 .with_memory_reservation(RuntimeMemoryReservation::new(100, 20))
1135 .with_admitted_parallelism(NonZeroUsize::new(4).unwrap())
1136 .with_io_wave_controller(Arc::new(RecordingIoController {
1137 active_slots: active_slots.clone(),
1138 }));
1139 let request = RuntimeTaskContext::with_timeout(Duration::from_secs(10))
1140 .with_memory_reservation(RuntimeMemoryReservation::new(30, 50))
1141 .with_admitted_parallelism(NonZeroUsize::new(2).unwrap());
1142 let combined = parent.constrained_by(&request).unwrap();
1143 assert_eq!(combined.deadline(), parent.deadline());
1144 assert_eq!(
1145 combined.memory_reservation(),
1146 Some(RuntimeMemoryReservation::new(30, 20))
1147 );
1148 assert_eq!(combined.admitted_parallelism().get(), 2);
1149 let io = combined.acquire_io_wave(NonZeroUsize::MIN).unwrap();
1150 assert_eq!(active_slots.load(Ordering::Acquire), 1);
1151 drop(io);
1152 assert_eq!(active_slots.load(Ordering::Acquire), 0);
1153 assert!(parent.constrained_by(&parent.child()).is_ok());
1154 let independent =
1155 request.with_io_wave_controller(Arc::new(RecordingIoController { active_slots }));
1156 assert!(parent.constrained_by(&independent).is_err());
1157 }
1158
1159 #[test]
1160 fn cancellation_future_is_woken_by_parent_cancellation() {
1161 let parent = RuntimeCancellationToken::new();
1162 let child = parent.child();
1163 let counter = Arc::new(WakeCounter::default());
1164 let waker = Waker::from(Arc::clone(&counter));
1165 let mut context = Context::from_waker(&waker);
1166 let mut cancelled = Box::pin(child.cancelled());
1167
1168 assert!(cancelled.as_mut().poll(&mut context).is_pending());
1169 assert!(parent.cancel());
1170 assert_eq!(counter.0.load(Ordering::Acquire), 1);
1171 assert!(cancelled.as_mut().poll(&mut context).is_ready());
1172 }
1173
1174 #[test]
1175 fn resource_exhaustion_wakes_waiters_on_descendants() {
1176 let parent = RuntimeTaskContext::default();
1177 let child = parent.child();
1178 let counter = Arc::new(WakeCounter::default());
1179 let waker = Waker::from(Arc::clone(&counter));
1180 let mut context = Context::from_waker(&waker);
1181 let mut cancelled = Box::pin(child.cancellation().cancelled());
1182 assert!(cancelled.as_mut().poll(&mut context).is_pending());
1183 assert!(parent.cancellation().cancel_for_resource_exhaustion());
1184 assert_eq!(counter.0.load(Ordering::Acquire), 1);
1185 assert!(cancelled.as_mut().poll(&mut context).is_ready());
1186 assert_eq!(
1187 child.checkpoint(),
1188 Err(RuntimeCancellationReason::ResourceExhausted)
1189 );
1190 }
1191
1192 #[test]
1193 fn dropped_cancellation_future_unregisters_from_its_parent_chain() {
1194 let parent = RuntimeCancellationToken::new();
1195 let child = parent.child();
1196 let counter = Arc::new(WakeCounter::default());
1197 let waker = Waker::from(Arc::clone(&counter));
1198 let mut context = Context::from_waker(&waker);
1199 let mut cancelled = Box::pin(child.cancelled());
1200
1201 assert!(cancelled.as_mut().poll(&mut context).is_pending());
1202 drop(cancelled);
1203 assert!(parent.cancel());
1204 assert_eq!(counter.0.load(Ordering::Acquire), 0);
1205 }
1206
1207 #[test]
1208 fn child_preserves_admitted_parallelism() {
1209 let context = RuntimeTaskContext::default()
1210 .with_admitted_parallelism(NonZeroUsize::new(4).expect("test parallelism is non-zero"))
1211 .with_executor_thread_limit(
1212 NonZeroUsize::new(2).expect("test thread limit is non-zero"),
1213 );
1214
1215 assert_eq!(context.admitted_parallelism().get(), 4);
1216 assert_eq!(context.child().admitted_parallelism().get(), 4);
1217 assert_eq!(context.child().executor_thread_limit().unwrap().get(), 2);
1218 }
1219
1220 #[test]
1221 fn child_preserves_memory_reservation() {
1222 let reservation = RuntimeMemoryReservation::new(128, 32);
1223 let context = RuntimeTaskContext::default().with_memory_reservation(reservation);
1224
1225 assert_eq!(context.memory_reservation(), Some(reservation));
1226 assert_eq!(context.child().memory_reservation(), Some(reservation));
1227 }
1228
1229 #[test]
1230 fn child_preserves_io_controller_and_permit_releases_slots() {
1231 let active_slots = Arc::new(AtomicUsize::new(0));
1232 let context = RuntimeTaskContext::default().with_io_wave_controller(Arc::new(
1233 RecordingIoController {
1234 active_slots: Arc::clone(&active_slots),
1235 },
1236 ));
1237
1238 let permit = context
1239 .child()
1240 .acquire_io_wave(NonZeroUsize::new(2).unwrap())
1241 .unwrap()
1242 .unwrap();
1243 assert_eq!(active_slots.load(Ordering::Acquire), 2);
1244 drop(permit);
1245 assert_eq!(active_slots.load(Ordering::Acquire), 0);
1246 }
1247
1248 #[test]
1249 fn ungoverned_try_acquire_is_immediately_ready() {
1250 let acquired = RuntimeTaskContext::default()
1251 .try_acquire_io_wave(NonZeroUsize::new(2).unwrap())
1252 .unwrap();
1253
1254 assert!(matches!(acquired, RuntimeIoWaveTryAcquire::Acquired(None)));
1255 }
1256}