1mod context;
2mod handle;
3pub mod root_lifecycle;
4mod single_flight;
5pub use context::{ExecutorApp, ExecutorContext};
6pub use root_lifecycle::SubcLifecycleAdmission;
7
8use std::{
9 collections::{HashMap, HashSet, VecDeque},
10 sync::{
11 atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering},
12 Arc, Weak,
13 },
14 thread::{self, JoinHandle},
15 time::{Duration, Instant},
16};
17
18use crossbeam_channel::{Receiver, RecvError, RecvTimeoutError, Sender};
19use parking_lot::{Condvar, Mutex, RwLock};
20use tokio::sync::oneshot;
21
22use crate::lock_diagnostics::{LockDiagnostics, TrackedMutex};
23use crate::{path_identity::ProjectRootId, protocol::Response};
24
25pub use single_flight::SingleFlight;
38
39const JOB_COST: isize = 1;
40const SCHEDULER_PROBE_WAIT: Duration = Duration::from_millis(5);
46#[rustfmt::skip]
47test_support_visibility! {
48const SCHEDULER_EVENT_BATCH_CAP: usize = 64;
52}
53pub const MAINTENANCE_QUEUE_CAP: usize = 512;
54const CALLGRAPH_ACQUISITION_REQUEST_ID: &str = "callgraph-view-acquire";
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58pub enum Lane {
59 PureRead,
62 SerialLspStatus,
65 HeavyInit,
70 Mutating,
75 MaintenanceCommit,
81 ProviderMetadata,
84 CallLedger,
103}
104
105const ALL_LANES: [Lane; 7] = [
106 Lane::PureRead,
107 Lane::SerialLspStatus,
108 Lane::HeavyInit,
109 Lane::Mutating,
110 Lane::MaintenanceCommit,
111 Lane::ProviderMetadata,
112 Lane::CallLedger,
113];
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
118pub enum JobClass {
119 Interactive,
120 Maintenance,
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
125pub enum MaintenanceCoalesceKey {
126 WatcherDrain,
127 LspDrain,
128 StandingPass,
132 ConfigReload,
135}
136
137pub type ExecutorJob<C> = Box<dyn FnOnce(&C) -> Response + Send + 'static>;
138
139#[rustfmt::skip]
140test_support_visibility! {
141const INTERACTIVE_WRITER_PROMOTION_AGE: Duration = Duration::from_secs(6);
148}
149#[rustfmt::skip]
150test_support_visibility! {
151const BIND_PROMOTION_AGE: Duration = Duration::from_millis(500);
156}
157#[rustfmt::skip]
158test_support_visibility! {
159const BIND_RESERVE_WORKERS: usize = 2;
165}
166#[rustfmt::skip]
167test_support_visibility! {
168const PROVIDER_RESERVE_WORKERS: usize = 2;
173}
174#[rustfmt::skip]
175test_support_visibility! {
176const READER_STUCK_CENSUS_AGE: Duration = Duration::from_secs(60);
179}
180const EXECUTOR_WORKER_STACK_BYTES: usize = 8 * 1024 * 1024;
184
185#[derive(Debug, Clone)]
186pub struct ExecutorConfig {
187 pub pool_size: usize,
188 pub read_cap: usize,
189 pub actor_cap: usize,
190 pub heavy_permits: usize,
191 pub drr_quantum: isize,
192}
193
194impl Default for ExecutorConfig {
195 fn default() -> Self {
196 let available = thread::available_parallelism()
197 .map(usize::from)
198 .unwrap_or(2);
199 let pool_size = available.saturating_sub(1).clamp(2, 8);
200 let actor_cap = pool_size.saturating_sub(1).clamp(1, 4);
201 let read_cap = actor_cap.clamp(1, 4);
202 let heavy_permits = pool_size.saturating_sub(1).clamp(2, 3);
203
204 Self {
205 pool_size,
206 read_cap,
207 actor_cap,
208 heavy_permits,
209 drr_quantum: 1,
210 }
211 }
212}
213
214#[rustfmt::skip]
215test_support_visibility! {
216#[derive(Debug, Clone)]
217struct EffectiveConfig {
218 pool_size: usize,
219 read_cap: usize,
220 actor_cap: usize,
221 #[cfg(any(test, feature = "test-support"))]
222 pub heavy_permits: usize,
223 #[cfg(not(any(test, feature = "test-support")))]
224 heavy_permits: usize,
225 drr_quantum: isize,
226 deficit_cap: isize,
227 interactive_reserve: usize,
228 maintenance_cap: usize,
229 bind_reserve: usize,
231 #[cfg(any(test, feature = "test-support"))]
232 pub provider_reserve: usize,
233 #[cfg(not(any(test, feature = "test-support")))]
234 provider_reserve: usize,
235}
236}
237
238impl EffectiveConfig {
239 #[rustfmt::skip]
240 test_support_visibility! {
241 fn total_workers(&self) -> usize {
243 self.pool_size + self.bind_reserve + self.provider_reserve
244 }
245
246 }
247}
248
249impl ExecutorConfig {
250 #[rustfmt::skip]
251 test_support_visibility! {
252 fn effective(&self) -> EffectiveConfig {
253 let pool_size = self.pool_size.clamp(2, 8);
254 let max_actor_cap = pool_size.saturating_sub(1).max(1);
255 let actor_cap = self.actor_cap.max(1).min(max_actor_cap);
256 let read_cap = self.read_cap.max(1).min(actor_cap).min(4);
257 let heavy_permits = self
261 .heavy_permits
262 .max(1)
263 .min(pool_size.saturating_sub(1).max(1))
264 .min(3);
265 let drr_quantum = self.drr_quantum.max(1);
266 let deficit_cap = (actor_cap.max(1) as isize) * 4;
267 let interactive_reserve = if pool_size >= 4 { 2 } else { 1 };
268 let maintenance_cap = pool_size.saturating_sub(interactive_reserve).max(1);
269
270 EffectiveConfig {
271 pool_size,
272 read_cap,
273 actor_cap,
274 heavy_permits,
275 drr_quantum,
276 deficit_cap,
277 interactive_reserve,
278 maintenance_cap,
279 bind_reserve: BIND_RESERVE_WORKERS,
280 provider_reserve: PROVIDER_RESERVE_WORKERS,
281 }
282 }
283
284 }
285}
286
287pub struct CompletionHandle {
290 rx: Receiver<Response>,
291}
292
293impl CompletionHandle {
294 pub fn recv(self) -> Result<Response, RecvError> {
295 self.rx.recv()
296 }
297
298 pub fn recv_timeout(&self, timeout: Duration) -> Result<Response, RecvTimeoutError> {
299 self.rx.recv_timeout(timeout)
300 }
301
302 pub fn into_receiver(self) -> Receiver<Response> {
303 self.rx
304 }
305}
306
307#[derive(Debug, Clone, PartialEq, Eq)]
308pub struct DispatchClassQueueSnapshot {
309 pub queued: usize,
310 pub oldest_age_ms: Option<u64>,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq)]
314pub struct DispatchRunningSnapshot {
315 pub interactive: usize,
316 pub maintenance: usize,
317 pub completion_owned_interactive: usize,
318 pub completion_owned_maintenance: usize,
319 pub oldest_worker_owned_maintenance_age_ms: Option<u64>,
322 pub phantom_interactive: usize,
323 pub phantom_maintenance: usize,
324}
325
326#[derive(Debug, Clone, PartialEq, Eq)]
327pub struct DispatchLivenessSnapshot {
328 pub interactive: DispatchClassQueueSnapshot,
329 pub maintenance: DispatchClassQueueSnapshot,
330 pub running: DispatchRunningSnapshot,
331 pub phantom_running_maintenance: usize,
332 pub interactive_reserve: usize,
333 pub maintenance_cap: usize,
334}
335
336struct DispatchLivenessAtomics {
340 origin: Instant,
341 interactive_queued: AtomicUsize,
342 interactive_oldest_enqueued_ms_plus_one: AtomicU64,
343 maintenance_queued: AtomicUsize,
344 maintenance_oldest_enqueued_ms_plus_one: AtomicU64,
345 interactive_running: AtomicUsize,
346 maintenance_running: AtomicUsize,
347 completion_owned_interactive: AtomicUsize,
348 completion_owned_maintenance: AtomicUsize,
349 oldest_worker_owned_maintenance_started_ms_plus_one: AtomicU64,
350 phantom_interactive: AtomicUsize,
351 phantom_maintenance: AtomicUsize,
352}
353
354impl DispatchLivenessAtomics {
355 fn new() -> Self {
356 Self {
357 origin: Instant::now(),
358 interactive_queued: AtomicUsize::new(0),
359 interactive_oldest_enqueued_ms_plus_one: AtomicU64::new(0),
360 maintenance_queued: AtomicUsize::new(0),
361 maintenance_oldest_enqueued_ms_plus_one: AtomicU64::new(0),
362 interactive_running: AtomicUsize::new(0),
363 maintenance_running: AtomicUsize::new(0),
364 completion_owned_interactive: AtomicUsize::new(0),
365 completion_owned_maintenance: AtomicUsize::new(0),
366 oldest_worker_owned_maintenance_started_ms_plus_one: AtomicU64::new(0),
367 phantom_interactive: AtomicUsize::new(0),
368 phantom_maintenance: AtomicUsize::new(0),
369 }
370 }
371
372 fn now_ms(&self) -> u64 {
373 duration_millis_u64(self.origin.elapsed())
374 }
375
376 fn record(&self, snapshot: &DispatchLivenessSnapshot) {
377 let now_ms = self.now_ms();
378 let encode_oldest = |queued: usize, oldest_age_ms: Option<u64>| {
379 if queued == 0 {
380 0
381 } else {
382 now_ms
383 .saturating_sub(oldest_age_ms.unwrap_or(0))
384 .saturating_add(1)
385 }
386 };
387 self.interactive_oldest_enqueued_ms_plus_one.store(
388 encode_oldest(
389 snapshot.interactive.queued,
390 snapshot.interactive.oldest_age_ms,
391 ),
392 Ordering::Relaxed,
393 );
394 self.maintenance_oldest_enqueued_ms_plus_one.store(
395 encode_oldest(
396 snapshot.maintenance.queued,
397 snapshot.maintenance.oldest_age_ms,
398 ),
399 Ordering::Relaxed,
400 );
401 self.interactive_running
402 .store(snapshot.running.interactive, Ordering::Release);
403 self.maintenance_running
404 .store(snapshot.running.maintenance, Ordering::Release);
405 self.completion_owned_interactive.store(
406 snapshot.running.completion_owned_interactive,
407 Ordering::Release,
408 );
409 self.completion_owned_maintenance.store(
410 snapshot.running.completion_owned_maintenance,
411 Ordering::Release,
412 );
413 self.oldest_worker_owned_maintenance_started_ms_plus_one
414 .store(
415 encode_oldest(
416 snapshot.running.completion_owned_maintenance,
417 snapshot.running.oldest_worker_owned_maintenance_age_ms,
418 ),
419 Ordering::Relaxed,
420 );
421 self.phantom_interactive
422 .store(snapshot.running.phantom_interactive, Ordering::Release);
423 self.phantom_maintenance
424 .store(snapshot.running.phantom_maintenance, Ordering::Release);
425 self.interactive_queued
426 .store(snapshot.interactive.queued, Ordering::Release);
427 self.maintenance_queued
428 .store(snapshot.maintenance.queued, Ordering::Release);
429 }
430
431 fn snapshot(&self, config: &EffectiveConfig) -> DispatchLivenessSnapshot {
432 let now_ms = self.now_ms();
433 let decode_oldest = |queued: usize, encoded: u64| {
434 (queued > 0 && encoded > 0).then(|| now_ms.saturating_sub(encoded - 1))
435 };
436 let interactive_queued = self.interactive_queued.load(Ordering::Acquire);
437 let maintenance_queued = self.maintenance_queued.load(Ordering::Acquire);
438 DispatchLivenessSnapshot {
439 interactive: DispatchClassQueueSnapshot {
440 queued: interactive_queued,
441 oldest_age_ms: decode_oldest(
442 interactive_queued,
443 self.interactive_oldest_enqueued_ms_plus_one
444 .load(Ordering::Relaxed),
445 ),
446 },
447 maintenance: DispatchClassQueueSnapshot {
448 queued: maintenance_queued,
449 oldest_age_ms: decode_oldest(
450 maintenance_queued,
451 self.maintenance_oldest_enqueued_ms_plus_one
452 .load(Ordering::Relaxed),
453 ),
454 },
455 running: DispatchRunningSnapshot {
456 interactive: self.interactive_running.load(Ordering::Acquire),
457 maintenance: self.maintenance_running.load(Ordering::Acquire),
458 completion_owned_interactive: self
459 .completion_owned_interactive
460 .load(Ordering::Acquire),
461 completion_owned_maintenance: self
462 .completion_owned_maintenance
463 .load(Ordering::Acquire),
464 oldest_worker_owned_maintenance_age_ms: decode_oldest(
465 self.completion_owned_maintenance.load(Ordering::Acquire),
466 self.oldest_worker_owned_maintenance_started_ms_plus_one
467 .load(Ordering::Relaxed),
468 ),
469 phantom_interactive: self.phantom_interactive.load(Ordering::Acquire),
470 phantom_maintenance: self.phantom_maintenance.load(Ordering::Acquire),
471 },
472 phantom_running_maintenance: self.phantom_maintenance.load(Ordering::Acquire),
473 interactive_reserve: config.interactive_reserve,
474 maintenance_cap: config.maintenance_cap,
475 }
476 }
477}
478
479pub struct DispatchLoopLiveness<C: ExecutorContext> {
484 #[cfg(any(test, feature = "test-support"))]
485 pub origin: Instant,
486 #[cfg(not(any(test, feature = "test-support")))]
487 origin: Instant,
488 #[cfg(any(test, feature = "test-support"))]
489 pub last_progress_ms: AtomicU64,
492 #[cfg(not(any(test, feature = "test-support")))]
493 last_progress_ms: AtomicU64,
496 #[cfg(any(test, feature = "test-support"))]
497 pub in_event: AtomicBool,
500 #[cfg(not(any(test, feature = "test-support")))]
501 in_event: AtomicBool,
504 #[cfg(any(test, feature = "test-support"))]
505 pub event_rx: Receiver<SchedulerEvent<C>>,
508 #[cfg(not(any(test, feature = "test-support")))]
509 event_rx: Receiver<SchedulerEvent<C>>,
512}
513
514impl<C: ExecutorContext> DispatchLoopLiveness<C> {
515 #[rustfmt::skip]
516 test_support_visibility! {
517 fn new(event_rx: Receiver<SchedulerEvent<C>>) -> Self {
518 Self {
519 origin: Instant::now(),
520 last_progress_ms: AtomicU64::new(0),
521 in_event: AtomicBool::new(false),
522 event_rx,
523 }
524 }
525 }
526
527 fn now_ms(&self) -> u64 {
528 duration_millis_u64(self.origin.elapsed())
529 }
530
531 #[rustfmt::skip]
532 test_support_visibility! {
533
534 fn wait_for_event(&self, next_retry_at: Option<Instant>) -> bool {
535 let mut select = crossbeam_channel::Select::new();
536 select.recv(&self.event_rx);
537 let ready = match next_retry_at {
538 Some(at) => select
539 .ready_timeout(at.saturating_duration_since(Instant::now()))
540 .is_ok(),
541 None => {
542 select.ready();
543 true
544 }
545 };
546 self.begin_event();
549 ready
550 }
551 }
552
553 fn begin_event(&self) {
554 self.last_progress_ms
555 .store(self.now_ms(), Ordering::Relaxed);
556 self.in_event.store(true, Ordering::Release);
557 }
558
559 #[rustfmt::skip]
560 test_support_visibility! {
561
562 fn end_event(&self) {
563 self.last_progress_ms
564 .store(self.now_ms(), Ordering::Relaxed);
565 self.in_event.store(false, Ordering::Release);
566 }
567 }
568
569 pub fn progress_age(&self) -> Duration {
571 let last = self.last_progress_ms.load(Ordering::Relaxed);
572 Duration::from_millis(self.now_ms().saturating_sub(last))
573 }
574
575 pub fn has_pending_work(&self) -> bool {
579 !self.event_rx.is_empty() || self.in_event.load(Ordering::Acquire)
582 }
583}
584
585#[derive(Debug, Clone, PartialEq, Eq)]
586pub struct MutatingLaneSnapshot {
587 pub root_id: ProjectRootId,
588 pub request_id: String,
589 pub command: String,
590 pub started_age_ms: u64,
591}
592
593#[derive(Debug, Clone)]
597pub struct RootJobSnapshot {
598 pub job_id: u64,
599 pub request_id: String,
600 pub command: String,
601 pub lane: Lane,
602 pub started_age_ms: u64,
603 pub execution_started: bool,
604 pub is_current: bool,
605}
606
607#[derive(Debug, Clone, PartialEq, Eq)]
609pub struct BindBlockerReaderSnapshot {
610 pub request_id: String,
611 pub command: String,
612 pub lane: Lane,
613 pub started_age_ms: u64,
614 pub execution_started: bool,
615 pub started_before_oldest_writer: bool,
616}
617
618#[derive(Debug, Clone, PartialEq, Eq)]
619pub struct BindBlockerSnapshot {
620 pub configure_state: &'static str,
621 pub configure_phase_timings: Option<String>,
622 pub blockers: Vec<String>,
623 pub oldest_queued_writer_age_ms: Option<u64>,
624 pub in_flight_readers: Vec<BindBlockerReaderSnapshot>,
625 pub in_flight_writer: Option<MutatingLaneSnapshot>,
626 pub reader_admissions_while_promoted_writer_waited: u64,
627}
628
629#[derive(Debug, Clone)]
640pub struct JobCancellation {
641 #[cfg(any(test, feature = "test-support"))]
642 pub inner: Arc<JobCancellationInner>,
643 #[cfg(not(any(test, feature = "test-support")))]
644 inner: Arc<JobCancellationInner>,
645 root: Option<Arc<std::path::PathBuf>>,
646 lifecycle: Option<crate::executor::root_lifecycle::SubcLifecycleAdmission>,
647}
648
649#[rustfmt::skip]
650test_support_visibility! {
651#[derive(Debug)]
652struct JobCancellationInner {
653 state: AtomicU8,
654 progress: Mutex<Option<crate::tool_progress::Progress>>,
655 wait_lock: Mutex<()>,
656 wake: Condvar,
657 #[cfg(any(test, feature = "test-support"))]
658 pub root_probe_barrier: Mutex<Option<(Sender<()>, Receiver<()>)>>,
659}
660}
661
662const JOB_CANCEL_STATE_PENDING: u8 = 0;
663const JOB_CANCEL_STATE_RUNNING: u8 = 1;
664const JOB_CANCEL_STATE_COMMITTED: u8 = 2;
665const JOB_CANCEL_STATE_CANCELLED: u8 = 3;
666
667impl JobCancellation {
668 pub fn new() -> Self {
669 Self {
670 inner: Arc::new(JobCancellationInner {
671 state: AtomicU8::new(JOB_CANCEL_STATE_PENDING),
672 progress: Mutex::new(None),
673 wait_lock: Mutex::new(()),
674 wake: Condvar::new(),
675 #[cfg(any(test, feature = "test-support"))]
676 root_probe_barrier: Mutex::new(None),
677 }),
678 root: None,
679 lifecycle: None,
680 }
681 }
682
683 pub fn with_root(mut self, root: &std::path::Path) -> Self {
684 self.root = Some(Arc::new(root.to_path_buf()));
685 self
686 }
687
688 pub fn set_progress(&self, progress: crate::tool_progress::Progress) {
689 *self.inner.progress.lock() = Some(progress);
690 }
691
692 pub fn has_progress_channel(&self, key: usize) -> bool {
693 self.inner
694 .progress
695 .lock()
696 .as_ref()
697 .is_some_and(|progress| progress.key() == key)
698 }
699
700 pub fn report_progress(&self) {
701 if !self.cancel_already_requested() {
702 let progress = self.inner.progress.lock().clone();
703 if let Some(progress) = progress {
704 progress.report();
705 }
706 }
707 }
708
709 pub fn with_lifecycle(
710 mut self,
711 lifecycle: crate::executor::root_lifecycle::SubcLifecycleAdmission,
712 ) -> Self {
713 self.lifecycle = Some(lifecycle);
714 self
715 }
716
717 pub fn fresh(&self) -> Self {
718 let mut token = Self::new();
719 token.root = self.root.clone();
720 token.lifecycle = self.lifecycle.clone();
721 token
722 }
723
724 fn mark_running(&self) -> bool {
725 match self.inner.state.compare_exchange(
726 JOB_CANCEL_STATE_PENDING,
727 JOB_CANCEL_STATE_RUNNING,
728 Ordering::SeqCst,
729 Ordering::SeqCst,
730 ) {
731 Ok(_) => true,
732 Err(state) => state != JOB_CANCEL_STATE_CANCELLED,
733 }
734 }
735
736 fn return_to_pending(&self) -> bool {
740 match self.inner.state.compare_exchange(
741 JOB_CANCEL_STATE_RUNNING,
742 JOB_CANCEL_STATE_PENDING,
743 Ordering::SeqCst,
744 Ordering::SeqCst,
745 ) {
746 Ok(_) => true,
747 Err(state) => {
748 debug_assert_ne!(
749 state, JOB_CANCEL_STATE_COMMITTED,
750 "a bind queued again must not have committed"
751 );
752 state == JOB_CANCEL_STATE_PENDING
753 }
754 }
755 }
756
757 fn try_cancel_before_running(&self) -> bool {
758 let cancelled = self
759 .inner
760 .state
761 .compare_exchange(
762 JOB_CANCEL_STATE_PENDING,
763 JOB_CANCEL_STATE_CANCELLED,
764 Ordering::SeqCst,
765 Ordering::SeqCst,
766 )
767 .is_ok();
768 if cancelled {
769 let _wait_guard = self.inner.wait_lock.lock();
770 self.inner.wake.notify_all();
771 }
772 cancelled
773 }
774
775 #[must_use]
779 pub fn try_seal_committed(&self) -> bool {
780 loop {
781 let current = self.state();
782 match current {
783 JOB_CANCEL_STATE_CANCELLED => return false,
784 JOB_CANCEL_STATE_COMMITTED => return true,
785 _ => {
786 if self
787 .inner
788 .state
789 .compare_exchange(
790 current,
791 JOB_CANCEL_STATE_COMMITTED,
792 Ordering::SeqCst,
793 Ordering::SeqCst,
794 )
795 .is_ok()
796 {
797 return true;
798 }
799 }
800 }
801 }
802 }
803
804 fn signal_cancel(&self) -> u8 {
807 let observed = loop {
808 let current = self.state();
809 match current {
810 JOB_CANCEL_STATE_COMMITTED | JOB_CANCEL_STATE_CANCELLED => break current,
811 _ => {
812 if self
813 .inner
814 .state
815 .compare_exchange(
816 current,
817 JOB_CANCEL_STATE_CANCELLED,
818 Ordering::SeqCst,
819 Ordering::SeqCst,
820 )
821 .is_ok()
822 {
823 break current;
824 }
825 }
826 }
827 };
828 if observed != JOB_CANCEL_STATE_COMMITTED {
829 let _wait_guard = self.inner.wait_lock.lock();
830 self.inner.wake.notify_all();
831 }
832 if observed != JOB_CANCEL_STATE_COMMITTED {
833 crate::cold_build_limiter::progress::cancel_token(self.progress_key());
834 }
835 observed
836 }
837
838 fn state(&self) -> u8 {
839 self.inner.state.load(Ordering::SeqCst)
840 }
841
842 pub fn request_cancel(&self) {
846 self.signal_cancel();
847 }
848
849 pub(crate) fn progress_key(&self) -> usize {
850 Arc::as_ptr(&self.inner) as usize
851 }
852
853 pub fn cancel_already_requested(&self) -> bool {
858 self.state() == JOB_CANCEL_STATE_CANCELLED
859 }
860
861 pub fn cancel_requested_before_commit(&self) -> bool {
867 let state = self.state();
868 match state {
869 JOB_CANCEL_STATE_CANCELLED => return true,
870 JOB_CANCEL_STATE_COMMITTED => return false,
871 _ => {}
872 }
873 if let Some(lifecycle) = &self.lifecycle {
874 lifecycle.cancel_if_abandoned(|| self.request_cancel());
875 if self.cancel_already_requested() {
876 return true;
877 }
878 }
879 if self.root.is_none() {
880 return false;
881 }
882 thread_local! {
890 static LAST_PROBE: std::cell::RefCell<Option<(std::sync::Weak<JobCancellationInner>, u8, u16, Instant)>> =
891 const { std::cell::RefCell::new(None) };
892 }
893 let probe = LAST_PROBE.with(|slot| {
894 let mut last = slot.borrow_mut();
895 if let Some((identity, previous_state, items, when)) = last.as_mut() {
896 if identity.as_ptr() == Arc::as_ptr(&self.inner) && *previous_state == state {
897 *items += 1;
898 #[cfg(not(any(test, feature = "test-support")))]
899 let elapsed = when.elapsed();
900 #[cfg(any(test, feature = "test-support"))]
901 let elapsed = crate::executor::audit::audit_cancel_elapsed(*when);
902 if *items < 256 && elapsed < Duration::from_millis(50) {
903 return false;
904 }
905 *items = 0;
906 *when = Instant::now();
907 return true;
908 }
909 }
910 *last = Some((Arc::downgrade(&self.inner), state, 0, Instant::now()));
911 true
912 });
913 #[cfg(any(test, feature = "test-support"))]
914 let barrier = self.inner.root_probe_barrier.lock().take();
915 #[cfg(any(test, feature = "test-support"))]
916 let probe = probe || barrier.is_some();
917 if !probe {
918 return self.state() == JOB_CANCEL_STATE_CANCELLED;
919 }
920 #[cfg(any(test, feature = "test-support"))]
921 crate::executor::audit::audit_record(|work| work.cancel_probes += 1);
922 #[cfg(any(test, feature = "test-support"))]
923 {
924 if let Some((parked, release)) = barrier {
925 parked.send(()).unwrap();
926 release.recv().unwrap();
927 }
928 }
929 if self
933 .root
934 .as_ref()
935 .is_some_and(|root| match std::fs::metadata(root.as_path()) {
936 Ok(metadata) => !metadata.is_dir(),
937 Err(error) => matches!(
938 error.kind(),
939 std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
940 ),
941 })
942 {
943 self.request_cancel();
944 }
945 self.state() == JOB_CANCEL_STATE_CANCELLED
946 }
947
948 pub fn wait_for_cancellation(&self, timeout: Duration) -> bool {
953 if self.cancel_requested_before_commit() {
954 return true;
955 }
956 {
957 let mut guard = self.inner.wait_lock.lock();
958 if self.cancel_already_requested() {
964 return true;
965 }
966 self.inner.wake.wait_for(&mut guard, timeout);
967 }
968 self.cancel_requested_before_commit()
969 }
970
971 fn same_token(&self, other: &JobCancellation) -> bool {
972 Arc::ptr_eq(&self.inner, &other.inner)
973 }
974}
975
976#[derive(Debug, Clone, Copy, PartialEq, Eq)]
978pub enum JobCancelOutcome {
979 QueuedRemoved,
982 RunningSignalled,
985 RunningCommitted,
988 NotFound,
990}
991
992#[derive(Debug, Clone, Copy, PartialEq, Eq)]
994pub enum PreExecutionCancelOutcome {
995 QueuedRemoved,
996 DispatchedCancelled,
997 AlreadyStarted,
998}
999
1000thread_local! {
1001 static CURRENT_JOB_CANCELLATION: std::cell::RefCell<Option<JobCancellation>> =
1002 const { std::cell::RefCell::new(None) };
1003}
1004
1005pub fn current_job_cancellation() -> Option<JobCancellation> {
1008 CURRENT_JOB_CANCELLATION.with(|slot| slot.borrow().clone())
1009}
1010
1011pub fn current_job_cancelled() -> bool {
1012 CURRENT_JOB_CANCELLATION.with(|slot| {
1013 slot.borrow()
1014 .as_ref()
1015 .is_some_and(JobCancellation::cancel_requested_before_commit)
1016 })
1017}
1018
1019pub struct JobCancellationContextGuard {
1020 previous: Option<JobCancellation>,
1021}
1022
1023impl JobCancellationContextGuard {
1024 fn install(token: Option<JobCancellation>) -> Self {
1025 let previous = CURRENT_JOB_CANCELLATION.with(|slot| slot.replace(token));
1026 Self { previous }
1027 }
1028}
1029
1030impl Drop for JobCancellationContextGuard {
1031 fn drop(&mut self) {
1032 CURRENT_JOB_CANCELLATION.with(|slot| {
1033 *slot.borrow_mut() = self.previous.take();
1034 });
1035 }
1036}
1037
1038pub fn install_job_cancellation(token: JobCancellation) -> JobCancellationContextGuard {
1044 JobCancellationContextGuard::install(Some(token))
1045}
1046
1047#[derive(Clone)]
1051struct ActorWriterDemand {
1052 queued: Arc<AtomicUsize>,
1053 detached: Option<Arc<AtomicUsize>>,
1054}
1055
1056impl ActorWriterDemand {
1057 fn waiting(&self) -> bool {
1058 self.queued.load(Ordering::Acquire) > 0
1059 || self
1060 .detached
1061 .as_ref()
1062 .is_some_and(|detached| detached.load(Ordering::Acquire) > 0)
1063 }
1064}
1065
1066thread_local! {
1067 static CURRENT_ACTOR_WAITING_WRITERS: std::cell::RefCell<Option<ActorWriterDemand>> =
1068 const { std::cell::RefCell::new(None) };
1069}
1070
1071pub fn current_actor_writer_waiting() -> bool {
1084 CURRENT_ACTOR_WAITING_WRITERS.with(|slot| {
1085 slot.borrow()
1086 .as_ref()
1087 .is_some_and(ActorWriterDemand::waiting)
1088 })
1089}
1090
1091#[rustfmt::skip]
1092test_support_visibility! {
1093pub(crate) struct ActorWaitingWritersGuard {
1094 previous: Option<ActorWriterDemand>,
1095}
1096}
1097
1098impl ActorWaitingWritersGuard {
1099 fn install(demand: ActorWriterDemand) -> Self {
1100 let previous = CURRENT_ACTOR_WAITING_WRITERS.with(|slot| slot.replace(Some(demand)));
1101 Self { previous }
1102 }
1103}
1104
1105impl Drop for ActorWaitingWritersGuard {
1106 fn drop(&mut self) {
1107 CURRENT_ACTOR_WAITING_WRITERS.with(|slot| {
1108 *slot.borrow_mut() = self.previous.take();
1109 });
1110 }
1111}
1112
1113#[cfg(any(test, feature = "test-support"))]
1116pub fn install_actor_waiting_writers_for_test(
1117 waiting: Arc<AtomicUsize>,
1118) -> ActorWaitingWritersGuard {
1119 ActorWaitingWritersGuard::install(ActorWriterDemand {
1120 queued: waiting,
1121 detached: None,
1122 })
1123}
1124
1125pub type RepeatableJob<C> = Arc<dyn Fn(&C) -> Response + Send + Sync + 'static>;
1130
1131thread_local! {
1132 static CURRENT_BIND_GATE_SHARED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1135 static EXCLUSIVE_RERUN_REQUESTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1137}
1138
1139struct SharedBindScope;
1141
1142impl SharedBindScope {
1143 fn install() -> Self {
1144 CURRENT_BIND_GATE_SHARED.with(|shared| shared.set(true));
1145 EXCLUSIVE_RERUN_REQUESTED.with(|requested| requested.set(false));
1146 Self
1147 }
1148
1149 fn rerun_requested(&self) -> bool {
1152 EXCLUSIVE_RERUN_REQUESTED.with(std::cell::Cell::get)
1153 }
1154}
1155
1156impl Drop for SharedBindScope {
1157 fn drop(&mut self) {
1158 CURRENT_BIND_GATE_SHARED.with(|shared| shared.set(false));
1159 EXCLUSIVE_RERUN_REQUESTED.with(|requested| requested.set(false));
1160 }
1161}
1162
1163pub fn current_bind_gate_is_shared() -> bool {
1176 CURRENT_BIND_GATE_SHARED.with(std::cell::Cell::get)
1177}
1178
1179pub fn request_exclusive_rerun() -> bool {
1190 if !current_bind_gate_is_shared() {
1191 return false;
1192 }
1193 EXCLUSIVE_RERUN_REQUESTED.with(|requested| requested.set(true));
1194 true
1195}
1196
1197#[rustfmt::skip]
1198test_support_visibility! {
1199#[derive(Debug, Clone)]
1200struct RunningJob {
1201 #[cfg(any(test, feature = "test-support"))]
1202 pub root_id: ProjectRootId,
1203 #[cfg(not(any(test, feature = "test-support")))]
1204 root_id: ProjectRootId,
1205 #[cfg(any(test, feature = "test-support"))]
1206 pub request_id: String,
1207 #[cfg(not(any(test, feature = "test-support")))]
1208 request_id: String,
1209 command: String,
1210 job_class: JobClass,
1211 lane: Lane,
1212 #[cfg(any(test, feature = "test-support"))]
1213 pub started_at: Instant,
1214 #[cfg(not(any(test, feature = "test-support")))]
1215 started_at: Instant,
1216 #[cfg(any(test, feature = "test-support"))]
1217 pub execution_started: Arc<AtomicBool>,
1218 #[cfg(not(any(test, feature = "test-support")))]
1219 execution_started: Arc<AtomicBool>,
1220 completion_ownership: Weak<JobCompletionOwnership>,
1221 occupancy_reported: bool,
1222 cancellation: Option<JobCancellation>,
1223}
1224}
1225
1226#[derive(Debug, Clone)]
1227pub struct LongRunningInteractiveJobSnapshot {
1228 pub root_id: ProjectRootId,
1229 pub request_id: String,
1230 pub command: String,
1231 pub lane: Lane,
1232 pub age: Duration,
1233 pub execution_started: bool,
1234}
1235
1236#[derive(Debug, Clone)]
1237struct RunningMutatingJob {
1238 request_id: String,
1239 command: String,
1240 started_at: Instant,
1241}
1242
1243pub struct Executor<C: ExecutorContext> {
1245 #[cfg(any(test, feature = "test-support"))]
1246 pub inner: Arc<ExecutorInner<C>>,
1247 #[cfg(not(any(test, feature = "test-support")))]
1248 inner: Arc<ExecutorInner<C>>,
1249}
1250
1251#[derive(Clone)]
1254pub struct RootMaintenanceExecutor {
1255 inner: Arc<dyn MaintenanceSubmit>,
1256}
1257
1258type MaintenanceJob = Box<dyn FnOnce() -> Response + Send + 'static>;
1259
1260trait MaintenanceSubmit: Send + Sync {
1261 fn submit_maintenance(
1262 &self,
1263 request_id: &str,
1264 lane: Lane,
1265 cancellation: JobCancellation,
1266 job: MaintenanceJob,
1267 ) -> bool;
1268}
1269
1270struct TypedMaintenanceExecutor<C: ExecutorContext> {
1271 inner: std::sync::Weak<ExecutorInner<C>>,
1272 root_id: ProjectRootId,
1273}
1274
1275struct SubmissionExecutor<C: ExecutorContext>(Option<Executor<C>>);
1276
1277impl<C: ExecutorContext> Drop for SubmissionExecutor<C> {
1278 fn drop(&mut self) {
1279 let executor = self.0.take();
1280 if current_thread_is_executor_worker() {
1281 std::thread::spawn(move || drop(executor));
1285 }
1286 }
1287}
1288
1289impl RootMaintenanceExecutor {
1290 fn new<C: ExecutorContext>(
1291 inner: std::sync::Weak<ExecutorInner<C>>,
1292 root_id: ProjectRootId,
1293 ) -> Self {
1294 Self {
1295 inner: Arc::new(TypedMaintenanceExecutor::<C> { inner, root_id }),
1296 }
1297 }
1298 pub fn submit_maintenance(
1319 &self,
1320 request_id: &str,
1321 lane: Lane,
1322 cancellation: JobCancellation,
1323 job: MaintenanceJob,
1324 ) -> bool {
1325 self.inner
1326 .submit_maintenance(request_id, lane, cancellation, job)
1327 }
1328}
1329
1330impl<C: ExecutorContext> MaintenanceSubmit for TypedMaintenanceExecutor<C> {
1331 fn submit_maintenance(
1332 &self,
1333 request_id: &str,
1334 lane: Lane,
1335 cancellation: JobCancellation,
1336 job: MaintenanceJob,
1337 ) -> bool {
1338 let Some(inner) = self.inner.upgrade() else {
1339 return false;
1340 };
1341 let owner = SubmissionExecutor::<C>(Some(Executor::<C> { inner }));
1343 let executor = owner.0.as_ref().unwrap();
1344 let root_exists = executor.maintenance_root_is_dir(&self.root_id);
1347 let admitted = {
1348 let state = executor.inner.state.lock();
1349 state
1350 .actors
1351 .get(&self.root_id)
1352 .filter(|actor| !actor.fatal && !actor.ctx.subc_unbound_quiesced())
1353 .map(|actor| {
1354 let token = cancellation
1355 .with_root(self.root_id.as_path())
1356 .with_lifecycle(actor.ctx.subc_lifecycle_admission());
1357 (Arc::clone(&actor.ctx), token)
1358 })
1359 };
1360 let Some((_ctx, token)) = admitted.filter(|_| root_exists) else {
1361 log::debug!(
1362 "executor refused maintenance: request_id={request_id} lane={lane:?} root={} \
1363 (unbound, missing or unregistered)",
1364 self.root_id.as_path().display()
1365 );
1366 return true;
1367 };
1368 if token.cancel_requested_before_commit() || !token.mark_running() {
1369 return true;
1370 }
1371 log::debug!(
1372 "executor admitted maintenance: request_id={request_id} lane={lane:?} root={}",
1373 self.root_id.as_path().display()
1374 );
1375 let _installed = JobCancellationContextGuard::install(Some(token));
1376 let _ = job();
1377 true
1378 }
1379}
1380
1381impl<C: ExecutorContext> Default for Executor<C> {
1382 fn default() -> Self {
1383 Self::new()
1384 }
1385}
1386
1387#[rustfmt::skip]
1388test_support_visibility! {
1389struct ExecutorInner<C: ExecutorContext> {
1390 #[cfg(any(test, feature = "test-support"))]
1391 pub state: Arc<TrackedMutex<SchedulerState<C>>>,
1392 #[cfg(not(any(test, feature = "test-support")))]
1393 state: Arc<TrackedMutex<SchedulerState<C>>>,
1394 event_tx: Sender<SchedulerEvent<C>>,
1395 scheduler_handle: Mutex<Option<JoinHandle<()>>>,
1396 worker_handles: Mutex<Vec<JoinHandle<()>>>,
1397 #[cfg(any(test, feature = "test-support"))]
1398 pub config: EffectiveConfig,
1399 #[cfg(not(any(test, feature = "test-support")))]
1400 config: EffectiveConfig,
1401 nonrunnable_dispatches: Arc<AtomicUsize>,
1402 completed_interactive: Arc<AtomicU64>,
1403 completed_maintenance: Arc<AtomicU64>,
1404 dispatch_liveness: Arc<DispatchLivenessAtomics>,
1405 dispatch_loop_liveness: Arc<DispatchLoopLiveness<C>>,
1406 #[cfg(any(test, feature = "test-support"))]
1407 pub maintenance_root_check_hook: Mutex<Option<Box<dyn FnOnce() + Send>>>,
1408}
1409}
1410
1411impl<C: ExecutorContext> Drop for ExecutorInner<C> {
1412 fn drop(&mut self) {
1413 {
1416 let mut state = self.state.lock();
1417 for job in state.running_jobs.values() {
1418 if job.job_class == JobClass::Maintenance {
1419 if let Some(token) = &job.cancellation {
1420 token.request_cancel();
1421 }
1422 }
1423 }
1424 for actor in state.actors.values_mut() {
1425 actor.maintenance.cancel_queued_jobs();
1426 }
1427 }
1428 let _ = self.event_tx.send(SchedulerEvent::<C>::Shutdown);
1429
1430 if let Some(handle) = self.scheduler_handle.lock().take() {
1431 if handle.thread().id() != std::thread::current().id() {
1432 let _ = handle.join();
1433 }
1434 }
1435
1436 let mut workers = self.worker_handles.lock();
1437 for handle in workers.drain(..) {
1438 if handle.thread().id() != std::thread::current().id() {
1441 let _ = handle.join();
1442 }
1443 }
1444 }
1445}
1446
1447#[rustfmt::skip]
1448test_support_visibility! {
1449struct SchedulerState<C: ExecutorContext> {
1450 #[cfg(any(test, feature = "test-support"))]
1451 pub actors: HashMap<ProjectRootId, ActorState<C>>,
1452 #[cfg(not(any(test, feature = "test-support")))]
1453 actors: HashMap<ProjectRootId, ActorState<C>>,
1454 #[cfg(any(test, feature = "test-support"))]
1455 pub actor_order: Vec<ProjectRootId>,
1456 #[cfg(not(any(test, feature = "test-support")))]
1457 actor_order: Vec<ProjectRootId>,
1458 cursor: usize,
1459 #[cfg(any(test, feature = "test-support"))]
1460 pub idle_workers: usize,
1461 #[cfg(not(any(test, feature = "test-support")))]
1462 idle_workers: usize,
1463 interactive_inflight: usize,
1464 maintenance_inflight: usize,
1465 #[cfg(any(test, feature = "test-support"))]
1466 pub provider_inflight: usize,
1467 #[cfg(not(any(test, feature = "test-support")))]
1468 provider_inflight: usize,
1469 #[cfg(any(test, feature = "test-support"))]
1470 pub binds_inflight: usize,
1471 #[cfg(not(any(test, feature = "test-support")))]
1472 binds_inflight: usize,
1473 #[cfg(any(test, feature = "test-support"))]
1474 pub config: EffectiveConfig,
1475 #[cfg(not(any(test, feature = "test-support")))]
1476 config: EffectiveConfig,
1477 #[cfg(any(test, feature = "test-support"))]
1478 pub running_jobs: HashMap<u64, RunningJob>,
1479 #[cfg(not(any(test, feature = "test-support")))]
1480 running_jobs: HashMap<u64, RunningJob>,
1481 next_job_id: u64,
1482 bind_retry_pending: bool,
1485}
1486}
1487
1488impl<C: ExecutorContext> SchedulerState<C> {
1489 #[rustfmt::skip]
1490 test_support_visibility! {
1491 fn new(config: EffectiveConfig) -> Self {
1492 Self {
1493 actors: HashMap::new(),
1494 actor_order: Vec::new(),
1495 cursor: 0,
1496 idle_workers: config.total_workers(),
1497 interactive_inflight: 0,
1498 maintenance_inflight: 0,
1499 provider_inflight: 0,
1500 binds_inflight: 0,
1501 config,
1502 running_jobs: HashMap::new(),
1503 next_job_id: 1,
1504 bind_retry_pending: false,
1505 }
1506 }
1507 }
1508
1509 fn next_bind_retry_at(&mut self) -> Option<Instant> {
1512 if !self.bind_retry_pending {
1513 return None;
1514 }
1515 let next = self
1516 .actors
1517 .values()
1518 .flat_map(|actor| actor.interactive.queue(Lane::Mutating).iter())
1519 .filter_map(|job| job.not_before)
1520 .min();
1521 self.bind_retry_pending = next.is_some();
1522 next
1523 }
1524
1525 fn dispatch_liveness_snapshot(&self) -> DispatchLivenessSnapshot {
1526 self.assert_running_invariants();
1527 let now = Instant::now();
1528 let (completion_owned_interactive, completion_owned_maintenance) = self
1529 .running_jobs
1530 .values()
1531 .filter(|job| job.completion_ownership.strong_count() > 0)
1532 .fold((0, 0), |(interactive, maintenance), job| {
1533 match job.job_class {
1534 JobClass::Interactive => (interactive + 1, maintenance),
1535 JobClass::Maintenance => (interactive, maintenance + 1),
1536 }
1537 });
1538 let oldest_worker_owned_maintenance_age_ms = self
1539 .running_jobs
1540 .values()
1541 .filter(|job| {
1542 job.job_class == JobClass::Maintenance
1543 && job.completion_ownership.strong_count() > 0
1544 })
1545 .map(|job| duration_millis_u64(now.saturating_duration_since(job.started_at)))
1546 .max();
1547 let mut interactive = QueueSnapshotAccumulator::default();
1548 let mut maintenance = QueueSnapshotAccumulator::default();
1549 for actor in self.actors.values() {
1550 interactive.add(actor.class_queues(JobClass::Interactive), now);
1551 maintenance.add(actor.class_queues(JobClass::Maintenance), now);
1552 }
1553
1554 DispatchLivenessSnapshot {
1555 interactive: interactive.finish(),
1556 maintenance: maintenance.finish(),
1557 running: DispatchRunningSnapshot {
1558 interactive: self.interactive_inflight,
1559 maintenance: self.maintenance_inflight,
1560 completion_owned_interactive,
1561 completion_owned_maintenance,
1562 oldest_worker_owned_maintenance_age_ms,
1563 phantom_interactive: self
1564 .interactive_inflight
1565 .saturating_sub(completion_owned_interactive),
1566 phantom_maintenance: self
1567 .maintenance_inflight
1568 .saturating_sub(completion_owned_maintenance),
1569 },
1570 phantom_running_maintenance: self
1571 .maintenance_inflight
1572 .saturating_sub(completion_owned_maintenance),
1573 interactive_reserve: self.config.interactive_reserve,
1574 maintenance_cap: self.config.maintenance_cap,
1575 }
1576 }
1577
1578 fn assert_running_invariants(&self) {
1579 let interactive = self
1580 .running_jobs
1581 .values()
1582 .filter(|job| job.job_class == JobClass::Interactive)
1583 .count();
1584 let maintenance = self
1585 .running_jobs
1586 .values()
1587 .filter(|job| job.job_class == JobClass::Maintenance)
1588 .count();
1589 debug_assert_eq!(self.interactive_inflight, interactive);
1590 debug_assert_eq!(self.maintenance_inflight, maintenance);
1591 debug_assert_eq!(
1592 self.binds_inflight,
1593 self.running_jobs
1594 .values()
1595 .filter(|job| is_bind_job(job.job_class, job.lane, &job.request_id))
1596 .count()
1597 );
1598 debug_assert_eq!(
1599 self.provider_inflight,
1600 self.running_jobs
1601 .values()
1602 .filter(|job| job.lane == Lane::ProviderMetadata)
1603 .count()
1604 );
1605 debug_assert!(self.provider_inflight <= self.config.provider_reserve);
1606 debug_assert_eq!(
1607 self.idle_workers + self.running_jobs.len(),
1608 self.config.total_workers()
1609 );
1610 debug_assert!(self
1611 .running_jobs
1612 .values()
1613 .all(|job| job.completion_ownership.strong_count() > 0));
1614 }
1615
1616 fn next_job_id(&mut self) -> u64 {
1617 let job_id = self.next_job_id;
1618 self.next_job_id = self.next_job_id.wrapping_add(1).max(1);
1619 job_id
1620 }
1621
1622 fn mutating_lane_snapshots(&self) -> Vec<MutatingLaneSnapshot> {
1623 let now = Instant::now();
1624 let mut snapshots: Vec<_> = self
1625 .actors
1626 .iter()
1627 .filter_map(|(root_id, actor)| {
1628 actor
1629 .mutating_inflight
1630 .as_ref()
1631 .map(|job| MutatingLaneSnapshot {
1632 root_id: root_id.clone(),
1633 request_id: job.request_id.clone(),
1634 command: job.command.clone(),
1635 started_age_ms: duration_millis_u64(
1636 now.saturating_duration_since(job.started_at),
1637 ),
1638 })
1639 })
1640 .collect();
1641 snapshots.sort_by(|left, right| left.root_id.as_path().cmp(right.root_id.as_path()));
1642 snapshots
1643 }
1644
1645 fn newest_in_flight_reader_started_at(&self, root_id: &ProjectRootId) -> Option<Instant> {
1648 self.running_jobs
1649 .values()
1650 .filter(|job| {
1651 job.root_id == *root_id
1652 && matches!(job.lane, Lane::PureRead | Lane::SerialLspStatus)
1653 })
1654 .map(|job| job.started_at)
1655 .max()
1656 }
1657
1658 fn mutating_job_state_label(&self, root_id: &ProjectRootId, request_id: &str) -> &'static str {
1659 let Some(actor) = self.actors.get(root_id) else {
1660 return "actor_missing";
1661 };
1662 if actor
1663 .mutating_inflight
1664 .as_ref()
1665 .is_some_and(|job| job.request_id == request_id)
1666 {
1667 return "running";
1668 }
1669 if actor.has_queued_mutating_job(request_id) {
1670 return "queued";
1671 }
1672 if actor.writer_inflight {
1673 return "blocked_by_other_mutating";
1674 }
1675 "not_found"
1676 }
1677
1678 #[rustfmt::skip]
1679 test_support_visibility! {
1680
1681 fn bind_blocker_snapshot(
1682 &self,
1683 root_id: &ProjectRootId,
1684 request_id: &str,
1685 ) -> BindBlockerSnapshot {
1686 let configure_state = self.mutating_job_state_label(root_id, request_id);
1687 let now = Instant::now();
1688 let actor = self.actors.get(root_id);
1689 let oldest_queued_writer_at = actor.and_then(ActorState::<C>::oldest_queued_writer_at);
1690 let oldest_queued_writer_age_ms = oldest_queued_writer_at
1691 .map(|queued_at| duration_millis_u64(now.saturating_duration_since(queued_at)));
1692 let mut in_flight_readers = self
1693 .running_jobs
1694 .values()
1695 .filter(|job| {
1696 job.root_id == *root_id
1697 && matches!(job.lane, Lane::PureRead | Lane::SerialLspStatus)
1698 })
1699 .map(|job| BindBlockerReaderSnapshot {
1700 request_id: job.request_id.clone(),
1701 command: job.command.clone(),
1702 lane: job.lane,
1703 started_age_ms: duration_millis_u64(now.saturating_duration_since(job.started_at)),
1704 execution_started: job.execution_started.load(Ordering::Acquire),
1705 started_before_oldest_writer: oldest_queued_writer_at
1706 .is_some_and(|queued_at| job.started_at <= queued_at),
1707 })
1708 .collect::<Vec<_>>();
1709 in_flight_readers.sort_by(|left, right| left.request_id.cmp(&right.request_id));
1710 let in_flight_writer = actor
1715 .and_then(|actor| actor.mutating_inflight.as_ref())
1716 .filter(|job| job.request_id != request_id)
1717 .map(|job| MutatingLaneSnapshot {
1718 root_id: root_id.clone(),
1719 request_id: job.request_id.clone(),
1720 command: job.command.clone(),
1721 started_age_ms: duration_millis_u64(now.saturating_duration_since(job.started_at)),
1722 });
1723
1724 let mut blockers = Vec::new();
1725 if let Some(actor) = actor {
1726 if configure_state == "queued" {
1727 let configure_count = actor.pending_configure_count();
1728 if configure_count > 0 {
1729 blockers.push(format!("queued_behind_configure({configure_count})"));
1730 }
1731 if actor.read_inflight > 0 || actor.lsp_inflight {
1732 let zombie_readers = in_flight_readers
1733 .iter()
1734 .filter(|reader| !reader.execution_started)
1735 .map(format_bind_blocker_reader)
1736 .collect::<Vec<_>>();
1737 let stuck_readers = in_flight_readers
1738 .iter()
1739 .filter(|reader| {
1740 reader.execution_started
1741 && reader.started_age_ms
1742 >= duration_millis_u64(READER_STUCK_CENSUS_AGE)
1743 })
1744 .map(format_bind_blocker_reader)
1745 .collect::<Vec<_>>();
1746 if !zombie_readers.is_empty() {
1747 blockers.push(format!("zombie_reader({})", zombie_readers.join("; ")));
1748 } else if !stuck_readers.is_empty() {
1749 blockers.push(format!(
1750 "waiting_on_readers_stuck({})",
1751 stuck_readers.join("; ")
1752 ));
1753 } else {
1754 blockers.push("waiting_on_readers".to_string());
1755 }
1756 }
1757 }
1758 }
1759
1760 if configure_state == "queued" {
1761 let maintenance: Vec<_> = self
1762 .running_jobs
1763 .values()
1764 .filter(|job| job.job_class == JobClass::Maintenance)
1765 .collect();
1766 if !maintenance.is_empty() {
1767 blockers.push(format!(
1768 "queued_behind_maintenance({})",
1769 format_running_jobs(&maintenance)
1770 ));
1771 }
1772 }
1773
1774 if let Some(actor) = actor {
1775 if configure_state == "queued" && actor.interactive.first_bind_is_forced_exclusive() {
1776 blockers.push("rerun_as_exclusive_writer".to_string());
1777 }
1778 if actor.detached_writers.load(Ordering::Acquire) > 0 {
1779 blockers.push("detached_view_publication_writer_waiting".to_string());
1780 }
1781 if let Some(stage) = actor.ctx.configure_tail_stage_snapshot() {
1784 blockers.push(format!("configure_tail_stage({stage})"));
1785 }
1786 }
1787
1788 if self.idle_workers == 0 {
1789 let running: Vec<_> = self.running_jobs.values().collect();
1790 blockers.push(format!(
1791 "idle_workers==0({})",
1792 format_running_jobs(&running)
1793 ));
1794 }
1795
1796 BindBlockerSnapshot {
1797 configure_state,
1798 configure_phase_timings: actor.map(|actor| actor.ctx.configure_ack_phase_snapshot()),
1799 blockers,
1800 oldest_queued_writer_age_ms,
1801 in_flight_readers,
1802 in_flight_writer,
1803 reader_admissions_while_promoted_writer_waited: actor
1804 .map(|actor| actor.reader_admissions_while_promoted_writer_waited)
1805 .unwrap_or(0),
1806 }
1807 }
1808
1809 }
1810}
1811
1812fn is_configure_request(request_id: &str) -> bool {
1813 request_id.starts_with("subc-bind-")
1814}
1815
1816fn is_bind_job(job_class: JobClass, lane: Lane, request_id: &str) -> bool {
1817 job_class == JobClass::Interactive && lane == Lane::Mutating && is_configure_request(request_id)
1818}
1819
1820fn is_callgraph_acquisition(job_class: JobClass, lane: Lane, request_id: &str) -> bool {
1821 job_class == JobClass::Maintenance
1822 && lane == Lane::HeavyInit
1823 && request_id == CALLGRAPH_ACQUISITION_REQUEST_ID
1824}
1825
1826fn format_bind_blocker_reader(reader: &BindBlockerReaderSnapshot) -> String {
1827 format!(
1828 "job={} command={} lane={:?} age_ms={} execution_started={} started_before_oldest_writer={}",
1829 reader.request_id,
1830 reader.command,
1831 reader.lane,
1832 reader.started_age_ms,
1833 reader.execution_started,
1834 reader.started_before_oldest_writer
1835 )
1836}
1837
1838fn format_running_jobs(jobs: &[&RunningJob]) -> String {
1839 let now = Instant::now();
1840 let mut labels: Vec<_> = jobs
1841 .iter()
1842 .map(|job| {
1843 format!(
1844 "job={} command={} lane={:?} root={} age_ms={}",
1845 job.request_id,
1846 job.command,
1847 job.lane,
1848 job.root_id.as_path().display(),
1849 duration_millis_u64(now.saturating_duration_since(job.started_at))
1850 )
1851 })
1852 .collect();
1853 labels.sort();
1854 labels.truncate(4);
1855 labels.join("; ")
1856}
1857
1858#[derive(Default)]
1859struct QueueSnapshotAccumulator {
1860 queued: usize,
1861 oldest_age_ms: Option<u64>,
1862}
1863
1864impl QueueSnapshotAccumulator {
1865 fn add<C: ExecutorContext>(&mut self, queues: &ClassQueues<C>, now: Instant) {
1866 self.queued += queues.queued_count();
1867 if let Some(queued_at) = queues.oldest_queued_at() {
1868 let age_ms = duration_millis_u64(now.saturating_duration_since(queued_at));
1869 self.oldest_age_ms = Some(
1870 self.oldest_age_ms
1871 .map_or(age_ms, |oldest| oldest.max(age_ms)),
1872 );
1873 }
1874 }
1875
1876 fn finish(self) -> DispatchClassQueueSnapshot {
1877 DispatchClassQueueSnapshot {
1878 queued: self.queued,
1879 oldest_age_ms: self.oldest_age_ms,
1880 }
1881 }
1882}
1883
1884#[rustfmt::skip]
1885test_support_visibility! {
1886
1887fn duration_millis_u64(duration: Duration) -> u64 {
1888 duration.as_millis().min(u128::from(u64::MAX)) as u64
1889}
1890}
1891
1892#[rustfmt::skip]
1893test_support_visibility! {
1894struct ActorState<C: ExecutorContext> {
1895 ctx: Arc<C>,
1896 #[cfg(any(test, feature = "test-support"))]
1897 pub epoch: Arc<RwLock<()>>,
1898 #[cfg(not(any(test, feature = "test-support")))]
1899 epoch: Arc<RwLock<()>>,
1900 #[cfg(any(test, feature = "test-support"))]
1901 pub read_inflight: usize,
1902 #[cfg(not(any(test, feature = "test-support")))]
1903 read_inflight: usize,
1904 lsp_inflight: bool,
1905 actor_total_inflight: usize,
1906 writer_inflight: bool,
1907 shared_bind_inflight: bool,
1911 maintenance_commit_inflight: bool,
1912 callgraph_acquisition_inflight: bool,
1914 provider_inflight: bool,
1915 call_ledger_inflight: bool,
1916 mutating_inflight: Option<RunningMutatingJob>,
1917 reader_admissions_while_promoted_writer_waited: u64,
1918 deficit: isize,
1919 interactive: ClassQueues<C>,
1920 maintenance: ClassQueues<C>,
1921 fatal: bool,
1922 #[cfg(any(test, feature = "test-support"))]
1923 pub waiting_writers: Arc<AtomicUsize>,
1927 #[cfg(not(any(test, feature = "test-support")))]
1928 waiting_writers: Arc<AtomicUsize>,
1932 #[cfg(any(test, feature = "test-support"))]
1933 pub detached_writers: Arc<AtomicUsize>,
1937 #[cfg(not(any(test, feature = "test-support")))]
1938 detached_writers: Arc<AtomicUsize>,
1942}
1943}
1944
1945impl<C: ExecutorContext> ActorState<C> {
1946 #[rustfmt::skip]
1947 test_support_visibility! {
1948 fn new(ctx: Arc<C>) -> Self {
1949 Self {
1950 ctx,
1951 epoch: Arc::new(RwLock::new(())),
1952 read_inflight: 0,
1953 lsp_inflight: false,
1954 actor_total_inflight: 0,
1955 writer_inflight: false,
1956 shared_bind_inflight: false,
1957 maintenance_commit_inflight: false,
1958 callgraph_acquisition_inflight: false,
1959 provider_inflight: false,
1960 call_ledger_inflight: false,
1961 mutating_inflight: None,
1962 reader_admissions_while_promoted_writer_waited: 0,
1963 deficit: 0,
1964 interactive: ClassQueues::<C>::new(),
1965 maintenance: ClassQueues::<C>::new(),
1966 fatal: false,
1967 waiting_writers: Arc::new(AtomicUsize::new(0)),
1968 detached_writers: Arc::new(AtomicUsize::new(0)),
1969 }
1970 }
1971 }
1972
1973 fn sync_waiting_writers(&self) {
1974 self.waiting_writers
1975 .store(self.interactive.mutating.len(), Ordering::Release);
1976 }
1977
1978 #[rustfmt::skip]
1979 test_support_visibility! {
1980
1981 fn push_job(&mut self, job_class: JobClass, lane: Lane, job: QueuedJob<C>) {
1982 self.class_queues_mut(job_class).push_job(lane, job);
1983 self.sync_waiting_writers();
1984 }
1985 }
1986
1987 #[rustfmt::skip]
1988 test_support_visibility! {
1989
1990 fn has_queued_jobs(&self) -> bool {
1991 self.interactive.has_queued_jobs() || self.maintenance.has_queued_jobs()
1992 }
1993 }
1994
1995 fn is_idle(&self) -> bool {
1996 self.actor_total_inflight == 0 && !self.has_queued_jobs()
1997 }
1998
1999 fn has_queued_jobs_for(&self, job_class: JobClass) -> bool {
2000 if job_class == JobClass::Interactive {
2001 self.interactive
2003 .order
2004 .iter()
2005 .any(|lane| !matches!(lane, Lane::ProviderMetadata | Lane::CallLedger))
2006 } else {
2007 self.class_queues(job_class).has_queued_jobs()
2008 }
2009 }
2010
2011 fn front_lane(&self, job_class: JobClass) -> Option<Lane> {
2012 self.class_queues(job_class).front_lane()
2013 }
2014
2015 fn pop_front_job(&mut self, job_class: JobClass, lane: Lane) -> Option<QueuedJob<C>> {
2016 let job = self.class_queues_mut(job_class).pop_front_job(lane);
2017 self.sync_waiting_writers();
2018 job
2019 }
2020
2021 fn pop_first_bind_job(&mut self) -> Option<QueuedJob<C>> {
2022 let job = self.interactive.remove_first_bind_job();
2023 self.sync_waiting_writers();
2024 job
2025 }
2026
2027 #[rustfmt::skip]
2028 test_support_visibility! {
2029
2030 fn higher_priority_writer_barrier_blocks(&self, job_class: JobClass) -> bool {
2031 matches!(job_class, JobClass::Maintenance)
2035 && !self.interactive.queue(Lane::Mutating).is_empty()
2036 }
2037 }
2038
2039 #[rustfmt::skip]
2040 test_support_visibility! {
2041
2042 fn class_queues(&self, job_class: JobClass) -> &ClassQueues<C> {
2043 match job_class {
2044 JobClass::Interactive => &self.interactive,
2045 JobClass::Maintenance => &self.maintenance,
2046 }
2047 }
2048 }
2049
2050 #[rustfmt::skip]
2051 test_support_visibility! {
2052
2053 fn class_queues_mut(&mut self, job_class: JobClass) -> &mut ClassQueues<C> {
2054 match job_class {
2055 JobClass::Interactive => &mut self.interactive,
2056 JobClass::Maintenance => &mut self.maintenance,
2057 }
2058 }
2059 }
2060
2061 fn fail_queued_jobs(&mut self) {
2062 self.interactive.fail_queued_jobs();
2063 self.maintenance.fail_queued_jobs();
2064 self.sync_waiting_writers();
2065 }
2066
2067 fn cancel_queued_root_work(&mut self) -> usize {
2068 self.maintenance.cancel_queued_jobs() + self.interactive.cancel_queued_provider_jobs()
2069 }
2070
2071 #[rustfmt::skip]
2072 test_support_visibility! {
2073
2074 fn has_queued_mutating_job(&self, request_id: &str) -> bool {
2075 self.interactive.has_queued_mutating_job(request_id)
2076 || self.maintenance.has_queued_mutating_job(request_id)
2077 }
2078 }
2079
2080 #[rustfmt::skip]
2081 test_support_visibility! {
2082
2083 fn remove_queued_cancellable(&mut self, token: &JobCancellation) -> Option<QueuedJob<C>> {
2084 let removed = self
2085 .interactive
2086 .remove_cancellable(token)
2087 .or_else(|| self.maintenance.remove_cancellable(token));
2088 self.sync_waiting_writers();
2089 removed
2090 }
2091 }
2092
2093 fn oldest_queued_writer_at(&self) -> Option<Instant> {
2094 [
2095 self.interactive.queue(Lane::Mutating).front(),
2096 self.maintenance.queue(Lane::Mutating).front(),
2097 ]
2098 .into_iter()
2099 .flatten()
2100 .map(|job| job.queued_at)
2101 .min()
2102 }
2103
2104 fn pending_configure_count(&self) -> usize {
2105 usize::from(
2106 self.mutating_inflight
2107 .as_ref()
2108 .is_some_and(|job| is_configure_request(&job.request_id)),
2109 ) + self.interactive.queued_configure_count()
2110 + self.maintenance.queued_configure_count()
2111 }
2112}
2113
2114#[rustfmt::skip]
2115test_support_visibility! {
2116struct ClassQueues<C: ExecutorContext> {
2117 order: VecDeque<Lane>,
2118 pure_reads: VecDeque<QueuedJob<C>>,
2119 lsp_status: VecDeque<QueuedJob<C>>,
2120 heavy_init: VecDeque<QueuedJob<C>>,
2121 mutating: VecDeque<QueuedJob<C>>,
2122 maintenance_commit: VecDeque<QueuedJob<C>>,
2123 provider_metadata: VecDeque<QueuedJob<C>>,
2124 call_ledger: VecDeque<QueuedJob<C>>,
2125}
2126}
2127
2128impl<C: ExecutorContext> ClassQueues<C> {
2129 fn new() -> Self {
2130 Self {
2131 order: VecDeque::new(),
2132 pure_reads: VecDeque::new(),
2133 lsp_status: VecDeque::new(),
2134 heavy_init: VecDeque::new(),
2135 mutating: VecDeque::new(),
2136 maintenance_commit: VecDeque::new(),
2137 provider_metadata: VecDeque::new(),
2138 call_ledger: VecDeque::new(),
2139 }
2140 }
2141
2142 fn push_job(&mut self, lane: Lane, job: QueuedJob<C>) {
2143 self.order.push_back(lane);
2144 self.queue_mut(lane).push_back(job);
2145 }
2146
2147 fn push_front_job(&mut self, lane: Lane, job: QueuedJob<C>) {
2151 self.order.push_front(lane);
2152 self.queue_mut(lane).push_front(job);
2153 }
2154
2155 fn first_bind_job(&self) -> Option<&QueuedJob<C>> {
2157 self.mutating
2158 .iter()
2159 .find(|job| is_configure_request(&job.request_id))
2160 }
2161
2162 fn first_bind_is_forced_exclusive(&self) -> bool {
2163 self.first_bind_job().is_some_and(|job| job.force_exclusive)
2164 }
2165
2166 #[rustfmt::skip]
2167 test_support_visibility! {
2168
2169 fn has_queued_jobs(&self) -> bool {
2170 !self.order.is_empty()
2171 }
2172 }
2173
2174 #[rustfmt::skip]
2175 test_support_visibility! {
2176
2177 fn front_lane(&self) -> Option<Lane> {
2178 self.order.front().copied()
2179 }
2180 }
2181
2182 #[rustfmt::skip]
2183 test_support_visibility! {
2184
2185 fn next_interactive_lane(
2200 &self,
2201 now: Instant,
2202 newest_reader_started_at: Option<Instant>,
2203 ) -> Option<Lane> {
2204 let stuck_readers_started_by = newest_reader_started_at
2205 .filter(|started| now.saturating_duration_since(*started) >= READER_STUCK_CENSUS_AGE);
2206 let starved_writer = self.mutating.iter().any(|job| {
2207 let promotion_age = if is_configure_request(&job.request_id) {
2208 BIND_PROMOTION_AGE
2209 } else {
2210 INTERACTIVE_WRITER_PROMOTION_AGE
2211 };
2212 let waits_only_on_stuck_readers =
2213 stuck_readers_started_by.is_some_and(|newest| newest <= job.queued_at);
2214 now.saturating_duration_since(job.queued_at) >= promotion_age
2215 && !waits_only_on_stuck_readers
2216 });
2217 if starved_writer {
2218 return Some(Lane::Mutating);
2221 }
2222 if !self.pure_reads.is_empty() {
2223 return Some(Lane::PureRead);
2224 }
2225 self.order.iter().copied().find(|lane| {
2226 !matches!(
2227 lane,
2228 Lane::PureRead | Lane::ProviderMetadata | Lane::CallLedger
2229 )
2230 })
2231 }
2232 }
2233
2234 #[rustfmt::skip]
2235 test_support_visibility! {
2236
2237 fn pop_front_job(&mut self, lane: Lane) -> Option<QueuedJob<C>> {
2238 let position = self.order.iter().position(|queued| *queued == lane)?;
2242 self.order.remove(position);
2243 self.queue_mut(lane).pop_front()
2244 }
2245 }
2246
2247 fn queued_count(&self) -> usize {
2248 self.order.len()
2249 }
2250
2251 fn has_maintenance_coalesce_key(&self, key: MaintenanceCoalesceKey) -> bool {
2252 ALL_LANES.into_iter().any(|lane| {
2253 self.queue(lane)
2254 .iter()
2255 .any(|job| job.maintenance_coalesce_key == Some(key))
2256 })
2257 }
2258
2259 fn remove_duplicate_maintenance_jobs(&mut self) -> Vec<QueuedJob<C>> {
2261 let mut seen = HashSet::new();
2262 let mut lane_positions = [0usize; ALL_LANES.len()];
2263 let mut duplicates = Vec::new();
2264
2265 for (order_position, lane) in self.order.iter().copied().enumerate() {
2266 let lane_index = lane_index(lane);
2267 let queue_position = lane_positions[lane_index];
2268 lane_positions[lane_index] += 1;
2269 let Some(key) = self
2270 .queue(lane)
2271 .get(queue_position)
2272 .and_then(|job| job.maintenance_coalesce_key)
2273 else {
2274 continue;
2275 };
2276 if !seen.insert(key) {
2277 duplicates.push((order_position, lane, queue_position));
2278 }
2279 }
2280
2281 let mut removed = Vec::with_capacity(duplicates.len());
2282 for (order_position, lane, queue_position) in duplicates.into_iter().rev() {
2283 self.order.remove(order_position);
2284 if let Some(job) = self.queue_mut(lane).remove(queue_position) {
2285 removed.push(job);
2286 }
2287 }
2288 removed
2289 }
2290
2291 fn oldest_queued_at(&self) -> Option<Instant> {
2292 self.front_lane()
2293 .and_then(|lane| self.queue(lane).front().map(|job| job.queued_at))
2294 }
2295
2296 fn fail_queued_jobs(&mut self) {
2297 self.order.clear();
2298 fail_queued_job_queue(&mut self.pure_reads);
2299 fail_queued_job_queue(&mut self.lsp_status);
2300 fail_queued_job_queue(&mut self.heavy_init);
2301 fail_queued_job_queue(&mut self.mutating);
2302 fail_queued_job_queue(&mut self.maintenance_commit);
2303 fail_queued_job_queue(&mut self.provider_metadata);
2304 fail_queued_job_queue(&mut self.call_ledger);
2305 }
2306
2307 fn cancel_queued_jobs(&mut self) -> usize {
2308 self.order.clear();
2309 cancel_queued_job_queue(&mut self.pure_reads)
2310 + cancel_queued_job_queue(&mut self.lsp_status)
2311 + cancel_queued_job_queue(&mut self.heavy_init)
2312 + cancel_queued_job_queue(&mut self.mutating)
2313 + cancel_queued_job_queue(&mut self.maintenance_commit)
2314 + cancel_queued_job_queue(&mut self.provider_metadata)
2315 + cancel_queued_job_queue(&mut self.call_ledger)
2316 }
2317
2318 fn cancel_queued_provider_jobs(&mut self) -> usize {
2319 self.order.retain(|lane| *lane != Lane::ProviderMetadata);
2320 let cancelled = self.provider_metadata.len();
2321 for queued in self.provider_metadata.drain(..) {
2322 if let Some(token) = &queued.cancellation {
2323 let _ = token.try_cancel_before_running();
2324 }
2325 queued.completion.send(Response::error(
2326 queued.request_id,
2327 "request_cancelled",
2328 "provider metadata root has no bound routes",
2329 ));
2330 }
2331 cancelled
2332 }
2333
2334 fn has_queued_mutating_job(&self, request_id: &str) -> bool {
2335 self.mutating.iter().any(|job| job.request_id == request_id)
2336 }
2337
2338 fn remove_first_bind_job(&mut self) -> Option<QueuedJob<C>> {
2342 let position = self
2343 .mutating
2344 .iter()
2345 .position(|job| is_configure_request(&job.request_id))?;
2346 let removed = self.mutating.remove(position);
2347 let mut occurrence = 0usize;
2348 if let Some(order_position) = self.order.iter().position(|entry| {
2349 if *entry != Lane::Mutating {
2350 return false;
2351 }
2352 let matched = occurrence == position;
2353 occurrence += 1;
2354 matched
2355 }) {
2356 self.order.remove(order_position);
2357 }
2358 removed
2359 }
2360
2361 fn remove_cancellable(&mut self, token: &JobCancellation) -> Option<QueuedJob<C>> {
2370 for lane in ALL_LANES {
2371 let queue = self.queue_mut(lane);
2372 let position = queue.iter().position(|queued| {
2373 queued
2374 .cancellation
2375 .as_ref()
2376 .is_some_and(|candidate| candidate.same_token(token))
2377 });
2378 if let Some(position) = position {
2379 let removed = queue.remove(position);
2380 let mut occurrence = 0usize;
2381 if let Some(order_position) = self.order.iter().position(|entry| {
2382 if *entry != lane {
2383 return false;
2384 }
2385 let matched = occurrence == position;
2386 occurrence += 1;
2387 matched
2388 }) {
2389 self.order.remove(order_position);
2390 }
2391 return removed;
2392 }
2393 }
2394 None
2395 }
2396
2397 fn queued_configure_count(&self) -> usize {
2398 self.mutating
2399 .iter()
2400 .filter(|job| is_configure_request(&job.request_id))
2401 .count()
2402 }
2403
2404 fn oldest_queued_bind_at(&self) -> Option<Instant> {
2406 self.mutating
2407 .iter()
2408 .filter(|job| is_configure_request(&job.request_id))
2409 .map(|job| job.queued_at)
2410 .min()
2411 }
2412
2413 fn queue(&self, lane: Lane) -> &VecDeque<QueuedJob<C>> {
2414 match lane {
2415 Lane::PureRead => &self.pure_reads,
2416 Lane::SerialLspStatus => &self.lsp_status,
2417 Lane::HeavyInit => &self.heavy_init,
2418 Lane::Mutating => &self.mutating,
2419 Lane::MaintenanceCommit => &self.maintenance_commit,
2420 Lane::ProviderMetadata => &self.provider_metadata,
2421 Lane::CallLedger => &self.call_ledger,
2422 }
2423 }
2424
2425 fn queue_mut(&mut self, lane: Lane) -> &mut VecDeque<QueuedJob<C>> {
2426 match lane {
2427 Lane::PureRead => &mut self.pure_reads,
2428 Lane::SerialLspStatus => &mut self.lsp_status,
2429 Lane::HeavyInit => &mut self.heavy_init,
2430 Lane::Mutating => &mut self.mutating,
2431 Lane::MaintenanceCommit => &mut self.maintenance_commit,
2432 Lane::ProviderMetadata => &mut self.provider_metadata,
2433 Lane::CallLedger => &mut self.call_ledger,
2434 }
2435 }
2436}
2437
2438#[rustfmt::skip]
2439test_support_visibility! {
2440struct QueuedJob<C: ExecutorContext> {
2441 #[cfg(any(test, feature = "test-support"))]
2442 pub job: ExecutorJob<C>,
2443 #[cfg(not(any(test, feature = "test-support")))]
2444 job: ExecutorJob<C>,
2445 #[cfg(any(test, feature = "test-support"))]
2446 pub completion: CompletionSender,
2447 #[cfg(not(any(test, feature = "test-support")))]
2448 completion: CompletionSender,
2449 #[cfg(any(test, feature = "test-support"))]
2450 pub request_id: String,
2451 #[cfg(not(any(test, feature = "test-support")))]
2452 request_id: String,
2453 #[cfg(any(test, feature = "test-support"))]
2454 pub command: String,
2455 #[cfg(not(any(test, feature = "test-support")))]
2456 command: String,
2457 #[cfg(any(test, feature = "test-support"))]
2458 pub queued_at: Instant,
2459 #[cfg(not(any(test, feature = "test-support")))]
2460 queued_at: Instant,
2461 #[cfg(any(test, feature = "test-support"))]
2462 pub cancellation: Option<JobCancellation>,
2463 #[cfg(not(any(test, feature = "test-support")))]
2464 cancellation: Option<JobCancellation>,
2465 #[cfg(any(test, feature = "test-support"))]
2466 pub maintenance_coalesce_key: Option<MaintenanceCoalesceKey>,
2467 #[cfg(not(any(test, feature = "test-support")))]
2468 maintenance_coalesce_key: Option<MaintenanceCoalesceKey>,
2469 #[cfg(any(test, feature = "test-support"))]
2470 pub rerun: Option<RepeatableJob<C>>,
2473 #[cfg(not(any(test, feature = "test-support")))]
2474 rerun: Option<RepeatableJob<C>>,
2477 #[cfg(any(test, feature = "test-support"))]
2478 pub force_exclusive: bool,
2481 #[cfg(not(any(test, feature = "test-support")))]
2482 force_exclusive: bool,
2485 #[cfg(any(test, feature = "test-support"))]
2486 pub not_before: Option<Instant>,
2489 #[cfg(not(any(test, feature = "test-support")))]
2490 not_before: Option<Instant>,
2493 #[cfg(any(test, feature = "test-support"))]
2494 pub exclusive_attempts: u32,
2496 #[cfg(not(any(test, feature = "test-support")))]
2497 exclusive_attempts: u32,
2499 #[cfg(any(test, feature = "test-support"))]
2500 pub provider_generation: Option<u64>,
2503 #[cfg(not(any(test, feature = "test-support")))]
2504 provider_generation: Option<u64>,
2507}
2508}
2509
2510fn lane_index(lane: Lane) -> usize {
2511 match lane {
2512 Lane::PureRead => 0,
2513 Lane::SerialLspStatus => 1,
2514 Lane::HeavyInit => 2,
2515 Lane::Mutating => 3,
2516 Lane::MaintenanceCommit => 4,
2517 Lane::ProviderMetadata => 5,
2518 Lane::CallLedger => 6,
2519 }
2520}
2521
2522fn fail_queued_job_queue<C: ExecutorContext>(queue: &mut VecDeque<QueuedJob<C>>) {
2523 for queued in queue.drain(..) {
2524 queued
2525 .completion
2526 .send(actor_fatal_response(queued.request_id));
2527 }
2528}
2529
2530fn cancel_queued_job_queue<C: ExecutorContext>(queue: &mut VecDeque<QueuedJob<C>>) -> usize {
2531 let cancelled = queue.len();
2532 for queued in queue.drain(..) {
2533 queued.completion.send(Response::error(
2534 queued.request_id,
2535 "maintenance_cancelled",
2536 "maintenance cancelled because the actor has no bound routes",
2537 ));
2538 }
2539 cancelled
2540}
2541
2542fn job_command(job_class: JobClass, lane: Lane) -> String {
2543 format!("executor::{job_class:?}::{lane:?}")
2544}
2545
2546fn maintenance_allowed_while_unbound(command: &str) -> bool {
2547 matches!(command, "unbound-teardown-persist" | "lsp-event-drain")
2548}
2549
2550fn maintenance_cancelled_response(
2551 request_id: impl Into<String>,
2552 message: impl Into<String>,
2553) -> Response {
2554 Response::error(request_id, "maintenance_cancelled", message)
2555}
2556
2557fn maintenance_backpressure_response(request_id: impl Into<String>) -> Response {
2558 Response::error_with_data(
2559 request_id,
2560 "maintenance_backpressure",
2561 format!("maintenance queue reached its per-actor capacity of {MAINTENANCE_QUEUE_CAP} jobs"),
2562 serde_json::json!({
2563 "retryable": true,
2564 "queue_cap": MAINTENANCE_QUEUE_CAP,
2565 }),
2566 )
2567}
2568
2569fn actor_fatal_response(request_id: impl Into<String>) -> Response {
2570 Response::error(
2571 request_id,
2572 "actor_fatal",
2573 "executor actor is fatal after a mutating job panic",
2574 )
2575}
2576
2577fn panic_payload_message(payload: &(dyn std::any::Any + Send)) -> String {
2578 if let Some(message) = payload.downcast_ref::<&'static str>() {
2579 (*message).to_string()
2580 } else if let Some(message) = payload.downcast_ref::<String>() {
2581 message.clone()
2582 } else {
2583 "unknown panic payload".to_string()
2584 }
2585}
2586
2587fn panic_response(
2588 request_id: impl Into<String>,
2589 command: &str,
2590 payload: &(dyn std::any::Any + Send),
2591) -> Response {
2592 let panic_message = panic_payload_message(payload);
2593 Response::error(
2594 request_id,
2595 "actor_fatal",
2596 format!("command '{command}' panicked: {panic_message}"),
2597 )
2598}
2599
2600#[rustfmt::skip]
2601test_support_visibility! {
2602enum CompletionSender {
2603 Sync(Sender<Response>),
2604 Async(oneshot::Sender<Response>),
2605}
2606}
2607
2608impl CompletionSender {
2609 fn send(self, response: Response) {
2610 match self {
2611 Self::Sync(tx) => {
2612 let _ = tx.send(response);
2613 }
2614 Self::Async(tx) => {
2615 let _ = tx.send(response);
2616 }
2617 }
2618 }
2619}
2620
2621#[rustfmt::skip]
2622test_support_visibility! {
2623struct RunJob<C: ExecutorContext> {
2624 root_id: ProjectRootId,
2625 job_class: JobClass,
2626 lane: Lane,
2627 ctx: Arc<C>,
2628 epoch: Arc<RwLock<()>>,
2629 job: ExecutorJob<C>,
2630 completion: Option<CompletionSender>,
2631 #[cfg(any(test, feature = "test-support"))]
2632 pub request_id: String,
2633 #[cfg(not(any(test, feature = "test-support")))]
2634 request_id: String,
2635 command: String,
2636 heavy_permit: Option<HeavyPermit>,
2637 cancellation: Option<JobCancellation>,
2638 execution_started: Arc<AtomicBool>,
2639 #[cfg(any(test, feature = "test-support"))]
2640 pub completion_guard: Option<JobCompletionGuard<C>>,
2641 #[cfg(not(any(test, feature = "test-support")))]
2642 completion_guard: Option<JobCompletionGuard<C>>,
2643 waiting_writers: Arc<AtomicUsize>,
2646 detached_writers: Arc<AtomicUsize>,
2649 shared_bind_gate: bool,
2652 rerun: Option<RepeatableJob<C>>,
2654 queued_at: Instant,
2657 exclusive_attempts: u32,
2658 provider_generation: Option<u64>,
2659}
2660}
2661
2662struct JobCompletionOwnership;
2663
2664#[rustfmt::skip]
2665test_support_visibility! {
2666#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2667enum JobCompletionOutcome {
2668 Completed,
2669 Panicked,
2670 Abandoned,
2671}
2672}
2673
2674#[rustfmt::skip]
2675test_support_visibility! {
2676struct CompletionEvent<C: ExecutorContext> {
2677 job_id: u64,
2678 heavy_permit: Option<HeavyPermit>,
2679 outcome: JobCompletionOutcome,
2680 ownership: Arc<JobCompletionOwnership>,
2681 requeue: Option<QueuedJob<C>>,
2685}
2686}
2687
2688#[rustfmt::skip]
2689test_support_visibility! {
2690struct JobCompletionGuard<C: ExecutorContext> {
2691 event_tx: Sender<SchedulerEvent<C>>,
2692 event: Option<CompletionEvent<C>>,
2693}
2694}
2695
2696impl<C: ExecutorContext> JobCompletionGuard<C> {
2697 fn new(event_tx: Sender<SchedulerEvent<C>>, event: CompletionEvent<C>) -> Self {
2698 Self {
2699 event_tx,
2700 event: Some(event),
2701 }
2702 }
2703
2704 #[rustfmt::skip]
2705 test_support_visibility! {
2706
2707 fn set_outcome(&mut self, outcome: JobCompletionOutcome) {
2708 if let Some(event) = self.event.as_mut() {
2709 event.outcome = outcome;
2710 }
2711 }
2712 }
2713
2714 fn set_requeue(&mut self, job: QueuedJob<C>) {
2715 if let Some(event) = self.event.as_mut() {
2716 event.requeue = Some(job);
2717 }
2718 }
2719}
2720
2721impl<C: ExecutorContext> Drop for JobCompletionGuard<C> {
2722 fn drop(&mut self) {
2723 let Some(mut event) = self.event.take() else {
2724 return;
2725 };
2726 if std::thread::panicking() {
2727 event.outcome = JobCompletionOutcome::Panicked;
2728 }
2729 let _ = self.event_tx.send(SchedulerEvent::<C>::Completed(event));
2730 }
2731}
2732
2733#[rustfmt::skip]
2734test_support_visibility! {
2735enum SchedulerEvent<C: ExecutorContext> {
2736 Wake,
2737 Completed(CompletionEvent<C>),
2738 Shutdown,
2739}
2740}
2741
2742fn scheduler_loop<C: ExecutorContext>(
2743 state: Arc<TrackedMutex<SchedulerState<C>>>,
2744 heavy: Arc<HeavySemaphore>,
2745 run_tx: Sender<RunJob<C>>,
2746 event_tx: Sender<SchedulerEvent<C>>,
2747 event_rx: Receiver<SchedulerEvent<C>>,
2748 nonrunnable_dispatches: Arc<AtomicUsize>,
2749 completed_interactive: Arc<AtomicU64>,
2750 completed_maintenance: Arc<AtomicU64>,
2751 dispatch_liveness: Arc<DispatchLivenessAtomics>,
2752 loop_liveness: Arc<DispatchLoopLiveness<C>>,
2753) {
2754 let mut next_retry_at: Option<Instant> = None;
2755 loop {
2756 let event = if loop_liveness.wait_for_event(next_retry_at) {
2759 match event_rx.try_recv() {
2762 Ok(event) => event,
2763 Err(crossbeam_channel::TryRecvError::Empty) => {
2764 loop_liveness.end_event();
2765 continue;
2766 }
2767 Err(crossbeam_channel::TryRecvError::Disconnected) => {
2768 loop_liveness.end_event();
2769 break;
2770 }
2771 }
2772 } else {
2773 SchedulerEvent::<C>::Wake
2774 };
2775 let shutdown;
2776 {
2777 let mut state = state.lock();
2778 shutdown = process_scheduler_event_batch(
2779 event,
2780 &event_rx,
2781 &mut state,
2782 &completed_interactive,
2783 &completed_maintenance,
2784 );
2785
2786 if !shutdown {
2787 dispatch_runnable(
2788 &mut state,
2789 &heavy,
2790 &run_tx,
2791 &event_tx,
2792 &nonrunnable_dispatches,
2793 );
2794 }
2795 dispatch_liveness.record(&state.dispatch_liveness_snapshot());
2796 next_retry_at = state.next_bind_retry_at();
2797 }
2798 loop_liveness.end_event();
2799
2800 if shutdown {
2801 break;
2802 }
2803 }
2804}
2805
2806#[rustfmt::skip]
2807test_support_visibility! {
2808
2809fn process_scheduler_event_batch<C: ExecutorContext>(
2810 first: SchedulerEvent<C>,
2811 event_rx: &Receiver<SchedulerEvent<C>>,
2812 state: &mut SchedulerState<C>,
2813 completed_interactive: &AtomicU64,
2814 completed_maintenance: &AtomicU64,
2815) -> bool {
2816 let mut event = Some(first);
2817 for _ in 0..SCHEDULER_EVENT_BATCH_CAP {
2818 let Some(current) = event.take().or_else(|| event_rx.try_recv().ok()) else {
2819 break;
2820 };
2821 if process_scheduler_event(current, state, completed_interactive, completed_maintenance) {
2822 return true;
2823 }
2824 }
2825 false
2826}
2827}
2828
2829fn note_completed_class(
2830 job_class: JobClass,
2831 completed_interactive: &AtomicU64,
2832 completed_maintenance: &AtomicU64,
2833) {
2834 match job_class {
2835 JobClass::Interactive => {
2836 completed_interactive.fetch_add(1, Ordering::Relaxed);
2837 }
2838 JobClass::Maintenance => {
2839 completed_maintenance.fetch_add(1, Ordering::Relaxed);
2840 }
2841 }
2842}
2843
2844fn process_scheduler_event<C: ExecutorContext>(
2845 event: SchedulerEvent<C>,
2846 state: &mut SchedulerState<C>,
2847 completed_interactive: &AtomicU64,
2848 completed_maintenance: &AtomicU64,
2849) -> bool {
2850 match event {
2851 SchedulerEvent::<C>::Wake => false,
2852 SchedulerEvent::<C>::Completed(event) => {
2853 if let Some(job_class) = complete_job(state, event) {
2854 note_completed_class(job_class, completed_interactive, completed_maintenance);
2855 }
2856 false
2857 }
2858 SchedulerEvent::<C>::Shutdown => true,
2859 }
2860}
2861
2862#[rustfmt::skip]
2863test_support_visibility! {
2864
2865fn complete_job<C: ExecutorContext>(
2866 state: &mut SchedulerState<C>,
2867 event: CompletionEvent<C>,
2868) -> Option<JobClass> {
2869 let CompletionEvent::<C> {
2870 job_id,
2871 heavy_permit,
2872 outcome,
2873 ownership,
2874 requeue,
2875 } = event;
2876 let Some(running) = state.running_jobs.remove(&job_id) else {
2877 log::error!("executor completion: unknown job_id={job_id} outcome={outcome:?}");
2878 return None;
2879 };
2880 debug_assert!(running
2881 .completion_ownership
2882 .upgrade()
2883 .is_some_and(|current| Arc::ptr_eq(¤t, &ownership)));
2884
2885 let RunningJob {
2886 root_id,
2887 request_id,
2888 job_class,
2889 lane,
2890 ..
2891 } = running;
2892 log::debug!(
2893 "executor completion: job_id={job_id} class={job_class:?} lane={lane:?} outcome={outcome:?} request_id={request_id} root={}",
2894 root_id.as_path().display()
2895 );
2896
2897 match job_class {
2898 JobClass::Interactive => {
2899 debug_assert!(state.interactive_inflight > 0);
2900 state.interactive_inflight = state.interactive_inflight.saturating_sub(1);
2901 }
2902 JobClass::Maintenance => {
2903 debug_assert!(state.maintenance_inflight > 0);
2904 state.maintenance_inflight = state.maintenance_inflight.saturating_sub(1);
2905 }
2906 }
2907
2908 if lane == Lane::ProviderMetadata {
2909 state.provider_inflight = state.provider_inflight.saturating_sub(1);
2910 }
2911 if is_bind_job(job_class, lane, &request_id) {
2912 state.binds_inflight = state.binds_inflight.saturating_sub(1);
2913 }
2914 if let Some(actor) = state.actors.get_mut(&root_id) {
2915 actor.actor_total_inflight = actor.actor_total_inflight.saturating_sub(1);
2916 match lane {
2917 Lane::PureRead => {
2918 actor.read_inflight = actor.read_inflight.saturating_sub(1);
2919 }
2920 Lane::SerialLspStatus => {
2921 actor.lsp_inflight = false;
2922 }
2923 Lane::HeavyInit => {
2924 if is_callgraph_acquisition(job_class, lane, &request_id) {
2925 actor.callgraph_acquisition_inflight = false;
2926 }
2927 }
2928 Lane::Mutating => {
2929 actor.writer_inflight = false;
2930 actor.shared_bind_inflight = false;
2931 actor.mutating_inflight = None;
2932 }
2933 Lane::MaintenanceCommit => {
2934 actor.maintenance_commit_inflight = false;
2935 }
2936 Lane::ProviderMetadata => actor.provider_inflight = false,
2937 Lane::CallLedger => actor.call_ledger_inflight = false,
2938 }
2939
2940 if outcome == JobCompletionOutcome::Panicked && lane == Lane::Mutating {
2941 actor.fatal = true;
2942 actor.fail_queued_jobs();
2943 }
2944 }
2945
2946 if let Some(queued) = requeue {
2947 match state.actors.get_mut(&root_id) {
2948 _ if queued
2954 .cancellation
2955 .as_ref()
2956 .is_some_and(JobCancellation::cancel_already_requested) =>
2957 {
2958 queued.completion.send(Response::error(
2959 queued.request_id,
2960 "request_cancelled",
2961 "request cancelled before execution",
2962 ));
2963 }
2964 Some(actor) if !actor.fatal => {
2965 actor.ctx.begin_configure_ack_phase("requeued_exclusive");
2968 let has_retry_time = queued.not_before.is_some();
2969 actor.interactive.push_front_job(Lane::Mutating, queued);
2970 actor.sync_waiting_writers();
2971 state.bind_retry_pending |= has_retry_time;
2972 }
2973 Some(_) => queued
2974 .completion
2975 .send(actor_fatal_response(queued.request_id)),
2976 None => queued.completion.send(Response::error(
2977 queued.request_id,
2978 "actor_not_registered",
2979 "executor actor is not registered",
2980 )),
2981 }
2982 }
2983
2984 drop(heavy_permit);
2985 drop(ownership);
2986 state.idle_workers += 1;
2987 state.assert_running_invariants();
2988 Some(job_class)
2989}
2990}
2991
2992#[rustfmt::skip]
2993test_support_visibility! {
2994
2995fn dispatch_runnable<C: ExecutorContext>(
2996 state: &mut SchedulerState<C>,
2997 heavy: &Arc<HeavySemaphore>,
2998 run_tx: &Sender<RunJob<C>>,
2999 event_tx: &Sender<SchedulerEvent<C>>,
3000 nonrunnable_dispatches: &AtomicUsize,
3001) {
3002 while state.idle_workers > 0 && !state.actor_order.is_empty() {
3003 let mut made_progress = false;
3004 let mut dispatch_failed = false;
3005
3006 made_progress |= dispatch_queued_binds(
3010 state,
3011 heavy,
3012 run_tx,
3013 event_tx,
3014 nonrunnable_dispatches,
3015 &mut dispatch_failed,
3016 );
3017 if dispatch_failed || state.idle_workers == 0 {
3018 return;
3019 }
3020
3021 made_progress |= dispatch_provider_metadata(
3022 state,
3023 heavy,
3024 run_tx,
3025 event_tx,
3026 nonrunnable_dispatches,
3027 &mut dispatch_failed,
3028 );
3029 if dispatch_failed || state.idle_workers == 0 {
3030 return;
3031 }
3032
3033 made_progress |= dispatch_call_ledger(
3034 state,
3035 heavy,
3036 run_tx,
3037 event_tx,
3038 nonrunnable_dispatches,
3039 &mut dispatch_failed,
3040 );
3041 if dispatch_failed || state.idle_workers == 0 {
3042 return;
3043 }
3044
3045 made_progress |= dispatch_runnable_class(
3046 state,
3047 JobClass::Interactive,
3048 heavy,
3049 run_tx,
3050 event_tx,
3051 nonrunnable_dispatches,
3052 &mut dispatch_failed,
3053 );
3054 if dispatch_failed || state.idle_workers == 0 {
3055 return;
3056 }
3057
3058 if can_dispatch_class(state, JobClass::Maintenance) {
3059 made_progress |= dispatch_runnable_class(
3060 state,
3061 JobClass::Maintenance,
3062 heavy,
3063 run_tx,
3064 event_tx,
3065 nonrunnable_dispatches,
3066 &mut dispatch_failed,
3067 );
3068 if dispatch_failed {
3069 return;
3070 }
3071 }
3072
3073 if !made_progress {
3074 break;
3075 }
3076 }
3077}
3078}
3079
3080fn dispatch_runnable_class<C: ExecutorContext>(
3081 state: &mut SchedulerState<C>,
3082 job_class: JobClass,
3083 heavy: &Arc<HeavySemaphore>,
3084 run_tx: &Sender<RunJob<C>>,
3085 event_tx: &Sender<SchedulerEvent<C>>,
3086 nonrunnable_dispatches: &AtomicUsize,
3087 dispatch_failed: &mut bool,
3088) -> bool {
3089 if !can_dispatch_class(state, job_class) || state.actor_order.is_empty() {
3090 return false;
3091 }
3092
3093 let actor_count = state.actor_order.len();
3094 let mut made_progress = false;
3095
3096 for _ in 0..actor_count {
3097 if !can_dispatch_class(state, job_class) || state.actor_order.is_empty() {
3098 break;
3099 }
3100
3101 if state.cursor >= state.actor_order.len() {
3102 state.cursor = 0;
3103 }
3104 let root_id = state.actor_order[state.cursor].clone();
3105 state.cursor = (state.cursor + 1) % state.actor_order.len();
3106 let newest_reader_started_at = match job_class {
3107 JobClass::Interactive => state.newest_in_flight_reader_started_at(&root_id),
3108 JobClass::Maintenance => None,
3109 };
3110
3111 let run_job = {
3112 let Some(actor) = state.actors.get_mut(&root_id) else {
3113 continue;
3114 };
3115
3116 if actor.fatal {
3117 actor.fail_queued_jobs();
3118 actor.deficit = 0;
3119 continue;
3120 }
3121
3122 if !actor.has_queued_jobs() {
3123 actor.deficit = 0;
3124 continue;
3125 }
3126
3127 if !actor.has_queued_jobs_for(job_class) {
3128 continue;
3129 }
3130
3131 actor.deficit =
3132 (actor.deficit + state.config.drr_quantum).min(state.config.deficit_cap);
3133 if actor.deficit < JOB_COST {
3134 continue;
3135 }
3136
3137 try_admit_actor(
3138 &root_id,
3139 actor,
3140 AdmissionPass::Class(job_class),
3141 &state.config,
3142 heavy,
3143 newest_reader_started_at,
3144 )
3145 };
3146
3147 if let Some(run_job) = run_job {
3148 made_progress = true;
3149 if !launch_run_job(state, run_job, run_tx, event_tx, nonrunnable_dispatches) {
3150 *dispatch_failed = true;
3151 return made_progress;
3152 }
3153 }
3154 }
3155
3156 made_progress
3157}
3158
3159fn dispatch_queued_binds<C: ExecutorContext>(
3164 state: &mut SchedulerState<C>,
3165 heavy: &Arc<HeavySemaphore>,
3166 run_tx: &Sender<RunJob<C>>,
3167 event_tx: &Sender<SchedulerEvent<C>>,
3168 nonrunnable_dispatches: &AtomicUsize,
3169 dispatch_failed: &mut bool,
3170) -> bool {
3171 let mut candidates = state
3172 .actors
3173 .iter()
3174 .filter(|(_, actor)| !actor.fatal)
3175 .filter_map(|(root_id, actor)| {
3176 actor
3177 .interactive
3178 .oldest_queued_bind_at()
3179 .map(|queued_at| (queued_at, root_id.clone()))
3180 })
3181 .collect::<Vec<_>>();
3182 if candidates.is_empty() {
3183 return false;
3184 }
3185 candidates.sort_by(|left, right| left.0.cmp(&right.0));
3186
3187 let mut made_progress = false;
3188 for (_, root_id) in candidates {
3189 if state.idle_workers
3190 <= state
3191 .config
3192 .provider_reserve
3193 .saturating_sub(state.provider_inflight)
3194 {
3195 break;
3196 }
3197 let run_job = {
3198 let Some(actor) = state.actors.get_mut(&root_id) else {
3199 continue;
3200 };
3201 try_admit_actor(
3202 &root_id,
3203 actor,
3204 AdmissionPass::Bind,
3205 &state.config,
3206 heavy,
3207 None,
3208 )
3209 };
3210 if let Some(run_job) = run_job {
3211 made_progress = true;
3212 if !launch_run_job(state, run_job, run_tx, event_tx, nonrunnable_dispatches) {
3213 *dispatch_failed = true;
3214 return made_progress;
3215 }
3216 }
3217 }
3218 made_progress
3219}
3220
3221fn dispatch_provider_metadata<C: ExecutorContext>(
3224 state: &mut SchedulerState<C>,
3225 heavy: &Arc<HeavySemaphore>,
3226 run_tx: &Sender<RunJob<C>>,
3227 event_tx: &Sender<SchedulerEvent<C>>,
3228 nonrunnable_dispatches: &AtomicUsize,
3229 dispatch_failed: &mut bool,
3230) -> bool {
3231 let mut made_progress = false;
3232 for _ in 0..state.actor_order.len() {
3233 if state.idle_workers == 0 || state.provider_inflight >= state.config.provider_reserve {
3234 break;
3235 }
3236 state.cursor %= state.actor_order.len();
3237 let root_id = state.actor_order[state.cursor].clone();
3238 state.cursor = (state.cursor + 1) % state.actor_order.len();
3239 let Some(actor) = state.actors.get_mut(&root_id).filter(|actor| !actor.fatal) else {
3240 continue;
3241 };
3242 if let Some(run_job) = try_admit_actor(
3243 &root_id,
3244 actor,
3245 AdmissionPass::ProviderMetadata,
3246 &state.config,
3247 heavy,
3248 None,
3249 ) {
3250 made_progress = true;
3251 if !launch_run_job(state, run_job, run_tx, event_tx, nonrunnable_dispatches) {
3252 *dispatch_failed = true;
3253 break;
3254 }
3255 }
3256 }
3257 made_progress
3258}
3259
3260fn dispatch_call_ledger<C: ExecutorContext>(
3266 state: &mut SchedulerState<C>,
3267 heavy: &Arc<HeavySemaphore>,
3268 run_tx: &Sender<RunJob<C>>,
3269 event_tx: &Sender<SchedulerEvent<C>>,
3270 nonrunnable_dispatches: &AtomicUsize,
3271 dispatch_failed: &mut bool,
3272) -> bool {
3273 let mut made_progress = false;
3274 for _ in 0..state.actor_order.len() {
3275 if !can_dispatch_class(state, JobClass::Interactive) {
3276 break;
3277 }
3278 state.cursor %= state.actor_order.len();
3279 let root_id = state.actor_order[state.cursor].clone();
3280 state.cursor = (state.cursor + 1) % state.actor_order.len();
3281 let Some(actor) = state.actors.get_mut(&root_id).filter(|actor| !actor.fatal) else {
3282 continue;
3283 };
3284 if let Some(run_job) = try_admit_actor(
3285 &root_id,
3286 actor,
3287 AdmissionPass::CallLedger,
3288 &state.config,
3289 heavy,
3290 None,
3291 ) {
3292 made_progress = true;
3293 if !launch_run_job(state, run_job, run_tx, event_tx, nonrunnable_dispatches) {
3294 *dispatch_failed = true;
3295 break;
3296 }
3297 }
3298 }
3299 made_progress
3300}
3301
3302fn launch_run_job<C: ExecutorContext>(
3305 state: &mut SchedulerState<C>,
3306 mut run_job: RunJob<C>,
3307 run_tx: &Sender<RunJob<C>>,
3308 event_tx: &Sender<SchedulerEvent<C>>,
3309 nonrunnable_dispatches: &AtomicUsize,
3310) -> bool {
3311 let job_id = state.next_job_id();
3312 let ownership = Arc::new(JobCompletionOwnership);
3313 run_job.completion_guard = Some(JobCompletionGuard::<C>::new(
3314 event_tx.clone(),
3315 CompletionEvent::<C> {
3316 job_id,
3317 heavy_permit: run_job.heavy_permit.take(),
3318 outcome: JobCompletionOutcome::Abandoned,
3319 ownership: Arc::clone(&ownership),
3320 requeue: None,
3321 },
3322 ));
3323 let replaced = state.running_jobs.insert(
3324 job_id,
3325 RunningJob {
3326 root_id: run_job.root_id.clone(),
3327 request_id: run_job.request_id.clone(),
3328 command: run_job.command.clone(),
3329 job_class: run_job.job_class,
3330 lane: run_job.lane,
3331 started_at: Instant::now(),
3332 execution_started: Arc::clone(&run_job.execution_started),
3333 completion_ownership: Arc::downgrade(&ownership),
3334 occupancy_reported: false,
3335 cancellation: run_job.cancellation.clone(),
3336 },
3337 );
3338 debug_assert!(replaced.is_none());
3339 state.idle_workers -= 1;
3340 match run_job.job_class {
3341 JobClass::Interactive => state.interactive_inflight += 1,
3342 JobClass::Maintenance => state.maintenance_inflight += 1,
3343 }
3344 if run_job.lane == Lane::ProviderMetadata {
3345 state.provider_inflight += 1;
3346 }
3347 if is_bind_job(run_job.job_class, run_job.lane, &run_job.request_id) {
3348 state.binds_inflight += 1;
3349 }
3350 state.assert_running_invariants();
3351 log::debug!(
3352 "executor dispatch: job_id={job_id} class={:?} lane={:?} request_id={} root={}",
3353 run_job.job_class,
3354 run_job.lane,
3355 run_job.request_id,
3356 run_job.root_id.as_path().display()
3357 );
3358 if run_tx.send(run_job).is_err() {
3359 nonrunnable_dispatches.fetch_add(1, Ordering::AcqRel);
3360 return false;
3361 }
3362 true
3363}
3364
3365fn can_dispatch_class<C: ExecutorContext>(state: &SchedulerState<C>, job_class: JobClass) -> bool {
3366 let provider_idle = state
3370 .config
3371 .provider_reserve
3372 .saturating_sub(state.provider_inflight);
3373 let bind_idle = state
3374 .config
3375 .bind_reserve
3376 .saturating_sub(state.binds_inflight);
3377 let general_idle = state.idle_workers.saturating_sub(bind_idle + provider_idle);
3378 if general_idle == 0 {
3379 return false;
3380 }
3381 match job_class {
3382 JobClass::Interactive => true,
3383 JobClass::Maintenance => {
3384 state.maintenance_inflight < state.config.maintenance_cap
3385 && general_idle > state.config.interactive_reserve
3386 }
3387 }
3388}
3389
3390#[rustfmt::skip]
3391test_support_visibility! {
3392#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3394enum AdmissionPass {
3395 Bind,
3399 ProviderMetadata,
3402 CallLedger,
3405 Class(JobClass),
3407}
3408}
3409
3410#[rustfmt::skip]
3411test_support_visibility! {
3412
3413fn try_admit_actor<C: ExecutorContext>(
3414 root_id: &ProjectRootId,
3415 actor: &mut ActorState<C>,
3416 pass: AdmissionPass,
3417 config: &EffectiveConfig,
3418 heavy: &Arc<HeavySemaphore>,
3419 newest_reader_started_at: Option<Instant>,
3420) -> Option<RunJob<C>> {
3421 let bind_pass = pass == AdmissionPass::Bind;
3422 let job_class = match pass {
3423 AdmissionPass::Bind | AdmissionPass::ProviderMetadata | AdmissionPass::CallLedger => {
3424 JobClass::Interactive
3425 }
3426 AdmissionPass::Class(job_class) => job_class,
3427 };
3428 let lane = match pass {
3429 AdmissionPass::ProviderMetadata => actor
3430 .interactive
3431 .provider_metadata
3432 .front()
3433 .map(|_| Lane::ProviderMetadata)?,
3434 AdmissionPass::CallLedger => actor
3435 .interactive
3436 .call_ledger
3437 .front()
3438 .map(|_| Lane::CallLedger)?,
3439 AdmissionPass::Bind => actor
3443 .interactive
3444 .oldest_queued_bind_at()
3445 .map(|_| Lane::Mutating)?,
3446 AdmissionPass::Class(JobClass::Interactive) => actor
3447 .class_queues(JobClass::Interactive)
3448 .next_interactive_lane(Instant::now(), newest_reader_started_at)?,
3449 AdmissionPass::Class(JobClass::Maintenance) => actor.front_lane(job_class)?,
3450 };
3451 let mut heavy_permit = None;
3452 let callgraph_acquisition = actor
3453 .class_queues(job_class)
3454 .queue(lane)
3455 .front()
3456 .is_some_and(|job| is_callgraph_acquisition(job_class, lane, &job.request_id));
3457
3458 let shared_bind_admits_lane = actor.shared_bind_inflight
3462 && matches!(
3463 lane,
3464 Lane::PureRead | Lane::SerialLspStatus | Lane::HeavyInit
3465 );
3466 if !matches!(lane, Lane::ProviderMetadata | Lane::CallLedger)
3467 && ((actor.writer_inflight && !shared_bind_admits_lane)
3468 || actor.higher_priority_writer_barrier_blocks(job_class))
3469 {
3470 return None;
3471 }
3472 if lane == Lane::Mutating {
3474 let head = if bind_pass {
3475 actor.interactive.first_bind_job()
3476 } else {
3477 actor.class_queues(job_class).queue(Lane::Mutating).front()
3478 };
3479 if head
3480 .and_then(|job| job.not_before)
3481 .is_some_and(|not_before| Instant::now() < not_before)
3482 {
3483 return None;
3484 }
3485 }
3486
3487 let has_epoch_reader =
3488 actor.read_inflight > 0 || actor.lsp_inflight || actor.maintenance_commit_inflight;
3489 let bind_may_share = bind_pass
3493 && actor
3494 .interactive
3495 .first_bind_job()
3496 .is_some_and(|job| job.rerun.is_some() && !job.force_exclusive);
3497 let actor_interactive_inflight = actor
3503 .actor_total_inflight
3504 .saturating_sub(usize::from(actor.maintenance_commit_inflight))
3505 .saturating_sub(usize::from(actor.callgraph_acquisition_inflight))
3506 .saturating_sub(usize::from(actor.provider_inflight))
3507 .saturating_sub(usize::from(actor.call_ledger_inflight));
3508 let actor_has_interactive_capacity = actor_interactive_inflight < config.actor_cap;
3509 let runnable = match lane {
3510 Lane::PureRead => actor.read_inflight < config.read_cap && actor_has_interactive_capacity,
3511 Lane::SerialLspStatus => !actor.lsp_inflight && actor_has_interactive_capacity,
3512 Lane::HeavyInit => {
3513 let capacity = if callgraph_acquisition {
3514 !actor.callgraph_acquisition_inflight
3515 } else {
3516 actor_has_interactive_capacity
3517 };
3518 if !capacity {
3519 false
3520 } else if let Some(permit) = heavy.try_acquire() {
3521 heavy_permit = Some(permit);
3522 true
3523 } else {
3524 false
3525 }
3526 }
3527 Lane::Mutating => {
3541 bind_may_share || (!has_epoch_reader && (bind_pass || actor_has_interactive_capacity))
3542 }
3543 Lane::MaintenanceCommit => !actor.maintenance_commit_inflight,
3547 Lane::ProviderMetadata => !actor.provider_inflight,
3548 Lane::CallLedger => !actor.call_ledger_inflight,
3551 };
3552
3553 if !runnable {
3554 return None;
3555 }
3556 let shared_bind_gate = bind_may_share && has_epoch_reader;
3557
3558 let promoted_writer_waiting = actor.oldest_queued_writer_at().is_some_and(|queued_at| {
3559 Instant::now().saturating_duration_since(queued_at) >= INTERACTIVE_WRITER_PROMOTION_AGE
3560 });
3561 if promoted_writer_waiting && matches!(lane, Lane::PureRead | Lane::SerialLspStatus) {
3562 actor.reader_admissions_while_promoted_writer_waited = actor
3563 .reader_admissions_while_promoted_writer_waited
3564 .saturating_add(1);
3565 }
3566
3567 let queued = if bind_pass {
3568 actor.pop_first_bind_job()?
3569 } else {
3570 actor.pop_front_job(job_class, lane)?
3571 };
3572 if matches!(pass, AdmissionPass::Class(_)) {
3574 actor.deficit -= JOB_COST;
3575 }
3576 if lane == Lane::Mutating {
3577 actor.mutating_inflight = Some(RunningMutatingJob {
3578 request_id: queued.request_id.clone(),
3579 command: queued.command.clone(),
3580 started_at: Instant::now(),
3581 });
3582 }
3583 match lane {
3584 Lane::PureRead => {
3585 actor.read_inflight += 1;
3586 actor.actor_total_inflight += 1;
3587 }
3588 Lane::SerialLspStatus => {
3589 actor.lsp_inflight = true;
3590 actor.actor_total_inflight += 1;
3591 }
3592 Lane::HeavyInit => {
3593 if callgraph_acquisition {
3594 actor.callgraph_acquisition_inflight = true;
3595 }
3596 actor.actor_total_inflight += 1;
3597 }
3598 Lane::Mutating => {
3599 actor.writer_inflight = true;
3600 actor.shared_bind_inflight = shared_bind_gate;
3601 actor.actor_total_inflight += 1;
3602 }
3603 Lane::MaintenanceCommit => {
3604 actor.maintenance_commit_inflight = true;
3605 actor.actor_total_inflight += 1;
3606 }
3607 Lane::ProviderMetadata => {
3608 actor.provider_inflight = true;
3609 actor.actor_total_inflight += 1;
3610 }
3611 Lane::CallLedger => {
3612 actor.call_ledger_inflight = true;
3613 actor.actor_total_inflight += 1;
3614 }
3615 }
3616
3617 Some(RunJob::<C> {
3618 root_id: root_id.clone(),
3619 job_class,
3620 lane,
3621 ctx: Arc::clone(&actor.ctx),
3622 epoch: Arc::clone(&actor.epoch),
3623 job: queued.job,
3624 completion: Some(queued.completion),
3625 request_id: queued.request_id,
3626 command: queued.command,
3627 heavy_permit,
3628 cancellation: queued.cancellation,
3629 execution_started: Arc::new(AtomicBool::new(false)),
3630 completion_guard: None,
3631 waiting_writers: Arc::clone(&actor.waiting_writers),
3632 detached_writers: Arc::clone(&actor.detached_writers),
3633 shared_bind_gate,
3634 rerun: queued.rerun,
3635 queued_at: queued.queued_at,
3636 exclusive_attempts: queued.exclusive_attempts,
3637 provider_generation: queued.provider_generation,
3638 })
3639}
3640}
3641
3642thread_local! {
3643 static IS_EXECUTOR_WORKER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3644}
3645
3646pub fn current_thread_is_executor_worker() -> bool {
3647 IS_EXECUTOR_WORKER.with(std::cell::Cell::get)
3648}
3649
3650fn worker_loop<C: ExecutorContext>(run_rx: Receiver<RunJob<C>>) {
3651 IS_EXECUTOR_WORKER.with(|worker| worker.set(true));
3652 while let Ok(mut run_job) = run_rx.recv() {
3653 let response =
3654 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run_lane_job(&mut run_job)));
3655 let panicked = response.is_err();
3656 let response = match response {
3657 Ok(LaneRun::Finished(response)) => response,
3658 Ok(LaneRun::RerunExclusive { retry_after }) => {
3659 match requeue_as_exclusive(&mut run_job, retry_after) {
3660 Ok(queued) => {
3661 let guard = run_job
3662 .completion_guard
3663 .as_mut()
3664 .expect("dispatched executor job is missing its completion guard");
3665 guard.set_requeue(queued);
3666 guard.set_outcome(JobCompletionOutcome::Completed);
3667 continue;
3668 }
3669 Err(response) => response,
3670 }
3671 }
3672 Err(payload) => panic_response(
3673 run_job.request_id.clone(),
3674 &run_job.command,
3675 payload.as_ref(),
3676 ),
3677 };
3678
3679 if let Some(completion) = run_job.completion.take() {
3680 completion.send(response);
3681 }
3682 run_job
3683 .completion_guard
3684 .as_mut()
3685 .expect("dispatched executor job is missing its completion guard")
3686 .set_outcome(if panicked {
3687 JobCompletionOutcome::Panicked
3688 } else {
3689 JobCompletionOutcome::Completed
3690 });
3691 }
3692}
3693
3694fn requeue_as_exclusive<C: ExecutorContext>(
3698 run_job: &mut RunJob<C>,
3699 retry_after: Option<Duration>,
3700) -> Result<QueuedJob<C>, Response> {
3701 let cancelled = || {
3702 Response::error(
3703 run_job.request_id.clone(),
3704 "request_cancelled",
3705 "request cancelled before execution",
3706 )
3707 };
3708 if run_job
3712 .cancellation
3713 .as_ref()
3714 .is_some_and(|token| !token.return_to_pending())
3715 {
3716 return Err(cancelled());
3717 }
3718 requeue_handoff_hook_for_test(&run_job.request_id);
3719 if run_job
3723 .cancellation
3724 .as_ref()
3725 .is_some_and(JobCancellation::cancel_requested_before_commit)
3726 {
3727 return Err(cancelled());
3728 }
3729 #[cfg(any(test, feature = "test-support"))]
3730 requeue_after_probe_hook_for_test(&run_job.request_id);
3731 let rerun = run_job
3732 .rerun
3733 .clone()
3734 .expect("only a repeatable bind runs with a shared hold");
3735 let completion = run_job
3736 .completion
3737 .take()
3738 .expect("a requeued bind still owns its completion");
3739 let next_run = Arc::clone(&rerun);
3740 Ok(QueuedJob::<C> {
3741 job: Box::new(move |ctx| next_run(ctx)),
3742 completion,
3743 request_id: run_job.request_id.clone(),
3744 command: run_job.command.clone(),
3745 queued_at: run_job.queued_at,
3746 cancellation: run_job.cancellation.clone(),
3747 maintenance_coalesce_key: None,
3748 rerun: Some(rerun),
3749 force_exclusive: true,
3750 not_before: retry_after.map(|delay| Instant::now() + delay),
3751 exclusive_attempts: run_job.exclusive_attempts + u32::from(retry_after.is_some()),
3752 provider_generation: None,
3753 })
3754}
3755
3756#[cfg(any(test, feature = "test-support"))]
3758type RequeueHandoffHook = (String, Box<dyn FnOnce() + Send>);
3759
3760#[cfg(any(test, feature = "test-support"))]
3761static REQUEUE_HANDOFF_HOOK: Mutex<Option<RequeueHandoffHook>> = Mutex::new(None);
3762
3763#[cfg(any(test, feature = "test-support"))]
3766pub fn set_requeue_handoff_hook_for_test(request_id: &str, hook: impl FnOnce() + Send + 'static) {
3767 *REQUEUE_HANDOFF_HOOK.lock() = Some((request_id.to_string(), Box::new(hook)));
3768}
3769
3770#[cfg(any(test, feature = "test-support"))]
3771fn requeue_handoff_hook_for_test(request_id: &str) {
3772 let hook = {
3773 let mut slot = REQUEUE_HANDOFF_HOOK.lock();
3774 match slot.take() {
3775 Some((id, hook)) if id == request_id => Some(hook),
3776 other => {
3777 *slot = other;
3778 None
3779 }
3780 }
3781 };
3782 if let Some(hook) = hook {
3783 hook();
3784 }
3785}
3786
3787#[cfg(not(any(test, feature = "test-support")))]
3788fn requeue_handoff_hook_for_test(_request_id: &str) {}
3789
3790#[cfg(any(test, feature = "test-support"))]
3791static REQUEUE_AFTER_PROBE_HOOK: Mutex<Option<RequeueHandoffHook>> = Mutex::new(None);
3792
3793#[cfg(any(test, feature = "test-support"))]
3796pub fn set_requeue_after_probe_hook_for_test(
3797 request_id: &str,
3798 hook: impl FnOnce() + Send + 'static,
3799) {
3800 *REQUEUE_AFTER_PROBE_HOOK.lock() = Some((request_id.to_string(), Box::new(hook)));
3801}
3802
3803#[cfg(any(test, feature = "test-support"))]
3804fn requeue_after_probe_hook_for_test(request_id: &str) {
3805 let hook = {
3806 let mut slot = REQUEUE_AFTER_PROBE_HOOK.lock();
3807 match slot.take() {
3808 Some((id, hook)) if id == request_id => Some(hook),
3809 other => {
3810 *slot = other;
3811 None
3812 }
3813 }
3814 };
3815 if let Some(hook) = hook {
3816 hook();
3817 }
3818}
3819
3820#[rustfmt::skip]
3821test_support_visibility! {
3822enum LaneRun {
3824 Finished(Response),
3825 RerunExclusive {
3829 retry_after: Option<Duration>,
3830 },
3831}
3832}
3833
3834fn detached_writer_backoff(attempts: u32) -> Duration {
3837 Duration::from_millis(10u64.saturating_mul(1u64 << attempts.min(5)).min(200))
3838}
3839
3840const EPOCH_WAIT_POLL: Duration = Duration::from_millis(25);
3842
3843#[rustfmt::skip]
3844test_support_visibility! {
3845
3846fn run_lane_job<C: ExecutorContext>(run_job: &mut RunJob<C>) -> LaneRun {
3847 let _cancellation_ctx = JobCancellationContextGuard::install(run_job.cancellation.clone());
3848 let _waiting_writers_ctx = ActorWaitingWritersGuard::install(ActorWriterDemand {
3849 queued: Arc::clone(&run_job.waiting_writers),
3850 detached: Some(Arc::clone(&run_job.detached_writers)),
3851 });
3852 let missing_request_id = run_job.request_id.clone();
3853 let job = std::mem::replace(
3854 &mut run_job.job,
3855 Box::new(move |_| {
3856 Response::error(
3857 missing_request_id,
3858 "job_missing",
3859 "executor job already taken",
3860 )
3861 }),
3862 );
3863
3864 let cancelled_before_execution = || {
3865 Response::error(
3866 run_job.request_id.clone(),
3867 "request_cancelled",
3868 "request cancelled before execution",
3869 )
3870 };
3871 let cancel_requested = || {
3872 run_job
3873 .cancellation
3874 .as_ref()
3875 .is_some_and(JobCancellation::cancel_requested_before_commit)
3876 };
3877 let run = |job: ExecutorJob<C>| {
3878 if cancel_requested()
3879 || ((run_job.job_class == JobClass::Maintenance
3880 || run_job.command == "inspect"
3881 || run_job.lane == Lane::ProviderMetadata)
3882 && ((run_job.ctx.subc_unbound_quiesced()
3883 && !maintenance_allowed_while_unbound(&run_job.command))
3884 || !run_job.root_id.as_path().is_dir()))
3885 {
3886 return cancelled_before_execution();
3887 }
3888 let can_start = if let Some(generation) = run_job.provider_generation {
3889 run_job
3892 .ctx
3893 .run_if_subc_bound_generation(generation, || {
3894 run_job
3895 .cancellation
3896 .as_ref()
3897 .is_none_or(|token| token.mark_running() && token.try_seal_committed())
3898 })
3899 .unwrap_or(false)
3900 } else {
3901 run_job
3902 .cancellation
3903 .as_ref()
3904 .is_none_or(JobCancellation::mark_running)
3905 };
3906 if !can_start {
3907 return cancelled_before_execution();
3908 }
3909 run_job.execution_started.store(true, Ordering::Release);
3910 job(&run_job.ctx)
3911 };
3912
3913 let response = match run_job.lane {
3914 Lane::PureRead | Lane::SerialLspStatus => {
3915 if run_job.cancellation.is_some() {
3916 loop {
3917 if let Some(_epoch) = run_job.epoch.try_read_for(EPOCH_WAIT_POLL) {
3918 return LaneRun::Finished(run(job));
3919 }
3920 if cancel_requested() {
3921 return LaneRun::Finished(cancelled_before_execution());
3922 }
3923 }
3924 }
3925 let _epoch = run_job.epoch.read();
3926 run(job)
3927 }
3928 Lane::HeavyInit => run(job),
3933 Lane::ProviderMetadata => {
3934 let _config = run_job.ctx.pin_config();
3935 run(job)
3936 }
3937 Lane::CallLedger => run(job),
3940 Lane::Mutating if run_job.shared_bind_gate => {
3941 if cancel_requested() {
3943 return LaneRun::Finished(cancelled_before_execution());
3944 }
3945 let Some(_epoch) = run_job.epoch.try_read() else {
3950 return LaneRun::RerunExclusive { retry_after: None };
3951 };
3952 let scope = SharedBindScope::install();
3953 let response = run(job);
3954 if scope.rerun_requested() {
3955 return LaneRun::RerunExclusive { retry_after: None };
3956 }
3957 response
3958 }
3959 Lane::Mutating if run_job.rerun.is_some() => {
3966 if cancel_requested() {
3967 return LaneRun::Finished(cancelled_before_execution());
3968 }
3969 let Some(_epoch) = run_job.epoch.try_write() else {
3970 return LaneRun::RerunExclusive {
3971 retry_after: Some(detached_writer_backoff(run_job.exclusive_attempts)),
3972 };
3973 };
3974 run(job)
3975 }
3976 Lane::Mutating => {
3977 if run_job.cancellation.is_some() {
3978 loop {
3979 if let Some(_epoch) = run_job.epoch.try_write_for(EPOCH_WAIT_POLL) {
3980 return LaneRun::Finished(run(job));
3981 }
3982 if cancel_requested() {
3983 return LaneRun::Finished(cancelled_before_execution());
3984 }
3985 }
3986 }
3987 let _epoch = run_job.epoch.write();
3988 run(job)
3989 }
3990 Lane::MaintenanceCommit => {
3991 loop {
3995 if cancel_requested() {
3996 return LaneRun::Finished(cancelled_before_execution());
3997 }
3998 if let Some(_epoch) = run_job.epoch.try_read_for(EPOCH_WAIT_POLL) {
3999 return LaneRun::Finished(run(job));
4000 }
4001 }
4002 }
4003 };
4004 LaneRun::Finished(response)
4005}
4006}
4007
4008#[rustfmt::skip]
4009test_support_visibility! {
4010#[derive(Debug)]
4011struct HeavySemaphore {
4012 available: AtomicUsize,
4013 max: usize,
4014}
4015}
4016
4017impl HeavySemaphore {
4018 #[rustfmt::skip]
4019 test_support_visibility! {
4020 fn new(permits: usize) -> Self {
4021 Self {
4022 available: AtomicUsize::new(permits),
4023 max: permits,
4024 }
4025 }
4026 }
4027
4028 #[rustfmt::skip]
4029 test_support_visibility! {
4030
4031 fn try_acquire(self: &Arc<Self>) -> Option<HeavyPermit> {
4032 loop {
4033 let available = self.available.load(Ordering::Acquire);
4034 if available == 0 {
4035 return None;
4036 }
4037 if self
4038 .available
4039 .compare_exchange(
4040 available,
4041 available - 1,
4042 Ordering::AcqRel,
4043 Ordering::Acquire,
4044 )
4045 .is_ok()
4046 {
4047 return Some(HeavyPermit {
4048 semaphore: Arc::clone(self),
4049 });
4050 }
4051 }
4052 }
4053
4054 }
4055}
4056
4057#[rustfmt::skip]
4058test_support_visibility! {
4059struct HeavyPermit {
4060 semaphore: Arc<HeavySemaphore>,
4061}
4062}
4063
4064impl Drop for HeavyPermit {
4065 fn drop(&mut self) {
4066 let previous = self.semaphore.available.fetch_add(1, Ordering::Release);
4067 debug_assert!(previous < self.semaphore.max);
4068 }
4069}
4070
4071#[cfg(any(test, feature = "test-support"))]
4072pub mod audit;
4073
4074#[cfg(any(test, feature = "test-support"))]
4075#[cfg_attr(not(test), allow(dead_code, unused_imports))]
4076pub mod tests;