1use hawdb_core::{RuntimeCancellationReason, RuntimeTaskContext};
16use hawdb_qos::{
17 RuntimeAdmissionCode, RuntimeAdmissionError, RuntimeGovernor, RuntimeGovernorSnapshot,
18 RuntimeRetainedMemory, RuntimeWorkKind, RuntimeWorkPriority, RuntimeWorkRequest,
19};
20use std::error::Error;
21use std::fmt::{self, Debug, Display, Formatter};
22use std::future::{poll_fn, Future};
23use std::num::NonZeroUsize;
24use std::sync::{Arc, Mutex};
25use std::task::Poll;
26use std::time::{Duration, Instant};
27use tokio::runtime::{Builder, Runtime};
28use tokio::sync::mpsc;
29use tokio::task::{JoinError, JoinHandle};
30
31mod segment_read;
32
33pub use segment_read::{TokioSegmentReadExecutionError, TokioSegmentReadExecutor};
34
35pub use tokio::runtime::Handle as TokioHandle;
36pub use tokio::runtime::{Builder as TokioRuntimeBuilder, Runtime as TokioRuntime};
37
38#[derive(Debug)]
39pub struct TokioBoundedSender<T>(mpsc::Sender<T>);
40
41impl<T> Clone for TokioBoundedSender<T> {
42 fn clone(&self) -> Self {
43 Self(self.0.clone())
44 }
45}
46
47impl<T> TokioBoundedSender<T> {
48 pub async fn send(&self, value: T) -> Result<(), T> {
49 self.0.send(value).await.map_err(|error| error.0)
50 }
51
52 pub fn try_send(&self, value: T) -> Result<(), TokioBoundedTrySendError<T>> {
53 self.0.try_send(value).map_err(|error| match error {
54 mpsc::error::TrySendError::Full(value) => TokioBoundedTrySendError::Full(value),
55 mpsc::error::TrySendError::Closed(value) => TokioBoundedTrySendError::Closed(value),
56 })
57 }
58}
59
60#[derive(Debug)]
61pub enum TokioBoundedTrySendError<T> {
62 Full(T),
63 Closed(T),
64}
65
66#[derive(Debug)]
67pub struct TokioBoundedReceiver<T>(mpsc::Receiver<T>);
68
69impl<T> TokioBoundedReceiver<T> {
70 pub async fn recv(&mut self) -> Option<T> {
71 self.0.recv().await
72 }
73
74 pub fn close(&mut self) {
75 self.0.close();
76 }
77}
78
79pub fn tokio_bounded_channel<T>(
80 capacity: NonZeroUsize,
81) -> (TokioBoundedSender<T>, TokioBoundedReceiver<T>) {
82 let (sender, receiver) = mpsc::channel(capacity.get());
83 (TokioBoundedSender(sender), TokioBoundedReceiver(receiver))
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum TokioRuntimeOwnership {
88 Borrowed,
89 Owned,
90}
91
92impl TokioRuntimeOwnership {
93 pub const fn as_str(self) -> &'static str {
94 match self {
95 Self::Borrowed => "borrowed",
96 Self::Owned => "owned",
97 }
98 }
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub struct TokioRuntimeConfig {
103 pub async_worker_threads: Option<NonZeroUsize>,
104 pub max_blocking_threads: Option<NonZeroUsize>,
105 pub resource_refresh_interval: Duration,
106 pub blocking_thread_keep_alive: Duration,
107}
108
109impl TokioRuntimeConfig {
110 pub fn from_governor(governor: &RuntimeGovernor) -> Self {
111 let snapshot = governor.snapshot();
112 let limits = snapshot.limits;
113 let async_workers = limits.effective_cpu_slots.get().clamp(1, 2);
114 Self {
115 async_worker_threads: NonZeroUsize::new(async_workers),
116 max_blocking_threads: Some(limits.effective_cpu_slots),
117 ..Self::default()
118 }
119 }
120}
121
122impl Default for TokioRuntimeConfig {
123 fn default() -> Self {
124 Self {
125 async_worker_threads: NonZeroUsize::new(1),
126 max_blocking_threads: NonZeroUsize::new(4),
127 resource_refresh_interval: Duration::from_secs(1),
128 blocking_thread_keep_alive: Duration::from_secs(10),
129 }
130 }
131}
132
133#[derive(Clone)]
134pub struct TokioRuntimeAdapter {
135 handle: TokioHandle,
136 ownership: TokioRuntimeOwnership,
137 owned_runtime: Option<Arc<OwnedRuntime>>,
138 governor: RuntimeGovernor,
139 config: TokioRuntimeConfig,
140 last_resource_refresh: Arc<Mutex<Instant>>,
141}
142
143impl Debug for TokioRuntimeAdapter {
144 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
145 formatter
146 .debug_struct("TokioRuntimeAdapter")
147 .field("ownership", &self.ownership)
148 .field("governor", &self.governor.snapshot())
149 .field("config", &self.config)
150 .finish_non_exhaustive()
151 }
152}
153
154struct OwnedRuntime {
155 runtime: Option<Runtime>,
156}
157
158impl Debug for OwnedRuntime {
159 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
160 formatter
161 .debug_struct("OwnedRuntime")
162 .field("running", &self.runtime.is_some())
163 .finish()
164 }
165}
166
167impl Drop for OwnedRuntime {
168 fn drop(&mut self) {
169 if let Some(runtime) = self.runtime.take() {
170 runtime.shutdown_background();
171 }
172 }
173}
174
175#[derive(Debug)]
176pub enum TokioRuntimeError {
177 NestedOwnedRuntime,
178 BlockOnWithinRuntime,
179 Build(std::io::Error),
180}
181
182impl Display for TokioRuntimeError {
183 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
184 match self {
185 Self::NestedOwnedRuntime => formatter.write_str(
186 "an owned HawDB Tokio runtime cannot be created inside an active Tokio runtime",
187 ),
188 Self::BlockOnWithinRuntime => formatter.write_str(
189 "blocking on the HawDB Tokio adapter is not allowed inside an active Tokio runtime",
190 ),
191 Self::Build(error) => write!(formatter, "failed to build HawDB Tokio runtime: {error}"),
192 }
193 }
194}
195
196impl Error for TokioRuntimeError {
197 fn source(&self) -> Option<&(dyn Error + 'static)> {
198 match self {
199 Self::Build(error) => Some(error),
200 Self::NestedOwnedRuntime | Self::BlockOnWithinRuntime => None,
201 }
202 }
203}
204
205#[derive(Debug)]
206pub enum TokioTaskError<E> {
207 Admission(RuntimeAdmissionError),
208 Stopped(RuntimeCancellationReason),
209 Join(JoinError),
210 Operation(E),
211}
212
213impl<E: Display> Display for TokioTaskError<E> {
214 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
215 match self {
216 Self::Admission(error) => Display::fmt(error, formatter),
217 Self::Stopped(reason) => write!(formatter, "runtime task stopped: {reason}"),
218 Self::Join(error) => write!(formatter, "runtime task join failed: {error}"),
219 Self::Operation(error) => write!(formatter, "runtime task failed: {error}"),
220 }
221 }
222}
223
224impl<E: Error + 'static> Error for TokioTaskError<E> {
225 fn source(&self) -> Option<&(dyn Error + 'static)> {
226 match self {
227 Self::Admission(error) => Some(error),
228 Self::Stopped(reason) => Some(reason),
229 Self::Join(error) => Some(error),
230 Self::Operation(error) => Some(error),
231 }
232 }
233}
234
235impl TokioRuntimeAdapter {
236 pub fn borrowed(
237 handle: TokioHandle,
238 governor: RuntimeGovernor,
239 config: TokioRuntimeConfig,
240 ) -> Self {
241 Self {
242 handle,
243 ownership: TokioRuntimeOwnership::Borrowed,
244 owned_runtime: None,
245 governor,
246 config,
247 last_resource_refresh: Arc::new(Mutex::new(Instant::now())),
248 }
249 }
250
251 pub fn owned(
252 governor: RuntimeGovernor,
253 config: TokioRuntimeConfig,
254 ) -> Result<Self, TokioRuntimeError> {
255 if TokioHandle::try_current().is_ok() {
256 return Err(TokioRuntimeError::NestedOwnedRuntime);
257 }
258 let mut builder = Builder::new_multi_thread();
259 builder.enable_time();
260 builder.thread_name("hawdb-runtime");
261 builder.thread_keep_alive(config.blocking_thread_keep_alive);
262 if let Some(worker_threads) = config.async_worker_threads {
263 builder.worker_threads(worker_threads.get());
264 }
265 if let Some(max_blocking_threads) = config.max_blocking_threads {
266 builder.max_blocking_threads(max_blocking_threads.get());
267 }
268 let runtime = builder.build().map_err(TokioRuntimeError::Build)?;
269 let handle = runtime.handle().clone();
270 Ok(Self {
271 handle,
272 ownership: TokioRuntimeOwnership::Owned,
273 owned_runtime: Some(Arc::new(OwnedRuntime {
274 runtime: Some(runtime),
275 })),
276 governor,
277 config,
278 last_resource_refresh: Arc::new(Mutex::new(Instant::now())),
279 })
280 }
281
282 pub fn ownership(&self) -> TokioRuntimeOwnership {
283 self.ownership
284 }
285
286 pub fn handle(&self) -> &TokioHandle {
287 &self.handle
288 }
289
290 pub fn governor(&self) -> &RuntimeGovernor {
291 &self.governor
292 }
293
294 pub fn governor_snapshot(&self) -> RuntimeGovernorSnapshot {
295 self.governor.snapshot()
296 }
297
298 pub fn config(&self) -> TokioRuntimeConfig {
299 self.config
300 }
301
302 pub fn owns_runtime(&self) -> bool {
303 self.owned_runtime.is_some()
304 }
305
306 pub fn block_on<F>(&self, future: F) -> Result<F::Output, TokioRuntimeError>
307 where
308 F: Future,
309 {
310 if TokioHandle::try_current().is_ok() {
311 return Err(TokioRuntimeError::BlockOnWithinRuntime);
312 }
313 Ok(self.handle.block_on(future))
314 }
315
316 pub async fn execute_blocking<T, E, F>(
317 &self,
318 request: RuntimeWorkRequest,
319 context: RuntimeTaskContext,
320 operation: F,
321 ) -> Result<T, TokioTaskError<E>>
322 where
323 T: Send + 'static,
324 E: Send + 'static,
325 F: FnOnce(&RuntimeTaskContext) -> Result<T, E> + Send + 'static,
326 {
327 self.execute_blocking_with_request_factory(move |_| request, context, operation)
328 .await
329 }
330
331 pub async fn prepare_blocking<T, E, F>(
338 &self,
339 priority: RuntimeWorkPriority,
340 memory_bytes: u64,
341 context: RuntimeTaskContext,
342 operation: F,
343 ) -> Result<(T, RuntimeRetainedMemory), TokioTaskError<E>>
344 where
345 T: Send + 'static,
346 E: Send + 'static,
347 F: FnOnce(&RuntimeTaskContext) -> Result<T, E> + Send + 'static,
348 {
349 let request = RuntimeWorkRequest::new(priority, RuntimeWorkKind::Control)
350 .with_cpu_slots(1)
351 .with_blocking(true)
352 .with_memory_bytes(memory_bytes);
353 let permit = self.acquire(request, &context).await?;
354 let task_context = permit.bind_task_context(context);
355 let join = self.handle.spawn_blocking(move || {
356 task_context.checkpoint().map_err(TokioTaskError::Stopped)?;
357 let result = operation(&task_context);
358 let value = finish_operation(&task_context, result, true)?;
359 let memory = permit
360 .into_retained_memory()
361 .expect("control work owns a fixed memory reservation");
362 Ok((value, memory))
363 });
364 self.await_join(join).await
365 }
366
367 pub async fn execute_blocking_with_request_factory<T, E, F, R>(
372 &self,
373 mut request_for_snapshot: R,
374 context: RuntimeTaskContext,
375 operation: F,
376 ) -> Result<T, TokioTaskError<E>>
377 where
378 T: Send + 'static,
379 E: Send + 'static,
380 F: FnOnce(&RuntimeTaskContext) -> Result<T, E> + Send + 'static,
381 R: FnMut(RuntimeGovernorSnapshot) -> RuntimeWorkRequest + Send,
382 {
383 let permit = self
384 .acquire_with(
385 move |snapshot| request_for_snapshot(snapshot).with_blocking(true),
386 &context,
387 )
388 .await?;
389 let observe_post_operation_cancellation =
390 permit.request().kind != RuntimeWorkKind::Mutation;
391 let task_context = permit.bind_task_context(context);
392 let join = self.handle.spawn_blocking(move || {
393 let _permit = permit;
394 task_context.checkpoint().map_err(TokioTaskError::Stopped)?;
395 let result = operation(&task_context);
396 finish_operation(&task_context, result, observe_post_operation_cancellation)
397 });
398 self.await_join(join).await
399 }
400
401 pub async fn execute_async<T, E, F, Fut>(
402 &self,
403 request: RuntimeWorkRequest,
404 context: RuntimeTaskContext,
405 operation: F,
406 ) -> Result<T, TokioTaskError<E>>
407 where
408 T: Send + 'static,
409 E: Send + 'static,
410 F: FnOnce(RuntimeTaskContext) -> Fut + Send + 'static,
411 Fut: Future<Output = Result<T, E>> + Send + 'static,
412 {
413 let observe_post_operation_cancellation = request.kind != RuntimeWorkKind::Mutation;
414 let permit = self.acquire(request, &context).await?;
415 let task_context = permit.bind_task_context(context);
416 let join = self.handle.spawn(async move {
417 let _permit = permit;
418 task_context.checkpoint().map_err(TokioTaskError::Stopped)?;
419 let checkpoint = task_context.clone();
420 let result = operation(task_context).await;
421 finish_operation(&checkpoint, result, observe_post_operation_cancellation)
422 });
423 self.await_join(join).await
424 }
425
426 pub async fn execute_blocking_with_reusable_state<T, E, S, F, R>(
434 &self,
435 state: S,
436 mut request_for_snapshot: R,
437 context: RuntimeTaskContext,
438 operation: F,
439 ) -> Result<T, TokioTaskError<E>>
440 where
441 T: Send + 'static,
442 E: Send + 'static,
443 S: Send + 'static,
444 F: FnOnce(Option<S>, &RuntimeTaskContext) -> Result<T, E> + Send + 'static,
445 R: FnMut(RuntimeGovernorSnapshot, Option<&S>) -> RuntimeWorkRequest + Send,
446 {
447 let mut state = Some(state);
448 let permit = self
449 .acquire_with_state(
450 &mut state,
451 move |snapshot, state| request_for_snapshot(snapshot, state).with_blocking(true),
452 &context,
453 )
454 .await?;
455 let observe_cancellation = permit.request().kind != RuntimeWorkKind::Mutation;
456 let task_context = permit.bind_task_context(context);
457 let join = self.handle.spawn_blocking(move || {
458 let _permit = permit;
459 task_context.checkpoint().map_err(TokioTaskError::Stopped)?;
460 let result = operation(state, &task_context);
461 finish_operation(&task_context, result, observe_cancellation)
462 });
463 self.await_join(join).await
464 }
465
466 async fn acquire<E>(
467 &self,
468 request: RuntimeWorkRequest,
469 context: &RuntimeTaskContext,
470 ) -> Result<hawdb_qos::RuntimePermit, TokioTaskError<E>> {
471 self.acquire_with(move |_| request, context).await
472 }
473
474 async fn acquire_with<E, R>(
475 &self,
476 mut request_for_snapshot: R,
477 context: &RuntimeTaskContext,
478 ) -> Result<hawdb_qos::RuntimePermit, TokioTaskError<E>>
479 where
480 R: FnMut(RuntimeGovernorSnapshot) -> RuntimeWorkRequest + Send,
481 {
482 self.acquire_with_state(
483 &mut None::<()>,
484 move |snapshot, _| request_for_snapshot(snapshot),
485 context,
486 )
487 .await
488 }
489
490 async fn acquire_with_state<E, S, R>(
491 &self,
492 state: &mut Option<S>,
493 mut request_for_snapshot: R,
494 context: &RuntimeTaskContext,
495 ) -> Result<hawdb_qos::RuntimePermit, TokioTaskError<E>>
496 where
497 S: Send,
498 R: FnMut(RuntimeGovernorSnapshot, Option<&S>) -> RuntimeWorkRequest + Send,
499 {
500 let mut wait = None;
501 self.refresh_resources_if_due();
502 let mut request = request_for_snapshot(self.governor.snapshot(), state.as_ref());
503 let mut waiter = self.governor.admission_waiter(request.priority);
504 loop {
505 if let Err(reason) = context.checkpoint() {
506 self.finish_admission_wait(request, wait.take());
507 self.governor.record_cancellation(reason);
508 return Err(TokioTaskError::Stopped(reason));
509 }
510 match self.governor.try_admit_waiter(&waiter, request) {
511 Ok(permit) => {
512 self.finish_admission_wait(request, wait.take());
513 return Ok(permit);
514 }
515 Err(error) if state.is_some() => {
516 drop(state.take());
520 request = request_for_snapshot(self.governor.snapshot(), None);
521 if !error.is_retryable() {
522 waiter = self.governor.admission_waiter(request.priority);
524 }
525 continue;
526 }
527 Err(error) if !error.is_retryable() => {
528 self.finish_admission_wait(request, wait.take());
529 return Err(TokioTaskError::Admission(error));
530 }
531 Err(error) => {
532 wait.get_or_insert_with(|| (Instant::now(), error.code));
533 }
534 }
535 if let Err(reason) = self.wait_for_admission_event(&mut waiter, context).await {
536 self.finish_admission_wait(request, wait.take());
537 self.governor.record_cancellation(reason);
538 return Err(TokioTaskError::Stopped(reason));
539 }
540 self.refresh_resources_if_due();
541 request = request_for_snapshot(self.governor.snapshot(), state.as_ref());
542 }
543 }
544
545 async fn wait_for_admission_event(
546 &self,
547 waiter: &mut hawdb_qos::RuntimeAdmissionWaiter,
548 context: &RuntimeTaskContext,
549 ) -> Result<(), RuntimeCancellationReason> {
550 loop {
551 let priority_change_at = waiter.next_priority_change_at();
552 let mut admission = Box::pin(waiter.notified());
553 let mut cancellation = Box::pin(context.cancellation().cancelled());
554 let mut deadline = context.deadline().map(|deadline| {
555 Box::pin(tokio::time::sleep_until(tokio::time::Instant::from_std(
556 deadline,
557 )))
558 });
559 let mut priority_change = priority_change_at.map(|deadline| {
560 Box::pin(tokio::time::sleep_until(tokio::time::Instant::from_std(
561 deadline,
562 )))
563 });
564 let mut refresh = (!self.governor.snapshot().resources_pinned).then(|| {
565 let last_refresh = *self
566 .last_resource_refresh
567 .lock()
568 .unwrap_or_else(|poisoned| poisoned.into_inner());
569 let interval = self
570 .config
571 .resource_refresh_interval
572 .max(Duration::from_millis(1));
573 let refresh_at = last_refresh
574 .checked_add(interval)
575 .unwrap_or_else(Instant::now);
576 Box::pin(tokio::time::sleep_until(tokio::time::Instant::from_std(
577 refresh_at,
578 )))
579 });
580 let admission_notified = poll_fn(|task| {
581 if cancellation.as_mut().poll(task).is_ready() {
582 return Poll::Ready(context.checkpoint().map(|()| false));
583 }
584 if deadline
585 .as_mut()
586 .is_some_and(|deadline| deadline.as_mut().poll(task).is_ready())
587 {
588 return Poll::Ready(Err(RuntimeCancellationReason::DeadlineExceeded));
589 }
590 if admission.as_mut().poll(task).is_ready() {
591 return Poll::Ready(Ok(true));
592 }
593 if priority_change
594 .as_mut()
595 .is_some_and(|change| change.as_mut().poll(task).is_ready())
596 {
597 return Poll::Ready(Ok(true));
598 }
599 if refresh
600 .as_mut()
601 .is_some_and(|refresh| refresh.as_mut().poll(task).is_ready())
602 {
603 return Poll::Ready(Ok(false));
604 }
605 Poll::Pending
606 })
607 .await?;
608 if admission_notified || self.refresh_resources_if_due() {
609 return Ok(());
610 }
611 }
612 }
613
614 fn finish_admission_wait(
615 &self,
616 request: RuntimeWorkRequest,
617 wait: Option<(Instant, RuntimeAdmissionCode)>,
618 ) {
619 let Some((started, code)) = wait else {
620 return;
621 };
622 let elapsed_micros = u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX);
623 self.governor
624 .record_admission_wait(request, code, elapsed_micros);
625 }
626
627 async fn await_join<T, E>(
628 &self,
629 join: JoinHandle<Result<T, TokioTaskError<E>>>,
630 ) -> Result<T, TokioTaskError<E>>
631 where
632 T: Send + 'static,
633 E: Send + 'static,
634 {
635 let result = join.await.map_err(TokioTaskError::Join)?;
636 if let Err(TokioTaskError::Stopped(reason)) = &result {
637 self.governor.record_cancellation(*reason);
638 }
639 result
640 }
641
642 fn refresh_resources_if_due(&self) -> bool {
643 let now = Instant::now();
644 let should_refresh = {
645 let mut last_refresh = self
646 .last_resource_refresh
647 .lock()
648 .unwrap_or_else(|poisoned| poisoned.into_inner());
649 if now.duration_since(*last_refresh) < self.config.resource_refresh_interval {
650 false
651 } else {
652 *last_refresh = now;
653 true
654 }
655 };
656 if should_refresh {
657 self.governor.refresh_from_host()
658 } else {
659 false
660 }
661 }
662}
663
664fn finish_operation<T, E>(
665 context: &RuntimeTaskContext,
666 result: Result<T, E>,
667 observe_cancellation: bool,
668) -> Result<T, TokioTaskError<E>> {
669 if observe_cancellation
670 && let Err(reason) = context.checkpoint()
671 && (reason != RuntimeCancellationReason::ResourceExhausted || result.is_ok())
674 {
675 return Err(TokioTaskError::Stopped(reason));
676 }
677 result.map_err(TokioTaskError::Operation)
678}
679
680#[cfg(test)]
681mod tests {
682 use super::*;
683 use hawdb_qos::{
684 IoConcurrencyBudget, RuntimeCancellationToken, RuntimeGovernorConfig,
685 RuntimeMemorySnapshot, RuntimeResourceBudget, RuntimeResourceSnapshot,
686 RuntimeTelemetryEvent, RuntimeTelemetryEventKind, RuntimeTelemetrySink,
687 RuntimeWorkPriority,
688 };
689 use std::convert::Infallible;
690 use std::sync::atomic::{AtomicUsize, Ordering};
691
692 fn runtime_resources(cpu: usize) -> RuntimeResourceSnapshot {
693 RuntimeResourceSnapshot::from_parts(
694 RuntimeResourceBudget::from_limits(NonZeroUsize::new(cpu).unwrap(), None, None),
695 RuntimeMemorySnapshot::from_limits(
696 Some(8 * 1024 * 1024 * 1024),
697 Some(4 * 1024 * 1024 * 1024),
698 None,
699 None,
700 None,
701 ),
702 )
703 }
704
705 fn governor(cpu: usize) -> RuntimeGovernor {
706 RuntimeGovernor::new(
707 RuntimeGovernorConfig::shared_host(),
708 runtime_resources(cpu),
709 IoConcurrencyBudget::new(4, 1),
710 )
711 }
712
713 #[derive(Debug, Default)]
714 struct RecordingRuntimeTelemetry {
715 events: Mutex<Vec<RuntimeTelemetryEvent>>,
716 }
717
718 impl RuntimeTelemetrySink for RecordingRuntimeTelemetry {
719 fn record_runtime(&self, event: RuntimeTelemetryEvent) {
720 self.events
721 .lock()
722 .unwrap_or_else(|poisoned| poisoned.into_inner())
723 .push(event);
724 }
725 }
726
727 fn cgroup_resources(limit: u64, current: u64) -> RuntimeResourceSnapshot {
728 RuntimeResourceSnapshot::from_parts(
729 RuntimeResourceBudget::from_limits(NonZeroUsize::new(2).unwrap(), None, None),
730 RuntimeMemorySnapshot::from_limits(
731 Some(8 * 1024 * 1024 * 1024),
732 Some(6 * 1024 * 1024 * 1024),
733 Some(limit),
734 None,
735 Some(current),
736 ),
737 )
738 }
739
740 #[test]
741 fn prepared_state_releases_the_single_cpu_slot_and_keeps_memory_until_execution() {
742 let governor = RuntimeGovernor::new(
743 RuntimeGovernorConfig {
744 memory_budget_bytes: Some(100),
745 ..RuntimeGovernorConfig::shared_host()
746 },
747 runtime_resources(1),
748 IoConcurrencyBudget::new(1, 1),
749 );
750 let adapter = TokioRuntimeAdapter::owned(
751 governor.clone(),
752 TokioRuntimeConfig::from_governor(&governor),
753 )
754 .unwrap();
755 adapter
756 .block_on(async {
757 let (value, memory) = adapter
758 .prepare_blocking(
759 RuntimeWorkPriority::Foreground,
760 40,
761 RuntimeTaskContext::default(),
762 |_| Ok::<_, Infallible>(42),
763 )
764 .await
765 .unwrap();
766 let prepared = governor.snapshot();
767 assert_eq!(prepared.active_cpu_slots, 0);
768 assert_eq!(prepared.active_blocking_tasks, 0);
769 assert_eq!(prepared.admitted_memory_bytes, 40);
770 let observed = governor.clone();
771 let result = adapter
772 .execute_blocking_with_reusable_state(
773 memory,
774 |_, memory| {
775 RuntimeWorkRequest::foreground_query(60, 0).with_retained_memory_bytes(
776 memory.map_or(0, |memory| memory.bytes()),
777 )
778 },
779 RuntimeTaskContext::with_timeout(Duration::from_secs(5)),
780 move |memory, _| {
781 assert!(
782 memory.is_some(),
783 "immediate admission must reuse preparation"
784 );
785 assert_eq!(observed.snapshot().admitted_memory_bytes, 100);
786 drop(memory);
787 Ok::<_, Infallible>(value)
788 },
789 )
790 .await
791 .unwrap();
792 assert_eq!(result, 42);
793 })
794 .unwrap();
795 assert_eq!(governor.snapshot().admitted_memory_bytes, 0);
796 assert_eq!(governor.snapshot().active_cpu_slots, 0);
797 }
798
799 #[test]
800 fn retained_preparation_is_released_before_a_hard_capacity_refusal() {
801 for execution_bytes in [80, 101] {
802 let governor = RuntimeGovernor::new(
803 RuntimeGovernorConfig {
804 memory_budget_bytes: Some(100),
805 ..RuntimeGovernorConfig::shared_host()
806 },
807 runtime_resources(1),
808 IoConcurrencyBudget::new(1, 1),
809 );
810 let adapter = TokioRuntimeAdapter::owned(
811 governor.clone(),
812 TokioRuntimeConfig::from_governor(&governor),
813 )
814 .unwrap();
815 let result = adapter
816 .block_on(async {
817 let (_, state) = adapter
818 .prepare_blocking(
819 RuntimeWorkPriority::Foreground,
820 40,
821 RuntimeTaskContext::default(),
822 |_| Ok::<_, Infallible>(()),
823 )
824 .await
825 .unwrap();
826 adapter
827 .execute_blocking_with_reusable_state(
828 state,
829 |_, state| {
830 RuntimeWorkRequest::foreground_query(execution_bytes, 0)
831 .with_retained_memory_bytes(
832 state.map_or(0, |state| state.bytes()),
833 )
834 },
835 RuntimeTaskContext::with_timeout(Duration::from_secs(5)),
836 |state, _| {
837 assert!(state.is_none());
838 Ok::<_, Infallible>(())
839 },
840 )
841 .await
842 })
843 .unwrap();
844 if execution_bytes <= 100 {
845 result.unwrap();
846 } else {
847 let Err(TokioTaskError::Admission(error)) = result else {
848 panic!("execution exceeding hard capacity must be rejected");
849 };
850 assert_eq!(error.code, RuntimeAdmissionCode::MemorySaturated);
851 assert!(!error.is_retryable());
852 }
853 assert_eq!(governor.snapshot().admitted_memory_bytes, 0);
854 assert_eq!(governor.snapshot().queued_admission_waiters, 0);
855 }
856 }
857
858 #[test]
859 fn dropping_or_cancelling_queued_execution_releases_prepared_memory() {
860 for cancel in [false, true] {
861 let governor = governor(1);
862 let adapter = TokioRuntimeAdapter::owned(
863 governor.clone(),
864 TokioRuntimeConfig::from_governor(&governor),
865 )
866 .unwrap();
867 adapter
868 .block_on(async {
869 let (_, memory) = adapter
870 .prepare_blocking(
871 RuntimeWorkPriority::Foreground,
872 40,
873 RuntimeTaskContext::default(),
874 |_| Ok::<_, Infallible>(()),
875 )
876 .await
877 .unwrap();
878 let held = governor
879 .try_admit(RuntimeWorkRequest::foreground_query(0, 0))
880 .unwrap();
881 let token = RuntimeCancellationToken::new();
882 let mut execution = Box::pin(adapter.execute_blocking_with_reusable_state(
883 memory,
884 |_, memory| {
885 RuntimeWorkRequest::foreground_query(60, 0).with_retained_memory_bytes(
886 memory.map_or(0, |memory| memory.bytes()),
887 )
888 },
889 RuntimeTaskContext::without_deadline(token.clone()),
890 move |memory, _| -> Result<(), Infallible> {
891 drop(memory);
892 panic!("execution must not start while the only CPU is held");
893 },
894 ));
895 std::future::poll_fn(|context| {
896 assert!(execution.as_mut().poll(context).is_pending());
897 std::task::Poll::Ready(())
898 })
899 .await;
900 assert_eq!(governor.snapshot().admitted_memory_bytes, 0);
901 if cancel {
902 token.cancel();
903 assert!(matches!(
904 execution.await,
905 Err(TokioTaskError::Stopped(
906 RuntimeCancellationReason::Cancelled
907 ))
908 ));
909 } else {
910 drop(execution);
911 }
912 assert_eq!(governor.snapshot().admitted_memory_bytes, 0);
913 assert_eq!(governor.snapshot().queued_admission_waiters, 0);
914 drop(held);
915 })
916 .unwrap();
917 }
918 }
919
920 #[test]
921 fn failed_or_panicking_preparation_releases_all_resources() {
922 let governor = governor(1);
923 let adapter =
924 TokioRuntimeAdapter::owned(governor.clone(), TokioRuntimeConfig::default()).unwrap();
925 for panic in [false, true] {
926 let result = adapter
927 .block_on(adapter.prepare_blocking(
928 RuntimeWorkPriority::Foreground,
929 40,
930 RuntimeTaskContext::default(),
931 move |_| -> Result<(), &'static str> {
932 assert!(!panic, "preparation panic");
933 Err("preparation failed")
934 },
935 ))
936 .unwrap();
937 assert!(result.is_err());
938 let after = governor.snapshot();
939 assert_eq!(after.admitted_memory_bytes, 0);
940 assert_eq!(after.active_cpu_slots, 0);
941 assert_eq!(after.active_blocking_tasks, 0);
942 }
943 }
944
945 #[test]
946 fn concurrent_preparations_cannot_hold_all_memory_while_waiting_for_each_other() {
947 let governor = RuntimeGovernor::new(
948 RuntimeGovernorConfig {
949 memory_budget_bytes: Some(100),
950 ..RuntimeGovernorConfig::shared_host()
951 },
952 runtime_resources(1),
953 IoConcurrencyBudget::new(1, 1),
954 );
955 let adapter = TokioRuntimeAdapter::owned(
956 governor.clone(),
957 TokioRuntimeConfig::from_governor(&governor),
958 )
959 .unwrap();
960 adapter
961 .block_on(async {
962 let mut states = Vec::new();
963 for _ in 0..2 {
964 let (_, memory) = adapter
965 .prepare_blocking(
966 RuntimeWorkPriority::Foreground,
967 40,
968 RuntimeTaskContext::default(),
969 |_| Ok::<_, Infallible>(()),
970 )
971 .await
972 .unwrap();
973 states.push(memory);
974 }
975 assert_eq!(governor.snapshot().admitted_memory_bytes, 80);
976 let execute = |state| {
977 adapter.execute_blocking_with_reusable_state(
978 state,
979 |_, memory: Option<&RuntimeRetainedMemory>| {
980 RuntimeWorkRequest::foreground_query(40, 0).with_retained_memory_bytes(
981 memory.map_or(0, |memory| memory.bytes()),
982 )
983 },
984 RuntimeTaskContext::default(),
985 |memory, _| Ok::<_, Infallible>(memory.is_some()),
986 )
987 };
988 let mut first = Box::pin(execute(states.pop().unwrap()));
989 let mut second = Box::pin(execute(states.pop().unwrap()));
990 let mut first_result = None;
991 let mut second_result = None;
992 let both = std::future::poll_fn(|context| {
993 if first_result.is_none()
994 && let Poll::Ready(result) = first.as_mut().poll(context)
995 {
996 first_result = Some(result);
997 }
998 if second_result.is_none()
999 && let Poll::Ready(result) = second.as_mut().poll(context)
1000 {
1001 second_result = Some(result);
1002 }
1003 if first_result.is_some() && second_result.is_some() {
1004 Poll::Ready((first_result.take().unwrap(), second_result.take().unwrap()))
1005 } else {
1006 Poll::Pending
1007 }
1008 });
1009 let (first, second) = tokio::time::timeout(Duration::from_secs(5), both)
1010 .await
1011 .expect("prepared queries must not form a memory wait cycle");
1012 let first_reused = first.unwrap();
1013 let second_reused = second.unwrap();
1014 assert!(!first_reused || !second_reused);
1015 })
1016 .unwrap();
1017 assert_eq!(governor.snapshot().admitted_memory_bytes, 0);
1018 assert_eq!(governor.snapshot().queued_admission_waiters, 0);
1019 }
1020
1021 #[test]
1022 fn governor_config_bounds_blocking_threads_to_effective_cpu_slots() {
1023 let resources = RuntimeResourceSnapshot::from_parts(
1024 RuntimeResourceBudget::from_limits(
1025 NonZeroUsize::new(32).unwrap(),
1026 NonZeroUsize::new(2),
1027 None,
1028 ),
1029 RuntimeMemorySnapshot::from_limits(
1030 Some(8 * 1024 * 1024 * 1024),
1031 Some(4 * 1024 * 1024 * 1024),
1032 None,
1033 None,
1034 None,
1035 ),
1036 );
1037 let governor = RuntimeGovernor::new(
1038 RuntimeGovernorConfig::shared_host(),
1039 resources,
1040 IoConcurrencyBudget::new(8, 2),
1041 );
1042
1043 let config = TokioRuntimeConfig::from_governor(&governor);
1044
1045 assert_eq!(governor.snapshot().limits.effective_cpu_slots.get(), 2);
1046 assert_eq!(config.async_worker_threads.unwrap().get(), 2);
1047 assert_eq!(config.max_blocking_threads.unwrap().get(), 2);
1048 }
1049
1050 #[test]
1051 fn borrowed_runtime_does_not_take_host_lifecycle_ownership() {
1052 let host = Builder::new_multi_thread().enable_time().build().unwrap();
1053 let adapter = TokioRuntimeAdapter::borrowed(
1054 host.handle().clone(),
1055 governor(2),
1056 TokioRuntimeConfig::default(),
1057 );
1058 assert_eq!(adapter.ownership(), TokioRuntimeOwnership::Borrowed);
1059 assert!(!adapter.owns_runtime());
1060 let value = host
1061 .block_on(adapter.execute_async(
1062 RuntimeWorkRequest::io(RuntimeWorkPriority::Foreground, 1, 0),
1063 RuntimeTaskContext::default(),
1064 |_| async { Ok::<_, Infallible>(42) },
1065 ))
1066 .unwrap();
1067 assert_eq!(value, 42);
1068 drop(adapter);
1069 assert_eq!(host.block_on(async { 7 }), 7);
1070 }
1071
1072 #[test]
1073 fn admitted_resources_reach_async_and_blocking_operations() {
1074 let host = Builder::new_multi_thread().enable_time().build().unwrap();
1075 let adapter = TokioRuntimeAdapter::borrowed(
1076 host.handle().clone(),
1077 governor(2),
1078 TokioRuntimeConfig::default(),
1079 );
1080 let request = RuntimeWorkRequest::foreground_query(128, 32).with_cpu_slots(2);
1081
1082 let async_resources = host
1083 .block_on(adapter.execute_async(
1084 request.with_blocking(false),
1085 RuntimeTaskContext::default(),
1086 |context| async move {
1087 Ok::<_, Infallible>((
1088 context.admitted_parallelism(),
1089 context.memory_reservation(),
1090 ))
1091 },
1092 ))
1093 .unwrap();
1094 let blocking_resources = host
1095 .block_on(
1096 adapter.execute_blocking(request, RuntimeTaskContext::default(), |context| {
1097 Ok::<_, Infallible>((
1098 context.admitted_parallelism(),
1099 context.memory_reservation(),
1100 ))
1101 }),
1102 )
1103 .unwrap();
1104
1105 for (parallelism, reservation) in [async_resources, blocking_resources] {
1106 assert_eq!(parallelism.get(), 2);
1107 let reservation = reservation.unwrap();
1108 assert_eq!(reservation.memory_bytes(), 128);
1109 assert_eq!(reservation.result_bytes(), 32);
1110 }
1111 }
1112
1113 #[test]
1114 fn request_factory_renegotiates_parallelism_after_resource_change() {
1115 let governor = governor(4);
1116 governor.pin_resources();
1117 let held = governor
1118 .try_admit(
1119 RuntimeWorkRequest::foreground_query(0, 0)
1120 .with_cpu_slots(4)
1121 .with_blocking(true),
1122 )
1123 .unwrap();
1124 let host = Builder::new_multi_thread().enable_time().build().unwrap();
1125 let adapter = TokioRuntimeAdapter::borrowed(
1126 host.handle().clone(),
1127 governor.clone(),
1128 TokioRuntimeConfig {
1129 resource_refresh_interval: Duration::from_secs(3600),
1130 ..TokioRuntimeConfig::default()
1131 },
1132 );
1133 let observed_slots = Arc::new(Mutex::new(Vec::new()));
1134 let request_slots = Arc::clone(&observed_slots);
1135
1136 host.block_on(async {
1137 let execution = adapter.execute_blocking_with_request_factory(
1138 move |snapshot| {
1139 let slots = snapshot.limits.effective_cpu_slots.get();
1140 request_slots
1141 .lock()
1142 .unwrap_or_else(|poisoned| poisoned.into_inner())
1143 .push(slots);
1144 RuntimeWorkRequest::foreground_query(0, 0).with_cpu_slots(slots)
1145 },
1146 RuntimeTaskContext::default(),
1147 |context| Ok::<_, Infallible>(context.admitted_parallelism().get()),
1148 );
1149 tokio::pin!(execution);
1150 assert!(
1151 tokio::time::timeout(Duration::from_millis(20), &mut execution)
1152 .await
1153 .is_err()
1154 );
1155
1156 assert!(governor.update_resources(runtime_resources(2)));
1157 tokio::task::yield_now().await;
1158 drop(held);
1159
1160 let parallelism = tokio::time::timeout(Duration::from_secs(1), &mut execution)
1161 .await
1162 .expect("released capacity must wake queued admission")
1163 .expect("renegotiated request must be admitted");
1164 assert_eq!(parallelism, 2);
1165 });
1166 let observed_slots = observed_slots
1167 .lock()
1168 .unwrap_or_else(|poisoned| poisoned.into_inner());
1169 assert_eq!(observed_slots.first(), Some(&4));
1170 assert!(observed_slots.iter().skip(1).any(|slots| *slots == 2));
1171 }
1172
1173 #[test]
1174 fn background_waiter_ages_without_an_external_resource_event() {
1175 let governor = governor(2);
1176 governor.pin_resources();
1177 let held = governor
1178 .try_admit(
1179 RuntimeWorkRequest::blocking_cpu(RuntimeWorkPriority::Foreground, 0)
1180 .with_cpu_slots(1),
1181 )
1182 .unwrap();
1183 let host = Builder::new_multi_thread().enable_time().build().unwrap();
1184 let adapter = TokioRuntimeAdapter::borrowed(
1185 host.handle().clone(),
1186 governor,
1187 TokioRuntimeConfig::default(),
1188 );
1189
1190 host.block_on(async {
1191 let foreground = adapter.execute_blocking(
1192 RuntimeWorkRequest::blocking_cpu(RuntimeWorkPriority::Foreground, 0)
1193 .with_cpu_slots(2),
1194 RuntimeTaskContext::default(),
1195 |_| Ok::<_, Infallible>(()),
1196 );
1197 let background = adapter.execute_blocking(
1198 RuntimeWorkRequest::blocking_cpu(RuntimeWorkPriority::Background, 0),
1199 RuntimeTaskContext::default(),
1200 |_| Ok::<_, Infallible>(()),
1201 );
1202 tokio::pin!(foreground);
1203 tokio::pin!(background);
1204
1205 assert!(
1206 tokio::time::timeout(Duration::from_millis(20), &mut foreground)
1207 .await
1208 .is_err()
1209 );
1210 tokio::time::timeout(Duration::from_secs(1), &mut background)
1211 .await
1212 .expect("background aging must trigger a one-shot admission retry")
1213 .expect("the aged background request must use the available slot");
1214 });
1215 drop(held);
1216 }
1217
1218 #[test]
1219 fn owned_runtime_rejects_nested_creation() {
1220 let host = Builder::new_current_thread().enable_time().build().unwrap();
1221 let result = host.block_on(async {
1222 TokioRuntimeAdapter::owned(governor(1), TokioRuntimeConfig::default())
1223 });
1224 assert!(matches!(result, Err(TokioRuntimeError::NestedOwnedRuntime)));
1225 }
1226
1227 #[test]
1228 fn owned_runtime_drop_is_safe_inside_another_runtime() {
1229 let adapter =
1230 TokioRuntimeAdapter::owned(governor(1), TokioRuntimeConfig::default()).unwrap();
1231 let host = Builder::new_current_thread().enable_time().build().unwrap();
1232 host.block_on(async move { drop(adapter) });
1233 }
1234
1235 #[test]
1236 fn admission_resource_refresh_is_shared_and_throttled() {
1237 let host = Builder::new_current_thread().enable_time().build().unwrap();
1238 let adapter = TokioRuntimeAdapter::borrowed(
1239 host.handle().clone(),
1240 governor(1),
1241 TokioRuntimeConfig {
1242 resource_refresh_interval: Duration::ZERO,
1243 ..TokioRuntimeConfig::default()
1244 },
1245 );
1246 let initial = *adapter
1247 .last_resource_refresh
1248 .lock()
1249 .unwrap_or_else(|poisoned| poisoned.into_inner());
1250
1251 adapter.refresh_resources_if_due();
1252 let refreshed = *adapter
1253 .last_resource_refresh
1254 .lock()
1255 .unwrap_or_else(|poisoned| poisoned.into_inner());
1256 let mut clone = adapter.clone();
1257 clone.config.resource_refresh_interval = Duration::from_secs(60 * 60);
1258 clone.refresh_resources_if_due();
1259 let throttled = *adapter
1260 .last_resource_refresh
1261 .lock()
1262 .unwrap_or_else(|poisoned| poisoned.into_inner());
1263
1264 assert!(refreshed >= initial);
1265 assert_eq!(throttled, refreshed);
1266 }
1267
1268 #[test]
1269 fn blocking_execution_respects_governor_parallelism() {
1270 let governor = governor(2);
1271 governor.pin_resources();
1272 let telemetry = Arc::new(RecordingRuntimeTelemetry::default());
1273 governor.set_telemetry_sink(Some(telemetry.clone()));
1274 let adapter = TokioRuntimeAdapter::owned(
1275 governor,
1276 TokioRuntimeConfig {
1277 max_blocking_threads: NonZeroUsize::new(8),
1278 ..TokioRuntimeConfig::default()
1279 },
1280 )
1281 .unwrap();
1282 let active = Arc::new(AtomicUsize::new(0));
1283 let peak = Arc::new(AtomicUsize::new(0));
1284 adapter
1285 .block_on(async {
1286 let (entered, started) = std::sync::mpsc::channel();
1287 let mut releases = Vec::new();
1288 let mut executions = (0..6)
1289 .map(|_| {
1290 let active = Arc::clone(&active);
1291 let peak = Arc::clone(&peak);
1292 let entered = entered.clone();
1293 let (release, released) = std::sync::mpsc::channel::<()>();
1294 releases.push(release);
1295 Box::pin(adapter.execute_blocking(
1296 RuntimeWorkRequest::blocking_cpu(RuntimeWorkPriority::Foreground, 0),
1297 RuntimeTaskContext::default(),
1298 move |_| {
1299 let current = active.fetch_add(1, Ordering::SeqCst) + 1;
1300 peak.fetch_max(current, Ordering::SeqCst);
1301 let _ = entered.send(());
1302 let _ = released.recv();
1304 active.fetch_sub(1, Ordering::SeqCst);
1305 Ok::<_, Infallible>(())
1306 },
1307 ))
1308 })
1309 .collect::<Vec<_>>();
1310 poll_fn(|context| {
1313 for execution in &mut executions {
1314 assert!(execution.as_mut().poll(context).is_pending());
1315 }
1316 Poll::Ready(())
1317 })
1318 .await;
1319 let snapshot = adapter.governor_snapshot();
1320 assert_eq!(snapshot.active_cpu_slots, 2);
1321 assert_eq!(snapshot.queued_admission_waiters, 4);
1322 assert!(snapshot.retryable_admission_rejections >= 4);
1323 let both_started =
1324 (0..2).all(|_| started.recv_timeout(Duration::from_secs(5)).is_ok());
1325 drop(releases);
1326 for execution in executions {
1327 execution.await.unwrap();
1328 }
1329 assert!(both_started, "both admitted blocking operations must start");
1330 })
1331 .unwrap();
1332 assert_eq!(peak.load(Ordering::SeqCst), 2);
1333 assert_eq!(active.load(Ordering::SeqCst), 0);
1334 assert_eq!(adapter.governor_snapshot().completions, 6);
1335 assert!(adapter.governor_snapshot().admission_waits > 0);
1336 assert!(adapter.governor_snapshot().retryable_admission_rejections > 0);
1337 assert!(telemetry
1338 .events
1339 .lock()
1340 .unwrap_or_else(|poisoned| poisoned.into_inner())
1341 .iter()
1342 .any(|event| {
1343 event.kind == RuntimeTelemetryEventKind::AdmissionWait && event.elapsed_micros > 0
1344 }));
1345 }
1346
1347 #[test]
1348 fn cancellation_returns_at_a_cooperative_blocking_checkpoint() {
1349 let adapter =
1350 TokioRuntimeAdapter::owned(governor(1), TokioRuntimeConfig::default()).unwrap();
1351 let token = RuntimeCancellationToken::new();
1352 let context = RuntimeTaskContext::without_deadline(token.clone());
1353 let handle = adapter.handle().clone();
1354 handle.spawn(async move {
1355 tokio::time::sleep(Duration::from_millis(15)).await;
1356 token.cancel();
1357 });
1358 let started = Instant::now();
1359 let result = adapter
1360 .block_on(adapter.execute_blocking(
1361 RuntimeWorkRequest::blocking_cpu(RuntimeWorkPriority::Foreground, 0),
1362 context,
1363 |context| -> Result<(), RuntimeCancellationReason> {
1364 loop {
1365 context.checkpoint()?;
1366 std::thread::sleep(Duration::from_millis(2));
1367 }
1368 },
1369 ))
1370 .unwrap();
1371 assert!(matches!(
1372 result,
1373 Err(TokioTaskError::Stopped(
1374 RuntimeCancellationReason::Cancelled
1375 ))
1376 ));
1377 assert!(started.elapsed() < Duration::from_millis(200));
1378 assert!(adapter.governor_snapshot().cancellations >= 1);
1379 }
1380
1381 #[test]
1382 fn deadline_stops_a_task_waiting_for_admission() {
1383 let governor = governor(1);
1384 let held = governor
1385 .try_admit(RuntimeWorkRequest::blocking_cpu(
1386 RuntimeWorkPriority::Foreground,
1387 0,
1388 ))
1389 .unwrap();
1390 let adapter =
1391 TokioRuntimeAdapter::owned(governor.clone(), TokioRuntimeConfig::default()).unwrap();
1392 let result = adapter
1393 .block_on(adapter.execute_blocking(
1394 RuntimeWorkRequest::blocking_cpu(RuntimeWorkPriority::Foreground, 0),
1395 RuntimeTaskContext::with_timeout(Duration::from_millis(20)),
1396 |_| Ok::<_, Infallible>(()),
1397 ))
1398 .unwrap();
1399 assert!(matches!(
1400 result,
1401 Err(TokioTaskError::Stopped(
1402 RuntimeCancellationReason::DeadlineExceeded
1403 ))
1404 ));
1405 assert_eq!(adapter.governor_snapshot().deadline_exceeded, 1);
1406 drop(held);
1407 }
1408
1409 #[test]
1410 fn cancellation_wakes_a_task_waiting_for_admission() {
1411 for reason in [
1412 RuntimeCancellationReason::Cancelled,
1413 RuntimeCancellationReason::ResourceExhausted,
1414 ] {
1415 let governor = governor(1);
1416 let held = governor
1417 .try_admit(RuntimeWorkRequest::blocking_cpu(
1418 RuntimeWorkPriority::Foreground,
1419 0,
1420 ))
1421 .unwrap();
1422 let host = Builder::new_multi_thread().enable_time().build().unwrap();
1423 let adapter = TokioRuntimeAdapter::borrowed(
1424 host.handle().clone(),
1425 governor,
1426 TokioRuntimeConfig {
1427 resource_refresh_interval: Duration::from_secs(3600),
1428 ..TokioRuntimeConfig::default()
1429 },
1430 );
1431 let token = RuntimeCancellationToken::new();
1432 let context = RuntimeTaskContext::without_deadline(token.clone());
1433 host.spawn(async move {
1434 tokio::time::sleep(Duration::from_millis(10)).await;
1435 if reason == RuntimeCancellationReason::ResourceExhausted {
1436 token.cancel_for_resource_exhaustion();
1437 } else {
1438 token.cancel();
1439 }
1440 });
1441
1442 let result = host
1443 .block_on(async {
1444 tokio::time::timeout(
1445 Duration::from_secs(1),
1446 adapter.execute_blocking(
1447 RuntimeWorkRequest::blocking_cpu(RuntimeWorkPriority::Foreground, 0),
1448 context,
1449 |_| Ok::<_, Infallible>(()),
1450 ),
1451 )
1452 .await
1453 })
1454 .expect("cancellation must wake admission without waiting for resource refresh");
1455 assert!(matches!(
1456 result,
1457 Err(TokioTaskError::Stopped(
1458 observed
1459 )) if observed == reason
1460 ));
1461 drop(held);
1462 }
1463 }
1464
1465 #[test]
1466 fn mutation_reports_the_committed_result_after_starting() {
1467 let adapter =
1468 TokioRuntimeAdapter::owned(governor(1), TokioRuntimeConfig::default()).unwrap();
1469 let token = RuntimeCancellationToken::new();
1470 let context = RuntimeTaskContext::without_deadline(token.clone());
1471 let (operation_started, wait_for_operation) = std::sync::mpsc::channel();
1472 let (cancellation_finished, wait_for_cancellation) = std::sync::mpsc::channel();
1473 let canceller = std::thread::spawn(move || {
1474 wait_for_operation.recv().unwrap();
1475 assert!(token.cancel());
1476 cancellation_finished.send(()).unwrap();
1477 });
1478 let result = adapter
1479 .block_on(adapter.execute_blocking(
1480 RuntimeWorkRequest::foreground_mutation(0),
1481 context,
1482 move |_| {
1483 operation_started.send(()).unwrap();
1484 wait_for_cancellation.recv().unwrap();
1485 Ok::<_, Infallible>(42)
1486 },
1487 ))
1488 .unwrap();
1489 canceller.join().unwrap();
1490 assert_eq!(result.unwrap(), 42);
1491 }
1492
1493 #[test]
1494 fn resource_cancellation_preserves_operation_errors_but_refuses_success() {
1495 let adapter =
1496 TokioRuntimeAdapter::owned(governor(1), TokioRuntimeConfig::default()).unwrap();
1497 let request = RuntimeWorkRequest::blocking_cpu(RuntimeWorkPriority::Foreground, 0);
1498 for fail in [true, false] {
1499 let blocking = adapter
1500 .block_on(adapter.execute_blocking(
1501 request,
1502 RuntimeTaskContext::default(),
1503 move |context| {
1504 context.cancellation().cancel_for_resource_exhaustion();
1505 if fail {
1506 Err("original resource error")
1507 } else {
1508 Ok(42)
1509 }
1510 },
1511 ))
1512 .unwrap();
1513 let asynchronous = adapter
1514 .block_on(adapter.execute_async(
1515 request,
1516 RuntimeTaskContext::default(),
1517 move |context| async move {
1518 context.cancellation().cancel_for_resource_exhaustion();
1519 if fail {
1520 Err("original resource error")
1521 } else {
1522 Ok(42)
1523 }
1524 },
1525 ))
1526 .unwrap();
1527 for result in [blocking, asynchronous] {
1528 if fail {
1529 assert!(matches!(
1530 result,
1531 Err(TokioTaskError::Operation("original resource error"))
1532 ));
1533 } else {
1534 assert!(matches!(
1535 result,
1536 Err(TokioTaskError::Stopped(
1537 RuntimeCancellationReason::ResourceExhausted
1538 ))
1539 ));
1540 }
1541 }
1542 }
1543 }
1544
1545 #[test]
1549 fn waiting_admission_succeeds_after_refresh_restores_headroom() {
1550 let limit = 512 * 1024 * 1024;
1551 let governor = RuntimeGovernor::new(
1552 RuntimeGovernorConfig::shared_host(),
1553 cgroup_resources(limit, limit),
1554 IoConcurrencyBudget::new(4, 1),
1555 );
1556 let host = Builder::new_multi_thread().enable_time().build().unwrap();
1557 let config = TokioRuntimeConfig {
1558 resource_refresh_interval: Duration::from_secs(3600),
1559 ..TokioRuntimeConfig::default()
1560 };
1561 let adapter = TokioRuntimeAdapter::borrowed(host.handle().clone(), governor, config);
1562 host.block_on(async {
1563 let request =
1564 RuntimeWorkRequest::blocking_cpu(RuntimeWorkPriority::Foreground, 48 * 1024 * 1024);
1565 let context = RuntimeTaskContext::default();
1566 let acquire = adapter.acquire::<Infallible>(request, &context);
1567 tokio::pin!(acquire);
1568 let still_waiting = tokio::time::timeout(Duration::from_millis(60), &mut acquire).await;
1569 assert!(
1570 still_waiting.is_err(),
1571 "admission must wait while the cgroup is saturated"
1572 );
1573 assert!(adapter
1574 .governor
1575 .update_resources(cgroup_resources(limit, 0)));
1576 let permit = tokio::time::timeout(Duration::from_secs(5), &mut acquire)
1577 .await
1578 .expect("admission must resume after the refresh")
1579 .expect("restored headroom must admit the waiting request");
1580 drop(permit);
1581 });
1582 }
1583
1584 #[test]
1589 fn waiting_admission_terminates_after_capacity_shrinks_below_request() {
1590 let initial_limit = 512 * 1024 * 1024;
1591 let governor = RuntimeGovernor::new(
1592 RuntimeGovernorConfig::shared_host(),
1593 cgroup_resources(initial_limit, initial_limit),
1594 IoConcurrencyBudget::new(4, 1),
1595 );
1596 let host = Builder::new_multi_thread().enable_time().build().unwrap();
1597 let config = TokioRuntimeConfig {
1598 resource_refresh_interval: Duration::from_secs(3600),
1599 ..TokioRuntimeConfig::default()
1600 };
1601 let adapter = TokioRuntimeAdapter::borrowed(host.handle().clone(), governor, config);
1602 host.block_on(async {
1603 let request =
1604 RuntimeWorkRequest::blocking_cpu(RuntimeWorkPriority::Foreground, 96 * 1024 * 1024);
1605 let context = RuntimeTaskContext::default();
1606 let acquire = adapter.acquire::<Infallible>(request, &context);
1607 tokio::pin!(acquire);
1608 let still_waiting = tokio::time::timeout(Duration::from_millis(60), &mut acquire).await;
1609 assert!(still_waiting.is_err());
1610
1611 assert!(adapter
1612 .governor
1613 .update_resources(cgroup_resources(64 * 1024 * 1024, 0)));
1614 let error = tokio::time::timeout(Duration::from_secs(5), &mut acquire)
1615 .await
1616 .expect("capacity shrink must terminate the admission loop")
1617 .expect_err("request above refreshed capacity must terminate");
1618 let TokioTaskError::Admission(error) = error else {
1619 panic!("capacity shrink must return an admission error");
1620 };
1621 assert_eq!(error.code, hawdb_qos::RuntimeAdmissionCode::MemorySaturated);
1622 assert!(!error.is_retryable());
1623 });
1624 }
1625}