Retention Calculus and TOCTOU Defenses¶
This deep dive formalizes FileCleaner's mathematical retention invariants (src/scanner.rs, src/policy.rs) alongside
the kernel-handle, staging, and cryptographic verification defenses (src/in_use.rs, src/actions.rs, src/hooks.rs,
src/s3.rs) that prevent race-condition corruption.
1. Candidate Filter Algebra and Deterministic Ordering¶
During Phase 1 (Scanner::scan_rule_compiled), each discovered regular non-internal file \(f\) inside rule.path is
evaluated against an include predicate \(I(f)\), an exclude predicate \(X(f)\), and an optional byte-size filter
\(B_{\text{range}}(f)\):
Notice that \(X(f)\) evaluates ancestor directory prefixes as well as the normalized / relative path and basename,
pruning excluded subtrees inside WalkDir::filter_entry before opening child entries. Furthermore, min_file_size and
max_file_size bound rule membership before backup-guard analysis, whereas backup_guard.min_valid_backup_bytes
classifies corrupt stubs within \(\mathcal{F}\).
Deterministic Total Order Across Coarse Clocks¶
Each candidate \(f \in \mathcal{F}\) resolves a UTC timestamp \(t(f)\) from TimeBasis::Modified, TimeBasis::Created
(never falling back to mtime if unsupported), or TimeBasis::FilenameDate (skipping unparseable names fail-closed).
Because FAT32 and network filesystems often exhibit 1-second or 2-second timestamp granularity, FileCleaner establishes
a strict total order \(\prec_{\text{new}}\) tie-broken by normalized relative path:
This guarantees identical SweepPlan outputs across repeated plan and run executions on the same directory
snapshot.
2. Backup Safety Partition and Dead-Man's-Switch Freeze¶
Given the valid-backup byte floor \(B_{\min} = \text{min\_valid\_backup\_bytes} \ge 0\), RetentionEngine::plan partitions
the newest-first sequence \(\mathcal{F} = (f_1, f_2, \dots, f_n)\) into valid backups \(\mathcal{F}_{\text{valid}}\) and
undersized stubs \(\mathcal{F}_{\text{stub}}\):
Excluding \(\mathcal{F}_{\text{stub}}\) from \(\mathcal{F}_{\text{valid}}\) stops a failing cron job that emits 0-byte
error dumps from displacing genuine older backups inside the protected floor or resetting the freshness clock
\(t_{\max}\):
Let \(\text{guard\_active}\) hold whenever backup_guard.enabled == true or any threshold (\(\text{min\_keep\_files} > 0\),
\(B_{\min} > 0\), \(\Delta_{\text{fresh}} = \text{require\_newer\_within}\), or
\(T_{\text{cutoff}} = \text{freeze\_if\_newest\_older\_than}\)) is configured. The freeze predicate
\(\text{Frozen}(\mathcal{F})\) triggers when any staleness or empty-valid condition fails:
Whenever \(\text{Frozen}(\mathcal{F})\) holds, the eviction set \(E\) is forced empty unconditionally:
When not frozen, let \(\mathcal{F}_{\text{valid}} = (v_1, \dots, v_m)\) preserve newest-first ordering. The protected backup floor \(P_{\text{floor}}\) and busy exclusion set \(S_{\text{busy}}\) combine into the immutable protection boundary \(P\):
By construction, \(E \cap P_{\text{floor}} = \emptyset\) and \(E \cap S_{\text{busy}} = \emptyset\) hold as strict algebraic
invariants regardless of max_files, max_age, or max_total_size.
3. Sequential Quota Calculus and In-Place Action Accounting¶
Evictable candidates \(\mathcal{C}\) are ordered into traversal sequence \(\pi_{\mathcal{C}}\) according to
eviction_order:
OldestFirst: \(t(f)\) ascending, tie-broken by \(\text{size}(f)\) descending, then \(\text{rel\_path}(f)\) ascending.LargestFirst: \(\text{size}(f)\) descending, tie-broken by \(t(f)\) ascending, then \(\text{rel\_path}(f)\) ascending.
Retention caps evaluate sequentially over a running pair \((c_{k-1}, b_{k-1})\) initialized at \(c_0 = |\mathcal{F}|\) and \(b_0 = \sum_{f \in \mathcal{F}} \text{size}(f)\), because protected files in \(P\) still occupy physical directory slots and disk bytes. At step \(k\) for candidate \(f = \pi_{\mathcal{C}, k}\), each active threshold in \(\mathcal{R}_{\text{active}} \subseteq \{\text{files}, \text{age}, \text{size}\}\) evaluates:
Predicates combine via CombineMode:
Action-Specific Quota Conservation (removes_file and reclaims_bytes)¶
Not every ActionStep removes a directory entry or frees local bytes (RCA-006). RetentionEngine::plan therefore
models two indicator booleans derived from rule.actions:
removes_file(\(\rho_{\text{file}}\)):trueifactionscontainsDelete,Trash, orMove, or ifCopyTruncateis combined withmin_file_size > 0(which excludes the truncated \(0\)-byte inode on subsequent scans).reclaims_bytes(\(\rho_{\text{bytes}}\)):trueifactionscontainsDelete,Trash,Move, orCopyTruncate.
When ShouldEvict accepts candidate \(f\), the running state transitions via:
Consequently, rules configured with pure in-place pipelines—such as actions = ["upload_s3"] (without delete),
actions = ["rename_by_date"], or actions = ["compress"] with compress_remove_source = false—retain
\(\rho_{\text{file}} = 0\) and \(\rho_{\text{bytes}} = 0\). If caps remain exceeded after processing all of \(\mathcal{C}\), or
if protected sets \(P\) alone exceed max_files / max_total_size, RetentionEngine::plan marks
RuleOutcome::Constrained rather than weakening safety floors:
4. TOCTOU and Race-Condition Defenses Across Boundaries¶
Because filesystem state can mutate between Phase 1 (Scanner) and Phase 6 (ActionExecutor), FileCleaner layers
non-intrusive detection with kernel-enforced handle pinning:
flowchart LR
S["Phase 1 Scan\nIgnore symlinks & .fc-tmp"] --> P2["Phase 2 InUse\nSidecars -> /proc fd -> Idle -> Lock -> Stability"]
P2 --> PIN["Phase 6 Open\nO_NOFOLLOW / REPARSE_POINT\nVerify (st_dev, st_ino)"]
PIN --> STG["Atomic Staging\n0o600 .fc-tmp.<pid>.<seq>\nsync_all() + TempFileGuard"]
STG --> VRF["Cryptographic Gate\nSHA-256 Re-Read / S3 Verify"]
VRF --> CMT["Atomic Rename -> Unlink Source"]
Non-Intrusive Probe Sequencing and Batched Stability¶
In InUseDetector::check_batch_scoped, probes evaluate cheapest and least intrusive signals first (sidecar_suffixes,
single-pass Linux /proc/*/fd snapshot in SweepLockProbe, and min_idle_age with future-skew protection when
\(\text{mtime}(f) > t_{\text{now}}\)). Native OS locks run only on candidates not already busy and not in \(P_{\text{floor}}\),
using non-exclusive LOCK_SH | LOCK_NB / FILE_SHARE_READ during plan and --dry-run so dry-run checks never contend
with readers.
Layer 6 (stability_window, \(\Delta_{\text{stab}}\)) batches all Layer 1–5 survivors into one initial \((s_0, m_0)\) pass,
one sleep of duration \(\Delta_{\text{stab}}\), and one closing \((s_1, m_1)\) pass, reducing wall-clock overhead from
\(O(N \cdot \Delta_{\text{stab}})\) to \(O(\Delta_{\text{stab}})\).
Symlink-Swap Resistance (open_regular_nofollow)¶
Even if an attacker swaps a regular file for a symlink between Phase 1 (WalkDir) and Phase 6 execution, three
sequential checks block symlink traversal when follow_symlinks = false:
- Pre-Action Check (
src/engine.rs): Inspectsfs::symlink_metadata(&candidate.path)immediately prior toActionExecutor. - Non-Following Kernel Open (
src/actions.rs): Callsopen_regular_nofollowusingO_NOFOLLOWon Unix (failing cleanly withELOOPon symlinks) andFILE_FLAG_OPEN_REPARSE_POINT(0x0020_0000) on Windows, followed by rejectingFILE_ATTRIBUTE_REPARSE_POINT(0x0400) on the opened handle metadata. - Inode Identity Continuity: Verifies
(handle_meta.dev(), handle_meta.ino()) == (sym_meta.dev(), sym_meta.ino())on Unix both when opening for copy/upload and immediately before callingset_len(0)duringCopyTruncate.
Residual CopyTruncate Window Trade-Off¶
ActionStep::CopyTruncate intentionally operates on active append-only logs whose writers keep descriptors open without
signal-based rotation. FileCleaner minimizes lost bytes by streaming, compressing, sync_all()-ing, and atomically
renaming the archive before opening the source descriptor for truncation (set_len(0) + sync_all()). Any bytes
written between the copy EOF read and set_len(0) cannot be recovered at the POSIX file-API level without cooperative
writer rotation (rename + SIGHUP/SIGUSR1), which is why CopyTruncate requires explicit opt-in and triggers a
warning in filecleaner validate.
5. Cryptographic Verification Gates (Move and UploadS3)¶
Cross-Filesystem Move and Trash Integrity¶
When std::fs::rename returns CrossesDevices (EXDEV), move_with_cross_fs_fallback computes the streaming source
SHA-256 digest \(H_{\text{src}}\) and byte count \(L_{\text{src}}\) while writing <dest>.fc-tmp.<pid>.<seq> (0o600),
flushes and calls sync_all(), then re-opens <dest>.fc-tmp... from disk to compute an independent digest
\(H_{\text{verify}}\) and length \(L_{\text{verify}}\). The source is unlinked if and only if:
Any divergence deletes <dest>.fc-tmp... via TempFileGuard::drop, preserves the source intact, and aborts with
FileCleanerError::IntegrityMismatch.
Fail-Closed S3 Single-Part and Multipart Verification¶
In src/s3.rs, HttpS3Uploader computes local \(H_{\text{local}}\) and \(L_{\text{local}}\) directly from the pinned
open_regular_nofollow_read descriptor. For files exceeding multipart_part_size, each part \(j \in \{1, \dots, N\}\)
carries its individual SHA-256 checksum header and contributes its raw 32-byte digest \(d_j\) toward the S3 composite
multipart checksum:
Post-upload verification enforces the fail-closed gating invariant before returning control to any subsequent Delete,
Trash, or Move step in rule.actions:
Under default ChecksumSha256 mode, a signed HeadObject (x-amz-checksum-mode: ENABLED) must return exact
Content-Length equal to \(L_{\text{local}}\) and an x-amz-checksum-sha256 matching either single-part
\(\text{base64}(H_{\text{local}})\) or \(H_{\text{composite}}\). Under ReadbackSha256 mode, FileCleaner streams the full
remote object via GetObject through a constant-memory Sha256 hasher to confirm end-to-end byte parity.
Related Documentation¶
- Pipeline topology and phase overview: Fail-Closed Six-Phase Pipeline
- Configuration fields and
INV-CFG-*invariants: Configuration Schema & Invariants - Error codes, probe reasons, and remediation matrix: Error & Alert Matrix
- Hook & TOCTOU security runbook: Enforce Pre-Delete Hooks and TOCTOU Guards
- Freeze & S3 failure incident runbook: Remediate Backup Freeze or S3 Failure