1use super::*;
2
3impl<C: ExecutorContext> Executor<C> {
4 pub fn new() -> Self {
5 Self::with_config(ExecutorConfig::default())
6 }
7
8 pub fn with_config(config: ExecutorConfig) -> Self {
9 let effective = config.effective();
10 let state = Arc::new(TrackedMutex::new(
11 SchedulerState::<C>::new(effective.clone()),
12 file!(),
13 ));
14 let heavy = Arc::new(HeavySemaphore::new(effective.heavy_permits));
15 let nonrunnable_dispatches = Arc::new(AtomicUsize::new(0));
16 let completed_interactive = Arc::new(AtomicU64::new(0));
17 let completed_maintenance = Arc::new(AtomicU64::new(0));
18 let dispatch_liveness = Arc::new(DispatchLivenessAtomics::new());
19 let (run_tx, run_rx) = crossbeam_channel::unbounded();
20 let (event_tx, event_rx) = crossbeam_channel::unbounded();
21 let dispatch_loop_liveness = Arc::new(DispatchLoopLiveness::<C>::new(event_rx.clone()));
22
23 let scheduler_event_tx = event_tx.clone();
24 let scheduler_loop_liveness = Arc::clone(&dispatch_loop_liveness);
25 let scheduler_state = Arc::clone(&state);
26 let scheduler_heavy = Arc::clone(&heavy);
27 let scheduler_violations = Arc::clone(&nonrunnable_dispatches);
28 let scheduler_completed_interactive = Arc::clone(&completed_interactive);
29 let scheduler_completed_maintenance = Arc::clone(&completed_maintenance);
30 let scheduler_dispatch_liveness = Arc::clone(&dispatch_liveness);
31 let scheduler_handle = thread::Builder::new()
32 .name("aft-executor-scheduler".to_string())
33 .spawn(move || {
34 scheduler_loop(
35 scheduler_state,
36 scheduler_heavy,
37 run_tx,
38 scheduler_event_tx,
39 event_rx,
40 scheduler_violations,
41 scheduler_completed_interactive,
42 scheduler_completed_maintenance,
43 scheduler_dispatch_liveness,
44 scheduler_loop_liveness,
45 );
46 })
47 .expect("spawn AFT executor scheduler");
48
49 let mut worker_handles = Vec::with_capacity(effective.total_workers());
50 for worker_id in 0..effective.total_workers() {
51 let worker_rx = run_rx.clone();
52 let handle = thread::Builder::new()
58 .name(format!("aft-executor-worker-{worker_id}"))
59 .stack_size(EXECUTOR_WORKER_STACK_BYTES)
60 .spawn(move || worker_loop(worker_rx))
61 .expect("spawn AFT executor worker");
62 worker_handles.push(handle);
63 }
64
65 Self {
66 inner: Arc::new(ExecutorInner::<C> {
67 state,
68 event_tx,
69 scheduler_handle: Mutex::new(Some(scheduler_handle)),
70 worker_handles: Mutex::new(worker_handles),
71 config: effective,
72 nonrunnable_dispatches,
73 completed_interactive,
74 completed_maintenance,
75 dispatch_liveness,
76 dispatch_loop_liveness,
77 #[cfg(any(test, feature = "test-support"))]
78 maintenance_root_check_hook: Mutex::new(None),
79 }),
80 }
81 }
82
83 pub fn register_actor(&self, root_id: ProjectRootId, ctx: Arc<C>) -> bool {
90 ctx.bind_status_context();
91 let maintenance =
92 RootMaintenanceExecutor::new(Arc::downgrade(&self.inner), root_id.clone());
93 let memory_root = root_id.as_path().to_path_buf();
94 let inserted = {
95 let mut state = self.inner.state.lock();
96 if state.actors.contains_key(&root_id) {
97 false
98 } else {
99 state.actor_order.push(root_id.clone());
100 state
101 .actors
102 .insert(root_id, ActorState::<C>::new(Arc::clone(&ctx)));
103 true
104 }
105 };
106 if inserted {
107 ctx.install_callgraph_executor(maintenance);
108 let app = ctx.app();
109 crate::cache_location::markers::register_live_scope(&ctx.storage_dir(), &memory_root);
110 app.register_memory_context(memory_root, &ctx);
111 app.actor_root_registered();
112 }
113 self.wake_scheduler();
114 inserted
115 }
116
117 pub fn remove_actor(&self, root_id: &ProjectRootId) {
125 let removed = {
126 let mut state = self.inner.state.lock();
127 state.actor_order.retain(|actor_root| actor_root != root_id);
128 state.actors.remove(root_id)
129 };
130 if let Some(actor) = removed.as_ref() {
131 let app = actor.ctx.app();
132 crate::cache_location::markers::unregister_live_scope(
133 &actor.ctx.storage_dir(),
134 root_id.as_path(),
135 );
136 app.unregister_memory_context(root_id.as_path(), &actor.ctx);
137 app.actor_root_unregistered();
138 }
139 drop(removed);
140 self.wake_scheduler();
141 }
142
143 pub fn actor_is_idle(&self, root_id: &ProjectRootId) -> bool {
145 let state = self.inner.state.lock();
146 state
147 .actors
148 .get(root_id)
149 .is_some_and(ActorState::<C>::is_idle)
150 }
151
152 pub fn try_actor_is_idle(&self, root_id: &ProjectRootId) -> Option<bool> {
157 let state = self.inner.state.try_lock_for(SCHEDULER_PROBE_WAIT)?;
158 Some(
159 state
160 .actors
161 .get(root_id)
162 .is_some_and(ActorState::<C>::is_idle),
163 )
164 }
165
166 pub fn retire_idle_actor_in_background(&self, root_id: &ProjectRootId) -> bool {
170 let removed = {
171 let mut state = self.inner.state.lock();
172 if !state
173 .actors
174 .get(root_id)
175 .is_some_and(ActorState::<C>::is_idle)
176 {
177 return false;
178 }
179 state.actor_order.retain(|actor_root| actor_root != root_id);
180 state.actors.remove(root_id)
181 };
182 self.finish_idle_actor_retirement(root_id, removed)
183 }
184
185 pub fn try_retire_idle_actor_in_background(&self, root_id: &ProjectRootId) -> Option<bool> {
189 let removed = {
190 let mut state = self.inner.state.try_lock_for(SCHEDULER_PROBE_WAIT)?;
191 if !state
192 .actors
193 .get(root_id)
194 .is_some_and(ActorState::<C>::is_idle)
195 {
196 return Some(false);
197 }
198 state.actor_order.retain(|actor_root| actor_root != root_id);
199 state.actors.remove(root_id)
200 };
201 Some(self.finish_idle_actor_retirement(root_id, removed))
202 }
203
204 fn finish_idle_actor_retirement(
205 &self,
206 root_id: &ProjectRootId,
207 removed: Option<ActorState<C>>,
208 ) -> bool {
209 let Some(actor) = removed else {
210 return false;
211 };
212 let app = actor.ctx.app();
213 crate::cache_location::markers::unregister_live_scope(
214 &actor.ctx.storage_dir(),
215 root_id.as_path(),
216 );
217 app.unregister_memory_context(root_id.as_path(), &actor.ctx);
218 app.actor_root_unregistered();
219 std::thread::spawn(move || {
220 actor.ctx.teardown_deleted_root();
221 drop(actor);
222 });
223 self.wake_scheduler();
224 true
225 }
226
227 pub fn cancel_queued_maintenance(&self, root_id: &ProjectRootId) -> usize {
233 let cancelled = {
234 let mut state = self.inner.state.lock();
235 state
236 .actors
237 .get_mut(root_id)
238 .map(|actor| actor.maintenance.cancel_queued_jobs())
239 .unwrap_or(0)
240 };
241 if cancelled > 0 {
242 self.wake_scheduler();
243 }
244 cancelled
245 }
246
247 pub fn cancel_queued_root_maintenance(&self, root_id: &ProjectRootId) -> usize {
251 let cancelled = self
252 .inner
253 .state
254 .lock()
255 .actors
256 .get_mut(root_id)
257 .map(ActorState::<C>::cancel_queued_root_work)
258 .unwrap_or(0);
259 self.wake_scheduler();
260 cancelled
261 }
262
263 pub fn cancel_root_maintenance(&self, root_id: &ProjectRootId) -> usize {
266 let mut state = self.inner.state.lock();
267 let mut cancelled = state
268 .actors
269 .get_mut(root_id)
270 .map(ActorState::<C>::cancel_queued_root_work)
271 .unwrap_or(0);
272 if let Some(actor) = state.actors.get_mut(root_id) {
273 for lane in ALL_LANES {
274 for job in actor
275 .interactive
276 .queue(lane)
277 .iter()
278 .filter(|job| job.command == "inspect")
279 {
280 if let Some(token) = &job.cancellation {
281 token.request_cancel();
282 cancelled += 1;
283 }
284 }
285 }
286 }
287 for job in state.running_jobs.values() {
288 if &job.root_id == root_id
289 && (job.job_class == JobClass::Maintenance || job.command == "inspect")
290 {
291 if let Some(token) = &job.cancellation {
292 token.request_cancel();
293 cancelled += 1;
294 }
295 }
296 }
297 drop(state);
298 self.wake_scheduler();
299 cancelled
300 }
301
302 pub fn actor_registered(&self, root_id: &ProjectRootId) -> bool {
304 let state = self.inner.state.lock();
305 state.actors.contains_key(root_id)
306 }
307
308 pub fn actor_context(&self, root_id: &ProjectRootId) -> Option<Arc<C>> {
311 let state = self.inner.state.lock();
312 state
313 .actors
314 .get(root_id)
315 .map(|actor| Arc::clone(&actor.ctx))
316 }
317
318 pub fn scheduler_lock_diagnostics(&self) -> Arc<LockDiagnostics> {
319 self.inner.state.diagnostics()
320 }
321
322 pub fn try_actor_context(&self, root_id: &ProjectRootId) -> Option<Option<Arc<C>>> {
328 let state = self.inner.state.try_lock_for(SCHEDULER_PROBE_WAIT)?;
329 Some(
330 state
331 .actors
332 .get(root_id)
333 .map(|actor| Arc::clone(&actor.ctx)),
334 )
335 }
336
337 #[cfg(any(test, feature = "test-support"))]
340 pub fn hold_state_lock_for_test(&self, while_held: impl FnOnce()) {
341 let _held = self.inner.state.lock();
342 while_held();
343 }
344
345 pub fn actor_contexts(&self) -> Vec<Arc<C>> {
350 let state = self.inner.state.lock();
351 state
352 .actors
353 .values()
354 .map(|actor_state| Arc::clone(&actor_state.ctx))
355 .collect()
356 }
357
358 pub fn actor_entries(&self) -> Vec<(ProjectRootId, Arc<C>)> {
360 let state = self.inner.state.lock();
361 state
362 .actors
363 .iter()
364 .map(|(root_id, actor_state)| (root_id.clone(), Arc::clone(&actor_state.ctx)))
365 .collect()
366 }
367
368 pub fn try_actor_entries(&self) -> Option<Vec<(ProjectRootId, Arc<C>)>> {
372 let state = self.inner.state.try_lock()?;
373 Some(
374 state
375 .actors
376 .iter()
377 .map(|(root_id, actor_state)| (root_id.clone(), Arc::clone(&actor_state.ctx)))
378 .collect(),
379 )
380 }
381
382 pub fn actor_count(&self) -> usize {
386 self.inner.state.lock().actors.len()
387 }
388
389 pub fn try_actor_count(&self) -> Option<usize> {
391 self.inner.state.try_lock().map(|state| state.actors.len())
392 }
393
394 pub fn submit(
395 &self,
396 root_id: ProjectRootId,
397 lane: Lane,
398 request_id: String,
399 job: ExecutorJob<C>,
400 ) -> CompletionHandle {
401 let (completion_tx, completion_rx) = crossbeam_channel::bounded(1);
402 self.submit_with_completion(
403 root_id,
404 JobClass::Interactive,
405 lane,
406 request_id,
407 job,
408 CompletionSender::Sync(completion_tx),
409 );
410 CompletionHandle { rx: completion_rx }
411 }
412
413 pub fn submit_async(
414 &self,
415 root_id: ProjectRootId,
416 lane: Lane,
417 request_id: String,
418 job: ExecutorJob<C>,
419 ) -> oneshot::Receiver<Response> {
420 let (completion_tx, completion_rx) = oneshot::channel();
421 self.submit_with_completion(
422 root_id,
423 JobClass::Interactive,
424 lane,
425 request_id,
426 job,
427 CompletionSender::Async(completion_tx),
428 );
429 completion_rx
430 }
431
432 pub fn submit_cancellable_async(
438 &self,
439 root_id: ProjectRootId,
440 lane: Lane,
441 request_id: String,
442 job: ExecutorJob<C>,
443 ) -> (oneshot::Receiver<Response>, JobCancellation) {
444 let cancellation = JobCancellation::new();
445 let (completion_tx, completion_rx) = oneshot::channel();
446 self.submit_with_completion_cancellable(
447 root_id,
448 JobClass::Interactive,
449 lane,
450 request_id,
451 job,
452 CompletionSender::Async(completion_tx),
453 Some(cancellation.clone()),
454 None,
455 None,
456 );
457 (completion_rx, cancellation)
458 }
459
460 pub fn submit_tool_call_cancellable_async(
464 &self,
465 root_id: ProjectRootId,
466 lane: Lane,
467 request_id: String,
468 tool: &str,
469 job: ExecutorJob<C>,
470 ) -> (oneshot::Receiver<Response>, JobCancellation) {
471 let cancellation = JobCancellation::new();
472 let completion_rx = self.submit_tool_call_with_cancellation_async(
473 root_id,
474 lane,
475 request_id,
476 tool,
477 job,
478 cancellation.clone(),
479 );
480 (completion_rx, cancellation)
481 }
482
483 pub fn submit_tool_call_with_cancellation_async(
486 &self,
487 root_id: ProjectRootId,
488 lane: Lane,
489 request_id: String,
490 tool: &str,
491 job: ExecutorJob<C>,
492 cancellation: JobCancellation,
493 ) -> oneshot::Receiver<Response> {
494 let lane = if lane == Lane::HeavyInit
498 && matches!(
499 tool,
500 "callgraph"
501 | "callers"
502 | "call_tree"
503 | "impact"
504 | "trace_to"
505 | "trace_to_symbol"
506 | "trace_data"
507 )
508 && self.actor_context(&root_id).is_some_and(|_ctx| false)
509 {
510 Lane::PureRead
511 } else {
512 lane
513 };
514 let (completion_tx, completion_rx) = oneshot::channel();
515 self.submit_labeled(
516 root_id,
517 JobClass::Interactive,
518 lane,
519 request_id,
520 tool.to_string(),
521 job,
522 CompletionSender::Async(completion_tx),
523 Some(cancellation.clone()),
524 None,
525 None,
526 );
527 completion_rx
528 }
529
530 pub fn submit_bind_cancellable_async(
538 &self,
539 root_id: ProjectRootId,
540 request_id: String,
541 job: RepeatableJob<C>,
542 ) -> (oneshot::Receiver<Response>, JobCancellation) {
543 debug_assert!(is_configure_request(&request_id));
544 let cancellation = JobCancellation::new();
545 let (completion_tx, completion_rx) = oneshot::channel();
546 let first_run = Arc::clone(&job);
547 self.submit_with_completion_cancellable(
548 root_id,
549 JobClass::Interactive,
550 Lane::Mutating,
551 request_id,
552 Box::new(move |ctx| first_run(ctx)),
553 CompletionSender::Async(completion_tx),
554 Some(cancellation.clone()),
555 None,
556 Some(job),
557 );
558 (completion_rx, cancellation)
559 }
560
561 pub fn cancel_job(&self, root_id: &ProjectRootId, token: &JobCancellation) -> JobCancelOutcome {
567 let observed = token.signal_cancel();
574 let (outcome, settled) = {
575 let mut state = self.inner.state.lock();
576 let Some(actor) = state.actors.get_mut(root_id) else {
577 return match observed {
578 JOB_CANCEL_STATE_COMMITTED => JobCancelOutcome::RunningCommitted,
579 JOB_CANCEL_STATE_RUNNING | JOB_CANCEL_STATE_PENDING => {
580 JobCancelOutcome::RunningSignalled
581 }
582 _ => JobCancelOutcome::NotFound,
583 };
584 };
585 match actor.remove_queued_cancellable(token) {
586 Some(queued) => (JobCancelOutcome::QueuedRemoved, Some(queued)),
587 None => match observed {
588 JOB_CANCEL_STATE_COMMITTED => (JobCancelOutcome::RunningCommitted, None),
590 JOB_CANCEL_STATE_RUNNING | JOB_CANCEL_STATE_PENDING => {
594 (JobCancelOutcome::RunningSignalled, None)
595 }
596 _ => (JobCancelOutcome::NotFound, None),
598 },
599 }
600 };
601 if let Some(queued) = settled {
602 queued.completion.send(Response::error(
603 queued.request_id,
604 "request_cancelled",
605 "request cancelled before execution",
606 ));
607 self.wake_scheduler();
608 }
609 outcome
610 }
611
612 pub fn cancel_job_before_execution(
620 &self,
621 root_id: &ProjectRootId,
622 token: &JobCancellation,
623 ) -> PreExecutionCancelOutcome {
624 let (outcome, settled) = {
625 let mut state = self.inner.state.lock();
626 if !token.try_cancel_before_running() {
627 return PreExecutionCancelOutcome::AlreadyStarted;
628 }
629 let settled = state
630 .actors
631 .get_mut(root_id)
632 .and_then(|actor| actor.remove_queued_cancellable(token));
633 let outcome = if settled.is_some() {
634 PreExecutionCancelOutcome::QueuedRemoved
635 } else {
636 PreExecutionCancelOutcome::DispatchedCancelled
637 };
638 (outcome, settled)
639 };
640 if let Some(queued) = settled {
641 queued.completion.send(Response::error(
642 queued.request_id,
643 "request_cancelled",
644 "request cancelled before execution",
645 ));
646 self.wake_scheduler();
647 }
648 outcome
649 }
650
651 pub fn submit_maintenance_async(
652 &self,
653 root_id: ProjectRootId,
654 lane: Lane,
655 request_id: String,
656 job: ExecutorJob<C>,
657 ) -> oneshot::Receiver<Response> {
658 self.submit_maintenance_async_with_key(root_id, lane, request_id, job, None)
659 }
660
661 pub fn submit_unbound_teardown_async(
664 &self,
665 root_id: ProjectRootId,
666 request_id: String,
667 job: ExecutorJob<C>,
668 ) -> oneshot::Receiver<Response> {
669 let (tx, rx) = oneshot::channel();
670 self.submit_labeled(
671 root_id,
672 JobClass::Maintenance,
673 Lane::MaintenanceCommit,
674 request_id,
675 "unbound-teardown-persist".to_owned(),
676 job,
677 CompletionSender::Async(tx),
678 None,
679 None,
680 None,
681 );
682 rx
683 }
684
685 #[cfg(any(test, feature = "test-support"))]
686 pub fn submit_maintenance_cancellable_async(
687 &self,
688 root_id: ProjectRootId,
689 lane: Lane,
690 request_id: String,
691 job: ExecutorJob<C>,
692 ) -> (oneshot::Receiver<Response>, JobCancellation) {
693 let (completion_tx, completion_rx) = oneshot::channel();
694 let cancellation = JobCancellation::new();
695 self.submit_with_completion_cancellable(
696 root_id,
697 JobClass::Maintenance,
698 lane,
699 request_id,
700 job,
701 CompletionSender::Async(completion_tx),
702 Some(cancellation.clone()),
703 None,
704 None,
705 );
706 (completion_rx, cancellation)
707 }
708
709 pub fn submit_coalescable_maintenance_async(
710 &self,
711 root_id: ProjectRootId,
712 lane: Lane,
713 request_id: String,
714 coalesce_key: MaintenanceCoalesceKey,
715 job: ExecutorJob<C>,
716 ) -> oneshot::Receiver<Response> {
717 self.submit_maintenance_async_with_key(root_id, lane, request_id, job, Some(coalesce_key))
718 }
719
720 fn submit_maintenance_async_with_key(
721 &self,
722 root_id: ProjectRootId,
723 lane: Lane,
724 request_id: String,
725 job: ExecutorJob<C>,
726 coalesce_key: Option<MaintenanceCoalesceKey>,
727 ) -> oneshot::Receiver<Response> {
728 let (completion_tx, completion_rx) = oneshot::channel();
729 self.submit_with_completion_cancellable(
730 root_id,
731 JobClass::Maintenance,
732 lane,
733 request_id,
734 job,
735 CompletionSender::Async(completion_tx),
736 None,
737 coalesce_key,
738 None,
739 );
740 completion_rx
741 }
742
743 fn submit_with_completion(
744 &self,
745 root_id: ProjectRootId,
746 job_class: JobClass,
747 lane: Lane,
748 request_id: String,
749 job: ExecutorJob<C>,
750 completion: CompletionSender,
751 ) {
752 self.submit_with_completion_cancellable(
753 root_id, job_class, lane, request_id, job, completion, None, None, None,
754 );
755 }
756
757 #[allow(clippy::too_many_arguments)]
758 fn submit_with_completion_cancellable(
759 &self,
760 root_id: ProjectRootId,
761 job_class: JobClass,
762 lane: Lane,
763 request_id: String,
764 job: ExecutorJob<C>,
765 completion: CompletionSender,
766 cancellation: Option<JobCancellation>,
767 maintenance_coalesce_key: Option<MaintenanceCoalesceKey>,
768 rerun: Option<RepeatableJob<C>>,
769 ) {
770 let command = if job_class == JobClass::Maintenance
773 && maintenance_coalesce_key == Some(MaintenanceCoalesceKey::LspDrain)
774 {
775 "lsp-event-drain".to_owned()
776 } else {
777 job_command(job_class, lane)
778 };
779 self.submit_labeled(
780 root_id,
781 job_class,
782 lane,
783 request_id,
784 command,
785 job,
786 completion,
787 cancellation,
788 maintenance_coalesce_key,
789 rerun,
790 );
791 }
792
793 #[allow(clippy::too_many_arguments)]
796 fn submit_labeled(
797 &self,
798 root_id: ProjectRootId,
799 job_class: JobClass,
800 lane: Lane,
801 request_id: String,
802 command: String,
803 job: ExecutorJob<C>,
804 completion: CompletionSender,
805 cancellation: Option<JobCancellation>,
806 maintenance_coalesce_key: Option<MaintenanceCoalesceKey>,
807 rerun: Option<RepeatableJob<C>>,
808 ) {
809 let cancellation = if job_class == JobClass::Maintenance
810 || command == "inspect"
811 || lane == Lane::ProviderMetadata
812 {
813 Some(cancellation.unwrap_or_else(JobCancellation::new))
814 } else {
815 cancellation
816 };
817 let mut cancellation = cancellation.map(|token| token.with_root(root_id.as_path()));
818 let mut rerun = rerun;
819 let mut job = Some(job);
820 let mut completion = Some(completion);
821 let mut duplicate_victims = Vec::new();
822
823 let maintenance_root_exists =
826 job_class != JobClass::Maintenance || self.maintenance_root_is_dir(&root_id);
827 let response = {
828 let mut state = self.inner.state.lock();
829 match state.actors.get_mut(&root_id) {
830 Some(actor) if actor.fatal => Some(actor_fatal_response(request_id.clone())),
831 Some(actor) => {
832 let provider_generation = if lane == Lane::ProviderMetadata {
836 let generation = actor.ctx.configure_generation();
837 actor
838 .ctx
839 .run_if_subc_bound_generation(generation, || generation)
840 } else {
841 None
842 };
843 if (job_class == JobClass::Maintenance
844 || command == "inspect"
845 || lane == Lane::ProviderMetadata)
846 && !maintenance_allowed_while_unbound(&command)
847 {
848 cancellation = cancellation.map(|token| {
849 token.with_lifecycle(actor.ctx.subc_lifecycle_admission())
850 });
851 }
852 let mut admission_error = None;
853 if lane == Lane::CallLedger && job_class != JobClass::Interactive {
854 admission_error = Some(Response::error(
855 request_id.clone(),
856 "invalid_lane",
857 "call ledger work requires interactive admission",
858 ));
859 }
860 if lane == Lane::ProviderMetadata {
861 if job_class != JobClass::Interactive {
862 admission_error = Some(Response::error(
863 request_id.clone(),
864 "invalid_lane",
865 "provider metadata requires interactive admission",
866 ));
867 } else if provider_generation.is_none() {
868 admission_error = Some(Response::error(
869 request_id.clone(),
870 "request_cancelled",
871 "provider metadata root is unbound",
872 ));
873 }
874 }
875 if job_class == JobClass::Maintenance {
876 if (actor.ctx.subc_unbound_quiesced()
877 && !maintenance_allowed_while_unbound(&command))
878 || !maintenance_root_exists
879 {
880 admission_error = Some(maintenance_cancelled_response(
881 request_id.clone(),
882 "maintenance root is unbound or missing",
883 ));
884 } else if maintenance_coalesce_key
885 .is_some_and(|key| actor.maintenance.has_maintenance_coalesce_key(key))
886 {
887 admission_error = Some(maintenance_cancelled_response(
888 request_id.clone(),
889 "maintenance drain coalesced behind an identical queued drain",
890 ));
891 } else {
892 if actor.maintenance.queued_count() >= MAINTENANCE_QUEUE_CAP {
893 duplicate_victims =
894 actor.maintenance.remove_duplicate_maintenance_jobs();
895 }
896 if actor.maintenance.queued_count() >= MAINTENANCE_QUEUE_CAP {
897 admission_error =
898 Some(maintenance_backpressure_response(request_id.clone()));
899 }
900 }
901 }
902
903 if admission_error.is_none() {
904 actor.push_job(
905 job_class,
906 lane,
907 QueuedJob::<C> {
908 job: job.take().expect("executor job already queued"),
909 completion: completion
910 .take()
911 .expect("executor completion already queued"),
912 request_id: request_id.clone(),
913 command,
914 queued_at: Instant::now(),
915 cancellation: cancellation.clone(),
916 maintenance_coalesce_key,
917 rerun: rerun.take(),
918 force_exclusive: false,
919 not_before: None,
920 exclusive_attempts: 0,
921 provider_generation,
922 },
923 );
924 }
925 admission_error
926 }
927 None => Some(Response::error(
928 request_id.clone(),
929 "actor_not_registered",
930 "executor actor is not registered",
931 )),
932 }
933 };
934
935 for victim in duplicate_victims {
936 victim.completion.send(maintenance_cancelled_response(
937 victim.request_id,
938 "duplicate maintenance drain removed to preserve queue capacity",
939 ));
940 }
941
942 if let Some(response) = response {
943 if let Some(completion) = completion {
944 completion.send(response);
945 }
946 return;
947 }
948
949 self.wake_scheduler();
950 }
951
952 pub(super) fn maintenance_root_is_dir(&self, root_id: &ProjectRootId) -> bool {
953 #[cfg(any(test, feature = "test-support"))]
954 {
955 let hook = self.inner.maintenance_root_check_hook.lock().take();
956 if let Some(hook) = hook {
957 hook();
958 }
959 }
960 root_id.as_path().is_dir()
961 }
962
963 #[cfg(any(test, feature = "test-support"))]
966 pub fn idle_workers_for_test(&self) -> usize {
967 self.inner.state.lock().idle_workers
968 }
969
970 #[cfg(any(test, feature = "test-support"))]
973 pub fn provider_reserve_for_test(&self) -> usize {
974 self.inner.config.provider_reserve
975 }
976
977 pub fn pool_size(&self) -> usize {
978 self.inner.config.pool_size
979 }
980
981 pub fn actor_cap(&self) -> usize {
982 self.inner.config.actor_cap
983 }
984
985 pub fn read_cap(&self) -> usize {
986 self.inner.config.read_cap
987 }
988
989 pub fn heavy_permits(&self) -> usize {
990 self.inner.config.heavy_permits
991 }
992
993 pub fn interactive_reserve(&self) -> usize {
994 self.inner.config.interactive_reserve
995 }
996
997 pub fn maintenance_cap(&self) -> usize {
998 self.inner.config.maintenance_cap
999 }
1000
1001 pub fn try_dispatch_liveness_snapshot(&self) -> Option<DispatchLivenessSnapshot> {
1002 Some(self.inner.dispatch_liveness.snapshot(&self.inner.config))
1003 }
1004
1005 pub fn try_running_read_requests(&self) -> Option<HashSet<String>> {
1007 self.inner.state.try_lock().map(|state| {
1008 state
1009 .running_jobs
1010 .values()
1011 .filter(|job| {
1012 matches!(job.lane, Lane::PureRead | Lane::SerialLspStatus)
1013 && job.execution_started.load(Ordering::Acquire)
1014 })
1015 .map(|job| job.request_id.clone())
1016 .collect()
1017 })
1018 }
1019
1020 pub fn try_mutating_lane_snapshots(&self) -> Option<Vec<MutatingLaneSnapshot>> {
1021 self.inner
1022 .state
1023 .try_lock()
1024 .map(|state| state.mutating_lane_snapshots())
1025 }
1026
1027 pub fn try_root_job_snapshots(
1028 &self,
1029 root_id: &ProjectRootId,
1030 current: Option<&JobCancellation>,
1031 ) -> Option<Vec<RootJobSnapshot>> {
1032 let state = self.inner.state.try_lock()?;
1033 let now = Instant::now();
1034 let mut jobs = state
1035 .running_jobs
1036 .iter()
1037 .filter(|(_, job)| &job.root_id == root_id)
1038 .map(|(job_id, job)| RootJobSnapshot {
1039 job_id: *job_id,
1040 request_id: job.request_id.clone(),
1041 command: job.command.clone(),
1042 lane: job.lane,
1043 started_age_ms: duration_millis_u64(now.saturating_duration_since(job.started_at)),
1044 execution_started: job.execution_started.load(Ordering::Acquire),
1045 is_current: current.is_some_and(|current| {
1046 job.cancellation
1047 .as_ref()
1048 .is_some_and(|token| token.same_token(current))
1049 }),
1050 })
1051 .collect::<Vec<_>>();
1052 jobs.sort_by_key(|job| job.job_id);
1053 Some(jobs)
1054 }
1055
1056 pub fn try_mutating_job_state_label(
1057 &self,
1058 root_id: &ProjectRootId,
1059 request_id: &str,
1060 ) -> Option<&'static str> {
1061 self.inner
1062 .state
1063 .try_lock()
1064 .map(|state| state.mutating_job_state_label(root_id, request_id))
1065 }
1066
1067 #[cfg(any(test, feature = "test-support"))]
1070 pub fn queued_lane_for_test(&self, root_id: &ProjectRootId, request_id: &str) -> Option<Lane> {
1071 let state = self.inner.state.lock();
1072 let actor = state.actors.get(root_id)?;
1073 for queues in [&actor.interactive, &actor.maintenance] {
1074 for lane in ALL_LANES {
1075 if queues
1076 .queue(lane)
1077 .iter()
1078 .any(|job| job.request_id == request_id)
1079 {
1080 return Some(lane);
1081 }
1082 }
1083 }
1084 None
1085 }
1086
1087 pub fn bind_blocker_snapshot(
1092 &self,
1093 root_id: &ProjectRootId,
1094 request_id: &str,
1095 ) -> BindBlockerSnapshot {
1096 self.inner
1097 .state
1098 .lock()
1099 .bind_blocker_snapshot(root_id, request_id)
1100 }
1101
1102 pub fn try_bind_blocker_snapshot(
1106 &self,
1107 root_id: &ProjectRootId,
1108 request_id: &str,
1109 ) -> Option<BindBlockerSnapshot> {
1110 self.inner
1111 .state
1112 .try_lock()
1113 .map(|state| state.bind_blocker_snapshot(root_id, request_id))
1114 }
1115
1116 pub fn try_take_long_running_interactive_jobs(
1120 &self,
1121 minimum_age: Duration,
1122 ) -> Option<Vec<LongRunningInteractiveJobSnapshot>> {
1123 let now = Instant::now();
1124 let mut state = self.inner.state.try_lock()?;
1125 let mut snapshots = state
1126 .running_jobs
1127 .values_mut()
1128 .filter_map(|job| {
1129 let age = now.saturating_duration_since(job.started_at);
1130 if job.job_class != JobClass::Interactive
1131 || job.occupancy_reported
1132 || age < minimum_age
1133 {
1134 return None;
1135 }
1136 job.occupancy_reported = true;
1137 Some(LongRunningInteractiveJobSnapshot {
1138 root_id: job.root_id.clone(),
1139 request_id: job.request_id.clone(),
1140 command: job.command.clone(),
1141 lane: job.lane,
1142 age,
1143 execution_started: job.execution_started.load(Ordering::Acquire),
1144 })
1145 })
1146 .collect::<Vec<_>>();
1147 snapshots.sort_by(|left, right| {
1148 left.root_id
1149 .as_path()
1150 .cmp(right.root_id.as_path())
1151 .then_with(|| left.request_id.cmp(&right.request_id))
1152 });
1153 Some(snapshots)
1154 }
1155
1156 pub fn dispatch_loop_liveness(&self) -> Arc<DispatchLoopLiveness<C>> {
1158 Arc::clone(&self.inner.dispatch_loop_liveness)
1159 }
1160
1161 #[cfg(any(test, feature = "test-support"))]
1166 pub fn hold_dispatch_loop_for_test(&self, release: Receiver<()>) -> JoinHandle<()> {
1167 let state = Arc::clone(&self.inner.state);
1168 let event_tx = self.inner.event_tx.clone();
1169 let (held_tx, held_rx) = crossbeam_channel::bounded(1);
1170 let handle = thread::spawn(move || {
1171 let _state = state.lock();
1172 let _ = event_tx.send(SchedulerEvent::<C>::Wake);
1173 let _ = held_tx.send(());
1174 let _ = release.recv();
1175 });
1176 held_rx.recv().expect("dispatch hold thread started");
1177 handle
1178 }
1179
1180 pub fn nonrunnable_dispatch_count(&self) -> usize {
1181 self.inner.nonrunnable_dispatches.load(Ordering::Acquire)
1182 }
1183
1184 pub fn completion_counts(&self) -> (u64, u64) {
1185 (
1186 self.inner.completed_interactive.load(Ordering::Relaxed),
1187 self.inner.completed_maintenance.load(Ordering::Relaxed),
1188 )
1189 }
1190
1191 pub fn actor_is_fatal(&self, root_id: &ProjectRootId) -> bool {
1192 self.inner
1193 .state
1194 .lock()
1195 .actors
1196 .get(root_id)
1197 .map(|actor| actor.fatal)
1198 .unwrap_or(false)
1199 }
1200
1201 fn wake_scheduler(&self) {
1202 let _ = self.inner.event_tx.send(SchedulerEvent::<C>::Wake);
1203 }
1204}