1use std::cell::RefCell;
4use std::collections::{BTreeMap, VecDeque};
5use std::path::Path;
6use std::sync::{Arc, LazyLock, Mutex, MutexGuard};
7use std::thread::ThreadId;
8use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
9
10use serde::Serialize;
11
12const LIST_CAP: usize = 20;
13const RATE_WINDOW: Duration = Duration::from_secs(300);
14static REGISTRY: LazyLock<Arc<Registry>> = LazyLock::new(|| Arc::new(Registry::default()));
15thread_local! {
16 static CURRENT: RefCell<Option<Arc<Mutex<Entry>>>> = const { RefCell::new(None) };
17}
18
19fn lock<T>(value: &Mutex<T>) -> MutexGuard<'_, T> {
20 value
21 .lock()
22 .unwrap_or_else(std::sync::PoisonError::into_inner)
23}
24
25#[derive(Debug, Default)]
26struct State {
27 next_id: u64,
28 running: BTreeMap<u64, Arc<Mutex<Entry>>>,
29 queued: BTreeMap<u64, Arc<Mutex<Entry>>>,
30}
31
32#[derive(Debug, Default)]
33pub(crate) struct Registry(Mutex<State>);
34
35#[derive(Debug)]
36struct Entry {
37 root: String,
38 root_label: String,
39 kind: String,
40 phase: &'static str,
41 started: Instant,
42 started_at_ms: u64,
43 done: u64,
44 total: Option<u64>,
45 chunks_embedded: Option<u64>,
46 samples: VecDeque<(Instant, u64)>,
47 thread: ThreadId,
48 fallback: bool,
49 shadowed: bool,
50 cancellation: Option<crate::executor::JobCancellation>,
51}
52
53#[derive(Debug, Serialize)]
54pub struct Running {
55 pub root: String,
56 pub root_label: String,
57 pub kind: String,
58 pub phase: &'static str,
59 pub started_at_ms: u64,
60 pub done: u64,
61 pub total: Option<u64>,
62 #[serde(skip_serializing_if = "Option::is_none")]
63 pub chunks_embedded: Option<u64>,
64 pub rate_per_minute: Option<f64>,
65 pub eta_seconds: Option<f64>,
66 pub age_seconds: f64,
67}
68
69#[derive(Debug, Serialize)]
70pub struct Queued {
71 pub root: String,
72 pub kind: String,
73 pub waited_seconds: f64,
74}
75
76#[derive(Debug, Serialize)]
77pub struct Snapshot {
78 pub running: Vec<Running>,
79 pub queued: Vec<Queued>,
80 pub warming_roots: u64,
81 #[serde(skip_serializing_if = "Omitted::is_empty")]
82 pub omitted: Omitted,
83}
84
85#[derive(Debug, Serialize)]
86pub struct Omitted {
87 pub running: usize,
88 pub queued: usize,
89}
90
91impl Omitted {
92 fn is_empty(&self) -> bool {
93 self.running == 0 && self.queued == 0
94 }
95}
96
97impl Entry {
100 fn render(&self, now: Instant) -> Running {
101 let baseline = self
102 .samples
103 .iter()
104 .find(|(at, _)| now.saturating_duration_since(*at) <= RATE_WINDOW);
105 let rate = baseline.and_then(|(at, done)| {
106 let elapsed = now.saturating_duration_since(*at).as_secs_f64();
107 let delta = self.done.saturating_sub(*done);
108 (elapsed >= 1.0 && delta > 0).then(|| delta as f64 * 60.0 / elapsed)
109 });
110 Running {
111 root: self.root.clone(),
112 root_label: self.root_label.clone(),
113 kind: self.kind.clone(),
114 phase: self.phase,
115 started_at_ms: self.started_at_ms,
116 done: self.done,
117 total: self.total,
118 chunks_embedded: self.chunks_embedded,
119 rate_per_minute: rate,
120 eta_seconds: self
121 .total
122 .zip(rate)
123 .map(|(total, rate)| total.saturating_sub(self.done) as f64 * 60.0 / rate),
124 age_seconds: now.saturating_duration_since(self.started).as_secs_f64(),
125 }
126 }
127
128 fn advance(&mut self, done: u64, now: Instant) {
129 if done > self.done {
130 if let Some(token) = &self.cancellation {
131 token.report_progress();
132 }
133 }
134 while self
137 .samples
138 .front()
139 .is_some_and(|(at, _)| now.saturating_duration_since(*at) > RATE_WINDOW)
140 {
141 self.samples.pop_front();
142 }
143 if self
144 .samples
145 .back()
146 .is_none_or(|(at, _)| now.saturating_duration_since(*at) >= Duration::from_secs(1))
147 {
148 self.samples.push_back((now, self.done));
149 }
150 self.done = done;
151 }
152}
153
154#[rustfmt::skip]
155test_support_visibility! {
156#[derive(Debug)]
157pub(crate) struct Job {
158 registry: Arc<Registry>,
159 id: u64,
160 queued: bool,
161 entry: Arc<Mutex<Entry>>,
162}
163}
164
165impl Registry {
166 fn register(self: &Arc<Self>, root: &str, kind: &str, queued: bool, fallback: bool) -> Job {
167 let now = Instant::now();
168 let cancellation = crate::executor::current_job_cancellation();
169 let mut samples = VecDeque::with_capacity(301);
170 samples.push_back((now, 0));
171 let entry = Arc::new(Mutex::new(Entry {
172 root: root.to_owned(),
173 root_label: root_label(Path::new(root)),
174 kind: kind.to_owned(),
175 phase: "starting",
176 started: now,
177 started_at_ms: SystemTime::now()
178 .duration_since(UNIX_EPOCH)
179 .unwrap_or_default()
180 .as_millis()
181 .min(u64::MAX as u128) as u64,
182 done: 0,
183 total: None,
184 chunks_embedded: None,
185 samples,
186 thread: std::thread::current().id(),
187 fallback,
188 shadowed: false,
189 cancellation: cancellation.clone(),
190 }));
191 let mut state = lock(&self.0);
192 if !queued && !fallback {
196 for old in state.running.values() {
197 let mut old = lock(old);
198 if old.fallback && old.thread == std::thread::current().id() {
199 old.shadowed = true;
200 old.root = root.to_owned();
201 old.root_label = lock(&entry).root_label.clone();
202 old.kind = kind.to_owned();
203 }
204 }
205 }
206 state.next_id += 1;
207 let id = state.next_id;
208 let entries = if queued {
209 &mut state.queued
210 } else {
211 &mut state.running
212 };
213 if !cancellation.is_some_and(|token| token.cancel_already_requested()) {
214 entries.insert(id, Arc::clone(&entry));
215 }
216 Job {
217 registry: Arc::clone(self),
218 id,
219 queued,
220 entry,
221 }
222 }
223
224 fn cancel_root(&self, root: &str) {
225 let mut state = lock(&self.0);
226 state.running.retain(|_, entry| lock(entry).root != root);
227 state.queued.retain(|_, entry| lock(entry).root != root);
228 }
229
230 fn cancel_token(&self, key: usize) {
231 let mut state = lock(&self.0);
232 let keep = |_: &u64, entry: &mut Arc<Mutex<Entry>>| {
233 !lock(entry)
234 .cancellation
235 .as_ref()
236 .is_some_and(|token| token.progress_key() == key)
237 };
238 state.running.retain(keep);
239 state.queued.retain(keep);
240 }
241
242 fn snapshot(&self, warming_roots: u64, now: Instant) -> Snapshot {
243 let state = lock(&self.0);
244 let running = state.running.values().filter(|entry| !lock(entry).shadowed);
245 let running_count = running.clone().count();
246 Snapshot {
247 running: running
248 .take(LIST_CAP)
249 .map(|entry| lock(entry).render(now))
250 .collect(),
251 queued: state
252 .queued
253 .values()
254 .take(LIST_CAP)
255 .map(|entry| {
256 let entry = lock(entry);
257 Queued {
258 root: entry.root.clone(),
259 kind: entry.kind.clone(),
260 waited_seconds: now.saturating_duration_since(entry.started).as_secs_f64(),
261 }
262 })
263 .collect(),
264 warming_roots,
265 omitted: Omitted {
266 running: running_count.saturating_sub(LIST_CAP),
267 queued: state.queued.len().saturating_sub(LIST_CAP),
268 },
269 }
270 }
271}
272
273fn root_label(root: &Path) -> String {
274 let basename = root
275 .file_name()
276 .unwrap_or(root.as_os_str())
277 .to_string_lossy();
278 let components: Vec<_> = root.components().map(|c| c.as_os_str()).collect();
283 let in_alfonso_worktrees = components
284 .windows(2)
285 .any(|pair| pair[0] == "alfonso" && pair[1] == "worktrees");
286 if in_alfonso_worktrees {
287 let marker = root.join(".git");
288 if std::fs::metadata(&marker).is_ok_and(|m| m.is_file() && m.len() <= 4096) {
289 if let Ok(marker) = std::fs::read_to_string(marker) {
290 if let Some(gitdir) = marker.trim().strip_prefix("gitdir: ") {
291 let gitdir = root.join(gitdir);
292 if let Some(repo) = gitdir
293 .ancestors()
294 .find(|p| p.file_name().is_some_and(|n| n == ".git"))
295 .and_then(Path::parent)
296 .and_then(Path::file_name)
297 {
298 return format!("{} (worker {})", repo.to_string_lossy(), basename)
299 .replace(['\n', '\r'], " ");
300 }
301 }
302 }
303 }
304 }
305 basename.replace(['\n', '\r'], " ")
306}
307
308impl Drop for Job {
309 fn drop(&mut self) {
310 let mut state = lock(&self.registry.0);
311 let entries = if self.queued {
312 &mut state.queued
313 } else {
314 &mut state.running
315 };
316 entries.remove(&self.id);
317 if !self.queued && !lock(&self.entry).fallback {
318 let thread = lock(&self.entry).thread;
319 let has_detail = state.running.values().any(|entry| {
320 let entry = lock(entry);
321 !entry.fallback && entry.thread == thread
322 });
323 if !has_detail {
324 for entry in state.running.values() {
325 let mut entry = lock(entry);
326 if entry.fallback && entry.thread == thread {
327 entry.shadowed = false;
328 entry.phase = "finishing";
329 entry.done = 0;
330 entry.total = None;
331 entry.samples.clear();
332 }
333 }
334 }
335 }
336 }
337}
338
339pub(crate) fn admitted(root: &str, kind: &str) -> Option<Job> {
340 if CURRENT.with(|current| current.borrow().is_some()) {
341 return None;
342 }
343 Some(REGISTRY.register(root, kind, false, true))
344}
345
346#[rustfmt::skip]
347test_support_visibility! {
348
349pub(crate) fn queued(root: &str, kind: &str) -> Job {
350 REGISTRY.register(root, kind, true, false)
351}
352}
353
354pub struct Scope {
357 _job: Job,
358 previous: Option<Arc<Mutex<Entry>>>,
359 _thread_bound: std::marker::PhantomData<std::rc::Rc<()>>,
360}
361
362#[derive(Clone, Copy)]
365pub enum StartLog {
366 Info,
367 #[cfg(any(test, feature = "test-support"))]
368 Quiet,
369}
370
371fn start_message(root: &Path, kind: &str, total: Option<usize>, log: StartLog) -> Option<String> {
372 match log {
373 #[cfg(any(test, feature = "test-support"))]
374 StartLog::Quiet => None,
375 StartLog::Info => Some(format!(
376 "indexing start root={} kind={} total={:?}",
377 root.display(),
378 kind,
379 total
380 )),
381 }
382}
383
384pub fn start(root: &Path, kind: &str, total: Option<usize>, log: StartLog) -> Scope {
385 let job = REGISTRY.register(&root.to_string_lossy(), kind, false, false);
386 lock(&job.entry).total = total.map(|n| n as u64);
387 if let Some(message) = start_message(root, kind, total, log) {
388 crate::slog_info!("{}", message);
389 }
390 let previous = CURRENT.with(|current| current.replace(Some(Arc::clone(&job.entry))));
391 Scope {
392 _job: job,
393 previous,
394 _thread_bound: std::marker::PhantomData,
395 }
396}
397
398impl Drop for Scope {
399 fn drop(&mut self) {
400 CURRENT.with(|current| current.replace(self.previous.take()));
401 }
402}
403
404pub fn phase(phase: &'static str, total: Option<usize>) {
405 CURRENT.with(|current| {
406 if let Some(entry) = current.borrow().as_ref() {
407 let mut entry = lock(entry);
408 if entry.phase != phase {
409 if let Some(token) = &entry.cancellation {
410 token.report_progress();
411 }
412 entry.done = 0;
413 entry.samples.clear();
414 entry.samples.push_back((Instant::now(), 0));
415 }
416 entry.phase = phase;
417 entry.total = total.map(|n| n as u64);
418 }
419 });
420}
421
422pub fn advance(files: usize) {
423 CURRENT.with(|current| {
424 if let Some(entry) = current.borrow().as_ref() {
425 let mut entry = lock(entry);
426 let done = entry.done.saturating_add(files as u64);
427 entry.advance(done, Instant::now());
428 }
429 });
430}
431
432pub struct Counter(Arc<Mutex<Entry>>);
433impl Counter {
434 pub fn advance(&self, files: usize) {
435 let mut entry = lock(&self.0);
436 let done = entry.done.saturating_add(files as u64);
437 entry.advance(done, Instant::now());
438 }
439}
440
441pub fn counter() -> Option<Counter> {
442 CURRENT.with(|current| {
443 current
444 .borrow()
445 .as_ref()
446 .map(|entry| Counter(Arc::clone(entry)))
447 })
448}
449
450pub fn embedded(chunks: usize) {
451 CURRENT.with(|current| {
452 if let Some(entry) = current.borrow().as_ref() {
453 let mut entry = lock(entry);
454 entry.chunks_embedded = Some(entry.chunks_embedded.unwrap_or(0) + chunks as u64);
455 if chunks > 0 {
456 if let Some(token) = &entry.cancellation {
457 token.report_progress();
458 }
459 }
460 }
461 });
462}
463
464pub fn cancel_root(root: &Path) {
465 REGISTRY.cancel_root(&root.to_string_lossy());
466}
467pub(crate) fn cancel_token(key: usize) {
468 REGISTRY.cancel_token(key);
469}
470pub fn snapshot(warming_roots: u64) -> Snapshot {
471 REGISTRY.snapshot(warming_roots, Instant::now())
472}
473
474#[cfg(any(test, feature = "test-support"))]
477pub fn snapshot_for_root(root: &Path, warming_roots: u64) -> Snapshot {
478 snapshot_for_roots(&[root], warming_roots)
479}
480
481#[cfg(any(test, feature = "test-support"))]
484pub fn snapshot_for_roots(roots: &[&Path], warming_roots: u64) -> Snapshot {
485 let roots = roots
486 .iter()
487 .map(|root| root.to_string_lossy())
488 .collect::<Vec<_>>();
489 let owned = |root: &str| roots.iter().any(|owned| owned == root);
490 let now = Instant::now();
491 let state = lock(®ISTRY.0);
492 Snapshot {
493 running: state
494 .running
495 .values()
496 .filter_map(|entry| {
497 let entry = lock(entry);
498 (owned(&entry.root) && !entry.shadowed).then(|| entry.render(now))
499 })
500 .collect(),
501 queued: state
502 .queued
503 .values()
504 .filter_map(|entry| {
505 let entry = lock(entry);
506 owned(&entry.root).then(|| Queued {
507 root: entry.root.clone(),
508 kind: entry.kind.clone(),
509 waited_seconds: now.saturating_duration_since(entry.started).as_secs_f64(),
510 })
511 })
512 .collect(),
513 warming_roots,
514 omitted: Omitted {
515 running: 0,
516 queued: 0,
517 },
518 }
519}
520
521#[cfg(test)]
522mod tests {
523 use super::*;
524
525 #[test]
526 fn quiet_refreshes_do_not_emit_info_start_messages() {
527 assert!(start_message(
528 Path::new("/repo"),
529 "callgraph refresh",
530 Some(1),
531 StartLog::Quiet
532 )
533 .is_none());
534 assert!(start_message(
535 Path::new("/repo"),
536 "view publication",
537 None,
538 StartLog::Quiet
539 )
540 .is_none());
541 assert!(
542 start_message(Path::new("/repo"), "callgraph build", None, StartLog::Info)
543 .unwrap()
544 .contains("indexing start root=/repo kind=callgraph build total=None")
545 );
546 }
547
548 #[test]
549 fn progress_and_recent_rate_are_measured() {
550 let registry = Arc::new(Registry::default());
551 let job = registry.register("/repo", "semantic fill", false, false);
552 let now = lock(&job.entry).started;
553 lock(&job.entry).total = Some(100);
554 lock(&job.entry).advance(20, now + Duration::from_secs(60));
555 let snapshot = registry.snapshot(3, now + Duration::from_secs(60));
556 let row = &snapshot.running[0];
557 assert_eq!(row.done, 20);
558 assert_eq!(row.total, Some(100));
559 assert_eq!(row.rate_per_minute, Some(20.0));
560 assert_eq!(row.eta_seconds, Some(240.0));
561 assert_eq!(row.age_seconds, 60.0);
562 assert!(registry
563 .snapshot(3, now + RATE_WINDOW + Duration::from_secs(61))
564 .running[0]
565 .eta_seconds
566 .is_none());
567 }
568
569 #[test]
570 fn unknown_total_and_unmeasured_rate_are_null() {
571 let registry = Arc::new(Registry::default());
572 let job = registry.register("/repo", "walk", false, false);
573 let value = serde_json::to_value(registry.snapshot(0, Instant::now())).unwrap();
574 assert!(value["running"][0]["total"].is_null());
575 assert!(value["running"][0]["rate_per_minute"].is_null());
576 assert!(value["running"][0]["eta_seconds"].is_null());
577 let now = lock(&job.entry).started;
578 lock(&job.entry).advance(20, now + Duration::from_secs(60));
579 let row = registry
580 .snapshot(0, now + Duration::from_secs(60))
581 .running
582 .remove(0);
583 assert_eq!(row.rate_per_minute, Some(20.0));
584 assert_eq!(row.total, None);
585 assert_eq!(
586 row.eta_seconds, None,
587 "a rate alone does not determine an ETA"
588 );
589 }
590
591 #[test]
592 fn empty_omission_counts_are_not_serialized() {
593 let snapshot = Snapshot {
594 running: Vec::new(),
595 queued: Vec::new(),
596 warming_roots: 0,
597 omitted: Omitted {
598 running: 0,
599 queued: 0,
600 },
601 };
602 let value = serde_json::to_value(snapshot).unwrap();
603 assert!(value.get("omitted").is_none());
604
605 let snapshot = Snapshot {
606 running: Vec::new(),
607 queued: Vec::new(),
608 warming_roots: 0,
609 omitted: Omitted {
610 running: 2,
611 queued: 3,
612 },
613 };
614 let value = serde_json::to_value(snapshot).unwrap();
615 assert_eq!(value["omitted"]["running"], 2);
616 assert_eq!(value["omitted"]["queued"], 3);
617 }
618
619 #[test]
620 fn worker_checkout_labels_name_the_repository_and_worker() {
621 let fixture = tempfile::tempdir().unwrap();
622 let repository = fixture.path().join("prefrontal");
623 let gitdir = repository.join(".git/worktrees/bg_1a2b");
624 let checkout = fixture.path().join("alfonso/worktrees/task-123/bg_1a2b");
625 std::fs::create_dir_all(&gitdir).unwrap();
626 std::fs::create_dir_all(&checkout).unwrap();
627 std::fs::write(
628 checkout.join(".git"),
629 format!("gitdir: {}", gitdir.display()),
630 )
631 .unwrap();
632
633 assert_eq!(root_label(&checkout), "prefrontal (worker bg_1a2b)");
634 }
635
636 #[test]
637 fn finished_job_is_removed() {
638 let registry = Arc::new(Registry::default());
639 let job = registry.register("/repo", "build", false, false);
640 assert_eq!(registry.snapshot(0, Instant::now()).running.len(), 1);
641 drop(job);
642 assert!(registry.snapshot(0, Instant::now()).running.is_empty());
643 let permit = registry.register("unknown", "unclassified", false, true);
644 let detail = registry.register("/repo", "build", false, false);
645 let snapshot = registry.snapshot(0, Instant::now());
646 assert_eq!(
647 snapshot.running.len(),
648 1,
649 "admission must not duplicate detailed work"
650 );
651 assert_eq!(snapshot.running[0].root, "/repo");
652 drop(detail);
653 let snapshot = registry.snapshot(0, Instant::now());
654 assert_eq!(
655 snapshot.running.len(),
656 1,
657 "post-build persistence still holds the permit"
658 );
659 assert_eq!(snapshot.running[0].phase, "finishing");
660 assert_eq!(snapshot.running[0].total, None);
661 drop(permit);
662 assert!(registry.snapshot(0, Instant::now()).running.is_empty());
663 }
664
665 #[test]
666 fn cancelled_root_removes_running_and_queued_without_resurrection() {
667 let registry = Arc::new(Registry::default());
668 let job = registry.register("/repo", "build", false, false);
669 let _queued = registry.register("/repo", "fill", true, false);
670 let _other = registry.register("/other", "fill", true, false);
671 registry.cancel_root("/repo");
672 lock(&job.entry).advance(1, Instant::now());
673 let snapshot = registry.snapshot(0, Instant::now());
674 assert!(snapshot.running.is_empty());
675 assert_eq!(snapshot.queued.len(), 1);
676 assert_eq!(snapshot.queued[0].root, "/other");
677 }
678
679 #[test]
680 fn lists_are_capped_and_count_omissions() {
681 let registry = Arc::new(Registry::default());
682 let mut jobs = Vec::new();
683 for _ in 0..23 {
684 jobs.push(registry.register("/repo", "build", false, false));
685 jobs.push(registry.register("/repo", "build", true, false));
686 }
687 let snapshot = registry.snapshot(49, Instant::now());
688 assert_eq!(snapshot.running.len(), 20);
689 assert_eq!(snapshot.queued.len(), 20);
690 assert_eq!(snapshot.omitted.running, 3);
691 assert_eq!(snapshot.omitted.queued, 3);
692 assert_eq!(snapshot.warming_roots, 49);
693 }
694
695 #[test]
696 fn token_cancellation_removes_scoped_work_immediately() {
697 let token = crate::executor::JobCancellation::new();
698 let _token = crate::executor::install_job_cancellation(token.clone());
699 let fixture = tempfile::tempdir().unwrap();
700 let root = fixture.path();
701 let _job = start(root, "fill", Some(10), StartLog::Quiet);
702 let _queued = queued(&root.to_string_lossy(), "other");
703 assert!(snapshot_for_root(root, 0)
704 .running
705 .iter()
706 .any(|job| job.root == root.to_string_lossy()));
707 token.request_cancel();
708 advance(1);
709 assert!(!snapshot_for_root(root, 0)
710 .running
711 .iter()
712 .any(|job| job.root == root.to_string_lossy()));
713 assert!(!snapshot_for_root(root, 0)
714 .queued
715 .iter()
716 .any(|job| job.root == root.to_string_lossy()));
717 }
718}