返回 CodeWhale
gc.rs
根目录 / crates / plugins / src / registry / gc.rs
1 //! Plugin-state garbage collection (`/plugin doctor`).
2 //!
3 //! Every build materializes its own built-in snapshot and, because a plugin id
4 //! is bound to its root path, gets its own `state.json` record. Nothing ever
5 //! retired the old ones: a developer home collects a record and a snapshot per
6 //! build, plus inert workspace records whose workspace is long gone. This
7 //! module retires them without ever deciding on evidence it does not have.
8 //!
9 //! Safety rules, in the order they bind:
10 //!
11 //! * **Fail closed.** A state file that cannot be parsed aborts the run before
12 //! anything is touched. The current build's snapshot must exist in the home
13 //! being cleaned, or no built-in work is done at all.
14 //! * **Dry run first.** [`dry_run`] reads only. It reports what [`apply`] would
15 //! do, split into the *automatic* subset that runs at startup and the
16 //! *explicit* subset that needs `--fix`.
17 //! * **Records before directories.** State is rewritten atomically (private
18 //! temp file, fsync, rename, directory fsync) under the registry's own state
19 //! lock, after a one-deep `state.json.pre-gc` backup. Directories go second:
20 //! a crash in between leaves unreferenced directories the next run removes,
21 //! never a record pointing at a missing one.
22 //! * **Directories move before they die.** A directory is renamed to a
23 //! `.retired-*` tombstone inside its own root, then deleted, so a partial
24 //! delete never leaves a half-removed live-looking tree. Only direct
25 //! children of the two Codewhale-owned roots are eligible, never links.
26 //! * **Trust is carried by the registry, not by this module.** A superseded
27 //! built-in record is retired only once the current build has its own
28 //! record (which the registry's carry-forward created, honouring the
29 //! capability-hash rule), or it is not the record carry-forward would use.
30 //! * **Nothing in use goes.** The current build's snapshot, anything backing a
31 //! loaded plugin, anything touched inside the grace window, and anything a
32 //! running process names on its command line are kept. When the process
33 //! list cannot be read, everything is assumed in use.
34 //! * **Never user-installed bundles.** Only records are ever pruned for user
35 //! and workspace plugins, and only when the evidence is unambiguous.
36
37 use std::cell::OnceCell;
38 use std::collections::{BTreeMap, BTreeSet};
39 use std::fs;
40 use std::io;
41 use std::path::{Path, PathBuf};
42 use std::time::{Duration, SystemTime};
43
44 use super::{
45 PersistedPluginState, PluginRegistry, PluginStateFile, builtin_predecessor,
46 ensure_private_plugin_state_directory, harden_plugin_state_file, load_state,
47 load_state_unlocked, metadata_is_link_or_reparse, open_state_lock, path_entry_exists,
48 runtime_stage_key, save_state, save_state_with_hardener, state_lock_path,
49 };
50 use crate::builtin::{
51 EmbeddedBundle, STAMP_NAME, embedded_bundles, parse_snapshot_dir_name, snapshots_dir,
52 };
53 use crate::discovery::{plugin_id, plugin_root_hash};
54 use crate::types::PluginScope;
55 use codewhale_config::PluginId;
56
57 /// How long a snapshot or stage must sit untouched before it may be removed.
58 /// Every start of a build re-stamps its snapshot, so this is "not started by
59 /// any binary for a day", which keeps parallel checkouts' builds safe.
60 pub const DEFAULT_GRACE: Duration = Duration::from_secs(24 * 60 * 60);
61 /// How long an inert (disabled, never trusted) record must be idle to be pruned.
62 pub const DEFAULT_INERT_STALE: Duration = Duration::from_secs(14 * 24 * 60 * 60);
63
64 const BACKUP_NAME: &str = "state.json.pre-gc";
65 const LEFTOVER_PREFIXES: [&str; 2] = [".staging-", ".retired-"];
66
67 /// Which findings a run may act on.
68 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
69 pub enum GcTier {
70 /// Superseded builds, inert records, leftovers: nothing that holds authority.
71 Safe,
72 /// Also records that still hold trust or enablement for a vanished bundle.
73 Explicit,
74 }
75
76 #[derive(Debug, Clone)]
77 pub struct GcOptions {
78 pub grace: Duration,
79 pub inert_stale: Duration,
80 pub now: SystemTime,
81 }
82
83 impl Default for GcOptions {
84 fn default() -> Self {
85 Self {
86 grace: DEFAULT_GRACE,
87 inert_stale: DEFAULT_INERT_STALE,
88 now: SystemTime::now(),
89 }
90 }
91 }
92
93 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
94 pub enum GcKind {
95 Record,
96 Snapshot,
97 RuntimeStage,
98 Leftover,
99 }
100
101 impl GcKind {
102 pub fn label(self) -> &'static str {
103 match self {
104 Self::Record => "record",
105 Self::Snapshot => "snapshot",
106 Self::RuntimeStage => "runtime stage",
107 Self::Leftover => "leftover",
108 }
109 }
110 }
111
112 #[derive(Debug, Clone, PartialEq, Eq)]
113 pub struct GcItem {
114 pub kind: GcKind,
115 /// Record id, or directory path.
116 pub target: String,
117 pub reason: String,
118 pub bytes: u64,
119 /// Needs `--fix`; the startup pass leaves it alone.
120 pub explicit: bool,
121 }
122
123 #[derive(Debug, Clone, Default)]
124 pub struct GcReport {
125 pub items: Vec<GcItem>,
126 /// Things deliberately left alone, with the reason.
127 pub kept: Vec<String>,
128 /// Environment facts that limited the run.
129 pub notes: Vec<String>,
130 pub applied: bool,
131 pub failures: Vec<String>,
132 pub records_before: usize,
133 pub records_after: usize,
134 pub state_bytes_before: u64,
135 pub state_bytes_after: u64,
136 }
137
138 impl GcReport {
139 pub fn is_clean(&self) -> bool {
140 self.items.is_empty()
141 }
142
143 pub fn reclaimable_bytes(&self) -> u64 {
144 self.items.iter().map(|item| item.bytes).sum()
145 }
146 }
147
148 // ---------------------------------------------------------------------------
149 // Observation: everything read from disk, before any decision.
150 // ---------------------------------------------------------------------------
151
152 struct Layout {
153 plugins_dir: PathBuf,
154 snapshots: PathBuf,
155 runtime_v2: PathBuf,
156 }
157
158 struct CurrentBuiltin {
159 digest: String,
160 id: String,
161 }
162
163 struct SnapshotDir {
164 bundle: &'static str,
165 path: PathBuf,
166 id: Option<String>,
167 is_current: bool,
168 last_used: SystemTime,
169 }
170
171 struct StageDir {
172 path: PathBuf,
173 key: String,
174 modified: SystemTime,
175 }
176
177 struct Leftover {
178 path: PathBuf,
179 root: PathBuf,
180 modified: SystemTime,
181 }
182
183 #[derive(Default)]
184 struct Observed {
185 layout: Option<Layout>,
186 state_exists: bool,
187 currents: BTreeMap<String, CurrentBuiltin>,
188 snapshots: Vec<SnapshotDir>,
189 stages: Vec<StageDir>,
190 leftovers: Vec<Leftover>,
191 /// Path hashes of every real directory under the user plugins root.
192 /// `None` when the root could not be listed, which disables user pruning.
193 user_hashes: Option<BTreeSet<String>>,
194 notes: Vec<String>,
195 }
196
197 fn real_dir(path: &Path) -> bool {
198 fs::symlink_metadata(path)
199 .is_ok_and(|metadata| metadata.is_dir() && !metadata_is_link_or_reparse(&metadata))
200 }
201
202 /// `<home>/plugins/state.json` is the only layout this module cleans around.
203 /// Any other state path still gets record pruning, but no directory is touched.
204 fn layout(state_path: &Path, resolved: &dyn Fn(&Path) -> Option<PathBuf>) -> Option<Layout> {
205 if state_path.file_name()? != "state.json" {
206 return None;
207 }
208 let plugins_dir = state_path.parent()?;
209 if plugins_dir.file_name()? != "plugins" {
210 return None;
211 }
212 let home = plugins_dir.parent().and_then(resolved)?;
213 let plugins_dir = home.join("plugins");
214 Some(Layout {
215 snapshots: snapshots_dir(&home),
216 runtime_v2: plugins_dir.join(".runtime").join("v2"),
217 plugins_dir,
218 })
219 }
220
221 fn modified(path: &Path) -> SystemTime {
222 fs::symlink_metadata(path)
223 .and_then(|metadata| metadata.modified())
224 .unwrap_or_else(|_| SystemTime::now())
225 }
226
227 fn observe(
228 state_path: &Path,
229 bundles: &[EmbeddedBundle],
230 resolved: &dyn Fn(&Path) -> Option<PathBuf>,
231 ) -> Observed {
232 let mut obs = Observed {
233 state_exists: path_entry_exists(state_path).unwrap_or(false),
234 ..Observed::default()
235 };
236 let Some(layout) = layout(state_path, resolved) else {
237 obs.notes.push(format!(
238 "{} is not <home>/plugins/state.json; only records were examined, no directory is touched",
239 state_path.display()
240 ));
241 return obs;
242 };
243
244 if real_dir(&layout.snapshots) {
245 for bundle in bundles {
246 let dir = layout.snapshots.join(bundle.snapshot_dir_name());
247 if !real_dir(&dir) {
248 continue;
249 }
250 if let Some(root) = resolved(&dir.join(bundle.name)) {
251 obs.currents.insert(
252 bundle.name.to_string(),
253 CurrentBuiltin {
254 digest: bundle.digest.clone(),
255 id: plugin_id(PluginScope::Builtin, bundle.name, &root).0,
256 },
257 );
258 }
259 }
260 if obs.currents.is_empty() {
261 obs.notes.push(
262 "this build's built-in snapshot is not present in this home; built-in records and snapshots were not examined"
263 .to_string(),
264 );
265 }
266 if let Ok(entries) = fs::read_dir(&layout.snapshots) {
267 for entry in entries.flatten() {
268 observe_snapshot_entry(&layout, bundles, &mut obs, &entry, resolved);
269 }
270 }
271 } else if fs::symlink_metadata(&layout.snapshots).is_ok() {
272 obs.notes.push(format!(
273 "{} is not a real directory; left alone",
274 layout.snapshots.display()
275 ));
276 }
277
278 if real_dir(&layout.runtime_v2)
279 && let Ok(entries) = fs::read_dir(&layout.runtime_v2)
280 {
281 for entry in entries.flatten() {
282 let path = entry.path();
283 let Some(name) = entry.file_name().to_str().map(str::to_string) else {
284 continue;
285 };
286 if !real_dir(&path) {
287 continue;
288 }
289 if LEFTOVER_PREFIXES.iter().any(|p| name.starts_with(p)) {
290 obs.leftovers.push(Leftover {
291 modified: modified(&path),
292 root: layout.runtime_v2.clone(),
293 path,
294 });
295 } else if is_sha256_hex(&name) {
296 obs.stages.push(StageDir {
297 modified: modified(&path),
298 key: name,
299 path,
300 });
301 }
302 }
303 }
304
305 if real_dir(&layout.plugins_dir) {
306 obs.user_hashes = fs::read_dir(&layout.plugins_dir).ok().and_then(|entries| {
307 let mut hashes = BTreeSet::new();
308 for entry in entries {
309 let path = entry.ok()?.path();
310 if real_dir(&path) {
311 hashes.insert(plugin_root_hash(PluginScope::User, &resolved(&path)?));
312 }
313 }
314 Some(hashes)
315 });
316 }
317 obs.layout = Some(layout);
318 obs
319 }
320
321 fn observe_snapshot_entry(
322 layout: &Layout,
323 bundles: &[EmbeddedBundle],
324 obs: &mut Observed,
325 entry: &fs::DirEntry,
326 resolved: &dyn Fn(&Path) -> Option<PathBuf>,
327 ) {
328 let path = entry.path();
329 let Some(name) = entry.file_name().to_str().map(str::to_string) else {
330 return;
331 };
332 let Ok(metadata) = fs::symlink_metadata(&path) else {
333 return;
334 };
335 if LEFTOVER_PREFIXES.iter().any(|p| name.starts_with(p)) {
336 if metadata.is_dir() && !metadata_is_link_or_reparse(&metadata) {
337 obs.leftovers.push(Leftover {
338 modified: metadata.modified().unwrap_or_else(|_| SystemTime::now()),
339 root: layout.snapshots.clone(),
340 path,
341 });
342 }
343 return;
344 }
345 let Some((bundle_name, digest)) = parse_snapshot_dir_name(&name, bundles) else {
346 return;
347 };
348 if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
349 obs.notes.push(format!(
350 "ignored {name}: a snapshot name that is not a real directory"
351 ));
352 return;
353 }
354 let id = resolved(&path.join(bundle_name))
355 .map(|root| plugin_id(PluginScope::Builtin, bundle_name, &root).0);
356 let is_current = obs
357 .currents
358 .get(bundle_name)
359 .is_some_and(|current| current.digest == digest);
360 let stamp = path.join(STAMP_NAME);
361 let last_used = fs::symlink_metadata(&stamp)
362 .and_then(|metadata| metadata.modified())
363 .unwrap_or_else(|_| modified(&path));
364 obs.snapshots.push(SnapshotDir {
365 bundle: bundle_name,
366 path,
367 id,
368 is_current,
369 last_used,
370 });
371 }
372
373 fn is_sha256_hex(name: &str) -> bool {
374 name.len() == 64 && name.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
375 }
376
377 /// Process list used to spot snapshots a running program still names.
378 /// Read at most once per run.
379 #[derive(Default)]
380 struct ProcessScan {
381 output: OnceCell<Option<String>>,
382 }
383
384 impl ProcessScan {
385 #[cfg(test)]
386 fn fixed(text: &str) -> Self {
387 Self {
388 output: OnceCell::from(Some(text.to_string())),
389 }
390 }
391
392 /// Unknown counts as in use: failing to look must never allow a delete.
393 fn names(&self, needle: &str) -> bool {
394 match self.output.get_or_init(capture_process_list) {
395 Some(text) => text.contains(needle),
396 None => true,
397 }
398 }
399
400 fn uses(&self, path: &Path) -> bool {
401 path.file_name()
402 .and_then(|name| name.to_str())
403 .is_none_or(|name| self.names(name))
404 }
405 }
406
407 #[cfg(unix)]
408 fn capture_process_list() -> Option<String> {
409 let output = std::process::Command::new("ps")
410 .args(["-axww", "-o", "command="])
411 .stdin(std::process::Stdio::null())
412 .stderr(std::process::Stdio::null())
413 .output()
414 .ok()?;
415 output
416 .status
417 .success()
418 .then(|| String::from_utf8_lossy(&output.stdout).into_owned())
419 }
420
421 #[cfg(not(unix))]
422 fn capture_process_list() -> Option<String> {
423 // Windows refuses to delete files a process has open, which is the same
424 // protection; there is no portable command-line scan to add.
425 Some(String::new())
426 }
427
428 // ---------------------------------------------------------------------------
429 // Planning: pure decisions over (state, observation, options).
430 // ---------------------------------------------------------------------------
431
432 struct Retire {
433 id: PluginId,
434 reason: String,
435 }
436
437 struct DirItem {
438 kind: GcKind,
439 path: PathBuf,
440 root: PathBuf,
441 reason: String,
442 }
443
444 #[derive(Default)]
445 struct Plan {
446 retire: Vec<Retire>,
447 dirs: Vec<DirItem>,
448 kept: Vec<String>,
449 }
450
451 fn split_id(id: &str) -> Option<(&str, &str, &str)> {
452 let mut parts = id.splitn(3, '/');
453 Some((parts.next()?, parts.next()?, parts.next()?))
454 }
455
456 fn is_inert(entry: &PersistedPluginState) -> bool {
457 !entry.enabled && entry.trust.is_none()
458 }
459
460 /// The most recent time a record was reviewed, if it ever was.
461 fn last_activity(entry: &PersistedPluginState) -> Option<SystemTime> {
462 entry
463 .trust
464 .iter()
465 .chain(entry.review_history.iter())
466 .filter_map(|receipt| chrono::DateTime::parse_from_rfc3339(&receipt.reviewed_at).ok())
467 .map(SystemTime::from)
468 .max()
469 }
470
471 fn age(now: SystemTime, then: SystemTime) -> Duration {
472 now.duration_since(then).unwrap_or_default()
473 }
474
475 fn short_age(duration: Duration) -> String {
476 let days = duration.as_secs() / 86_400;
477 if days > 0 {
478 format!("{days}d")
479 } else {
480 format!("{}h", duration.as_secs() / 3_600)
481 }
482 }
483
484 fn plan(
485 state: &PluginStateFile,
486 obs: &Observed,
487 live: &BTreeSet<String>,
488 opts: &GcOptions,
489 tier: GcTier,
490 in_use: &dyn Fn(&Path) -> bool,
491 ) -> Plan {
492 let mut plan = Plan::default();
493 let mut retire: BTreeMap<PluginId, String> = BTreeMap::new();
494
495 // Which superseded snapshots may go. A snapshot belongs to another build
496 // when its digest is not the one this binary embeds.
497 let mut removable: BTreeMap<PathBuf, String> = BTreeMap::new();
498 // Only bundles whose current snapshot is present in this home are
499 // examined: without it there is nothing to compare "superseded" against.
500 for snapshot in obs
501 .snapshots
502 .iter()
503 .filter(|s| !s.is_current && obs.currents.contains_key(s.bundle))
504 {
505 let name = snapshot
506 .path
507 .file_name()
508 .map(|n| n.to_string_lossy().into_owned())
509 .unwrap_or_default();
510 if snapshot.id.as_ref().is_some_and(|id| live.contains(id)) {
511 plan.kept
512 .push(format!("snapshot {name}: backs a loaded plugin"));
513 } else if age(opts.now, snapshot.last_used) < opts.grace {
514 plan.kept.push(format!(
515 "snapshot {name}: started {} ago, inside the grace window",
516 short_age(age(opts.now, snapshot.last_used))
517 ));
518 } else if in_use(&snapshot.path) {
519 plan.kept
520 .push(format!("snapshot {name}: named by a running process"));
521 } else {
522 removable.insert(
523 snapshot.path.clone(),
524 format!(
525 "built by another binary; last started {} ago",
526 short_age(age(opts.now, snapshot.last_used))
527 ),
528 );
529 }
530 }
531
532 for (id, entry) in &state.plugins {
533 if live.contains(id.as_str()) {
534 continue;
535 }
536 let Some((scope, hash, name)) = split_id(id.as_str()) else {
537 continue;
538 };
539 let stale = || last_activity(entry).is_none_or(|t| age(opts.now, t) >= opts.inert_stale);
540 let reason = match scope {
541 "builtin" => {
542 let Some(current) = obs.currents.get(name) else {
543 continue;
544 };
545 if current.id == id.as_str() {
546 continue;
547 }
548 let current_id = PluginId(current.id.clone());
549 // Until the current build has its own record, the registry's
550 // carry-forward still needs the predecessor it would pick.
551 if !state.plugins.contains_key(&current_id)
552 && builtin_predecessor(state, &current_id, name)
553 .is_some_and(|source| std::ptr::eq(source, entry))
554 {
555 plan.kept.push(format!(
556 "{id}: the newest review, kept until this build carries it forward"
557 ));
558 continue;
559 }
560 match obs
561 .snapshots
562 .iter()
563 .find(|s| s.id.as_deref() == Some(id.as_str()))
564 {
565 Some(snapshot) => match removable.get(&snapshot.path) {
566 Some(why) => format!("superseded built-in; {why}"),
567 None => {
568 plan.kept
569 .push(format!("{id}: its snapshot is still in use or recent"));
570 continue;
571 }
572 },
573 None => match last_activity(entry) {
574 Some(t) if age(opts.now, t) < opts.grace => {
575 plan.kept
576 .push(format!("{id}: reviewed inside the grace window"));
577 continue;
578 }
579 None if entry.trust.is_some() => continue,
580 _ => "superseded built-in whose snapshot no longer exists".to_string(),
581 },
582 }
583 }
584 "user" => {
585 let Some(hashes) = &obs.user_hashes else {
586 continue;
587 };
588 if hashes.contains(hash) {
589 continue;
590 }
591 if is_inert(entry) {
592 if !stale() {
593 continue;
594 }
595 "inert record for a bundle directory that no longer exists".to_string()
596 } else if tier >= GcTier::Explicit {
597 "holds trust or enablement for a bundle directory that no longer exists"
598 .to_string()
599 } else {
600 continue;
601 }
602 }
603 "workspace" => {
604 if !is_inert(entry) || !stale() {
605 continue;
606 }
607 format!(
608 "inert (never trusted, disabled) and idle for {}",
609 last_activity(entry).map_or_else(
610 || "an unknown time".to_string(),
611 |t| short_age(age(opts.now, t))
612 )
613 )
614 }
615 _ => continue,
616 };
617 retire.insert(id.clone(), reason);
618 }
619
620 for (path, reason) in removable {
621 if let Some(layout) = &obs.layout {
622 plan.dirs.push(DirItem {
623 kind: GcKind::Snapshot,
624 path,
625 root: layout.snapshots.clone(),
626 reason,
627 });
628 }
629 }
630
631 for leftover in &obs.leftovers {
632 if age(opts.now, leftover.modified) >= opts.grace && !in_use(&leftover.path) {
633 plan.dirs.push(DirItem {
634 kind: GcKind::Leftover,
635 path: leftover.path.clone(),
636 root: leftover.root.clone(),
637 reason: "abandoned staging or tombstone directory".to_string(),
638 });
639 }
640 }
641
642 // A runtime stage is referenced by the record whose id hashes to its key.
643 // Only with a state file on disk: a missing file proves nothing, and must
644 // not read as "every stage is an orphan".
645 if obs.state_exists && obs.layout.is_some() {
646 let referenced: BTreeSet<String> = state
647 .plugins
648 .keys()
649 .filter(|id| !retire.contains_key(*id))
650 .map(runtime_stage_key)
651 .chain(
652 live.iter()
653 .map(|id| runtime_stage_key(&PluginId(id.clone()))),
654 )
655 .collect();
656 for stage in &obs.stages {
657 if referenced.contains(&stage.key)
658 || age(opts.now, stage.modified) < opts.grace
659 || in_use(&stage.path)
660 {
661 continue;
662 }
663 if let Some(layout) = &obs.layout {
664 plan.dirs.push(DirItem {
665 kind: GcKind::RuntimeStage,
666 path: stage.path.clone(),
667 root: layout.runtime_v2.clone(),
668 reason: "runtime snapshot of a plugin with no remaining record".to_string(),
669 });
670 }
671 }
672 }
673
674 plan.retire = retire
675 .into_iter()
676 .map(|(id, reason)| Retire { id, reason })
677 .collect();
678 plan
679 }
680
681 fn dir_size(path: &Path) -> u64 {
682 let mut total = 0u64;
683 let mut stack = vec![path.to_path_buf()];
684 let mut visited = 0usize;
685 while let Some(dir) = stack.pop() {
686 let Ok(entries) = fs::read_dir(&dir) else {
687 continue;
688 };
689 for entry in entries.flatten() {
690 visited += 1;
691 if visited > 200_000 {
692 return total;
693 }
694 let Ok(metadata) = fs::symlink_metadata(entry.path()) else {
695 continue;
696 };
697 if metadata_is_link_or_reparse(&metadata) {
698 continue;
699 }
700 if metadata.is_dir() {
701 stack.push(entry.path());
702 } else {
703 total = total.saturating_add(metadata.len());
704 }
705 }
706 }
707 total
708 }
709
710 fn serialized_len(state: &PluginStateFile) -> u64 {
711 serde_json::to_string_pretty(state).map_or(0, |body| body.len() as u64 + 1)
712 }
713
714 fn items_of(plan: &Plan, explicit: impl Fn(GcKind, &str) -> bool) -> Vec<GcItem> {
715 let records = plan.retire.iter().map(|retire| {
716 let target = retire.id.0.clone();
717 GcItem {
718 kind: GcKind::Record,
719 explicit: explicit(GcKind::Record, &target),
720 target,
721 reason: retire.reason.clone(),
722 bytes: 0,
723 }
724 });
725 let dirs = plan.dirs.iter().map(|dir| {
726 let target = dir.path.display().to_string();
727 GcItem {
728 kind: dir.kind,
729 explicit: explicit(dir.kind, &target),
730 bytes: dir_size(&dir.path),
731 target,
732 reason: dir.reason.clone(),
733 }
734 });
735 records.chain(dirs).collect()
736 }
737
738 fn state_after(state: &PluginStateFile, plan: &Plan) -> PluginStateFile {
739 let mut next = state.clone();
740 for retire in &plan.retire {
741 next.plugins.remove(&retire.id);
742 }
743 next
744 }
745
746 fn report_header(state: &PluginStateFile, obs: &Observed, plan: &Plan) -> GcReport {
747 let after = state_after(state, plan);
748 GcReport {
749 kept: plan.kept.clone(),
750 notes: obs.notes.clone(),
751 records_before: state.plugins.len(),
752 records_after: after.plugins.len(),
753 state_bytes_before: serialized_len(state),
754 state_bytes_after: serialized_len(&after),
755 ..GcReport::default()
756 }
757 }
758
759 // ---------------------------------------------------------------------------
760 // Entry points.
761 // ---------------------------------------------------------------------------
762
763 /// Read-only: what `apply(.., GcTier::Explicit)` would do, with the startup
764 /// subset distinguished from the `--fix`-only remainder.
765 pub fn dry_run(
766 state_path: &Path,
767 live: &BTreeSet<String>,
768 opts: &GcOptions,
769 ) -> Result<GcReport, String> {
770 dry_run_with(
771 state_path,
772 live,
773 opts,
774 &embedded_bundles(),
775 &ProcessScan::default(),
776 )
777 }
778
779 fn dry_run_with(
780 state_path: &Path,
781 live: &BTreeSet<String>,
782 opts: &GcOptions,
783 bundles: &[EmbeddedBundle],
784 scan: &ProcessScan,
785 ) -> Result<GcReport, String> {
786 let state = load_state(state_path)?;
787 let resolved = resolved_paths(state_path, bundles);
788 let lookup = |path: &Path| resolved.get(path).cloned();
789 let obs = observe(state_path, bundles, &lookup);
790 let in_use = |path: &Path| scan.uses(path);
791 let all = plan(&state, &obs, live, opts, GcTier::Explicit, &in_use);
792 let safe = plan(&state, &obs, live, opts, GcTier::Safe, &in_use);
793 let safe_targets: BTreeSet<(GcKind, String)> = safe
794 .retire
795 .iter()
796 .map(|retire| (GcKind::Record, retire.id.0.clone()))
797 .chain(
798 safe.dirs
799 .iter()
800 .map(|dir| (dir.kind, dir.path.display().to_string())),
801 )
802 .collect();
803 let mut report = report_header(&state, &obs, &all);
804 report.items = items_of(&all, |kind, target| {
805 !safe_targets.contains(&(kind, target.to_string()))
806 });
807 Ok(report)
808 }
809
810 /// Apply every finding at or below `tier`.
811 pub fn apply(
812 state_path: &Path,
813 live: &BTreeSet<String>,
814 opts: &GcOptions,
815 tier: GcTier,
816 ) -> Result<GcReport, String> {
817 apply_with(
818 state_path,
819 live,
820 opts,
821 tier,
822 &embedded_bundles(),
823 &ProcessScan::default(),
824 )
825 }
826
827 fn apply_with(
828 state_path: &Path,
829 live: &BTreeSet<String>,
830 opts: &GcOptions,
831 tier: GcTier,
832 bundles: &[EmbeddedBundle],
833 scan: &ProcessScan,
834 ) -> Result<GcReport, String> {
835 // A malformed or future-schema state file aborts here, before any change.
836 let state = load_state(state_path)?;
837 let resolved = resolved_paths(state_path, bundles);
838 let lookup = |path: &Path| resolved.get(path).cloned();
839 let obs = observe(state_path, bundles, &lookup);
840 let in_use = |path: &Path| scan.uses(path);
841 let mut chosen = plan(&state, &obs, live, opts, tier, &in_use);
842 let mut report = report_header(&state, &obs, &chosen);
843
844 if !chosen.retire.is_empty() {
845 // Re-derive the record decisions under the registry's own state lock,
846 // from the file as it is now, so a concurrent trust/enable is honoured.
847 let lock_path = state_lock_path(state_path);
848 if let Some(parent) = lock_path.parent() {
849 ensure_private_plugin_state_directory(parent)?;
850 }
851 let lock_file = open_state_lock(&lock_path, true)?;
852 let mut lock = fd_lock::RwLock::new(lock_file);
853 let _guard = lock
854 .write()
855 .map_err(|error| format!("failed to lock plugin state for cleanup: {error}"))?;
856 let current = load_state_unlocked(state_path)?;
857 chosen = plan(&current, &obs, live, opts, tier, &in_use);
858 report = report_header(&current, &obs, &chosen);
859 if !chosen.retire.is_empty() {
860 let next = state_after(&current, &chosen);
861 if next.plugins.len() + chosen.retire.len() != current.plugins.len() {
862 return Err("plugin cleanup would remove an unexpected number of records".into());
863 }
864 let backup = state_path.with_file_name(BACKUP_NAME);
865 save_state_with_hardener(&backup, &current, harden_plugin_state_file)?;
866 save_state(state_path, &next)?;
867 }
868 }
869
870 report.items = items_of(&chosen, |_, _| false);
871 report.applied = true;
872 for dir in &chosen.dirs {
873 if let Err(error) = retire_dir(&dir.root, &dir.path) {
874 report
875 .failures
876 .push(format!("{}: {error}", dir.path.display()));
877 }
878 }
879 Ok(report)
880 }
881
882 /// Remove one direct child of a Codewhale-owned root. The child is first made
883 /// removable (staged runtime trees are deliberately read-only), renamed to a
884 /// tombstone inside the same root, then deleted. Links are never followed.
885 fn retire_dir(root: &Path, path: &Path) -> Result<(), String> {
886 if path.parent() != Some(root) {
887 return Err("not a direct child of its root".to_string());
888 }
889 if !real_dir(root) {
890 return Err("root is not a real directory".to_string());
891 }
892 let metadata = match fs::symlink_metadata(path) {
893 Ok(metadata) => metadata,
894 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
895 Err(error) => return Err(error.to_string()),
896 };
897 if metadata_is_link_or_reparse(&metadata) || !metadata.is_dir() {
898 return Err("not a real directory; left alone".to_string());
899 }
900 make_tree_removable(path).map_err(|error| format!("could not unlock for removal: {error}"))?;
901 let tombstone = root.join(format!(".retired-{}", uuid::Uuid::new_v4().simple()));
902 fs::rename(path, &tombstone).map_err(|error| format!("could not retire: {error}"))?;
903 fs::remove_dir_all(&tombstone).map_err(|error| {
904 format!(
905 "retired to {} but could not finish deleting: {error}",
906 tombstone.display()
907 )
908 })
909 }
910
911 fn make_tree_removable(path: &Path) -> io::Result<()> {
912 let metadata = fs::symlink_metadata(path)?;
913 if metadata_is_link_or_reparse(&metadata) {
914 return Ok(());
915 }
916 if metadata.is_dir() {
917 #[cfg(unix)]
918 {
919 // Removal is the goal here; a mount that assigns its own modes
920 // already leaves the owner able to delete, and `tighten_mode`
921 // keeps the error for a filesystem that stores modes.
922 codewhale_config::private_directory::tighten_mode(path, 0o700)
923 .map_err(|error| io::Error::other(error.to_string()))?;
924 }
925 #[cfg(not(unix))]
926 {
927 let mut permissions = metadata.permissions();
928 permissions.set_readonly(false);
929 fs::set_permissions(path, permissions)?;
930 }
931 for entry in fs::read_dir(path)? {
932 make_tree_removable(&entry?.path())?;
933 }
934 } else {
935 #[cfg(not(unix))]
936 {
937 let mut permissions = metadata.permissions();
938 permissions.set_readonly(false);
939 fs::set_permissions(path, permissions)?;
940 }
941 }
942 Ok(())
943 }
944
945 impl PluginRegistry {
946 /// The automatic startup pass: the [`GcTier::Safe`] subset, at most once
947 /// per process and state file, after built-in trust has been carried to
948 /// this build. Never fatal: a failure is logged and startup continues.
949 pub fn collect_garbage_at_startup(&self) {
950 static DONE: std::sync::Mutex<BTreeSet<PathBuf>> = std::sync::Mutex::new(BTreeSet::new());
951 let Some(state_path) = self.state_path() else {
952 return;
953 };
954 if self.state_error.is_some() || !path_entry_exists(state_path).unwrap_or(false) {
955 return;
956 }
957 let first = DONE
958 .lock()
959 .map(|mut done| done.insert(state_path.to_path_buf()))
960 .unwrap_or(false);
961 if !first {
962 return;
963 }
964 let live = self.plugins.keys().map(|id| id.0.clone()).collect();
965 match run(
966 state_path.to_path_buf(),
967 live,
968 GcOptions::default(),
969 Some(GcTier::Safe),
970 ) {
971 Ok(report) if !report.is_clean() => tracing::info!(
972 target: "plugins",
973 items = report.items.len(),
974 bytes = report.reclaimable_bytes(),
975 failures = report.failures.len(),
976 "retired superseded plugin state; see /plugin doctor"
977 ),
978 Ok(_) => {}
979 Err(error) => tracing::warn!(
980 target: "plugins",
981 %error,
982 "plugin state cleanup skipped"
983 ),
984 }
985 }
986 }
987
988 /// The command and the startup pass. `tier` is `None` for the read-only
989 /// report; startup applies [`GcTier::Safe`] and `--fix` applies
990 /// [`GcTier::Explicit`]. Path identity is resolved inside the walk, off the
991 /// caller's thread.
992 pub fn run(
993 state_path: PathBuf,
994 live: BTreeSet<String>,
995 opts: GcOptions,
996 tier: Option<GcTier>,
997 ) -> Result<GcReport, String> {
998 let bundles = embedded_bundles();
999 let scan = ProcessScan::default();
1000 match tier {
1001 Some(tier) => apply_with(&state_path, &live, &opts, tier, &bundles, &scan),
1002 None => dry_run_with(&state_path, &live, &opts, &bundles, &scan),
1003 }
1004 }
1005
1006 /// Resolve the paths the walk identifies records by.
1007 ///
1008 /// One blocking task resolves the home, lists that resolved home, and
1009 /// resolves what the listing found. Listing the link and walking the target
1010 /// would see none of the same snapshots, and the doctor would then refuse to
1011 /// clean. A directory created after this returns is absent from the map, and
1012 /// the walk keeps its record rather than retiring it for a hash it could not
1013 /// compute.
1014 fn resolved_paths(state_path: &Path, bundles: &[EmbeddedBundle]) -> BTreeMap<PathBuf, PathBuf> {
1015 let bundles = bundles.to_vec();
1016 let state_path = state_path.to_path_buf();
1017 // `spawn_blocking` needs a runtime, and startup and the tests have none.
1018 // Enter one first, then spawn. The brace stays on the `spawn_blocking`
1019 // line: that is the scope the ratchet treats as off the runtime.
1020 let run = async move {
1021 match tokio::task::spawn_blocking(move || {
1022 let mut resolved = BTreeMap::new();
1023 let Some(plugins_dir) = state_path.parent() else {
1024 return resolved;
1025 };
1026 if plugins_dir.file_name().is_none_or(|name| name != "plugins") {
1027 return resolved;
1028 }
1029 let Some(link) = plugins_dir.parent() else {
1030 return resolved;
1031 };
1032 let Ok(home) = link.canonicalize() else {
1033 return resolved;
1034 };
1035 // Both keys: the walk asks with the path it was given, and the
1036 // listing below uses the resolved one. They differ when the home
1037 // is a link.
1038 resolved.insert(link.to_path_buf(), home.clone());
1039 resolved.insert(home.clone(), home.clone());
1040 let mut paths = Vec::new();
1041 collect_children(&home, &bundles, &mut paths);
1042 for path in paths {
1043 if let Ok(real) = path.canonicalize() {
1044 resolved.insert(path, real);
1045 }
1046 }
1047 resolved
1048 })
1049 .await
1050 {
1051 Ok(resolved) => resolved,
1052 Err(error) => std::panic::resume_unwind(error.into_panic()),
1053 }
1054 };
1055 // Already on a worker: leave it before waiting on another runtime.
1056 match tokio::runtime::Handle::try_current() {
1057 Ok(_) => tokio::task::block_in_place(|| POOL.block_on(run)),
1058 Err(_) => POOL.block_on(run),
1059 }
1060 }
1061
1062 /// Snapshot and user-plugin directories under an already-resolved home.
1063 fn collect_children(home: &Path, bundles: &[EmbeddedBundle], paths: &mut Vec<PathBuf>) {
1064 let snapshots = snapshots_dir(home);
1065 if real_dir(&snapshots) {
1066 for bundle in bundles {
1067 let dir = snapshots.join(bundle.snapshot_dir_name());
1068 if real_dir(&dir) {
1069 paths.push(dir.join(bundle.name));
1070 }
1071 }
1072 if let Ok(entries) = fs::read_dir(&snapshots) {
1073 for entry in entries.flatten() {
1074 let path = entry.path();
1075 let Some(name) = entry.file_name().to_str().map(str::to_string) else {
1076 continue;
1077 };
1078 if LEFTOVER_PREFIXES
1079 .iter()
1080 .any(|prefix| name.starts_with(prefix))
1081 {
1082 continue;
1083 }
1084 let Some((bundle_name, _)) = parse_snapshot_dir_name(&name, bundles) else {
1085 continue;
1086 };
1087 let Ok(metadata) = fs::symlink_metadata(&path) else {
1088 continue;
1089 };
1090 if !metadata_is_link_or_reparse(&metadata) && metadata.is_dir() {
1091 paths.push(path.join(bundle_name));
1092 }
1093 }
1094 }
1095 }
1096 let plugins_dir = home.join("plugins");
1097 if real_dir(&plugins_dir)
1098 && let Ok(entries) = fs::read_dir(&plugins_dir)
1099 {
1100 for entry in entries.flatten() {
1101 let path = entry.path();
1102 if real_dir(&path) {
1103 paths.push(path);
1104 }
1105 }
1106 }
1107 }
1108
1109 static POOL: std::sync::LazyLock<tokio::runtime::Runtime> = std::sync::LazyLock::new(|| {
1110 tokio::runtime::Builder::new_current_thread()
1111 .enable_all()
1112 .thread_name("plugin-doctor")
1113 .build()
1114 .expect("plugin doctor path resolver")
1115 });
1116
1117 /// Human-readable size for reports.
1118 pub fn format_bytes(bytes: u64) -> String {
1119 const KIB: f64 = 1024.0;
1120 let value = bytes as f64;
1121 if value >= KIB * KIB {
1122 format!("{:.1} MB", value / (KIB * KIB))
1123 } else if value >= KIB {
1124 format!("{:.1} KB", value / KIB)
1125 } else {
1126 format!("{bytes} B")
1127 }
1128 }
1129
1130 #[cfg(test)]
1131 #[path = "gc_tests.rs"]
1132 mod tests;
1133
1133 lines RUST