Skip to main content

aft_base/executor/
handle.rs

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            // Workers run every tool call, including tree-sitter walks over
53            // whatever a URL or file turns out to contain. The standalone loop
54            // runs those on the 8 MiB main thread; the 2 MiB default for spawned
55            // threads let a deep parse tree abort the whole daemon while the same
56            // request succeeded standalone. Match the main thread.
57            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    /// Register an actor if one is not already present.
84    ///
85    /// Existing actors keep their current context and scheduler state; subc
86    /// routing reuses them and reconfigures through the Mutating lane
87    /// rather than replacing the per-root [`ExecutorContext`]. Returns `true` when a
88    /// new actor was inserted.
89    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    /// Remove an actor from scheduler state.
118    ///
119    /// This is intentionally minimal: subc uses it only for a just-created
120    /// RouteBind actor whose configure failed before any route was installed, so
121    /// there is no in-flight work to quiesce. The removed [`ExecutorContext`] is
122    /// dropped after releasing the scheduler lock so watcher/LSP teardown never
123    /// runs under that mutex.
124    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    /// Return true only when the actor has no queued or running executor work.
144    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    /// Idle probe for maintenance sweeps that waits at most
153    /// [`SCHEDULER_PROBE_WAIT`] for the scheduler lock. A contended scheduler
154    /// is reported separately so root retirement can conservatively wait for
155    /// the next sweep without stalling the module loop.
156    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    /// Forget an idle actor and drop its root-scoped registries off the scheduler
167    /// thread. This is reserved for roots whose project directory no longer
168    /// exists; retained existing roots are reused on a later bind.
169    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    /// [`Self::retire_idle_actor_in_background`] for the subc frame loop:
186    /// `None` when the scheduler lock stays contended past
187    /// [`SCHEDULER_PROBE_WAIT`], so the caller retries on its next sweep.
188    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    /// Cancel maintenance jobs that have not started for one retained actor.
228    ///
229    /// Interactive work and already-running maintenance remain untouched. Each
230    /// cancelled job receives a normal completion so its caller can settle
231    /// bookkeeping through the same path as an executed job.
232    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    /// When a root becomes unbound, cancel queued maintenance and metadata.
248    /// Started provider commits retain their result. Running maintenance checks
249    /// at checkpoints whether the root stayed unbound past the abandonment grace.
250    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    /// Cancel queued maintenance and signal running root work at its checkpoints.
264    /// Interactive tools other than inspect retain their normal completion path.
265    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    /// Return whether scheduler state currently has an actor for this root.
303    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    /// Snapshot one actor context without retaining the scheduler lock while
309    /// maintenance drops root-scoped resources.
310    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    /// [`Self::actor_context`] waiting at most [`SCHEDULER_PROBE_WAIT`] for
323    /// the scheduler lock: the outer `None` means it stayed contended. The subc frame
324    /// loop's maintenance sweeps use this and retry on the next sweep. Request
325    /// routing keeps the blocking form, because there a missing actor and a
326    /// busy scheduler mean different things.
327    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    /// Hold the scheduler state lock for the duration of `while_held`, so a
338    /// test can prove a caller does not wait for it.
339    #[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    /// Snapshot the registered actor contexts.
346    ///
347    /// The returned [`Arc`]s keep contexts alive after the scheduler lock is
348    /// released, so callers can run teardown without holding executor state.
349    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    /// Snapshot the registered root ids paired with their actor contexts.
359    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    /// Non-blocking variant for the health path: the probe reply must stay
369    /// cheap under any load, so it skips the actor list (reported as busy)
370    /// rather than waiting on the scheduler state lock.
371    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    /// Registered actor count under the scheduler lock. Tests that assert a
383    /// bind had no actor side effect use this rather than the try-lock form,
384    /// which reports contention (`None`) instead of a count.
385    pub fn actor_count(&self) -> usize {
386        self.inner.state.lock().actors.len()
387    }
388
389    /// Constant-time scheduler contention signal for the health reply path.
390    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    /// Submit an interactive job with an exact-job cancellation token.
433    ///
434    /// The returned token cancels THIS job only (queued: removed and settled
435    /// with `request_cancelled`; running: signalled cooperatively). The job
436    /// observes the token via [`current_job_cancellation`].
437    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    /// [`Executor::submit_cancellable_async`] for a tool call: the job is
461    /// labelled with the tool's name, so the census and the blockers a
462    /// waiting bind reports say which tool a long-running job is running.
463    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    /// Allows a receipt deadline to cancel admission even while submission is
484    /// waiting for the scheduler state lock on a blocking worker.
485    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        // Checkout callgraph views rebuild as Maintenance/HeavyInit jobs.
495        // Admit their tool reads as PureRead so a one-permit pool can answer
496        // Building while the rebuild owns the heavy permit.
497        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    /// Submit a route-bind configure (a request id starting `subc-bind-`)
531    /// that may run more than once, with an exact-job cancellation token.
532    ///
533    /// Unlike [`Executor::submit_cancellable_async`], the scheduler may admit
534    /// it beside a running maintenance job or readers of its actor with only a
535    /// shared hold on the epoch gate; see [`request_exclusive_rerun`] for how a run
536    /// that must change the root hands its worker back.
537    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    /// Cancel one exact job by its token.
562    ///
563    /// Queued jobs are removed and settled immediately; running jobs are
564    /// signalled and return through their normal completion path at the next
565    /// cooperative checkpoint. Jobs that sealed their commit finish normally.
566    pub fn cancel_job(&self, root_id: &ProjectRootId, token: &JobCancellation) -> JobCancelOutcome {
567        // Signal BEFORE actor lookup, deliberately: a job whose actor was
568        // already torn down (fatal teardown, root removal) must still abort at
569        // its next checkpoint, so the token is cancelled regardless. The
570        // outcome must then reflect what the signal actually did — reporting
571        // NotFound for a token that was RUNNING at signal time would mislead
572        // the caller into treating a signalled job as nonexistent.
573        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                    // The seal won the race: the job commits and finishes.
589                    JOB_CANCEL_STATE_COMMITTED => (JobCancelOutcome::RunningCommitted, None),
590                    // RUNNING at signal time, or PENDING at signal time but
591                    // dispatched before we took the scheduler lock: either way
592                    // the job aborts at its next checkpoint.
593                    JOB_CANCEL_STATE_RUNNING | JOB_CANCEL_STATE_PENDING => {
594                        (JobCancelOutcome::RunningSignalled, None)
595                    }
596                    // Already cancelled by an earlier call and no longer queued.
597                    _ => (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    /// Cancel a route job only while its command closure has not started.
613    ///
614    /// Detaching a route must discard work that cannot produce a live reply,
615    /// while a command already executing remains eligible for session replay.
616    /// A dispatched job may already reserve scheduler capacity; its worker sees
617    /// the cancelled token before invoking the closure and releases that
618    /// reservation through the normal completion event.
619    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    /// Final persistence is allowed after unbind so TTL eviction does not lose
662    /// retained deltas. This exception does not admit indexing or refresh work.
663    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        // Final LSP receipts must drain after the last route closes, even
771        // though configure, watcher and indexing maintenance are suspended.
772        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    /// Queue one job. `command` is the label census, blocker and panic lines
794    /// show for it.
795    #[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        // A root stat can stall on disk I/O. Probe before taking the shared
824        // scheduler lock; execution checks again if the root disappears later.
825        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                    // Validate the sampled configure generation against the bound
833                    // root under its lifecycle lock. A separate bound check and
834                    // later sample could let an older request use a rebind's generation.
835                    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    /// Workers not running a job right now, for tests that assert nothing
964    /// holds a worker while it waits.
965    #[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    /// Number of workers reserved for provider metadata, so tests can distinguish
971    /// those idle workers from the separate bind reservation.
972    #[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    /// In-memory read-job identities for management attribution; contention stays unknown.
1006    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    /// The lane in which a job with this request id is queued on `root_id`,
1068    /// for tests that hold a lane and must see the job wait behind it.
1069    #[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    /// Snapshot RouteBind blockers, waiting for the scheduler lock if it is
1088    /// held. The module's bind-deadline refusal uses it to name what held the
1089    /// bind; it takes the same lock right after to cancel the bind, so
1090    /// waiting here costs nothing extra.
1091    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    /// Snapshot RouteBind blockers without waiting on scheduler state. The subc
1103    /// health path uses this only for a delayed-bind breadcrumb, so contention
1104    /// is reported as scheduler busy rather than delaying the transport loop.
1105    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    /// Return each over-age interactive occupant once. Marking happens under the
1117    /// scheduler lock so repeated transport-loop censuses cannot flood logs while
1118    /// the same job remains stuck.
1119    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    /// Progress marker of the scheduler loop, for the subc stall watchdog.
1157    pub fn dispatch_loop_liveness(&self) -> Arc<DispatchLoopLiveness<C>> {
1158        Arc::clone(&self.inner.dispatch_loop_liveness)
1159    }
1160
1161    /// Holds the scheduler state mutex on a helper thread and wakes the
1162    /// scheduler, so the scheduler loop receives an event and then blocks on
1163    /// the lock: a stalled dispatch loop with pending work. The hold ends when
1164    /// `release` receives a message or its sender is dropped.
1165    #[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}