From ed6296a9c5e945372fc6a72d398f6dcfcbb9c2ed Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Mon, 16 Nov 2026 21:22:52 +0700 Subject: [PATCH] fix: a failed heartbeat no longer abandons a restore once the apply permit is spent Before the permit the lease is still given up on; after it the failure is logged and the apply runs to its terminal report instead of being killed mid-flight. Co-Authored-By: Claude Sonnet 5.5 --- crates/tessera-agent/src/restore.rs | 29 ++++++- crates/tessera-agent/src/restore/tests.rs | 99 +++++++++++++++++++---- 2 files changed, 111 insertions(+), 17 deletions(-) diff --git a/crates/tessera-agent/src/restore.rs b/crates/tessera-agent/src/restore.rs index 63f592a..235ac64 100644 --- a/crates/tessera-agent/src/restore.rs +++ b/crates/tessera-agent/src/restore.rs @@ -5,7 +5,15 @@ use crate::{ use anyhow::{ensure, Context, Result}; use async_trait::async_trait; use serde::Deserialize; -use std::{collections::HashMap, fs::File, sync::Arc, time::Duration}; +use std::{ + collections::HashMap, + fs::File, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, + }, + time::Duration, +}; use tessera_core::{ job::CaptureFormat, restore::{DatabaseIdentity, RestoreLease, RestoreProgress}, @@ -184,12 +192,14 @@ pub(super) async fn poll( lease.job.target.id == *target_id && lease.job.target.application_id == application, "hub returned an unexpected restore target" ); + let permit_taken = AtomicBool::new(false); let work = run( hub, &lease, target, source, Duration::from_secs(timeout_seconds), + &permit_taken, ); tokio::pin!(work); loop { @@ -197,7 +207,17 @@ pub(super) async fn poll( biased; result = &mut work => return result.map(|()| true), _ = tokio::time::sleep(heartbeat) => { - report(hub, &lease, RestoreProgress::Heartbeat).await?; + if let Err(error) = report(hub, &lease, RestoreProgress::Heartbeat).await { + // Once the apply permit is spent, dropping `work` would kill the apply + // half way (its children are `kill_on_drop`) and leave the target + // half-restored with no terminal report. Keep going and let the outcome + // report decide. Before the permit nothing destructive has happened, + // so give up and let the lease expire. + if !permit_taken.load(Ordering::SeqCst) { + return Err(error); + } + tracing::warn!(restore = %lease.job.id, %error, "heartbeat failed during apply; letting the restore finish"); + } } } } @@ -211,6 +231,7 @@ async fn run( target: &T, source: Option<&S>, timeout: Duration, + permit_taken: &AtomicBool, ) -> Result<()> { report(hub, lease, RestoreProgress::Checking).await?; let downloaded = tokio::time::timeout(timeout, async { @@ -271,7 +292,9 @@ async fn run( return Ok(()); } - // The permit is single-use. A lost response leaves the target locked for reconciliation. + // The permit is single-use. A lost response leaves the target locked for reconciliation. Mark it + // taken before asking: from here on the hub may consider the apply started. + permit_taken.store(true, Ordering::SeqCst); hub.send( format!("restore/{}/apply", lease.job.id), serde_json::Value::Null, diff --git a/crates/tessera-agent/src/restore/tests.rs b/crates/tessera-agent/src/restore/tests.rs index ec71da9..fe34a46 100644 --- a/crates/tessera-agent/src/restore/tests.rs +++ b/crates/tessera-agent/src/restore/tests.rs @@ -72,6 +72,8 @@ enum Step { Ok, Fail, Hang, + /// Succeeds after this many milliseconds. + Slow(u64), } impl Step { @@ -80,6 +82,10 @@ impl Step { Step::Ok => Ok(()), Step::Fail => anyhow::bail!("{what} exploded"), Step::Hang => std::future::pending().await, + Step::Slow(ms) => { + tokio::time::sleep(Duration::from_millis(ms)).await; + Ok(()) + } } } } @@ -277,7 +283,15 @@ async fn drive( target: FakeTarget, source: Option, ) -> Outcome { - let result = run(&hub, lease, &target, source.as_ref(), SHORT).await; + let result = run( + &hub, + lease, + &target, + source.as_ref(), + SHORT, + &AtomicBool::new(false), + ) + .await; let log = log.lock().unwrap().clone(); Outcome { result, log } } @@ -657,6 +671,7 @@ async fn crash_between_permit_and_apply_leaves_no_terminal_report() { &target, None::<&FakeSource>, Duration::from_secs(30), + &AtomicBool::new(false), ), ) .await; @@ -755,17 +770,16 @@ async fn poll_runs_a_matching_lease() { assert!(log.lock().unwrap().contains(&"report:applied".to_owned())); } -/// Current behaviour, flagged in the report as a risk: a failed heartbeat report abandons the in-flight -/// restore future (and with it the apply, whose child processes are `kill_on_drop`), so a transient hub -/// blip mid-apply can kill a restore half way with no terminal report. Pinned so a deliberate change shows. +/// Before the apply permit nothing destructive has happened, so a failed heartbeat gives up on the lease +/// (the hub will expire it) rather than carrying on unobserved. #[tokio::test] -async fn failed_heartbeat_abandons_the_in_flight_restore() { +async fn failed_heartbeat_before_the_permit_abandons_the_restore() { let log = log(); let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4()); let lease = lease_for(target_id, application, false); - let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id); + let (mut hub, targets) = poll_fixture(&log, &lease, target_id); hub.fail_progress = Some("heartbeat"); - targets.get_mut(&target_id).unwrap().apply = Step::Hang; + hub.download = Step::Hang; let err = tokio::time::timeout( Duration::from_secs(5), poll( @@ -782,11 +796,68 @@ async fn failed_heartbeat_abandons_the_in_flight_restore() { .unwrap_err(); assert!(err.to_string().contains("hub unreachable")); let log = log.lock().unwrap().clone(); - assert!( - log.contains(&"target.apply".to_owned()), - "apply had started" - ); - assert!(log - .iter() - .all(|e| e != "report:applied" && !e.starts_with("failed:"))); + assert!(log.contains(&"hub.download".to_owned())); + assert!(log.iter().all(|e| e != "hub.apply-permit" + && e != "target.apply" + && e != "report:applied" + && !e.starts_with("failed:"))); +} + +/// After the permit is spent, dropping the restore would kill the apply half way (its children are +/// `kill_on_drop`). A failed heartbeat is only logged and the apply runs to its terminal report. +#[tokio::test] +async fn failed_heartbeat_after_the_permit_lets_the_apply_finish() { + let log = log(); + let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4()); + let lease = lease_for(target_id, application, false); + let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id); + hub.fail_progress = Some("heartbeat"); + targets.get_mut(&target_id).unwrap().apply = Step::Slow(300); + let did = tokio::time::timeout( + Duration::from_secs(5), + poll( + &hub, + application, + None::<&FakeSource>, + &targets, + 30, + Duration::from_millis(50), + ), + ) + .await + .expect("poll finishes") + .unwrap(); + assert!(did); + let log = log.lock().unwrap().clone(); + let beats = log.iter().filter(|e| *e == "report:heartbeat").count(); + assert!(beats >= 2, "heartbeats kept being attempted: {beats}"); + assert_eq!(log.last().map(String::as_str), Some("report:applied")); +} + +/// If the apply itself fails while heartbeats are failing, the failure is still reported. +#[tokio::test] +async fn failed_apply_is_still_reported_when_heartbeats_fail() { + let log = log(); + let (target_id, application) = (Uuid::new_v4(), Uuid::new_v4()); + let lease = lease_for(target_id, application, false); + let (mut hub, mut targets) = poll_fixture(&log, &lease, target_id); + hub.fail_progress = Some("heartbeat"); + targets.get_mut(&target_id).unwrap().apply = Step::Hang; + let err = tokio::time::timeout( + Duration::from_secs(5), + poll( + &hub, + application, + None::<&FakeSource>, + &targets, + 1, + Duration::from_millis(50), + ), + ) + .await + .expect("apply timeout ends the poll") + .unwrap(); + assert!(err); + let log = log.lock().unwrap().clone(); + assert!(log.iter().any(|e| e.starts_with("failed:apply_failed:"))); }