diff --git a/.cargo/config.toml b/.cargo/config.toml index f7988f32..c373bb75 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -13,4 +13,8 @@ index = "sparse+https://pkgs.dev.azure.com/devdiv/_packaging/DeepPrompt/Cargo/in # BinSkim compliance flags (OneBranch BA2007) # Required for Windows builds in the ADO sign pipeline. [target.'cfg(target_os = "windows")'] -rustflags = ["-Ccontrol-flow-guard", "-Ctarget-feature=+crt-static", "-Clink-args=/DYNAMICBASE /CETCOMPAT"] +rustflags = ["-Ccontrol-flow-guard", "-Ctarget-feature=+crt-static", "-Clink-arg=/DYNAMICBASE"] + +# CET shadow stacks are x64-only; the ARM64 linker rejects /CETCOMPAT. +[target.'cfg(all(target_os = "windows", target_arch = "x86_64"))'] +rustflags = ["-Clink-arg=/CETCOMPAT"] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fe344bfb..fbc7af8f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -69,11 +69,24 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, macos-latest, windows-latest] + os: [ubuntu-latest, macos-latest, windows-latest, windows-11-arm] runs-on: ${{ matrix.os }} timeout-minutes: 40 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Verify native Windows ARM64 toolchain + if: matrix.os == 'windows-11-arm' + shell: pwsh + run: | + if ($env:RUNNER_ARCH -ne 'ARM64') { + throw "Expected an ARM64 runner, got $env:RUNNER_ARCH" + } + $version = rustc --version --verbose + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $version + if ($version -notcontains 'host: aarch64-pc-windows-msvc') { + throw "Expected a native aarch64-pc-windows-msvc Rust toolchain" + } - name: Test Unix installer if: runner.os != 'Windows' run: bash scripts/test-install.sh diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fcb20bd8..fa69ad18 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,10 +36,10 @@ cargo build --release After the version bump is merged and CI passes, open **Actions > Release > Run workflow**, select **main**, and enter the tag matching the workspace -version in `Cargo.toml`, for example `v1.2.9`. The equivalent CLI command is: +version in `Cargo.toml`, for example `v1.3.0`. The equivalent CLI command is: ```bash -gh workflow run release.yml --repo microsoft/tgrep --ref main -f tag=v1.2.9 +gh workflow run release.yml --repo microsoft/tgrep --ref main -f tag=v1.3.0 ``` The workflow validates the version, creates a missing tag at the exact commit @@ -72,7 +72,12 @@ the publish step creates a missing tag and a tag named like a branch (such as The CI workflow runs on PRs and pushes to `main`, weekly on Monday at 08:00 UTC, and manually with **Actions > CI > Run workflow**. Its native Linux, macOS and -Windows matrix is fail-fast disabled and bounded to 40 minutes per test job. +Windows x64/ARM64 test matrix is fail-fast disabled and bounded to 40 minutes +per test job. The `windows-11-arm` job verifies an ARM64 runner and the native +`aarch64-pc-windows-msvc` Rust host before running the same locked workspace, +managed lifecycle, pinned legacy compatibility and vendored tests as Windows x64. +Both Windows architectures retain control-flow guard, static CRT and +`/DYNAMICBASE`; the x64-only `/CETCOMPAT` linker flag is not passed on ARM64. Existing Rust and Python agent integration coverage is retained. Workspace builds/tests are locked; the separately excluded `vendor/ignore` manifest runs its upstream unit/integration tests **and doctests** on each OS at version diff --git a/Cargo.lock b/Cargo.lock index f8f9b6b9..8095d98e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1360,7 +1360,7 @@ checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" [[package]] name = "tgrep-cli" -version = "1.2.10" +version = "1.3.0" dependencies = [ "anyhow", "assert_cmd", @@ -1389,7 +1389,7 @@ dependencies = [ [[package]] name = "tgrep-core" -version = "1.2.10" +version = "1.3.0" dependencies = [ "anyhow", "blake3", diff --git a/Cargo.toml b/Cargo.toml index 3f4592a1..85b09ea7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ exclude = ["vendor/ignore"] resolver = "2" [workspace.package] -version = "1.2.10" +version = "1.3.0" edition = "2024" rust-version = "1.88" license = "MIT" diff --git a/SHARED_WORKTREE_INDEXES.md b/SHARED_WORKTREE_INDEXES.md index 52da670c..7d596285 100644 --- a/SHARED_WORKTREE_INDEXES.md +++ b/SHARED_WORKTREE_INDEXES.md @@ -1787,7 +1787,12 @@ or changes something resets the backoff, and the rest of that traversal continues at the base interval. A traversal that changes nothing keeps its current backoff on every continuation and doubles it on completion, so an idle namespace is paced rather than rescanned back to back. Lifecycle triggers -still run the next pass at the base interval. Catalog transactions that change +still run the next pass at the base interval. When a collection traversal +completes after any of its passes retired, removed or recovered something, the +daemon starts another traversal at the base interval instead of waiting for +the periodic schedule: retiring a checkpoint can make its generations +collectable only in a later traversal. Traversals repeat until one changes +nothing. Catalog transactions that change no rows do not invalidate workers' cached operation control. Reclamation throughput follows these bounds, not free space. Before a member's @@ -1877,6 +1882,8 @@ seal, but never synthesizes one from the abandoned bytes. Deletion journals exact owned identities and each bounded physical step before performing it, then records the result. Authentication-block-aligned tail truncations and final unlink cannot exceed the remaining deletion-byte budget. +A verified member that fits the remaining budget is unlinked in one journaled +step; only larger members are first truncated in `chunk_bytes` steps. After interruption, the exact journaled target length alone is not success: recovery verifies every surviving prefix block against the original producer proof before crediting the removed tail. A rewritten prefix at that same length @@ -1946,6 +1953,11 @@ its actual and recovered credits and continue from the returned cursor with a fresh operation token and current policy/allocation versions. Require the final `Removed` state and complete accounting before claiming the object was reclaimed. +Bounded metadata cleanup can reclaim producer proof rows for a confirmed removed +member while its object is still `PendingDeletion`. The member's deletion record +remains until the whole object is removed, and proofs for surviving members are +retained. Freed catalog pages can be reused; this does not vacuum the database. + ```bash tgrep shared discover /trusted/cache tgrep shared maintenance /trusted/cache/tgrep-managed-v2/ hello @@ -1962,6 +1974,22 @@ live asynchronous `.start` is unavailable offline. Recovery requests are `{"cursor":null-or-returned-recovery-cursor}` and use policy bounds. Concurrent replay preserves the first completed, failed or cancelled recovery receipt. Newly eligible work requires a new token, not reuse of that receipt. +Recovery passes resumed past the operation phase first examine a bounded +prefix of unfinished (`accepted`, `preparing` or `cancelling`) receipts, +resolving those whose instance has ended, or that were cancelled or exhausted +their lifetime. This fast path uses at most half the examination and time +budgets so deferred receipts cannot starve the ordinary sweep; a one-row +budget uses only that sweep. It releases their reservations, then ends each +receipt: a not-committed one is +`cancelled` with recovery-required `interrupted-operation` (or +`operation-deadline` once expired), and a committed collection keeps its +saved progress as a completed result. A receipt whose reservation belongs to a +producer of this instance that has not ended, or whose operation still names a +live object, is left to the full sweep. `operations_recovered` and +`reservations_released` count this work. Replaying such a token then returns +its terminal receipt; look it up, acknowledge it and use a new token. +Malformed receipts and per-receipt eligibility errors are reported in `issues` +without preventing unrelated recovery and catalog cleanup. A maintenance `session` accepts NDJSON `{"id":1,"method":"objects.page","params":{"cursor":null}}` diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index a58f12f3..4c1a0fdd 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -770,7 +770,7 @@ dependencies = [ [[package]] name = "tgrep-core" -version = "1.2.10" +version = "1.3.0" dependencies = [ "anyhow", "blake3", diff --git a/tgrep-cli/src/serve/shared/managed.rs b/tgrep-cli/src/serve/shared/managed.rs index e318ddc2..b0480448 100644 --- a/tgrep-cli/src/serve/shared/managed.rs +++ b/tgrep-cli/src/serve/shared/managed.rs @@ -915,6 +915,31 @@ impl RetrySchedule { } } +/// Records a finished automatic collection pass and returns its continuation. +/// A sweep that retired, removed or recovered anything requests another at +/// the base retry interval, because retiring a checkpoint can make its +/// generations collectable only in a later sweep. Sweeping stops once a whole +/// sweep changes nothing, and the retry schedule then backs off. +fn collection_pass_completed( + progress: CollectionProgress, + now: Instant, + schedule: &mut RetrySchedule, + sweep_changed: &mut bool, + requested: &mut bool, +) -> Option { + *sweep_changed |= progress.retired != 0 + || progress.removed != 0 + || progress.recovered_objects != 0 + || progress.logical_bytes_reclaimed != 0 + || progress.recovered_logical_bytes != 0; + schedule.completed(now, *sweep_changed, progress.next.is_some()); + if progress.next.is_none() { + *requested |= *sweep_changed; + *sweep_changed = false; + } + progress.next +} + const SCHEDULER_TICK: Duration = Duration::from_millis(100); const SCHEDULER_IDLE_TICK: Duration = Duration::from_millis(1600); @@ -3096,11 +3121,10 @@ pub(super) fn run(root: &Path, options: Options<'_>, policy: Policy) -> Result<( } Ok(previous) => match previous.result.map(serde_json::from_value::) { Some(Ok(progress)) => { - collection_changes |= progress.retired != 0 || progress.removed != 0 || progress.recovered_objects != 0 - || progress.logical_bytes_reclaimed != 0 || progress.recovered_logical_bytes != 0; - collection_cursor = progress.next; - collection_schedule.completed(Instant::now(), collection_changes, collection_cursor.is_some()); - if collection_cursor.is_none() { collection_changes = false; } + collection_cursor = collection_pass_completed( + progress, Instant::now(), &mut collection_schedule, + &mut collection_changes, &mut collection_requested, + ); } Some(Err(error)) => { collection_cursor = None; @@ -3168,7 +3192,9 @@ pub(super) fn run(root: &Path, options: Options<'_>, policy: Policy) -> Result<( })(); failures.check("collection", started_collection); if collection.is_some() || !failures.names().is_empty() { quiet = false; } - if collection_cursor.is_some() { wake = collection_schedule.next_due(retry); } + if collection.is_none() && (collection_cursor.is_some() || (enabled && collection_requested)) { + 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, @@ -3948,6 +3974,49 @@ mod scheduling_tests { ); } + #[test] + fn productive_collection_sweeps_continue_until_one_changes_nothing() { + let base = Duration::from_millis(100); + let now = Instant::now(); + let mut schedule = RetrySchedule::default(); + let (mut changed, mut requested) = (false, false); + let continuation = CollectionProgress { + removed: 1, + next: Some(managed::CollectionCursor::default()), + ..CollectionProgress::default() + }; + let next = collection_pass_completed( + continuation, + now, + &mut schedule, + &mut changed, + &mut requested, + ); + assert!(next.is_some() && changed && !requested); + // A sweep's final pass can be unproductive; an earlier pass still counts. + let next = collection_pass_completed( + CollectionProgress::default(), + now, + &mut schedule, + &mut changed, + &mut requested, + ); + assert!(next.is_none() && !changed && requested); + assert_eq!(schedule.delay(base), base); + assert!(schedule.due(now + base, base)); + + requested = false; + collection_pass_completed( + CollectionProgress::default(), + now + base, + &mut schedule, + &mut changed, + &mut requested, + ); + assert!(!requested, "a sweep that changes nothing stops sweeping"); + assert_eq!(schedule.delay(base), base * 2); + } + #[test] fn waiting_continuations_let_ticks_back_off_and_start_on_time() { let retry = Duration::from_secs(5); diff --git a/tgrep-cli/tests/watcher_watch_registration.rs b/tgrep-cli/tests/watcher_watch_registration.rs index 0fd6b397..810419fb 100644 --- a/tgrep-cli/tests/watcher_watch_registration.rs +++ b/tgrep-cli/tests/watcher_watch_registration.rs @@ -238,8 +238,12 @@ fn assert_polling_server_refreshes(mode_args: &[&str]) { ); thread::sleep(Duration::from_millis(50)); } + // Disk evidence is published before the live reader and cache are swapped. + assert!( + wait_for_no_match(port, "poll_added_marker", Duration::from_secs(15)), + "poll did not publish the deletion to search results" + ); assert_eq!(search_matches(port, "poll_modified_marker"), 1); - assert_eq!(search_matches(port, "poll_added_marker"), 0); let status = server_status(port); assert_eq!(status["watch_mode_active"], "poll"); assert!(status["last_reconcile_error"].is_null()); diff --git a/tgrep-core/src/managed/collection.rs b/tgrep-core/src/managed/collection.rs index 4def4767..124e630a 100644 --- a/tgrep-core/src/managed/collection.rs +++ b/tgrep-core/src/managed/collection.rs @@ -136,6 +136,32 @@ mod tests { namespace.collect_pass(&operation.id, request).unwrap() } + /// Continues policy-bounded passes until one reports an error or the sweep + /// ends, so members larger than one pass's byte budget finish verifying. + fn sweep(namespace: &Arc, token: &str) -> CollectionProgress { + let policy = namespace.policy().unwrap(); + let mut request = CollectionRequest { + policy_version: policy.version, + allocation_version: namespace.allocation().unwrap().version, + bounds: CollectionBounds::from_policy(&policy.policy.collection), + cursor: None, + }; + let mut total = CollectionProgress::default(); + for sequence in 0..16 { + let progress = request_pass(namespace, &request, &format!("{token}-{sequence}")); + total.errors += progress.errors; + total.logical_bytes_reclaimed += progress.logical_bytes_reclaimed; + total.recovered_logical_bytes += progress.recovered_logical_bytes; + total.details.extend(progress.details); + total.verification_context_retained = progress.verification_context_retained; + request.cursor = progress.next; + if total.errors != 0 || request.cursor.is_none() { + return total; + } + } + panic!("collection sweep did not finish: {total:?}"); + } + fn cached_prefix(namespace: &Arc, token: &str) -> (CollectionRequest, u32) { let mut request = CollectionRequest { policy_version: namespace.policy().unwrap().version, @@ -1173,6 +1199,12 @@ mod tests { ] { let original = vec![b'a'; 96 * 1024]; let (_temp, namespace, _object, path) = authenticated_fixture(&original); + let mut policy = namespace.policy().unwrap(); + // Keep a surviving prefix for the post-I/O mutation instead of unlinking. + policy.policy.collection.max_delete_bytes = 64 * 1024; + namespace + .update_policy(policy.version, policy.policy) + .unwrap(); let fault = namespace .install_test_fault(Specification { point, @@ -1182,7 +1214,7 @@ mod tests { }) .unwrap(); let result = std::thread::scope(|scope| { - let worker = scope.spawn(|| pass(&namespace, "macos-prefix-barrier")); + let worker = scope.spawn(|| sweep(&namespace, "macos-prefix-barrier")); let deadline = Instant::now() + Duration::from_secs(5); let mut reached = false; while Instant::now() < deadline { @@ -1217,7 +1249,7 @@ mod tests { 0 ); assert!(!result.verification_context_retained); - let recovered = pass(&namespace, "macos-prefix-recovery"); + let recovered = sweep(&namespace, "macos-prefix-recovery"); assert_eq!(recovered.errors, 1, "{point:?}: {recovered:?}"); assert_eq!( recovered.logical_bytes_reclaimed + recovered.recovered_logical_bytes, @@ -1783,6 +1815,10 @@ mod tests { let temp = tempfile::tempdir().unwrap(); let mut policy = crate::managed::policy::fixture_policy(); policy.collection.chunk_bytes = 4096; + // A budget below the payload makes verification span passes and keeps + // the first intent a tail truncation; a member that fits the budget + // would be unlinked in one step instead. + policy.collection.max_delete_bytes = 8191; policy.collection.max_pages = 64; let namespace = Namespace::initialize_identity(&"a".repeat(64), temp.path(), policy).unwrap(); @@ -1835,7 +1871,7 @@ mod tests { }, }) .unwrap(); - let interrupted = pass(&namespace, "intent"); + let interrupted = sweep(&namespace, "intent"); assert_eq!(interrupted.errors, 1, "{interrupted:?}"); assert_eq!(interrupted.logical_bytes_reclaimed, 0); let path = namespace @@ -1850,7 +1886,7 @@ mod tests { } else { std::fs::write(&path, vec![b'b'; changed_length as usize]).unwrap(); } - let resumed = pass(&namespace, "resume"); + let resumed = sweep(&namespace, "resume"); if authentic_truncation { assert_eq!(resumed.errors, 0, "{resumed:?}"); assert_eq!(resumed.recovered_logical_bytes, 4096); @@ -1877,6 +1913,81 @@ mod tests { } } + #[test] + fn verified_member_within_the_byte_budget_is_unlinked_in_one_step() { + let payload = vec![b'a'; 40_000]; + let (_temp, namespace, object, path) = authenticated_fixture(&payload); + let progress = pass(&namespace, "unlink"); + assert_eq!(progress.errors, 0, "{progress:?}"); + assert_eq!(progress.removed, 1, "{progress:?}"); + // Chunked truncation would need ten 4 KiB steps for this member alone. + assert!(progress.pages < 10, "{progress:?}"); + assert!(progress.logical_bytes_reclaimed >= payload.len() as u64); + assert_eq!( + namespace.object(&object.id).unwrap().state, + ObjectState::Removed + ); + assert!(!path.exists()); + } + + #[test] + fn cleanup_reclaims_deleted_member_proofs_before_the_object_is_removed() { + let payload = vec![b'a'; 32 * 1024]; + let (_temp, namespace, object, path) = authenticated_fixture(&payload); + let mut policy = namespace.policy().unwrap(); + policy.policy.collection.max_delete_bytes = payload.len() as u64; + namespace + .update_policy(policy.version, policy.policy) + .unwrap(); + let proof_count = |name: &str| -> u64 { + namespace + .read(|connection| { + Ok(connection.query_row( + "SELECT count(*) FROM member_seals WHERE object_id=?1 AND name=?2", + params![object.id.as_str(), name], + |row| super::super::catalog::unsigned(row, 0), + )?) + }) + .unwrap() + }; + let payload_proofs = proof_count("payload.bin"); + let header_proofs = proof_count("object.json"); + assert!(payload_proofs > 0 && header_proofs > 0); + + let first = pass(&namespace, "partial-unlink"); + assert_eq!(first.errors, 0, "{first:?}"); + assert_eq!(first.logical_bytes_reclaimed, payload.len() as u64); + assert_eq!(first.removed, 0); + assert!(!path.exists()); + assert_eq!( + namespace.object(&object.id).unwrap().state, + ObjectState::PendingDeletion + ); + let cleanup = namespace + .recover_pass(Some(super::super::RecoveryCursor { + phase: 5, + ..Default::default() + })) + .unwrap(); + assert!(cleanup.issues.is_empty(), "{cleanup:?}"); + assert_eq!(u64::from(cleanup.cleanup.proof_rows), payload_proofs); + assert_eq!(cleanup.cleanup.member_rows, 0); + assert_eq!(proof_count("payload.bin"), 0); + assert_eq!(proof_count("object.json"), header_proofs); + + let second = pass(&namespace, "finish-unlink"); + assert_eq!(second.errors, 0, "{second:?}"); + assert_eq!(second.removed, 1); + assert_eq!( + first.logical_bytes_reclaimed + second.logical_bytes_reclaimed, + object.logical_bytes + ); + assert_eq!( + namespace.object(&object.id).unwrap().state, + ObjectState::Removed + ); + } + #[test] fn collection_progress_is_not_published_from_a_rolled_back_transaction() { for point in [Point::CatalogBeforeCommit, Point::CatalogAfterCommit] { @@ -2944,7 +3055,9 @@ impl Namespace { let remaining = pass.request.bounds.max_delete_bytes - pass.progress.logical_bytes_reclaimed; let chunk = self.policy()?.policy.collection.chunk_bytes.min(remaining); - let target = if current <= chunk { + // A fully verified member that fits the remaining budget is unlinked in one + // step; chunked tail truncation is only needed for larger members. + let target = if current <= remaining { 0 } else { current diff --git a/tgrep-core/src/managed/housekeeping.rs b/tgrep-core/src/managed/housekeeping.rs index fd338b02..789b2489 100644 --- a/tgrep-core/src/managed/housekeeping.rs +++ b/tgrep-core/src/managed/housekeeping.rs @@ -1272,7 +1272,9 @@ impl Namespace { let reclaimable: bool = self.read(|connection| { Ok(connection .query_row( - "SELECT o.state='removed' OR (o.state='quarantined' + "SELECT o.state='removed' + OR (o.state='pending-deletion' AND json_extract(m.record,'$.removed')=1) + OR (o.state='quarantined' AND json_extract(m.record,'$.seal') IS NULL) FROM members m JOIN objects o ON o.id=m.object_id WHERE m.rowid=CAST(?1 AS INTEGER)", @@ -1285,16 +1287,20 @@ impl Namespace { if !reclaimable { return Ok(()); } - counts.proof_rows += self.transaction(|transaction| Ok(transaction.execute( - "DELETE FROM member_seals WHERE rowid IN ( + counts.proof_rows += self.transaction(|transaction| { + Ok(transaction.execute( + "DELETE FROM member_seals WHERE rowid IN ( SELECT s.rowid FROM member_seals s JOIN members m ON m.object_id=s.object_id AND m.name=s.name JOIN objects o ON o.id=m.object_id WHERE m.rowid=CAST(?1 AS INTEGER) AND - (o.state='removed' OR (o.state='quarantined' AND json_extract(m.record,'$.seal') IS NULL)) + (o.state='removed' + OR (o.state='pending-deletion' AND json_extract(m.record,'$.removed')=1) + OR (o.state='quarantined' AND json_extract(m.record,'$.seal') IS NULL)) ORDER BY s.block_index LIMIT ?2)", - params![id, super::authentication::PROOF_RECLAIM_BATCH as u32], - )? as u32))?; + params![id, super::authentication::PROOF_RECLAIM_BATCH as u32], + )? as u32) + })?; counts.member_rows += self.transaction(|transaction| Ok(transaction.execute( "DELETE FROM members WHERE rowid=CAST(?1 AS INTEGER) AND EXISTS(SELECT 1 FROM objects WHERE id=members.object_id AND state='removed') diff --git a/tgrep-core/src/managed/maintenance.rs b/tgrep-core/src/managed/maintenance.rs index e5b08593..ab7cf0b4 100644 --- a/tgrep-core/src/managed/maintenance.rs +++ b/tgrep-core/src/managed/maintenance.rs @@ -635,6 +635,17 @@ impl Namespace { next: None, elapsed_nanos: 0, }; + if cursor.phase > 3 { + let receipt_deadline = started + .checked_add(Duration::from_millis(policy.collection.max_duration_ms / 2)) + .ok_or_else(|| Error::invalid("receipt recovery deadline overflow"))?; + self.recover_interrupted_operations( + &policy, + operation, + receipt_deadline, + &mut progress, + )?; + } while progress.examined < policy.collection.max_examined.min(policy.work.page_objects) && progress .cleanup @@ -977,59 +988,7 @@ impl Namespace { if operation.is_some_and(|operation| operation.as_str() == id) { return Ok(true); } - let mut operation: OperationRecord = serde_json::from_str(&encoded)?; - if matches!( - operation.state, - OperationState::Completed - | OperationState::Failed - | OperationState::Cancelled - ) { - return Ok(true); - } - let old = operation.instance != *self.instance(); - let now = self.clock.now()?; - let expired = now.boot == operation.accepted_at.boot - && now - .millis - .checked_sub(operation.accepted_at.millis) - .is_some_and(|elapsed| elapsed >= policy.work.operation_timeout_ms); - let reserved: bool = self.read(|connection| { - Ok(connection.query_row( - "SELECT EXISTS(SELECT 1 FROM reservations WHERE operation_id=?1)", - [&id], - |row| row.get(0), - )?) - })?; - if !reserved && (old || operation.cancelled || expired) { - operation.state = if operation.committed_state == CommitState::Committed { - OperationState::Completed - } else { - OperationState::Cancelled - }; - operation.cancelled = operation.committed_state != CommitState::Committed; - if operation.result.is_none() { - if operation.kind == "collection" - && operation.committed_state == CommitState::Committed - { - let progress: super::CollectionProgress = - serde_json::from_value(operation.progress.clone())?; - operation.result = Some(serde_json::to_value(progress)?); - } else { - let error = if expired { - Error::new(ErrorCategory::Deadline, "operation-deadline", "unstarted work exhausted its accepted lifetime") - } else { Error::new(ErrorCategory::RecoveryRequired, "interrupted-operation", - "the operation ended before a complete receipt; recover the authoritative view or resume with a new token") } - .committed(operation.committed_state).operation(operation.id.to_string()); - operation.error = Some(serde_json::to_value(error)?); - if operation.committed_state != CommitState::NotCommitted { - operation.state = OperationState::Failed; - } - } - } - self.transaction(|transaction| { - transaction.execute("DELETE FROM refs WHERE source_kind IN ('migration','builder','predecessor','attachment') AND source_id=?1", [&id])?; - Self::save_operation(transaction, &operation) - })?; + if self.resolve_stale_operation(&id, &encoded, &policy)? { progress.operations_recovered += 1; } Ok(true) @@ -1062,6 +1021,206 @@ impl Namespace { .map_err(|_| Error::corrupt("recovery duration overflow"))?; Ok(progress) } + + /// A sweep resumed past the operation phase would leave an interrupted + /// receipt pending until the cursor wraps, which can take many passes over + /// a large catalog. Examine a bounded prefix of pending receipts first, + /// reserving at least half the pass for the full sweep. Deferred receipts + /// must not consume every pass and prevent that sweep from advancing. + fn recover_interrupted_operations( + &self, + policy: &super::policy::Policy, + current: Option<&Id>, + deadline: Instant, + progress: &mut RecoveryProgress, + ) -> Result<()> { + let limit = policy.collection.max_examined.min(policy.work.page_objects) / 2; + let mut after = String::new(); + while progress.examined < limit && Instant::now() < deadline { + if let Some(current) = current { + let record = self.operation(current)?; + if record.cancelled { + progress.cancelled = true; + break; + } + self.check_operation_lifetime(&record)?; + } + let next: Option<(String, String)> = self.read(|connection| { + Ok(connection.query_row( + "SELECT id,record FROM operations WHERE state IN ('accepted','preparing','cancelling') AND id>?1 AND id!=?2 ORDER BY id LIMIT 1", + params![after, current.map(Id::as_str).unwrap_or("")], + |row| Ok((row.get(0)?, row.get(1)?)), + ).optional()?) + })?; + let Some((id, encoded)) = next else { + break; + }; + after = id.clone(); + progress.examined += 1; + let result = (|| -> Result { + let record: OperationRecord = serde_json::from_str(&encoded)?; + if !self.operation_resolvable(&record, policy)? { + return Ok(false); + } + Ok(self.release_interrupted_reservations(&id, progress)? + && self.resolve_stale_operation(&id, &encoded, policy)?) + })(); + match result { + Ok(recovered) => progress.operations_recovered += u32::from(recovered), + Err(error) => { + progress.mutation_committed |= error.committed_state == CommitState::Committed; + if error.committed_state != CommitState::NotCommitted { + progress.measurements_complete = false; + } + progress.issues.push(MaintenanceIssue { + kind: "operations".into(), + identity: id, + error: serde_json::to_value(error)?, + }); + } + } + } + Ok(()) + } + + /// Non-terminal receipts that recovery may resolve once no reservation + /// remains: an ended instance's, a cancelled one, or one past its lifetime. + fn operation_resolvable( + &self, + operation: &OperationRecord, + policy: &super::policy::Policy, + ) -> Result { + if matches!( + operation.state, + OperationState::Completed | OperationState::Failed | OperationState::Cancelled + ) { + return Ok(false); + } + Ok(operation.instance != *self.instance() + || operation.cancelled + || self.operation_expired(operation, policy)?) + } + + fn operation_expired( + &self, + operation: &OperationRecord, + policy: &super::policy::Policy, + ) -> Result { + let now = self.clock.now()?; + Ok(now.boot == operation.accepted_at.boot + && now + .millis + .checked_sub(operation.accepted_at.millis) + .is_some_and(|elapsed| elapsed >= policy.work.operation_timeout_ms)) + } + + /// Releases an interrupted operation's reservations that produced no + /// object needing recovery. Returns false when any must wait for phase 1. + fn release_interrupted_reservations( + &self, + operation: &str, + progress: &mut RecoveryProgress, + ) -> Result { + let reservations: Vec = self.read(|connection| { + let mut statement = connection + .prepare("SELECT record FROM reservations WHERE operation_id=?1 ORDER BY id")?; + let rows = statement + .query_map([operation], |row| row.get(0))? + .collect::>>()?; + Ok(rows) + })?; + for encoded in reservations { + let reservation: ReservationRecord = serde_json::from_str(&encoded)?; + if reservation.instance == *self.instance() && !reservation.producer_ended { + return Ok(false); + } + let produced: bool = self.read(|connection| { + Ok(connection.query_row( + "SELECT EXISTS(SELECT 1 FROM objects WHERE json_extract(record,'$.operation')=?1 AND state!='removed')", + [reservation.operation.as_str()], + |row| row.get(0), + )?) + })?; + if produced { + return Ok(false); + } + let mut memory = self.memory.lock()?; + self.transaction(|transaction| { + transaction.execute( + "DELETE FROM reservations WHERE id=?1", + [reservation.id.as_str()], + )?; + Ok(()) + })?; + memory.finish_reservation(&reservation.id); + progress.reservations_released += 1; + } + Ok(true) + } + + /// Phase-3 receipt recovery for one operation row. Returns whether the + /// receipt was resolved. + fn resolve_stale_operation( + &self, + id: &str, + encoded: &str, + policy: &super::policy::Policy, + ) -> Result { + let mut operation: OperationRecord = serde_json::from_str(encoded)?; + if !self.operation_resolvable(&operation, policy)? { + return Ok(false); + } + let expired = self.operation_expired(&operation, policy)?; + let reserved: bool = self.read(|connection| { + Ok(connection.query_row( + "SELECT EXISTS(SELECT 1 FROM reservations WHERE operation_id=?1)", + [id], + |row| row.get(0), + )?) + })?; + if reserved { + return Ok(false); + } + operation.state = if operation.committed_state == CommitState::Committed { + OperationState::Completed + } else { + OperationState::Cancelled + }; + operation.cancelled = operation.committed_state != CommitState::Committed; + if operation.result.is_none() { + if operation.kind == "collection" && operation.committed_state == CommitState::Committed + { + let progress: super::CollectionProgress = + serde_json::from_value(operation.progress.clone())?; + operation.result = Some(serde_json::to_value(progress)?); + } else { + let error = if expired { + Error::new( + ErrorCategory::Deadline, + "operation-deadline", + "unstarted work exhausted its accepted lifetime", + ) + } else { + Error::new( + ErrorCategory::RecoveryRequired, + "interrupted-operation", + "the operation ended before a complete receipt; recover the authoritative view or resume with a new token", + ) + } + .committed(operation.committed_state) + .operation(operation.id.to_string()); + operation.error = Some(serde_json::to_value(error)?); + if operation.committed_state != CommitState::NotCommitted { + operation.state = OperationState::Failed; + } + } + } + self.transaction(|transaction| { + transaction.execute("DELETE FROM refs WHERE source_kind IN ('migration','builder','predecessor','attachment') AND source_id=?1", [id])?; + Self::save_operation(transaction, &operation) + })?; + Ok(true) + } } #[cfg(test)] @@ -1069,6 +1228,205 @@ mod independent_tests { use super::super::{OperationToken, Token}; use super::*; + #[test] + fn resumed_recovery_resolves_an_ended_instances_pending_receipt_and_its_reservation() { + let temp = tempfile::tempdir().unwrap(); + let namespace = Namespace::initialize_identity( + &"a".repeat(64), + temp.path(), + super::super::policy::fixture_policy(), + ) + .unwrap(); + namespace.activate().unwrap(); + let operation = namespace + .accept_system_operation( + Token::parse("interrupted-collection").unwrap(), + "collection", + serde_json::json!({}), + ) + .unwrap(); + let ended = Id::new().unwrap(); + let mut record = namespace.operation(&operation.id).unwrap(); + record.instance = ended.clone(); + record.state = OperationState::Preparing; + let reservation = ReservationRecord { + id: Id::new().unwrap(), + instance: ended, + operation: operation.id.clone(), + owner: None, + request: super::super::WorkRequest { + allocation_version: namespace.allocation().unwrap().version, + staging_bytes: 0, + private_bytes: 0, + slots: 1, + }, + producer_ended: false, + error: None, + }; + namespace + .transaction(|transaction| { + transaction.execute( + "INSERT INTO reservations(id,operation_id,owner,bytes,slots,record) VALUES (?1,?2,NULL,0,1,?3)", + params![ + reservation.id.as_str(), + operation.id.as_str(), + serde_json::to_string(&reservation)? + ], + )?; + Namespace::save_operation(transaction, &record) + }) + .unwrap(); + + let progress = namespace + .recover_pass(Some(RecoveryCursor { + phase: 4, + ..RecoveryCursor::default() + })) + .unwrap(); + + assert!(progress.issues.is_empty(), "{:?}", progress.issues); + assert_eq!(progress.reservations_released, 1); + assert_eq!(progress.operations_recovered, 1); + let resolved = namespace.operation(&operation.id).unwrap(); + assert_eq!(resolved.state, OperationState::Cancelled); + assert_eq!(resolved.committed_state, CommitState::NotCommitted); + assert_eq!( + resolved.error.as_ref().unwrap()["reason_code"], + "interrupted-operation" + ); + assert_eq!(namespace.work_usage().unwrap().reservations, 0); + } + + #[test] + fn resumed_recovery_reports_malformed_receipts_without_blocking_cleanup() { + let temp = tempfile::tempdir().unwrap(); + let namespace = Namespace::initialize_identity( + &"a".repeat(64), + temp.path(), + super::super::policy::fixture_policy(), + ) + .unwrap(); + namespace.activate().unwrap(); + let mut pending = ["pending-a", "pending-b"].map(|name| { + namespace + .accept_system_operation( + Token::parse(name).unwrap(), + "collection", + serde_json::json!({}), + ) + .unwrap() + }); + pending.sort_by(|left, right| left.id.as_str().cmp(right.id.as_str())); + let [damaged, mut interrupted] = pending; + interrupted.instance = Id::new().unwrap(); + interrupted.state = OperationState::Preparing; + namespace + .transaction(|transaction| { + transaction.execute( + "UPDATE operations SET record=json_remove(record,'$.accepted_at') WHERE id=?1", + [damaged.id.as_str()], + )?; + Namespace::save_operation(transaction, &interrupted) + }) + .unwrap(); + + for expected_recovered in [1, 0] { + let progress = namespace + .recover_pass(Some(RecoveryCursor { + phase: 4, + after: "169899".into(), + ..RecoveryCursor::default() + })) + .expect("one malformed receipt must not abort unrelated recovery"); + assert_eq!(progress.operations_recovered, expected_recovered); + assert!( + progress.issues.iter().any(|issue| { + issue.kind == "operations" + && issue.identity == damaged.id.as_str() + && issue.error["category"] == "corrupt-metadata" + }), + "{progress:?}" + ); + assert!( + progress.next.is_none(), + "cleanup did not finish: {progress:?}" + ); + } + assert_eq!( + namespace.operation(&interrupted.id).unwrap().state, + OperationState::Cancelled + ); + assert_eq!( + namespace.operation(&damaged.id).unwrap_err().category, + ErrorCategory::CorruptMetadata + ); + } + + #[test] + fn deferred_receipts_do_not_starve_a_resumed_cleanup_cursor() { + for limit in [1, 2, 4] { + let temp = tempfile::tempdir().unwrap(); + let mut policy = super::super::policy::fixture_policy(); + policy.collection.max_examined = limit; + policy.work.page_objects = limit; + policy.work.workers = limit; + let namespace = + Namespace::initialize_identity(&"a".repeat(64), temp.path(), policy).unwrap(); + namespace.activate().unwrap(); + let mut producers = Vec::new(); + for index in 0..limit { + let operation = namespace + .accept_system_operation( + Token::parse(format!("live-collection-{index}")).unwrap(), + "collection", + serde_json::json!({}), + ) + .unwrap(); + producers.push( + namespace + .reserve( + &operation.id, + None, + super::super::WorkRequest { + allocation_version: namespace.allocation().unwrap().version, + staging_bytes: 0, + private_bytes: 1, + slots: 1, + }, + ) + .unwrap(), + ); + namespace.cancel_operation(&operation.id).unwrap(); + } + let mut cursor = Some(RecoveryCursor { + phase: 4, + after: "169899".into(), + ..RecoveryCursor::default() + }); + for _ in 0..32 { + let progress = namespace.recover_pass(cursor.take()).unwrap(); + assert!(progress.issues.is_empty(), "{progress:?}"); + assert!(progress.examined <= limit, "{progress:?}"); + assert_eq!(progress.operations_recovered, 0); + assert_eq!(progress.reservations_released, 0); + cursor = progress.next; + if cursor.is_none() { + break; + } + } + assert!( + cursor.is_none(), + "deferred receipts starved cleanup at limit {limit}: {cursor:?}" + ); + assert_eq!( + namespace.work_usage().unwrap().reservations, + u64::from(limit), + "live producer reservations must remain protected" + ); + drop(producers); + } + } + #[test] fn independent_concurrent_recovery_preserves_terminal_receipt_and_defers_new_work() { use super::super::OwnerGuard;