Skip to main content

aft_base/executor/
mod.rs

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
25// Mutation lock order: the executor's per-root mutating lane and context epoch
26// gate precede source-file admission, then backup and checkpoint locks. Never
27// wait for source-file admission while holding a backup/checkpoint lock. The
28// scheduler mutex is not held by handlers.
29// Multi-file writers admit their complete set in one registry turn, sorted by
30// resolved names with native identities covering hard-link aliases; they never
31// hold one file while waiting for another. A patch (and a symbol move) may keep
32// not-yet-written files admitted during earlier hunks' formatter runs, bounded
33// by formatter timeouts. Completed files are released after their last write
34// or delete, before their formatter/LSP waits. Single-file writers release
35// admission immediately after the atomic write, before formatting/validation.
36
37pub use single_flight::SingleFlight;
38
39const JOB_COST: isize = 1;
40/// How long the subc frame loop's scheduler probes (`try_actor_context`,
41/// `try_actor_is_idle`, `try_retire_idle_actor_in_background`) wait for the
42/// scheduler lock before answering "busy". The lock guards short map
43/// updates; a few milliseconds rides out an ordinary holder that was
44/// preempted, while a holder stuck for longer cannot stall the loop.
45const SCHEDULER_PROBE_WAIT: Duration = Duration::from_millis(5);
46#[rustfmt::skip]
47test_support_visibility! {
48/// Continuous wake producers must not keep the scheduler mutex across an
49/// unbounded receiver drain; health probes and submitters get a lock turn
50/// between batches.
51const 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/// Scheduler lane for command-handler execution.
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58pub enum Lane {
59    /// Pure read-only work. Runs under the actor epoch read gate and is capped
60    /// per actor.
61    PureRead,
62    /// LSP/status work. Serialized per actor by scheduler admission while still
63    /// using the shared epoch read gate.
64    SerialLspStatus,
65    /// Heavy lazy initialization. The scheduler acquires a process-wide heavy
66    /// permit before dispatch; cache and index builders reject stale generations
67    /// and serialize publication internally, so no actor epoch guard wraps the
68    /// command or the delivery of its response.
69    HeavyInit,
70    /// Mutating work. Becomes a writer barrier at the actor queue head, drains
71    /// in-flight reads, and runs under the actor epoch write gate. Reserved for
72    /// configure and user-initiated tool mutations: background maintenance must
73    /// use `MaintenanceCommit` so it can never exclude interactive reads.
74    Mutating,
75    /// Maintenance work that mutates only subsystem state behind that
76    /// subsystem's own lock (watcher/LSP drains, completed-build installs,
77    /// callgraph store writes). Runs under the actor epoch READ gate and
78    /// overlaps PureReads; serialized to one in-flight per actor so
79    /// maintenance cannot self-stack.
80    MaintenanceCommit,
81    /// Provider discovery and policy-store operations. Serialized per root on
82    /// reserved capacity, without an index epoch hold or writer-barrier wait.
83    ProviderMetadata,
84    /// Call-ledger bookkeeping for keyed tool calls: the row a call writes
85    /// before it dispatches, the settlement its terminal reply waits for
86    /// before the transport writer may send it, the row reads a repeated call
87    /// makes while it waits for that settlement, and the ledger and grant
88    /// writes that end a scope. Each job is one short SQLite transaction
89    /// behind the database's own mutex and touches no index state, so it takes
90    /// no epoch gate and does not wait for readers, LSP or maintenance jobs,
91    /// or a running writer. On the Mutating lane it would wait until every
92    /// read on its root had drained, and each keyed reply would wait with it.
93    /// Running beside a writer such as a configure loses no protection:
94    /// `AppContext::open_db` returns the process-shared database handle and
95    /// replaces it only when the storage path changes, so ledger jobs of other
96    /// roots always ran beside any configure. Jobs run one at a time per actor
97    /// in submission order, so one root's ledger writes land in the order they
98    /// were queued; a scope end therefore settles every admission queued on
99    /// its root before it. Queued ProviderMetadata jobs are cancelled when the
100    /// root's last route unbinds; these are not, because a settlement records
101    /// a call that already ran.
102    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/// Scheduler class used to keep deferrable maintenance from occupying the
116/// workers reserved for interactive route binds, tool calls, and bash.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
118pub enum JobClass {
119    Interactive,
120    Maintenance,
121}
122
123/// Idempotent maintenance drains that can share one queued execution.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
125pub enum MaintenanceCoalesceKey {
126    WatcherDrain,
127    LspDrain,
128    /// Standing maintenance is coalesced inside each actor queue. The executor
129    /// already scopes queue state by root, so this key cannot coalesce work for
130    /// separate standing roots.
131    StandingPass,
132    /// A live config reload re-reads the files, so one queued reload covers
133    /// every edit made before it runs.
134    ConfigReload,
135}
136
137pub type ExecutorJob<C> = Box<dyn FnOnce(&C) -> Response + Send + 'static>;
138
139#[rustfmt::skip]
140test_support_visibility! {
141/// Age at which a queued interactive mutating job (route binds, edits) jumps
142/// ahead of pure reads in interactive admission. Reads-first admission would
143/// otherwise let a sustained read stream starve queued writers; this bounds
144/// that wait. For binds it matches the half-deadline breadcrumb point: the
145/// daemon rejects binds at 12s, so promotion at 6s leaves half the budget for
146/// draining readers and running the configure itself.
147const INTERACTIVE_WRITER_PROMOTION_AGE: Duration = Duration::from_secs(6);
148}
149#[rustfmt::skip]
150test_support_visibility! {
151/// Age at which a queued route-bind configure stops new same-root pure reads
152/// from being admitted ahead of it. Much shorter than the general writer
153/// promotion: a bind is a short configure, and after a daemon restart dozens
154/// arrive together, so reads-first admission must not spend the relay budget.
155const BIND_PROMOTION_AGE: Duration = Duration::from_millis(500);
156}
157#[rustfmt::skip]
158test_support_visibility! {
159/// Worker threads reserved for route-bind configures, on top of `pool_size`.
160/// General interactive and maintenance jobs never occupy them, so a bind never
161/// waits for another session's long read, bash call, or maintenance tail to
162/// release a worker. Two, so a cold root's slower full configure does not
163/// serialize every other bind behind it.
164const BIND_RESERVE_WORKERS: usize = 2;
165}
166#[rustfmt::skip]
167test_support_visibility! {
168/// Provider metadata (tool catalogs, role descriptions, grants) has reserved
169/// workers, so these short requests never wait for an index builder,
170/// configure writer or maintenance job to free a worker. Callers such as a
171/// worker launch check ask for them under a deadline of a few seconds.
172const PROVIDER_RESERVE_WORKERS: usize = 2;
173}
174#[rustfmt::skip]
175test_support_visibility! {
176/// Readers older than this still block queued writer jobs; report their job
177/// metadata instead of only the generic `waiting_on_readers` diagnosis.
178const READER_STUCK_CENSUS_AGE: Duration = Duration::from_secs(60);
179}
180/// Stack for executor worker threads: the standalone main thread's size, so a
181/// request that fits there cannot overflow only under the daemon. Stack pages
182/// are committed on touch, so idle workers cost nothing extra.
183const 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    /// Workers beyond `pool_size` that only route-bind configures may use.
230    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    /// Every worker thread, including the bind and provider reservations.
242    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        // HeavyInit jobs share workers with RouteBind/configure. Keep one worker
258        // available even in a two-worker pool so a heavy-init storm cannot hold
259        // a fresh bind behind every executor worker.
260        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
287/// Synchronous completion handle used by the executor tests and the
288/// future standalone bridge.
289pub 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    /// Age of the oldest maintenance reservation still owned by a dispatched
320    /// worker. This distinguishes a blocked worker from a phantom reservation.
321    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
336/// Scheduler-owned mirror read by health probes without taking the actor map
337/// lock or scanning every root. Oldest queue timestamps use `0` for absent and
338/// elapsed-milliseconds-plus-one for a present timestamp.
339struct 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
479/// Progress marker for the scheduler (dispatch) loop, read by the subc stall
480/// watchdog from its own thread. Everything here is an atomic or a channel
481/// length read, so reading it never waits on the scheduler state mutex that a
482/// stalled loop may be blocked on or holding.
483pub 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    /// Milliseconds since `origin` when the loop last became ready to receive
490    /// or finished an event.
491    pub last_progress_ms: AtomicU64,
492    #[cfg(not(any(test, feature = "test-support")))]
493    /// Milliseconds since `origin` when the loop last became ready to receive
494    /// or finished an event.
495    last_progress_ms: AtomicU64,
496    #[cfg(any(test, feature = "test-support"))]
497    /// True from channel readiness (or a due retry) until the loop has
498    /// processed the event and released the scheduler lock.
499    pub in_event: AtomicBool,
500    #[cfg(not(any(test, feature = "test-support")))]
501    /// True from channel readiness (or a due retry) until the loop has
502    /// processed the event and released the scheduler lock.
503    in_event: AtomicBool,
504    #[cfg(any(test, feature = "test-support"))]
505    /// Clone of the scheduler's event receiver. Readiness waits and watchdog
506    /// queue checks never dequeue; only the scheduler consumes events.
507    pub event_rx: Receiver<SchedulerEvent<C>>,
508    #[cfg(not(any(test, feature = "test-support")))]
509    /// Clone of the scheduler's event receiver. Readiness waits and watchdog
510    /// queue checks never dequeue; only the scheduler consumes events.
511    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        // Readiness does not dequeue. Publish the active marker first so the
547        // watchdog cannot see an empty queue with an unmarked received event.
548        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    /// Time since the loop last became ready to receive or finished an event.
570    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    /// The loop owes work when it is inside an event or events are queued for
576    /// it. An idle scheduler waiting for readiness with an empty channel owes
577    /// nothing, however long ago it last ran.
578    pub fn has_pending_work(&self) -> bool {
579        // Sample the queue before the marker: receiving the last queued event
580        // publishes the marker before emptying the queue.
581        !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/// Scheduler occupants of one root, including jobs still waiting to enter
594/// their callback. Each call has a unique cancellation token, which distinguishes
595/// it from an older job that reused the same transport request ID.
596#[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/// Non-blocking scheduler explanation attached to a delayed RouteBind warning.
608#[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/// Cooperative cancellation for one cancellable executor job.
630///
631/// One atomic state machine (pending → running → committed | cancelled) is
632/// shared by the executor, the canceller, and the job. `cancel` and
633/// `try_seal_committed` race through compare-exchange on the same cell, so
634/// exactly one wins: a cancel that lands first makes the seal fail (the job
635/// must abort before mutating), and a seal that lands first makes the cancel
636/// report `RunningCommitted` (the mutation tail finishes normally). A job
637/// observes cancellation only at its own checkpoints
638/// ([`JobCancellation::cancel_requested_before_commit`]).
639#[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    /// Undo [`JobCancellation::mark_running`] for a job that is being queued
737    /// again without having committed. Returns false when a cancel already
738    /// won, in which case the job must be settled as cancelled instead.
739    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    /// Seal the job as committed. Returns `false` when a cancel already won
776    /// the race: the job must return early WITHOUT mutating, because the
777    /// canceller was told `RunningSignalled` and will discard its completion.
778    #[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    /// Move to cancelled unless the job already sealed its commit. Returns the
805    /// state the transition observed (`COMMITTED` when the seal won).
806    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    /// Request cooperative cancellation without requiring an executor actor.
843    /// Detached continuations use this after their setup job has already left
844    /// the scheduler's running-job table.
845    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    /// True when a cancel has already won the state race. A pure read: unlike
854    /// [`Self::cancel_requested_before_commit`] it never checks the root on
855    /// disk or the abandon grace and never signals, so it is safe to call
856    /// while holding `wait_lock` and from observers such as health reports.
857    pub fn cancel_already_requested(&self) -> bool {
858        self.state() == JOB_CANCEL_STATE_CANCELLED
859    }
860
861    /// True when a cancel won the state race and the job must abort.
862    ///
863    /// This also cancels the job when its root was deleted or abandoned, which
864    /// signals and so takes `wait_lock`. Never call it while holding that lock
865    /// (it is not reentrant), and keep it out of read-only observers.
866    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        // Every checkpoint observes explicit cancellation and the in-memory
883        // lifecycle signal. Only the filesystem deletion probe is bounded to
884        // one per 256 checkpoints or 50ms on each worker, whichever comes
885        // first. A weak identity prevents a new token reusing an allocation
886        // from inheriting the previous job's delay.
887        // The first running checkpoint probes again after admission: setup may
888        // have blocked before the command got a chance to observe its root.
889        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        // A deleted checkout cannot publish useful work. Check here as well as
930        // at admission so deletion during a batch does not wait for the reaper.
931        // Permission/transient I/O failures do not prove that it was deleted.
932        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    /// Sleep until cancellation is requested or the timeout expires.
949    ///
950    /// Cancellation takes the same lock before notifying, so a waiter cannot
951    /// miss a signal between its state check and the condition-variable wait.
952    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            // Only the pure state read may run under `wait_lock`: the full check
959            // can decide the root is deleted or abandoned and signal, and
960            // signalling takes this same lock. Doing that here deadlocked the
961            // waiting job and then every caller that signalled it, including
962            // the health report on the module's frame loop.
963            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/// Outcome of [`Executor::cancel_job`].
977#[derive(Debug, Clone, Copy, PartialEq, Eq)]
978pub enum JobCancelOutcome {
979    /// The job had not started; it was removed from the queue and its
980    /// completion settled with `request_cancelled`.
981    QueuedRemoved,
982    /// The job is running; its token is signalled and the job returns through
983    /// its normal completion path at the next checkpoint.
984    RunningSignalled,
985    /// The job already sealed its commit; it finishes normally and the caller
986    /// must discard its late completion.
987    RunningCommitted,
988    /// No queued or tracked job matched the token.
989    NotFound,
990}
991
992/// Result of cancelling only work whose command closure has not started.
993#[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
1005/// The cancellation token of the job running on this worker thread, when the
1006/// job was submitted through [`Executor::submit_cancellable_async`].
1007pub 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
1038/// Install a cancellable executor job's token on a continuation thread.
1039///
1040/// Executor workers install this automatically. A setup job that hands work to
1041/// a detached thread must install the same token there so existing cooperative
1042/// checkpoints keep observing route or transport abandonment.
1043pub fn install_job_cancellation(token: JobCancellation) -> JobCancellationContextGuard {
1044    JobCancellationContextGuard::install(Some(token))
1045}
1046
1047/// The writer demand of one actor as seen by a job running on it: interactive
1048/// writers still queued, and detached threads waiting to write the actor's
1049/// epoch gate (content-addressed view publication).
1050#[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
1071/// True when interactive mutating work (a route-bind configure or a tool
1072/// edit) is queued on the actor whose job runs on this worker thread, or a
1073/// detached view publication is parked waiting to write the actor's epoch.
1074///
1075/// A long maintenance job holds its actor's epoch read gate, and a queued
1076/// writer can only start once that gate is free. Maintenance that runs in
1077/// resumable steps polls this between steps and hands the actor back instead
1078/// of making the writer wait for the whole job. The parked publication counts
1079/// too: the epoch lock is task-fair, so while that thread waits every new
1080/// reader of the actor (reads, shared route binds, the next tail unit) is
1081/// held behind it, and its write is a short install once the gate is free.
1082/// Always false off an executor worker.
1083pub 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/// Make [`current_actor_writer_waiting`] report the given counter on this
1114/// thread, for tests that run a maintenance step outside an executor worker.
1115#[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
1125/// A route-bind job that can run more than once. The scheduler may admit such
1126/// a bind beside a running maintenance job or interactive readers with only a
1127/// shared hold on the actor's epoch gate; when the configure finds it must change the root, the
1128/// run is discarded and the same job is queued again as an exclusive writer.
1129pub type RepeatableJob<C> = Arc<dyn Fn(&C) -> Response + Send + Sync + 'static>;
1130
1131thread_local! {
1132    /// True while the job on this worker is a route bind holding its actor's
1133    /// epoch gate only for reading.
1134    static CURRENT_BIND_GATE_SHARED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1135    /// Set by a shared-hold bind that needs exclusive use of its actor.
1136    static EXCLUSIVE_RERUN_REQUESTED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1137}
1138
1139/// Marks the job on this worker as a shared-hold bind for its lifetime.
1140struct 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    /// True when the job asked, through [`request_exclusive_rerun`], to be run
1150    /// again with exclusive use of the actor.
1151    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
1163/// True while the job on this worker is a route bind that holds its actor's
1164/// epoch gate only for reading.
1165///
1166/// Most route binds re-attach a session to a root whose configuration is
1167/// unchanged. That rebind only reads the published configuration and records
1168/// the session in state behind its own locks, so it is safe next to readers,
1169/// and making it wait for exclusive use would park it behind a configure tail
1170/// unit that can run for many seconds on a large root, or behind a slow
1171/// interactive read for as long as that read runs. Such a bind starts with a
1172/// shared hold beside whatever already holds the gate for reading; a
1173/// configure that turns out to change the root calls
1174/// [`request_exclusive_rerun`] before its first change to actor state.
1175pub fn current_bind_gate_is_shared() -> bool {
1176    CURRENT_BIND_GATE_SHARED.with(std::cell::Cell::get)
1177}
1178
1179/// Ask for the shared-hold bind on this worker to be run again as an exclusive
1180/// writer. Returns false (and does nothing) for every other job.
1181///
1182/// The caller must return at once, without changing actor state: the executor
1183/// discards the response, frees the worker, and queues the same job at the
1184/// head of the actor's binds, where it counts as a waiting writer (so a
1185/// running configure tail steps aside at its next unit) and is admitted once
1186/// no reader or maintenance job holds the gate. The rerun starts from
1187/// scratch and observes whatever changed meanwhile. No worker ever waits for
1188/// the actor on the bind's behalf.
1189pub 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
1243/// Concurrent scheduler-dispatch executor.
1244pub 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/// A root may submit maintenance without keeping its owning executor alive.
1252/// The weak link avoids a cycle through the executor's actor context.
1253#[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            // Shutdown may leave this temporary as the last executor owner.
1282            // Other workers can depend on this worker returning, so release
1283            // the temporary off-worker rather than joining them here.
1284            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    /// Admits `job` as this root's maintenance and runs it at once on the
1299    /// calling thread, with the root's cancellation installed as the current
1300    /// job's: `cancellation` gains the root and its bind lifecycle, so a root
1301    /// unbinding cancels whatever the job starts at its checkpoints. The
1302    /// executor refuses the job, and drops it unrun, under the same rules as
1303    /// a maintenance job on a worker: the root is unbound, its folder is
1304    /// gone, its actor is not registered or failed, or the token is already
1305    /// cancelled. `false` when the executor has shut down; the caller must
1306    /// not run the work some other way, which would reactivate a retired
1307    /// root.
1308    ///
1309    /// The data layer's background work is the only caller, and its job only
1310    /// hands the work to a pool of its own threads. The job does not wait
1311    /// for a worker: a call-graph read waits on a worker for the build or
1312    /// refresh it asked for, and the scheduler keeps its last
1313    /// `interactive_reserve` general workers from maintenance. When the
1314    /// handoff was queued as maintenance, two such reads on a four-worker
1315    /// pool (one on a two-worker pool) held exactly the workers the handoff
1316    /// waited for, so the build started only after each read had given up.
1317    /// `lane` only labels the admission in the log.
1318    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        // Dropped off-worker if it turns out to be the executor's last owner.
1342        let owner = SubmissionExecutor::<C>(Some(Executor::<C> { inner }));
1343        let executor = owner.0.as_ref().unwrap();
1344        // A root stat can stall on disk I/O; probe it before taking the
1345        // scheduler lock, as a queued submission does.
1346        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        // Stop maintenance before joining workers. Queued closures must also
1414        // release their captured builders instead of surviving a stopped loop.
1415        {
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            // A job can own the last Executor handle. Its worker will exit once
1439            // this job returns; joining that same thread would panic.
1440            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    /// Set when a bind was queued again with a retry time, so the loop knows
1483    /// to look for the earliest one and wake for it.
1484    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    /// The earliest time a bind queued with a retry time becomes admissible,
1510    /// clearing `bind_retry_pending` once none is left.
1511    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    /// When the most recently admitted reader still running on `root_id`
1646    /// started, for interactive admission (see `next_interactive_lane`).
1647    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        // The bind's own configure job can hold the mutating slot while it
1711        // runs. It is not a blocker of the bind; reporting it as one would
1712        // tell the caller to wait for a different job when the bind's own
1713        // configure is what is slow.
1714        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            // Name the configure-tail stage in progress on this root, so a
1782            // bind held up by a long tail unit says which one.
1783            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    /// The running writer is a route bind that started with a shared epoch
1908    /// hold beside running maintenance or readers (see
1909    /// `current_bind_gate_is_shared`).
1910    shared_bind_inflight: bool,
1911    maintenance_commit_inflight: bool,
1912    /// Only the internal callgraph acquisition bypasses interactive capacity.
1913    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    /// Number of queued interactive mutating jobs, shared with this actor's
1924    /// running jobs through [`current_actor_writer_waiting`]. Kept equal to
1925    /// `interactive.mutating.len()` by every method that changes that queue.
1926    pub waiting_writers: Arc<AtomicUsize>,
1927    #[cfg(not(any(test, feature = "test-support")))]
1928    /// Number of queued interactive mutating jobs, shared with this actor's
1929    /// running jobs through [`current_actor_writer_waiting`]. Kept equal to
1930    /// `interactive.mutating.len()` by every method that changes that queue.
1931    waiting_writers: Arc<AtomicUsize>,
1932    #[cfg(any(test, feature = "test-support"))]
1933    /// Detached threads (content-addressed view publication) waiting to write
1934    /// this actor's epoch gate. Reported through
1935    /// [`current_actor_writer_waiting`].
1936    pub detached_writers: Arc<AtomicUsize>,
1937    #[cfg(not(any(test, feature = "test-support")))]
1938    /// Detached threads (content-addressed view publication) waiting to write
1939    /// this actor's epoch gate. Reported through
1940    /// [`current_actor_writer_waiting`].
1941    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            // Provider and call-ledger jobs are admitted by their own passes.
2002            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        // Maintenance must not start while interactive mutating work (tool
2032        // mutations, route binds) waits: a maintenance job that takes the
2033        // actor's writer slot would push the interactive writer behind it.
2034        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    /// Queue a job ahead of everything else in its lane. `order` pairs its
2148    /// lane entries with each lane's queue first-to-first, so the entry goes
2149    /// to the front as well.
2150    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    /// The route bind the bind pass would admit next.
2156    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    /// Interactive admission order: a starved writer preempts everything so
2186    /// its deadline survives. A queued RouteBind configure counts as starved
2187    /// after `BIND_PROMOTION_AGE`, any other writer after
2188    /// `INTERACTIVE_WRITER_PROMOTION_AGE`. Otherwise pure reads go first (they
2189    /// overlap each other and never barrier the actor), then remaining lanes
2190    /// in arrival order. Maintenance keeps strict arrival order via
2191    /// `front_lane`.
2192    ///
2193    /// `newest_reader_started_at` is when the most recently admitted reader
2194    /// still running on this actor started. A writer is not promoted while
2195    /// every running reader started before it queued and has run for
2196    /// `READER_STUCK_CENSUS_AGE`: the writer cannot run until those readers
2197    /// end, which may be never, so holding back new reads would only add an
2198    /// outage of every read on the root to the writer's own wait.
2199    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            // Also stops NEW readers from being admitted on this actor while
2219            // the promoted writer waits for in-flight readers to drain.
2220            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        // Keep `order` consistent with per-lane queues when admission picks a
2239        // lane other than the arrival-order head: remove the FIRST occurrence
2240        // of the chosen lane from `order`, not necessarily the front.
2241        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    /// Remove only redundant idempotent drains while preserving survivor order.
2260    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    /// Remove the oldest queued route-bind configure from the Mutating lane,
2339    /// even when other mutating jobs are ahead of it. Keeps `order` paired
2340    /// with the lane queue the same way `remove_cancellable` does.
2341    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    /// Remove the queued job carrying this exact cancellation token.
2362    ///
2363    /// `order` holds one lane entry per push, and per-lane entries pair FIFO
2364    /// with the lane queue: the k-th occurrence of a lane in `order`
2365    /// corresponds to the k-th element of that lane's queue. Removing the
2366    /// FIRST matching order entry for a job deeper in its lane queue would
2367    /// shift the pairing and reorder the survivors, so the occurrence at the
2368    /// job's own queue position is removed instead.
2369    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    /// Queue time of the oldest queued route-bind configure, if any.
2405    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    /// Present for a route bind that may run beside maintenance with a shared
2471    /// hold and be queued again (see [`RepeatableJob`]).
2472    pub rerun: Option<RepeatableJob<C>>,
2473    #[cfg(not(any(test, feature = "test-support")))]
2474    /// Present for a route bind that may run beside maintenance with a shared
2475    /// hold and be queued again (see [`RepeatableJob`]).
2476    rerun: Option<RepeatableJob<C>>,
2477    #[cfg(any(test, feature = "test-support"))]
2478    /// A bind queued again after a shared-hold attempt: it is admitted only
2479    /// with exclusive use of the actor.
2480    pub force_exclusive: bool,
2481    #[cfg(not(any(test, feature = "test-support")))]
2482    /// A bind queued again after a shared-hold attempt: it is admitted only
2483    /// with exclusive use of the actor.
2484    force_exclusive: bool,
2485    #[cfg(any(test, feature = "test-support"))]
2486    /// Not admissible before this time: a bind that found the epoch gate
2487    /// held by a detached writer backs off instead of waiting on a worker.
2488    pub not_before: Option<Instant>,
2489    #[cfg(not(any(test, feature = "test-support")))]
2490    /// Not admissible before this time: a bind that found the epoch gate
2491    /// held by a detached writer backs off instead of waiting on a worker.
2492    not_before: Option<Instant>,
2493    #[cfg(any(test, feature = "test-support"))]
2494    /// How many times this bind found the gate held by a detached writer.
2495    pub exclusive_attempts: u32,
2496    #[cfg(not(any(test, feature = "test-support")))]
2497    /// How many times this bind found the gate held by a detached writer.
2498    exclusive_attempts: u32,
2499    #[cfg(any(test, feature = "test-support"))]
2500    /// Checked before metadata starts, so unbind or reconfiguration rejects
2501    /// queued or dispatched work from an older configure generation.
2502    pub provider_generation: Option<u64>,
2503    #[cfg(not(any(test, feature = "test-support")))]
2504    /// Checked before metadata starts, so unbind or reconfiguration rejects
2505    /// queued or dispatched work from an older configure generation.
2506    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    /// The actor's queued-interactive-writer counter, exposed to the running
2644    /// job through [`current_actor_writer_waiting`].
2645    waiting_writers: Arc<AtomicUsize>,
2646    /// The actor's parked detached writers, also reported through
2647    /// [`current_actor_writer_waiting`].
2648    detached_writers: Arc<AtomicUsize>,
2649    /// A route bind admitted while a maintenance job or reader held the epoch
2650    /// gate: it runs with a shared hold (see [`current_bind_gate_is_shared`]).
2651    shared_bind_gate: bool,
2652    /// How to run this bind again if it has to be queued again.
2653    rerun: Option<RepeatableJob<C>>,
2654    /// When the job first queued; a requeued bind keeps its age so its
2655    /// promotion over new readers is not reset.
2656    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    /// A shared-hold bind that must run again as an exclusive writer. The
2682    /// scheduler queues it at the head of the actor's binds in the same step
2683    /// that releases the finished run's reservation.
2684    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        // A bind waiting out a retry time has no event to wake the loop, so
2757        // the loop wakes itself when the earliest one comes due.
2758        let event = if loop_liveness.wait_for_event(next_retry_at) {
2759            // Select readiness can be spurious. Do not block with the active
2760            // marker set when there is actually no event to process.
2761            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(&current, &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            // A cancel that landed after the worker returned the token to
2949            // pending, but before this event, found the job neither queued
2950            // nor able to observe it. Settle it here, under the scheduler
2951            // lock that `cancel_job` also takes, instead of queuing cancelled
2952            // writer demand behind whatever holds the actor.
2953            _ 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                // Pending-bind diagnostics read the configure phases; name the
2966                // wait instead of leaving the phase the discarded run reached.
2967                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        // Route binds first, on any idle worker including the bind reserve:
3007        // subc refuses the module once a bind relay exceeds its deadline, so a
3008        // bind must never wait for a DRR turn behind other roots' work.
3009        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
3159/// Admit every queued route-bind configure whose actor can take a writer now,
3160/// oldest bind first. Binds skip the DRR deficit and the per-actor interactive
3161/// cap: a configure is short, and waiting a round-robin turn behind dozens of
3162/// busy roots is what pushed binds past the daemon's relay deadline.
3163fn 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
3221/// Provider work uses the same root queues, completion and cancellation machinery
3222/// as other jobs, but never waits for an index lane's capacity or epoch gate.
3223fn 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
3260/// Call-ledger jobs are admitted ahead of the interactive deficit round-robin
3261/// (DRR) pass, on general workers, without the actor's read cap, epoch gate or
3262/// writer barrier: a keyed reply cannot be written until its settlement
3263/// commits, so it must not wait for the reads queued or running on its root.
3264/// Each actor runs one at a time, in submission order.
3265fn 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
3302/// Record an admitted job as running and hand it to a worker. Returns false
3303/// when the worker channel is closed.
3304fn 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    // Running binds and metadata have already reduced idle_workers. Hold back
3367    // only the unused part of each reservation, or each running bind would also
3368    // remove a general-pool slot. All jobs still use one worker channel.
3369    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/// Which dispatch pass is asking an actor for a job.
3393#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3394enum AdmissionPass {
3395    /// The route-bind pass: only a queued route-bind configure, taken from the
3396    /// Mutating lane ahead of any other writer queued before it. This pass may
3397    /// use the reserved bind workers, so it must never admit anything else.
3398    Bind,
3399    /// Provider jobs bypass ordinary per-root deficit scheduling and do not
3400    /// acquire the index epoch gate.
3401    ProviderMetadata,
3402    /// Call-ledger jobs: like provider jobs they bypass the deficit round-robin
3403    /// pass and the epoch gate, but they use general workers.
3404    CallLedger,
3405    /// The ordinary DRR pass for one job class.
3406    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        // Only the bind itself: an edit queued ahead of it waits for the
3440        // general pool (it is not admitted here, so it can never occupy a
3441        // reserved bind worker), and the bind runs first.
3442        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    // A bind that runs with a shared hold (see `current_bind_gate_is_shared`)
3459    // blocks other writers and maintenance like any running writer, but
3460    // readers may keep coming: it never waits for exclusive use in place.
3461    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    // A bind backing off from a detached writer waits out its retry time.
3473    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    // Only a repeatable bind that has not already been sent back may start
3490    // with a shared hold: a run that finds it must change the root has to be
3491    // able to hand its worker back and run again.
3492    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    // MaintenanceCommit and callgraph acquisition use global maintenance capacity and
3498    // must not consume the per-actor slots reserved for interactive work. This
3499    // matters when a two-worker executor has actor_cap=1: the global reserve
3500    // leaves one worker idle, and this accounting makes that worker reachable
3501    // by an interactive request for the same actor.
3502    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        // A bind skips the per-actor interactive cap: HeavyInit jobs count
3528        // toward that cap without holding the epoch gate, and the writer only
3529        // needs the gate itself to be free. A repeatable bind also does not
3530        // wait for whatever holds the gate for reading (a configure tail,
3531        // whose single units can run for seconds on a large root, or
3532        // interactive readers, which are usually short but are not bounded:
3533        // one slow read would otherwise hold every bind of its root until the
3534        // bind deadline). It starts beside them with a shared hold, which is
3535        // all a rebind of an unchanged root needs, the same hold readers
3536        // admitted after it already overlap. A run that must change the root
3537        // is sent back and queued again as an exclusive writer, which does
3538        // wait for readers and maintenance. `writer_inflight` above still
3539        // serializes binds and other writers per root.
3540        Lane::Mutating => {
3541            bind_may_share || (!has_epoch_reader && (bind_pass || actor_has_interactive_capacity))
3542        }
3543        // This lane has separate global and per-actor bounds: maintenance_cap
3544        // reserves workers globally, and the boolean prevents same-actor
3545        // maintenance from stacking without consuming an interactive slot.
3546        Lane::MaintenanceCommit => !actor.maintenance_commit_inflight,
3547        Lane::ProviderMetadata => !actor.provider_inflight,
3548        // Short database bookkeeping, outside the per-actor interactive cap:
3549        // one at a time keeps each actor's ledger writes in submission order.
3550        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    // The bind pass runs outside DRR, so it does not spend the actor's turn.
3573    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
3694/// Rebuild a shared-hold bind that must run again as a queued exclusive
3695/// writer, keeping its completion, cancellation token, and original age.
3696/// Returns the response to send instead when the bind was cancelled meanwhile.
3697fn 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    // The token went to running when the first attempt started. Put it back
3709    // to pending so the queued job is cancellable exactly like any other
3710    // queued job; a cancel that already landed wins.
3711    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    // Root and lifecycle probes can block. Keep them on the worker; completion
3720    // still checks the atomic cancellation state under the scheduler lock so a
3721    // cancel in the handoff window cannot leave queued writer demand behind.
3722    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/// A request id and callback for one worker-to-scheduler requeue handoff.
3757#[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/// Run `hook` after returning `request_id`'s token to pending, before the
3764/// worker's full cancellation probe.
3765#[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/// Run `hook` after the worker's cancellation probe passes, before the
3794/// scheduler receives `request_id`'s requeue.
3795#[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! {
3822/// How one dispatched job ended on its worker.
3823enum LaneRun {
3824    Finished(Response),
3825    /// A repeatable bind that must run again as an exclusive writer; its
3826    /// response (if it ran at all) is discarded. `retry_after` delays the
3827    /// next admission when a detached writer held the epoch gate.
3828    RerunExclusive {
3829        retry_after: Option<Duration>,
3830    },
3831}
3832}
3833
3834/// Delay before a repeatable bind that found the epoch gate held by a
3835/// detached writer is admitted again: 10 ms, doubling, capped at 200 ms.
3836fn detached_writer_backoff(attempts: u32) -> Duration {
3837    Duration::from_millis(10u64.saturating_mul(1u64 << attempts.min(5)).min(200))
3838}
3839
3840/// Poll interval for epoch waits that must stay responsive to cancellation.
3841const 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            // Only the start decision holds the root lifecycle lock. Once a
3890            // provider may have committed policy, unbind must not discard it.
3891            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        // Cache and index builders reject stale generations and serialize
3929        // publication internally. Taking the actor write gate after the command
3930        // constructs its response would delay completion behind maintenance and
3931        // park later readers behind an otherwise unnecessary writer.
3932        Lane::HeavyInit => run(job),
3933        Lane::ProviderMetadata => {
3934            let _config = run_job.ctx.pin_config();
3935            run(job)
3936        }
3937        // Call-ledger writes go through the database's own mutex and touch no
3938        // index state, so they take no epoch gate.
3939        Lane::CallLedger => run(job),
3940        Lane::Mutating if run_job.shared_bind_gate => {
3941            // A cancelled bind never touches the gate.
3942            if cancel_requested() {
3943                return LaneRun::Finished(cancelled_before_execution());
3944            }
3945            // The epoch lock is task-fair: a reader waits behind any parked
3946            // writer (a detached view publication, typically) even while only
3947            // readers hold it. Never wait here; a bind that cannot take the
3948            // shared hold at once is queued again as an exclusive writer.
3949            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        // An exclusive repeatable bind is admitted only when no scheduler-
3960        // tracked reader or maintenance job holds the gate, so a held gate
3961        // here means a detached view publication. Its write can outlast one
3962        // install (it takes the process-wide publication lock while holding
3963        // the gate), so the bind backs off in the queue rather than wait on
3964        // a worker.
3965        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            // Same gate as reads: the job's mutations are protected by the
3992            // touched subsystems' own locks, and holding only the read gate
3993            // lets interactive PureReads overlap freely.
3994            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;