Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
16 changes: 11 additions & 5 deletions SHARED_WORKTREE_INDEXES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -1815,8 +1818,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,
Expand Down
2 changes: 1 addition & 1 deletion fuzz/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

64 changes: 61 additions & 3 deletions tgrep-cli/src/serve/shared/managed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Instant> {
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.
Expand All @@ -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<Instant>,
quiet: u32,
wake: Option<Instant>,
}

impl IdlePacer {
Expand All @@ -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<Instant>,
) {
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);
}
}

Expand Down Expand Up @@ -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"))?;
Expand Down Expand Up @@ -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,
Expand All @@ -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:#}"))) {
Expand Down Expand Up @@ -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,
Expand Down
59 changes: 56 additions & 3 deletions tgrep-core/src/managed/collection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand All @@ -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]);
Expand Down Expand Up @@ -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,
},
);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
Expand Down
Loading
Loading