1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Disk-template cache cleanup: orphaned per-test temp-dir sweeping and
//! whole-cache teardown. Split from `mod.rs` for module locality; reaches
//! the cache-path and store helpers (`cache_root`, `store_atomic`,
//! `ensure_template`, `clone_to_per_test`, `lookup`, …) via `use super::*`.
use *;
/// Sweep stale staging debris out of the disk-template cache root.
///
/// Three debris shapes accumulate when a template-build peer or a
/// per-test consumer dies before its cleanup arm completes:
///
/// 1. **`template.img.in-flight.<cache_key>.<pid>`** — sparse
/// staging images created by [`create_and_size_staging_image`]
/// when [`build_template_via_vm`] runs. Normally unlinked at
/// the failure-cleanup arms inside that function, AND moved
/// into a `.tmp.<pid>/` directory by `store_atomic` on success.
/// A SIGKILL between size-up and store_atomic leaks the file.
/// 2. **`<cache_key>.tmp.<pid>/`** — staging directories created
/// by [`store_atomic`] for the rename-into-place dance.
/// Normally renamed onto the final `<cache_key>/` directory at
/// the end of `store_atomic`. A SIGKILL during the
/// src→staging_image rename or the staging→final_dir rename
/// leaves the populated tmpdir on disk.
/// 3. **`.per-test-<pid>-<ns>-<rnd>.img`** — per-test FICLONE
/// backing files created by [`crate::vmm::KtstrVm::init_virtio_blk`]
/// for the `Filesystem::Btrfs` branch. The setter unlinks the
/// path immediately after FICLONE (the open `File` keeps the
/// inode alive for the device's lifetime), but a SIGKILL
/// between FICLONE and unlink — or an unlink failure surfaced
/// only as a `tracing::warn!` — leaves the dest path on disk.
/// Without sweeping, every crashed test accumulates one such
/// file in the cache root forever.
///
/// All three shapes embed the originating peer's pid in the filename.
/// The sweep parses that pid and probes liveness via
/// `kill(pid, None)` (rust-side: [`nix::sys::signal::kill`] with
/// `Signal::None`). The kernel returns:
/// - `Ok(())` — pid is live AND in-policy for our uid (the signal
/// COULD have been delivered). Debris is owned by a peer that
/// may still publish; leave alone.
/// - `Err(ESRCH)` — pid does not exist. Debris is safe to remove.
/// - `Err(EPERM)` — pid is live but owned by a different uid.
/// Not ours to clean up; leave alone.
/// - any other errno — treat as live and skip; false negatives
/// (debris left on disk) are recoverable, false positives
/// (deleting live state) are not.
///
/// Mirrors `crate::cache::clean_orphaned_tmp_dirs` in
/// `src/cache.rs` — the disk-template cache and the kernel-image
/// cache use the same pid-in-suffix + ESRCH-probe contract for
/// cross-process cleanup. The two are independent because their
/// debris namespaces don't overlap (kernel cache uses `.tmp-`
/// prefix, disk-template cache uses `.tmp.` infix on the
/// directories, a `template.img.in-flight.` prefix on the
/// staging images, and a `.per-test-` prefix on per-test
/// backing files).
///
/// Returns the count of debris entries removed. Errors during
/// individual `remove_dir_all` / `remove_file` calls are logged
/// at `warn` and the sweep continues — operator visibility into
/// "this entry could not be cleaned" beats abandoning the rest of
/// the sweep on the first failure.
///
/// Refuses to descend into the `.locks/` subdirectory (the only
/// non-debris namespace inside the cache root); the prefix filter
/// excludes it via the `template.img.in-flight.`, `*.tmp.*`, and
/// `.per-test-` pattern match. Published cache entries
/// (`<cache_key>/`) are left untouched — they have no pid suffix
/// and don't match any debris shape.
///
/// # When to call this
///
/// **Library code (the steady state):** [`clean_all`] invokes this
/// before walking published entries, and the framework can also
/// call it opportunistically before a `store_atomic` to keep the
/// cache root tidy. Library callers do NOT need to invoke this
/// directly to make a workload run — `ensure_template` does not
/// trip on stale debris because each new build picks a unique
/// `(cache_key, pid)` filename via [`staging_image_path`].
///
/// **Operator-driven (the rare case):** call this from a host
/// admin tool or a CI cleanup hook when:
/// - The host has hosted long-running ktstr peers that crashed
/// without graceful shutdown (SIGKILL, kernel oops, OOM kill,
/// panic) and the cache root is accumulating
/// `template.img.in-flight.*` / `*.tmp.*` / `.per-test-*`
/// entries.
/// - Disk pressure is rising and an inventory of the cache root
/// shows debris files significantly outweigh published entries.
/// - You're scripting a "clean cache" subcommand that does NOT
/// want to remove published entries (use [`clean_all`] for that).
///
/// **What this does NOT do:**
/// - Does not remove published cache entries — those have no pid
/// suffix and are filtered out by the prefix patterns. Use
/// [`clean_all`] when you want a full cache wipe.
/// - Does not remove the `.locks/` subdirectory — lockfile inodes
/// may be held by live peers and dropping them would orphan
/// their fds.
/// - Does not coordinate with live peers via flock — the pid-
/// liveness probe (`kill(pid, None)` returning `ESRCH`) is the
/// only synchronization. A peer in the brief window between
/// pid allocation and store_atomic completion may have its
/// debris removed mid-transaction; the pid-liveness probe
/// protects against this by reporting "live" until the peer
/// actually exits.
///
/// Returns the count of removed debris entries (info-level
/// tracing also logs each removal).
///
/// `dead_code` allow: kept as the operator-facing entry point
/// for a future `cargo ktstr clean` subcommand and the
/// opportunistic in-process sweep before `store_atomic`.
/// Remove every published disk-template cache entry, returning the
/// count of entries actually removed.
///
/// Mirrors [`crate::cache::CacheDir::clean_all`] in `src/cache.rs`.
///
/// # When to call this
///
/// **Operator-driven only.** No production code path calls
/// `clean_all` automatically — the framework's runtime path is
/// `ensure_template` → cache hit / build, never a full sweep.
/// Operators reach for `clean_all` in three scenarios:
///
/// 1. **Disk-pressure escape hatch.** A long-running host has
/// accumulated dozens of cache entries across distinct
/// `(fs, capacity, mkfs version)` triples (each capacity-mib
/// setting and each mkfs upgrade rotates the key). When disk
/// pressure rises, `clean_all` is the nuclear option — wipe
/// every published template and let the next test run rebuild
/// only what it needs.
///
/// 2. **Defense against a fingerprint-blind upgrade.** The cache
/// key includes a fingerprint derived from
/// [`mkfs_version_fingerprint`] (the SHA-256 prefix of
/// `mkfs.<fstype> --version` output), so an mkfs upgrade that
/// changes the version banner rotates the key automatically
/// and the cache self-invalidates. `clean_all` remains the
/// fallback when the version banner does NOT change across an
/// upgrade (a downstream patch that bumps the on-disk format
/// without bumping `--version`) — a rare distro-specific case
/// that operators discover via "the new kernel rejects the
/// cached template" failures.
///
/// 3. **Cleanup before benchmarking.** Empty cache state lets a
/// benchmark measure the full `(template build + clone)` cost
/// deterministically. `clean_all` followed by `ensure_template`
/// is the canonical "cold cache" sequence.
///
/// **What this does NOT do:**
/// - Does not remove the `.locks/` subdirectory — lockfile inodes
/// may be held by live peers and dropping them would orphan
/// their fds (see "What gets skipped" below).
/// - Does not block on live peers — entries whose flock is held
/// by a live peer are skipped (logged at `info`); only quiescent
/// entries are removed.
/// - Does not fall back to a per-key wipe loop on a busy cache —
/// if every entry is locked the function returns 0, not an
/// error. Operators who need to force-remove a locked entry
/// should kill the holder and re-run.
///
/// # Companion: stale-debris sweep
///
/// `clean_all` calls [`clean_orphaned_tmp_dirs`] up front so a
/// rebuilding peer that hits the freshly-empty cache doesn't trip
/// on stale staging debris from a crashed predecessor during its
/// first `store_atomic`. Operators who want ONLY the debris sweep
/// (without removing published entries) should call
/// [`clean_orphaned_tmp_dirs`] directly.
///
/// # Concurrency
///
/// Each entry's per-key lockfile is acquired non-blocking in
/// `LOCK_EX` mode via [`crate::flock::try_flock`]. An entry whose
/// lock is held by a live peer (an active test run mid-FICLONE,
/// or a concurrent template build that finished its rename but is
/// still inside the lock holder's critical section) is skipped
/// rather than removed — the holder is using the entry; deleting
/// it would yank the template out from under a live `clone_to_per_test`.
///
/// The flock is held across the `remove_dir_all` so a peer that
/// blocks on the lock while we're removing observes a clean
/// "entry gone, rebuild from scratch" sequence: their post-lock
/// `lookup()` returns `None` and `ensure_template` proceeds to
/// rebuild. Without holding the lock during removal, a peer that
/// raced through `acquire_template_lock` → `lookup` between our
/// lock-release and our `remove_dir_all` would see the template
/// path, `clone_to_per_test` would race against the rmtree, and
/// either side could win unpredictably.
///
/// The lockfile inode itself is NOT removed — other peers may
/// have it open, and dropping the file while peers wait on it
/// would orphan their fds. Lockfile inodes are sized at a few
/// bytes each and accumulate at the rate of distinct
/// `(fs, capacity, mkfs version)` keys; leaving them is bounded
/// growth, not a leak.
///
/// # Sweeps debris first
///
/// Calls [`clean_orphaned_tmp_dirs`] before walking published
/// entries so a rebuilding peer that hits the freshly-empty cache
/// doesn't trip on stale staging debris from a crashed predecessor
/// during its first `store_atomic`.
///
/// # What gets skipped
///
/// - The `.locks/` subdirectory (lockfile namespace).
/// - Any cache entry whose lockfile is currently held by a live
/// peer (logged at `info` so the operator sees what was kept).
/// - Any cache entry whose `template.img` is missing (corrupt /
/// half-installed) — those are removed regardless of lock state
/// because they can't serve a `clone_to_per_test` and waste
/// inode space.
/// - Non-UTF-8 entry names (foreign — not produced by ktstr).
/// - Files at the cache root (only directories are cache entries;
/// `clean_orphaned_tmp_dirs` already swept the staging-image
/// files before we got here).
///
/// `dead_code` allow: kept as the operator-facing entry point
/// for a future `cargo ktstr clean --all` subcommand; not yet
/// wired into any command surface.