From 53b82733e17921df53e1cb8c0bbb021203f3ee02 Mon Sep 17 00:00:00 2001 From: Shengyu Fu Date: Sun, 29 Nov 2026 23:02:24 -0800 Subject: [PATCH 1/4] Let waiting collection continuations idle the scheduler A collection continuation waiting out its retry interval (up to 64x the 5 s base) kept every full scheduler tick at 100 ms, so an otherwise idle namespace re-read the catalog and reopened its anchor files ten times a second. On Windows this showed up as steady CPU in tgrep and in Defender. Treat the wait as quiet so ticks back off to the idle tick, and record the continuation's due time as a pacer wake so it still starts on the first base tick after it falls due. A wake that is not after the tick is dropped so work that was due but did not start cannot hold the scheduler at the base tick. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- SHARED_WORKTREE_INDEXES.md | 7 ++- tgrep-cli/src/serve/shared/managed.rs | 64 +++++++++++++++++++++++++-- 2 files changed, 66 insertions(+), 5 deletions(-) diff --git a/SHARED_WORKTREE_INDEXES.md b/SHARED_WORKTREE_INDEXES.md index fbacf21..598fdb7 100644 --- a/SHARED_WORKTREE_INDEXES.md +++ b/SHARED_WORKTREE_INDEXES.md @@ -1815,8 +1815,11 @@ ticks find nothing to do, ticks back off exponentially to at most every signature (a lifecycle trigger, a view input epoch from a watcher event or refresh, an attached or detached view, or a job finishing) runs the next full tick immediately. Other changes, such as a lease release on an otherwise idle -namespace, may be noticed up to one idle tick later. This trades a bounded -scheduling lag for less catalog I/O competing with running reconciliation. +namespace, may be noticed up to one idle tick later. A collection continuation +waiting out its retry interval counts as idle, so ticks back off while it +waits; the continuation still starts on the first 100 ms tick after it falls +due. This trades a bounded scheduling lag for less catalog I/O competing with +running reconciliation. Accepted work waits in one queue of at most `work.queue_items` jobs, served by `work.workers` workers, in three classes. Foreground covers attachment, diff --git a/tgrep-cli/src/serve/shared/managed.rs b/tgrep-cli/src/serve/shared/managed.rs index 57b0ceb..e318ddc 100644 --- a/tgrep-cli/src/serve/shared/managed.rs +++ b/tgrep-cli/src/serve/shared/managed.rs @@ -897,6 +897,10 @@ impl RetrySchedule { .is_none_or(|last| now.saturating_duration_since(last) >= self.delay(base)) } + fn next_due(&self, base: Duration) -> Option { + self.last?.checked_add(self.delay(base)) + } + /// `progress` resets the backoff. An unproductive continuation keeps the /// current backoff so a traversal that reclaims nothing is paced instead /// of spinning; the backoff grows when such a traversal completes. @@ -919,11 +923,14 @@ const SCHEDULER_IDLE_TICK: Duration = Duration::from_millis(1600); /// change runs a full tick at once. Otherwise consecutive quiet full ticks /// back off to `SCHEDULER_IDLE_TICK`, so an idle namespace does not spend /// catalog and anchor-verification I/O that competes with running work. +/// Work waiting out a retry interval, such as a collection continuation, +/// counts as quiet; its wake runs a full tick once it falls due. #[derive(Default)] struct IdlePacer { signature: Option<(u64, u64, usize, usize)>, last: Option, quiet: u32, + wake: Option, } impl IdlePacer { @@ -938,12 +945,22 @@ impl IdlePacer { || self .last .is_none_or(|last| now.saturating_duration_since(last) >= self.delay()) + || self.wake.is_some_and(|wake| now >= wake) } - fn completed(&mut self, now: Instant, signature: (u64, u64, usize, usize), quiet: bool) { + /// A wake that is not after this tick is dropped: work that was due but + /// did not start must not hold the scheduler at the base tick. + fn completed( + &mut self, + now: Instant, + signature: (u64, u64, usize, usize), + quiet: bool, + wake: Option, + ) { self.signature = Some(signature); self.last = Some(now); self.quiet = if quiet { (self.quiet + 1).min(4) } else { 0 }; + self.wake = wake.filter(|wake| *wake > now); } } @@ -2976,6 +2993,7 @@ pub(super) fn run(root: &Path, options: Options<'_>, policy: Policy) -> Result<( continue; } let mut quiet = signature.is_ok(); + let mut wake = None; let tick = (|| -> Result<()> { { let admission = scheduler.admission.lock().map_err(|_| Error::corrupt("admission gate poisoned"))?; @@ -3149,7 +3167,8 @@ pub(super) fn run(root: &Path, options: Options<'_>, policy: Policy) -> Result<( Ok(()) })(); failures.check("collection", started_collection); - if collection.is_some() || collection_cursor.is_some() || !failures.names().is_empty() { quiet = false; } + if collection.is_some() || !failures.names().is_empty() { quiet = false; } + if collection_cursor.is_some() { wake = collection_schedule.next_due(retry); } let phase_failures = failures.names(); *scheduler.scheduler_snapshot.lock().map_err(|_| Error::corrupt("scheduler observations poisoned"))? = json!({ "initializing":false,"tick_ms":SCHEDULER_TICK.as_millis(),"idle_tick_ms":SCHEDULER_IDLE_TICK.as_millis(),"maximum_backoff_multiplier":64, @@ -3170,7 +3189,7 @@ pub(super) fn run(root: &Path, options: Options<'_>, policy: Policy) -> Result<( failures.into_result() })(); if let Ok(signature) = signature { - pacer.completed(tick_started, signature, quiet && tick.is_ok()); + pacer.completed(tick_started, signature, quiet && tick.is_ok(), wake); } let mut diagnostics = scheduler.scheduler_diagnostics.lock().expect("scheduler diagnostics"); if diagnostics.observe(started.elapsed(), tick.err().map(|error| format!("{error:#}"))) { @@ -3929,6 +3948,45 @@ mod scheduling_tests { ); } + #[test] + fn waiting_continuations_let_ticks_back_off_and_start_on_time() { + let retry = Duration::from_secs(5); + let signature = (1, 2, 3, 4); + let started = Instant::now(); + let mut schedule = RetrySchedule::default(); + schedule.completed(started, false, true); + let due = schedule.next_due(retry).unwrap(); + assert_eq!(due, started + retry); + + let mut pacer = IdlePacer::default(); + let mut now = started; + let mut full_ticks = Vec::new(); + while !schedule.due(now, retry) { + if pacer.due(now, signature) { + full_ticks.push((now - started).as_millis()); + pacer.completed(now, signature, true, schedule.next_due(retry)); + } + now += SCHEDULER_TICK; + } + assert_eq!( + full_ticks, + [0, 200, 600, 1400, 3000, 4600], + "full ticks back off while the continuation waits" + ); + assert_eq!(now, due); + assert!( + pacer.due(now, signature), + "the continuation starts on the first base tick after it falls due" + ); + + pacer.completed(now, signature, true, schedule.next_due(retry)); + assert!( + !pacer.due(now + SCHEDULER_TICK, signature), + "a wake that did not start its work must not keep ticks hot" + ); + assert!(pacer.due(now + SCHEDULER_IDLE_TICK, signature)); + } + fn recovery( cleanup: managed::CleanupCounts, objects_retired: u32, From 60a74a22174249e3b3c4b8b79a24dc21e802ab55 Mon Sep 17 00:00:00 2001 From: Shengyu Fu Date: Mon, 30 Nov 2026 09:55:43 -0800 Subject: [PATCH 2/4] Renew retained collection proofs after credited truncation A verified member can take many bounded collection passes to delete. Treat each credited truncation as activity on its retained proof, using the current pass policy without rereading the catalog. Keep native invalidation and genuine idle expiry unchanged. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- SHARED_WORKTREE_INDEXES.md | 9 ++-- tgrep-core/src/managed/collection.rs | 59 ++++++++++++++++++++++++-- tgrep-core/src/managed/verification.rs | 43 ++++++------------- 3 files changed, 76 insertions(+), 35 deletions(-) diff --git a/SHARED_WORKTREE_INDEXES.md b/SHARED_WORKTREE_INDEXES.md index 598fdb7..52da670 100644 --- a/SHARED_WORKTREE_INDEXES.md +++ b/SHARED_WORKTREE_INDEXES.md @@ -1797,9 +1797,12 @@ below. Each verification page and each deletion step counts against `max_pages`, and verified bytes count against `max_delete_bytes`. The verification context survives between passes until it has been idle for `cursor_lifetime_ms` or the policy or allocation version changes, so a pass -that ends mid-verification reclaims nothing and the next pass resumes it. Each -deletion step then costs two FULL-sync catalog commits and a file sync, -whatever its length. `chunk_bytes` does not widen the crash window, because +that ends mid-verification reclaims nothing and the next pass resumes it. +On Windows and Linux, each credited truncation renews that idle deadline for +the retained proof: deleting a member can take longer than `cursor_lifetime_ms` +in total without rereading its prefix. Each deletion step then costs two +FULL-sync catalog commits and a file sync, whatever its length. +`chunk_bytes` does not widen the crash window, because every step first journals its exact block-aligned target length. To drain large stages sooner, raise `chunk_bytes` up to `max_delete_bytes`, raise `max_duration_ms` (for example to 1000) together with `max_pages` (for example diff --git a/tgrep-core/src/managed/collection.rs b/tgrep-core/src/managed/collection.rs index 3d566dd..4def476 100644 --- a/tgrep-core/src/managed/collection.rs +++ b/tgrep-core/src/managed/collection.rs @@ -372,11 +372,18 @@ mod tests { } } + fn elapse_verification_idle_time(namespace: &Namespace, elapsed: Duration) { + let mut active = namespace.active_verification().unwrap(); + let expires = &mut active.context.as_mut().unwrap().expires; + *expires -= elapsed.min(expires.saturating_duration_since(Instant::now())); + active.keep = true; + } + #[test] fn expiration_releases_cached_native_resources_and_restarts_at_the_first_byte() { let (_temp, namespace, _object, path) = authenticated_fixture(&vec![b'a'; 128 * 1024 + 17]); cached_prefix(&namespace, "initial"); - namespace.expire_verification_for_test().unwrap(); + elapse_verification_idle_time(&namespace, Duration::MAX); namespace.expire_cursors().unwrap(); assert_eq!( namespace.verification_diagnostics().unwrap()["state"], @@ -394,6 +401,47 @@ mod tests { cached_prefix(&namespace, "after-expiry"); } + // macOS intentionally drops the native proof on each truncation. + #[cfg(any(windows, target_os = "linux"))] + #[test] + fn active_truncation_outlives_the_original_verification_deadline() { + const BLOCK: usize = crate::managed::authentication::BLOCK_BYTES; + let payload = [b'a'; 4 * BLOCK]; + let (_temp, namespace, _object, path) = authenticated_fixture(&payload); + let mut policy = namespace.policy().unwrap(); + policy.policy.work.cursor_lifetime_ms = 24 * 60 * 60 * 1000; + policy.policy.collection.max_duration_ms = policy.policy.work.operation_timeout_ms; + let lifetime = Duration::from_millis(policy.policy.work.cursor_lifetime_ms); + let policy = namespace + .update_policy(policy.version, policy.policy) + .unwrap(); + let (mut request, _) = cached_prefix(&namespace, "prefix"); + request.bounds.max_duration_ms = policy.policy.collection.max_duration_ms; + let mut reclaimed = 0; + for sequence in 0..(2 * payload.len() / BLOCK) { + let progress = request_pass(&namespace, &request, &format!("truncate-{sequence}")); + assert_eq!(progress.errors, 0, "{progress:?}"); + if reclaimed > 0 { + assert_eq!( + progress.verification_bytes, 0, + "an actively shrinking member was reverified: {progress:?}" + ); + } + reclaimed += progress.logical_bytes_reclaimed; + if reclaimed == payload.len() as u64 { + break; + } + request.cursor = Some(progress.next.expect("payload still pending")); + if progress.logical_bytes_reclaimed > 0 { + // Two gaps exceed the original lifetime, but neither gap is idle long enough. + elapse_verification_idle_time(&namespace, lifetime / 3 * 2); + namespace.expire_cursors().unwrap(); + } + } + assert_eq!(reclaimed, payload.len() as u64); + assert!(!path.exists()); + } + #[test] fn idle_shutdown_discards_cached_proof_but_an_active_verifier_keeps_admission_open() { let (_temp, namespace, _object, path) = authenticated_fixture(&vec![b'a'; 128 * 1024 + 17]); @@ -2471,6 +2519,7 @@ impl Namespace { progress: &mut progress, permit: &permit, deadline, + cursor_lifetime: Duration::from_millis(policy.policy.work.cursor_lifetime_ms), context: &mut verification.context, }, ); @@ -2846,14 +2895,14 @@ impl Namespace { && !context.matches(&object.id, &member, pass.request) { pass.progress.verification_restarts += 1; - if !context.rebind(self, directory, &object.id, &member, pass.request)? { + if !context.rebind(directory, &object.id, &member, pass)? { verification.take(); } } if exists { if verification.is_none() { verification = Some(super::verification::Verification::new( - self, directory, &object.id, &member, pass, + directory, &object.id, &member, pass, )?); } let ready = verification @@ -3089,6 +3138,10 @@ impl Namespace { Ok(()) })?; self.fault(super::faults::Point::MemberAfterCredit, Some(operation))?; + if let Some(context) = &mut verification { + // Credited truncation is activity on the retained proof, even with no new proof pages. + context.expires = pass.verification_expiry()?; + } *pass.context = verification; Ok(true) } diff --git a/tgrep-core/src/managed/verification.rs b/tgrep-core/src/managed/verification.rs index e0a3fa9..244135d 100644 --- a/tgrep-core/src/managed/verification.rs +++ b/tgrep-core/src/managed/verification.rs @@ -39,10 +39,17 @@ pub(super) struct Pass<'a> { pub(super) progress: &'a mut CollectionProgress, pub(super) permit: &'a Arc, pub(super) deadline: Instant, + pub(super) cursor_lifetime: Duration, pub(super) context: &'a mut Option, } impl Pass<'_> { + pub(super) fn verification_expiry(&self) -> Result { + Instant::now() + .checked_add(self.cursor_lifetime) + .ok_or_else(|| Error::invalid("verification expiry overflow")) + } + pub(super) fn recheck(&self, namespace: &Namespace) -> Result<()> { self.permit.check_now()?; let policy = namespace.policy()?.version; @@ -67,7 +74,7 @@ pub(super) struct Verification { pub(super) current_length: u64, policy_version: u64, allocation_version: u64, - expires: Instant, + pub(super) expires: Instant, next_block: u64, partial: usize, partial_hash: blake3::Hasher, @@ -268,7 +275,6 @@ pub(super) fn authenticate_complete_member( impl Verification { pub(super) fn new( - namespace: &Namespace, directory: &Directory, object: &Id, member: &FileRecord, @@ -320,7 +326,7 @@ impl Verification { current_length, policy_version: pass.request.policy_version, allocation_version: pass.request.allocation_version, - expires: Self::expiration(namespace)?, + expires: pass.verification_expiry()?, next_block: 0, partial: 0, partial_hash: blake3::Hasher::new(), @@ -334,14 +340,6 @@ impl Verification { Ok(result) } - fn expiration(namespace: &Namespace) -> Result { - Instant::now() - .checked_add(Duration::from_millis( - namespace.policy()?.policy.work.cursor_lifetime_ms, - )) - .ok_or_else(|| Error::invalid("verification expiry overflow")) - } - pub(super) fn matches( &self, object: &Id, @@ -366,20 +364,19 @@ impl Verification { pub(super) fn rebind( &mut self, - namespace: &Namespace, directory: &Directory, object: &Id, member: &FileRecord, - request: &CollectionRequest, + pass: &Pass<'_>, ) -> Result { if !self.same_member(object, member) || self.expires <= Instant::now() { return Ok(false); } self.check(directory)?; self.reset_proof(); - self.policy_version = request.policy_version; - self.allocation_version = request.allocation_version; - self.expires = Self::expiration(namespace)?; + self.policy_version = pass.request.policy_version; + self.allocation_version = pass.request.allocation_version; + self.expires = pass.verification_expiry()?; Ok(true) } @@ -494,7 +491,7 @@ impl Verification { )?; self.check(directory)?; pass.recheck(namespace)?; - self.expires = Self::expiration(namespace)?; + self.expires = pass.verification_expiry()?; if self.next_block == self.seal.blocks { let extra: bool = namespace.read(|connection| Ok(connection.query_row( "SELECT EXISTS(SELECT 1 FROM member_seals WHERE object_id=?1 AND name=?2 AND block_index>=?3)", @@ -589,18 +586,6 @@ impl Namespace { Ok(true) } - #[cfg(test)] - pub(super) fn expire_verification_for_test(&self) -> Result<()> { - let mut active = self.active_verification()?; - active - .context - .as_mut() - .ok_or_else(|| Error::corrupt("missing verification fixture"))? - .expires = Instant::now(); - active.keep = true; - Ok(()) - } - pub(super) fn verification_diagnostics(&self) -> Result { self.discard_idle_verification(true)?; let cache = match self.verification.try_lock() { From 306ea3a92a1f608a3eb140f39ad3ce187eb4d2f9 Mon Sep 17 00:00:00 2001 From: Shengyu Fu Date: Mon, 30 Nov 2026 10:37:29 -0800 Subject: [PATCH 3/4] Prepare v1.2.10 with idle collection fixes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 488acfa..f8f9b6b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1360,7 +1360,7 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "tgrep-cli" -version = "1.2.9" +version = "1.2.10" dependencies = [ "anyhow", "assert_cmd", @@ -1389,7 +1389,7 @@ dependencies = [ [[package]] name = "tgrep-core" -version = "1.2.9" +version = "1.2.10" dependencies = [ "anyhow", "blake3", diff --git a/Cargo.toml b/Cargo.toml index f516b41..3f4592a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ exclude = ["vendor/ignore"] resolver = "2" [workspace.package] -version = "1.2.9" +version = "1.2.10" edition = "2024" rust-version = "1.88" license = "MIT" From e90fe722594a5651a44276fe8abe11f75c724115 Mon Sep 17 00:00:00 2001 From: Shengyu Fu Date: Mon, 30 Nov 2026 10:39:30 -0800 Subject: [PATCH 4/4] Update fuzz lockfile for v1.2.10 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- fuzz/Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 535f22b..a58f12f 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -770,7 +770,7 @@ dependencies = [ [[package]] name = "tgrep-core" -version = "1.2.9" +version = "1.2.10" dependencies = [ "anyhow", "blake3",