//! Item verbs: recording a driver's subjects, leasing them under a //! campaign's pacing, and recording outcomes under the lease. Every verb //! takes or reads the subject kind, so one set of verbs serves every //! campaign kind; only the lease's node pacing differs by kind //! ([`CampaignKind::paces_per_node`]). Leasing and renewal run the steps of //! [`pplx_space_rollout_queue::claim`] and [`pplx_space_rollout_queue::renew`] //! on these tables. pub(crate) mod nodeless; pub(crate) mod receipts; use std::collections::{HashMap, HashSet}; use std::sync::LazyLock; use std::time::Duration; use pplx_space_accounts::NodeId; use pplx_space_postgres_pool::{Db, DbError, Executor, Tx}; pub(crate) use pplx_space_rollout_queue::LEASE_EXPIRED; use pplx_space_rollout_queue::{Candidates, ClaimStore, FailedItems, Pacing, RenewStore}; use pplx_space_sql_locator::sql; use receipts::{ RUN_STARTED, STARTED_HOLD_PREFIX, UNSTARTED_PREFIX, partial_move_error, sanitized_outcome_str, unstarted_release_error, }; pub use receipts::{leased_partial_move_recorded, lock_leasing_campaign, mark_leased_partial_move}; /// What re-driving lapsed leases did. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct RedriveReport { /// Items returned to `pending` for another lease. pub requeued: u64, /// Items that had used up their attempts, now `failed`. pub failed: u64, /// Final-attempt `sandbox_memory_drops` items settled to `done` from a drop receipt. pub done: u64, } use crate::{ CampaignId, CampaignKind, CampaignPhase, ItemError, ItemPhase, SubjectKind, end_transaction, }; /// `attempts` of a retired item: above any `max_attempts` a caller passes, /// so no limit, even one a later release raises, makes it pending again. pub const RETIRED_ATTEMPTS: u64 = i64::MAX as u64; /// Use up the leases of `campaign_id`'s skipped `subject_kind` items for /// `subject_ids`, which the caller's driver found off the campaign's source, /// so a driver that excludes items out of attempts doesn't find them again. /// `attempts` becomes [`RETIRED_ATTEMPTS`]. Items in other phases are left /// alone. Returns how many were retired. Retirement is permanent: /// [`insert_pending`] never makes a retired item pending again, whatever /// `max_attempts` it's given. pub async fn retire_skipped( executor: impl Executor<'_>, campaign_id: CampaignId, subject_kind: SubjectKind, subject_ids: &[uuid::Uuid], ) -> Result { if subject_ids.is_empty() { return Ok(0); } Ok(sqlx::query(sql!( "UPDATE runtime_upgrade_items SET attempts = $4 WHERE campaign_id = $1 AND subject_kind = $2 AND subject_id = ANY($3) AND phase = $5 AND attempts < $4" )) .bind(campaign_id) .bind(subject_kind.as_str()) .bind(subject_ids) .bind(RETIRED_ATTEMPTS as i64) .bind(ItemPhase::Skipped.as_str()) .execute(executor.into_sqlx()) .await? .rows_affected()) } /// Record `subject_ids` as pending `subject_kind` items of `campaign_id`. An /// item that was skipped (its sandbox had started when it was leased, say) is /// pending again while it has leases left of `max_attempts`, keeping its /// count, so a subject the node keeps declining is dispatched a bounded /// number of times. Items in any other phase are left alone. Inserts nothing /// unless the campaign is unfinished and of the kind whose subjects these /// are, which it locks for the insert so a concurrent completion can't finish /// it under new items. Returns how many items were added or made pending /// again. Opens a transaction on `db`. pub async fn insert_pending( db: &Db, campaign_id: CampaignId, subject_kind: SubjectKind, subject_ids: &[uuid::Uuid], max_attempts: u64, ) -> Result { if subject_ids.is_empty() { return Ok(0); } let mut tx = db.begin().await?; let inserted = insert_pending_in( &mut tx, campaign_id, subject_kind, subject_ids, max_attempts, ) .await; end_transaction(tx, inserted).await } async fn insert_pending_in( tx: &mut Tx<'_>, campaign_id: CampaignId, subject_kind: SubjectKind, subject_ids: &[uuid::Uuid], max_attempts: u64, ) -> Result { let kinds: Vec<&str> = CampaignKind::ALL .iter() .filter(|kind| kind.subject_kind() == subject_kind) .map(|kind| kind.as_str()) .collect(); let open = sqlx::query_scalar::<_, i32>(sql!( "SELECT 1 FROM runtime_upgrade_campaigns WHERE id = $1 AND kind = ANY($2) AND finished_at IS NULL FOR SHARE" )) .bind(campaign_id) .bind(&kinds) .fetch_optional((&mut *tx).into_sqlx()) .await? .is_some(); if !open { return Ok(0); } Ok(sqlx::query(sql!( "INSERT INTO runtime_upgrade_items (campaign_id, subject_kind, subject_id, phase) SELECT DISTINCT $1, $2, subject_id, $4 FROM unnest($3::uuid[]) AS subject_id ON CONFLICT (campaign_id, subject_kind, subject_id) DO UPDATE SET phase = EXCLUDED.phase, last_error = NULL WHERE runtime_upgrade_items.phase = $5 AND runtime_upgrade_items.attempts < $6" )) .bind(campaign_id) .bind(subject_kind.as_str()) .bind(subject_ids) .bind(ItemPhase::Pending.as_str()) .bind(ItemPhase::Skipped.as_str()) .bind(i64::try_from(max_attempts).unwrap_or(i64::MAX)) .execute(tx.into_sqlx()) .await? .rows_affected()) } /// One item leased to the caller. #[derive(Clone, Debug, Eq, PartialEq)] pub struct LeasedItem { pub campaign_id: CampaignId, pub subject_kind: SubjectKind, /// The sandbox or template release id, as `subject_kind` says. pub subject_id: uuid::Uuid, /// The token the outcome must be recorded under. pub lease_token: uuid::Uuid, /// Leases taken on this item so far, this one included. pub attempts: u64, /// For a kind where [`CampaignKind::paces_per_node`] holds, the node that /// last published the subject, if it still has a published state. Always /// `None` for other kinds. pub node_id: Option, } /// Lease pending items of `campaign_id` for `lease` (clamped to 1 second /// through [`MAX_LEASE`](crate::MAX_LEASE)), up to the campaign's pacing: /// /// * nothing unless the campaign is in `canary` or `rolling` and its failed /// items haven't reached its failure budget; /// * in `canary`, one item at a time, and nothing once one is done: the /// canary then waits for an operator to resume the campaign; /// * at most `max_in_flight_per_cluster` items in flight in all, counting /// those already leased; /// * for a kind where [`CampaignKind::paces_per_node`] holds, at most /// `max_in_flight_per_node` in flight on any node, by the node that last /// published each sandbox, and only on a node that's reachable and whose /// status is evidence of its environments /// ([`pplx_space_node_status_store::environment_evidence`]). An item on /// any other node stays pending, holding the campaign open, until its node /// qualifies again. An item with no published node counts toward the /// cluster cap only and is leased: the driver finds it on neither end of /// the campaign and skips it, where pending it would hold the campaign open /// for good. Items of other kinds are paced by the cluster cap only. /// /// * never a subject another campaign holds in flight under a live lease /// (an aborted campaign's, while its worker may still be on it); the item /// stays pending until that lease lapses. /// /// Only the first `scan_limit` pending items in subject order are /// considered (nodeless `canary` campaigns prioritize a started pending item /// first), so items on a saturated node can hold back items behind them until /// the node drains. /// /// Each lease runs from the moment it's written (`clock_timestamp()`), not /// from the transaction's start, so time spent waiting for the locks below /// doesn't use it up. /// /// Locks the campaign row for the whole lease, so concurrent leasers are /// serialized and a pause committed first is seen, and then the lease /// handoff lock of the campaign's subject kind, which renewals of that kind /// wait on. Opens a transaction on `db`. It must run at `READ COMMITTED`, /// Postgres's default; `db.begin()` sets no isolation level of its own. A /// `REPEATABLE READ` snapshot would predate the handoff lock, so a renewal /// committed while this lease waited for it would go unseen. pub async fn lease_items( db: &Db, campaign_id: CampaignId, lease: Duration, scan_limit: u32, ) -> Result, LeaseError> { let (leased, _) = lease_in(db, campaign_id, None, None, lease, scan_limit).await?; Ok(leased) } /// [`lease_items`] rotating through `campaign_id`'s pending `subject_id` ring after `*after`. pub async fn lease_items_after( db: &Db, id: CampaignId, after: &mut Option, lease: Duration, lim: u32, ) -> Result, LeaseError> { let cur = (*after).unwrap_or_else(uuid::Uuid::nil); let (leased, next) = lease_in(db, id, None, Some(cur), lease, lim).await?; if let Some(next) = next { *after = Some(next); } Ok(leased) } /// Lease only `subject_ids` (in slice order) from `campaign_id`'s `pending` items. pub async fn lease_selected_items( db: &Db, id: CampaignId, subject_ids: &[uuid::Uuid], lease: Duration, lim: u32, ) -> Result, LeaseError> { if subject_ids.is_empty() { return Ok(Vec::new()); } Ok(lease_in(db, id, Some(subject_ids), None, lease, lim) .await? .0) } async fn lease_in( db: &Db, campaign_id: CampaignId, only_subjects: Option<&[uuid::Uuid]>, after: Option, lease: Duration, scan_limit: u32, ) -> Result<(Vec, Option), LeaseError> { let mut tx = db.begin().await?; let mut c = Claiming { tx: &mut tx, campaign_id, only_subjects, after, on_node: HashMap::new(), failure_budget: 0, last_scanned: None, skipped_on_saturated_node: false, cursor_before_saturated_skip: None, }; let res = pplx_space_rollout_queue::claim(&mut c, lease, scan_limit).await; let next = if c.skipped_on_saturated_node { c.cursor_before_saturated_skip } else { res.as_ref() .ok() .and_then(|l| l.last().map(|i| i.subject_id)) .or(c.last_scanned) }; Ok((end_transaction(tx, res).await?, next)) } #[derive(Debug, thiserror::Error)] pub enum LeaseError { #[error(transparent)] UnknownValue(#[from] crate::UnknownValue), #[error(transparent)] Database(#[from] DbError), } /// [`lease_items`]'s steps. The shared claim paces by the cluster cap; the /// per-node cap is this store's, applied in [`ClaimStore::claim`]. struct Claiming<'c, 't, 's> { tx: &'c mut Tx<'t>, campaign_id: CampaignId, only_subjects: Option<&'s [uuid::Uuid]>, after: Option, /// Items in flight by the node that last published each sandbox, /// counting those this lease takes. on_node: HashMap, failure_budget: u64, last_scanned: Option, skipped_on_saturated_node: bool, cursor_before_saturated_skip: Option, } /// What [`lease_items`] read of the campaign under its lock that it needs /// after. pub(super) struct LeaseHeader { pub(super) kind: CampaignKind, pub(super) subject_kind: SubjectKind, pub(super) canary: bool, pub(super) per_node: u64, pub(super) effective_per_cluster: i64, } impl FailedItems for Claiming<'_, '_, '_> { type Error = LeaseError; async fn failed(&mut self) -> Result { let failed = crate::phase::count_failed(self.tx, self.campaign_id).await?; if failed >= self.failure_budget { self.last_scanned = None; } Ok(failed) } } impl ClaimStore for Claiming<'_, '_, '_> { type Header = LeaseHeader; type Subject = uuid::Uuid; /// The node that last published the subject, if it has one. type Placement = Option; type Claimed = LeasedItem; async fn lock_leasable(&mut self) -> Result, LeaseError> { let leasing: Vec<&str> = CampaignPhase::ALL .iter() .filter(|phase| phase.leases()) .map(|phase| phase.as_str()) .collect(); let Some((kind, canary, per_node, per_cluster, failure_budget)) = sqlx::query_as::<_, (String, bool, i64, i64, i64)>(sql!( "SELECT kind, phase = $2, max_in_flight_per_node, max_in_flight_per_cluster, failure_budget FROM runtime_upgrade_campaigns WHERE id = $1 AND phase = ANY($3) FOR UPDATE" )) .bind(self.campaign_id) .bind(CampaignPhase::Canary.as_str()) .bind(&leasing) .fetch_optional((&mut *self.tx).into_sqlx()) .await .map_err(DbError::from)? else { return Ok(None); }; let parsed_kind = kind.parse::()?; let subject_kind = parsed_kind.subject_kind(); let effective_per_cluster = if canary { 1 } else { per_cluster.max(0) }; let failure_budget = u64::try_from(failure_budget).unwrap_or(0); self.failure_budget = failure_budget; Ok(Some(( LeaseHeader { kind: parsed_kind, subject_kind, canary, per_node: u64::try_from(per_node).unwrap_or(0), effective_per_cluster, }, Pacing { canary, per_cluster: u64::try_from(per_cluster).unwrap_or(0), failure_budget, }, ))) } async fn canary_progress(&mut self) -> Result<(bool, u64), LeaseError> { let (canary_done, canary_in_flight) = sqlx::query_as::<_, (bool, i64)>(sql!( "SELECT coalesce(bool_or(phase = $2), false), count(*) FILTER (WHERE phase = $3) FROM runtime_upgrade_items WHERE campaign_id = $1 AND phase = ANY(ARRAY[$2, $3])" )) .bind(self.campaign_id) .bind(ItemPhase::Done.as_str()) .bind(ItemPhase::InFlight.as_str()) .fetch_one((&mut *self.tx).into_sqlx()) .await .map_err(DbError::from)?; Ok((canary_done, u64::try_from(canary_in_flight).unwrap_or(0))) } async fn lock_handoff(&mut self, header: &LeaseHeader) -> Result<(), LeaseError> { Ok(lock_lease_handoff(self.tx, header.subject_kind, Handoff::Lease).await?) } async fn held_elsewhere( &mut self, header: &LeaseHeader, ) -> Result, LeaseError> { Ok(held_by_other_campaigns(self.tx, self.campaign_id, header.subject_kind).await?) } async fn candidates( &mut self, header: &LeaseHeader, scan_limit: u32, ) -> Result>, LeaseError> { let (id, sel, cur) = (self.campaign_id, self.only_subjects, self.after); let ((in_flight, pending), last_scanned) = if header.kind.paces_per_node() { node_bound_candidates(self.tx, id, header.subject_kind, sel, cur, scan_limit).await? } else { nodeless::nodeless_candidates(self.tx, id, header, sel, cur, scan_limit).await? }; let mut in_cluster = 0_u64; for (node_id, count) in in_flight { // count(*) is never negative. let count = u64::try_from(count).unwrap_or(0); in_cluster += count; if let Some(node_id) = node_id { *self.on_node.entry(node_id).or_default() += count; } } if in_cluster < u64::try_from(header.effective_per_cluster).unwrap_or(0) { self.last_scanned = last_scanned; } Ok(Candidates { in_flight: in_cluster, pending, }) } async fn claim( &mut self, header: &LeaseHeader, subject_id: uuid::Uuid, node_id: &Option, lease_token: uuid::Uuid, lease: Duration, ) -> Result, LeaseError> { let node_id = *node_id; // Only a sandbox published on a node in a node-paced campaign has one; // it counts against the cluster cap alone otherwise. if let Some(node_id) = node_id && self.on_node.get(&node_id).copied().unwrap_or(0) >= header.per_node { self.skipped_on_saturated_node = true; return Ok(None); } let attempts = sqlx::query_scalar::<_, i64>(sql!( "UPDATE runtime_upgrade_items SET phase = $4, lease_token = $5, lease_expires_at = clock_timestamp() + make_interval(secs => $6), attempts = attempts + 1 WHERE campaign_id = $1 AND subject_kind = $2 AND subject_id = $3 AND phase = $7 RETURNING attempts" )) .bind(self.campaign_id) .bind(header.subject_kind.as_str()) .bind(subject_id) .bind(ItemPhase::InFlight.as_str()) .bind(lease_token) .bind(lease.as_secs_f64()) .bind(ItemPhase::Pending.as_str()) .fetch_optional((&mut *self.tx).into_sqlx()) .await .map_err(DbError::from)?; let Some(attempts) = attempts else { return Ok(None); }; if !self.skipped_on_saturated_node { self.cursor_before_saturated_skip = Some(subject_id); } if let Some(node_id) = node_id { *self.on_node.entry(node_id).or_default() += 1; } Ok(Some(LeasedItem { campaign_id: self.campaign_id, subject_kind: header.subject_kind, subject_id, lease_token, attempts: u64::try_from(attempts).unwrap_or(0), node_id, })) } } /// The `subject_kind` subjects another campaign holds in flight under a live /// lease, which this lease must skip: one subject is upgraded by one worker /// at a time, whichever campaigns name it. The case that needs it is an /// aborted campaign, whose worker may still be mid-upgrade until its next /// renewal fails ([`renew_lease`]), while a new campaign for the same source /// leases the same subjects. /// /// Read after [`lock_lease_handoff`], which serializes it per subject kind /// and is taken after the campaign row lock like every leaser takes it, so /// two campaigns' leases can't both read a subject as free and both take it. async fn held_by_other_campaigns( tx: &mut Tx<'_>, campaign_id: CampaignId, subject_kind: SubjectKind, ) -> Result, DbError> { // Campaigns first, so each one's in-flight items come from the // (campaign_id, phase, subject_id) index. A completed campaign has none: // completion needs no item in flight, under the lock leasers take. let held = sqlx::query_scalar::<_, uuid::Uuid>(sql!( "SELECT i.subject_id FROM runtime_upgrade_campaigns c JOIN runtime_upgrade_items i ON i.campaign_id = c.id AND i.phase = $3 WHERE c.id <> $1 AND c.phase <> $4 AND i.subject_kind = $2 AND i.lease_expires_at > clock_timestamp()" )) .bind(campaign_id) .bind(subject_kind.as_str()) .bind(ItemPhase::InFlight.as_str()) .bind(CampaignPhase::Completed.as_str()) .fetch_all(tx.into_sqlx()) .await?; Ok(held.into_iter().collect()) } /// Who takes the lease handoff lock, which decides its mode. #[derive(Clone, Copy)] pub(super) enum Handoff { /// A lease: exclusive, so leases of one kind serialize with each other /// and with renewals. Lease, /// A renewal: shared, so renewals don't block each other. A renewal /// that arrives while a lease waits for the lock queues behind that /// lease, though, as Postgres queues a shared request behind a waiting /// exclusive one. Renewal, } /// Take the transaction-scoped advisory lock that hands `subject_kind`'s /// subjects between campaigns. Leases take it exclusively and renewals /// shared, so a lease reads another campaign's lease either before a /// renewal or after the renewal commits, never a renewal that's written but /// not yet committed. pub(super) async fn lock_lease_handoff( tx: &mut C, subject_kind: SubjectKind, handoff: Handoff, ) -> Result<(), DbError> where for<'a> &'a mut C: Executor<'a>, { let statement = match handoff { Handoff::Lease => sql!("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))"), Handoff::Renewal => { sql!("SELECT pg_advisory_xact_lock_shared(hashtextextended($1, 0))") } }; sqlx::query(statement) .bind(format!("runtime_upgrade_items/lease/{subject_kind}")) .execute(tx.into_sqlx()) .await?; Ok(()) } /// In-flight counts by node, and the pending items to consider with their /// nodes. pub(super) type NodeCandidates = ( Vec<(Option, i64)>, Vec<(uuid::Uuid, Option)>, ); /// For node-paced sandbox items: in flight by the node that last published /// each sandbox, and pending items whose node qualifies or that have none. async fn node_bound_candidates( tx: &mut Tx<'_>, campaign_id: CampaignId, subject_kind: SubjectKind, only_subjects: Option<&[uuid::Uuid]>, after: Option, scan_limit: u32, ) -> Result<(NodeCandidates, Option), DbError> { debug_assert_eq!(subject_kind, SubjectKind::Sandbox); // One statement, so one snapshot: the in-flight counts and the pending // items see each sandbox on the same node. Read in two, a sandbox // published on another node in between could be counted on its old node // while a pending item on its new one is leased past the cap. A sandbox // a node publishes after this read is seen by the next lease. // // A sandbox published on a node is leased only while that node is // reachable and its status is evidence of its environments. One with no // published node is leased, for the driver to skip. /// Built once: the node evidence predicate is the only interpolation. static CANDIDATES: LazyLock = LazyLock::new(|| { sql!(format!( "WITH in_flight AS ( SELECT o.node_id, count(*) AS items FROM runtime_upgrade_items i LEFT JOIN sandbox_observed_states o ON o.sandbox_id = i.subject_id WHERE i.campaign_id = $1 AND i.subject_kind = $2 AND i.phase = $5 GROUP BY o.node_id ), pending AS ( SELECT i.subject_id, o.node_id FROM runtime_upgrade_items i LEFT JOIN sandbox_observed_states o ON o.sandbox_id = i.subject_id LEFT JOIN node_status_snapshots nss ON nss.node_id = o.node_id WHERE i.campaign_id = $1 AND i.subject_kind = $2 AND i.phase = $3 AND (o.node_id IS NULL OR (nss.reachable IS TRUE AND {})) ORDER BY i.subject_id LIMIT $4 ) SELECT node_id, items, NULL::uuid AS subject_id FROM in_flight UNION ALL SELECT node_id, NULL::bigint, subject_id FROM pending", pplx_space_node_status_store::environment_evidence("nss") )) }); static CANDIDATES_AFTER: LazyLock = LazyLock::new(|| { let ev = pplx_space_node_status_store::environment_evidence("nss"); sql!(format!( "WITH in_flight AS (SELECT o.node_id, count(*) AS items FROM runtime_upgrade_items i LEFT JOIN sandbox_observed_states o ON o.sandbox_id = i.subject_id WHERE i.campaign_id = $1 AND i.subject_kind = $2 AND i.phase = $5 GROUP BY o.node_id), pending AS (SELECT w.subject_id, w.node_id FROM ( (SELECT i.subject_id, o.node_id FROM runtime_upgrade_items i LEFT JOIN sandbox_observed_states o ON o.sandbox_id = i.subject_id LEFT JOIN node_status_snapshots nss ON nss.node_id = o.node_id WHERE i.campaign_id = $1 AND i.subject_kind = $2 AND i.phase = $3 AND i.subject_id > $6 AND (o.node_id IS NULL OR (nss.reachable IS TRUE AND {ev})) ORDER BY i.subject_id LIMIT $4) UNION ALL (SELECT i.subject_id, o.node_id FROM runtime_upgrade_items i LEFT JOIN sandbox_observed_states o ON o.sandbox_id = i.subject_id LEFT JOIN node_status_snapshots nss ON nss.node_id = o.node_id WHERE i.campaign_id = $1 AND i.subject_kind = $2 AND i.phase = $3 AND i.subject_id <= $6 AND (o.node_id IS NULL OR (nss.reachable IS TRUE AND {ev})) ORDER BY i.subject_id LIMIT $4) ) w LIMIT $4) SELECT node_id, items, NULL::uuid AS subject_id FROM in_flight UNION ALL SELECT node_id, NULL::bigint, subject_id FROM pending" )) }); static CANDIDATES_SELECTED: LazyLock = LazyLock::new(|| { let ev = pplx_space_node_status_store::environment_evidence("nss"); sql!(format!( "WITH in_flight AS (SELECT o.node_id, count(*) AS items FROM runtime_upgrade_items i LEFT JOIN sandbox_observed_states o ON o.sandbox_id = i.subject_id WHERE i.campaign_id = $1 AND i.subject_kind = $2 AND i.phase = $5 GROUP BY o.node_id), pending AS (SELECT i.subject_id, o.node_id FROM runtime_upgrade_items i LEFT JOIN sandbox_observed_states o ON o.sandbox_id = i.subject_id LEFT JOIN node_status_snapshots nss ON nss.node_id = o.node_id WHERE i.campaign_id = $1 AND i.subject_kind = $2 AND i.phase = $3 AND i.subject_id = ANY($6) AND (o.node_id IS NULL OR (nss.reachable IS TRUE AND {ev})) ORDER BY array_position($6, i.subject_id), i.subject_id LIMIT $4) SELECT node_id, items, NULL::uuid AS subject_id FROM in_flight UNION ALL SELECT node_id, NULL::bigint, subject_id FROM pending" )) }); type Row = (Option, Option, Option); let base = |q: &'static str| { sqlx::query_as::<_, Row>(sqlx::AssertSqlSafe(q)) .bind(campaign_id) .bind(subject_kind.as_str()) .bind(ItemPhase::Pending.as_str()) .bind(i64::from(scan_limit)) .bind(ItemPhase::InFlight.as_str()) }; let q = match (only_subjects, after) { (Some(sel), _) => base(&CANDIDATES_SELECTED).bind(sel), (None, Some(cur)) => base(&CANDIDATES_AFTER).bind(cur), (None, None) => base(&CANDIDATES), }; let rows = q.fetch_all(tx.into_sqlx()).await?; let mut in_flight = Vec::new(); let mut pending = Vec::new(); for (node_id, items, subject_id) in rows { match (items, subject_id) { (Some(items), _) => in_flight.push((node_id, items)), (None, Some(subject_id)) => pending.push((subject_id, node_id)), (None, None) => {} } } // UNION ALL doesn't promise the branch's order. if let Some(sel) = only_subjects { let mut pos = HashMap::with_capacity(sel.len()); for (i, &id) in sel.iter().enumerate().rev() { pos.insert(id, i); } pending.sort_unstable_by_key(|(id, _)| (pos.get(id).copied().unwrap_or(usize::MAX), *id)); } else if let Some(cur) = after { pending.sort_unstable_by_key(|(id, _)| (*id <= cur, *id)); pending.truncate(scan_limit as usize); } else { pending.sort_unstable_by_key(|(id, _)| *id); } let last_scanned = pending.last().map(|(subject_id, _)| *subject_id); Ok(((in_flight, pending), last_scanned)) } /// Extend `item`'s lease to `lease` from now (clamped as for /// [`lease_items`]). `false` when the lease is no longer the caller's: it /// expired on the database clock, it was re-driven, another outcome was /// recorded, or its campaign finished (an operator aborted it). The caller /// then stops working on the item. /// /// A worker renews at a third of its lease, so after an abort it stops /// at its next renewal attempt, a third of a lease after its last renewal. /// If that renewal can't reach the database it stops at its own deadline /// instead, which is never later than the database's lease. Either way it /// stops before the lease lapses, and until it lapses [`lease_items`] gives /// the subject to no other campaign. /// /// Takes the lease handoff lock [`lease_items`] takes, shared, so a lease of /// the same subject for another campaign waits for the renewal to commit, /// and then sees the renewed lease. Without it, a renewal whose transaction /// is still open past the old expiry would be invisible to that lease, and /// both campaigns would hold the subject once it committed. It takes a share /// lock on the campaign row first, in the lock order every leaser follows, /// so it waits out a lease or a phase change of the same campaign and reads /// whether the campaign has finished exactly. Opens a transaction on `db`. pub async fn renew_lease(db: &Db, item: &LeasedItem, lease: Duration) -> Result { let mut tx = db.begin().await?; let mut renewing = Renewing { tx: &mut tx, item }; let renewed = pplx_space_rollout_queue::renew(&mut renewing, lease).await; end_transaction(tx, renewed).await } /// [`renew_lease`]'s steps. struct Renewing<'c, 't, 'i> { tx: &'c mut Tx<'t>, item: &'i LeasedItem, } impl RenewStore for Renewing<'_, '_, '_> { type Error = DbError; async fn lock_unfinished(&mut self) -> Result { // Shared, so renewals of one campaign don't wait on each other here. let unfinished = sqlx::query_scalar::<_, i32>(sql!( "SELECT 1 FROM runtime_upgrade_campaigns WHERE id = $1 AND finished_at IS NULL FOR SHARE" )) .bind(self.item.campaign_id) .fetch_optional((&mut *self.tx).into_sqlx()) .await?; Ok(unfinished.is_some()) } async fn lock_handoff(&mut self) -> Result<(), DbError> { lock_lease_handoff(self.tx, self.item.subject_kind, Handoff::Renewal).await } async fn lock_item(&mut self) -> Result<(), DbError> { // insert_pending's conflict check, say, locks a row without // updating it. sqlx::query(sql!( "SELECT 1 FROM runtime_upgrade_items WHERE campaign_id = $1 AND subject_kind = $2 AND subject_id = $3 FOR UPDATE" )) .bind(self.item.campaign_id) .bind(self.item.subject_kind.as_str()) .bind(self.item.subject_id) .fetch_optional((&mut *self.tx).into_sqlx()) .await?; Ok(()) } async fn extend(&mut self, lease: Duration) -> Result { let renewed = sqlx::query(sql!( "UPDATE runtime_upgrade_items SET lease_expires_at = clock_timestamp() + make_interval(secs => $5) WHERE campaign_id = $1 AND subject_kind = $2 AND subject_id = $3 AND phase = $6 AND lease_token = $4 AND lease_expires_at > clock_timestamp()" )) .bind(self.item.campaign_id) .bind(self.item.subject_kind.as_str()) .bind(self.item.subject_id) .bind(self.item.lease_token) .bind(lease.as_secs_f64()) .bind(ItemPhase::InFlight.as_str()) .execute((&mut *self.tx).into_sqlx()) .await? .rows_affected(); Ok(renewed == 1) } } /// How a leased item ended. #[derive(Clone, Debug, Eq, PartialEq)] pub enum ItemOutcome { /// Upgraded, or already on the target. Done, /// Not upgraded, and not a failure: the subject is gone or no longer /// one this campaign moves. Skipped(ItemError), /// Failed; counts against the failure budget. Failed(ItemError), /// Not upgraded this time; back to pending for a later lease. The lease /// counts as an attempt. The store doesn't cap retries: a caller records /// a retry on the item's last attempt ([`LeasedItem::attempts`]) as /// [`Self::Failed`] instead. Retry(ItemError), /// Not attempted: the subject wasn't ready (a sandbox mid-transition, /// say). Back to pending, and the lease doesn't count as an attempt. Release(ItemError), } impl ItemOutcome { fn phase(&self) -> ItemPhase { match self { Self::Done => ItemPhase::Done, Self::Skipped(_) => ItemPhase::Skipped, Self::Failed(_) => ItemPhase::Failed, Self::Retry(_) | Self::Release(_) => ItemPhase::Pending, } } /// Attempts to give back: a release undoes its lease's. const fn refunded_attempts(&self) -> i64 { match self { Self::Release(_) => 1, Self::Done | Self::Skipped(_) | Self::Failed(_) | Self::Retry(_) => 0, } } const fn fallback_error(&self) -> Option<&'static str> { match self { Self::Done => None, Self::Skipped(_) => Some("skipped"), Self::Failed(_) => Some("failed"), Self::Retry(_) => Some("retry"), Self::Release(_) => Some("released"), } } /// The error text to store, if any, stripped of internal receipt markers. fn error(&self) -> Option<&str> { let fb = self.fallback_error()?; match self { Self::Done => None, Self::Skipped(e) | Self::Failed(e) | Self::Retry(e) | Self::Release(e) => { e.as_deref().map(|raw| sanitized_outcome_str(raw, fb)) } } } } /// Record `outcome` for `item` and release its lease, returning the stored /// [`ItemPhase`] (`Some(ItemPhase::Done)` when a committed /// `sandbox_memory_drops` receipt promotes `Skipped`/`Failed`), or `None` when /// the lease is no longer the caller's. pub async fn finish_item_phase( executor: impl Executor<'_>, item: &LeasedItem, outcome: &ItemOutcome, ) -> Result, DbError> { let pm = partial_move_error(outcome); let ur = unstarted_release_error(outcome); let sf = matches!(outcome, ItemOutcome::Skipped(_) | ItemOutcome::Failed(_)); let stored = sqlx::query_scalar::<_, String>(sql!( "UPDATE runtime_upgrade_items SET phase = CASE WHEN $16 AND (last_error = $9 OR starts_with(last_error, $10)) AND EXISTS (SELECT 1 FROM runtime_upgrade_campaigns WHERE id = $1 AND kind = $14) THEN $15 ELSE $5 END, last_error = CASE WHEN $16 AND (last_error = $9 OR starts_with(last_error, $10)) AND EXISTS (SELECT 1 FROM runtime_upgrade_campaigns WHERE id = $1 AND kind = $14) THEN NULL WHEN $11 IS NOT NULL AND (last_error = $9 OR starts_with(last_error, $10)) THEN $11 WHEN $8 > 0 AND attempts > $8 AND (last_error IS NULL OR starts_with(last_error, $12)) THEN $13 WHEN $8 > 0 AND $6 IS NULL AND attempts > $8 AND last_error IS NOT NULL AND NOT starts_with(last_error, $12) THEN last_error WHEN last_error IS NOT NULL AND starts_with(last_error, $12) THEN COALESCE($6, $17) WHEN $18 AND $6 IS NULL AND EXISTS ( SELECT 1 FROM runtime_upgrade_campaigns c WHERE c.id = $1 AND (c.phase = $19 OR (c.phase = $20 AND NOT EXISTS ( SELECT 1 FROM runtime_upgrade_items d WHERE d.campaign_id = $1 AND d.phase = $15)))) THEN $17 ELSE $6 END, attempts = GREATEST(attempts - $8, 0), lease_token = NULL, lease_expires_at = NULL WHERE campaign_id = $1 AND subject_kind = $2 AND subject_id = $3 AND phase = $7 AND lease_token = $4 RETURNING phase" )) .bind(item.campaign_id) .bind(item.subject_kind.as_str()) .bind(item.subject_id) .bind(item.lease_token) .bind(outcome.phase().as_str()) .bind(outcome.error()) .bind(ItemPhase::InFlight.as_str()) .bind(outcome.refunded_attempts()) .bind(RUN_STARTED) .bind(STARTED_HOLD_PREFIX) .bind(pm.as_ref().and_then(ItemError::as_deref)) .bind(UNSTARTED_PREFIX) .bind(ur.as_ref().and_then(ItemError::as_deref)) .bind(CampaignKind::SandboxMemoryDrops.as_str()) .bind(ItemPhase::Done.as_str()) .bind(sf) .bind(outcome.fallback_error()) .bind(matches!(outcome, ItemOutcome::Retry(_))) .bind(CampaignPhase::Canary.as_str()) .bind(CampaignPhase::Paused.as_str()) .fetch_optional(executor.into_sqlx()) .await?; Ok(stored.map(|p| p.parse::().unwrap_or_else(|_| outcome.phase()))) } /// Record `outcome` for `item` and release its lease (`false` if lost); see [`finish_item_phase`]. pub async fn finish_item( executor: impl Executor<'_>, item: &LeasedItem, outcome: &ItemOutcome, ) -> Result { Ok(finish_item_phase(executor, item, outcome).await?.is_some()) } /// Re-drive `campaign_id`'s items stuck `in_flight` past their lease: back to /// pending, to `done` when a final-attempt `sandbox_memory_drops` item already /// committed its drop receipt, or to failed after `max_attempts` leases. pub async fn redrive_expired( executor: impl Executor<'_>, campaign_id: CampaignId, max_attempts: u64, ) -> Result { let pme = ItemError::new(format!("{STARTED_HOLD_PREFIX}{LEASE_EXPIRED}")); let phases = sqlx::query_scalar::<_, String>(sql!( "UPDATE runtime_upgrade_items SET phase = CASE WHEN attempts >= $2 AND (last_error = $7 OR starts_with(last_error, $8)) AND EXISTS (SELECT 1 FROM runtime_upgrade_campaigns WHERE id = $1 AND kind = $10) THEN $11 WHEN attempts >= $2 THEN $3 ELSE $4 END, last_error = CASE WHEN attempts >= $2 AND (last_error = $7 OR starts_with(last_error, $8)) AND EXISTS (SELECT 1 FROM runtime_upgrade_campaigns WHERE id = $1 AND kind = $10) THEN NULL WHEN last_error = $7 OR starts_with(last_error, $8) THEN $9 ELSE $5 END, lease_token = NULL, lease_expires_at = NULL WHERE campaign_id = $1 AND phase = $6 AND lease_expires_at <= clock_timestamp() RETURNING phase" )) .bind(campaign_id) .bind(i64::try_from(max_attempts).unwrap_or(i64::MAX)) .bind(ItemPhase::Failed.as_str()) .bind(ItemPhase::Pending.as_str()) .bind(LEASE_EXPIRED) .bind(ItemPhase::InFlight.as_str()) .bind(RUN_STARTED) .bind(STARTED_HOLD_PREFIX) .bind(pme.as_deref()) .bind(CampaignKind::SandboxMemoryDrops.as_str()) .bind(ItemPhase::Done.as_str()) .fetch_all(executor.into_sqlx()) .await?; let count = |p: ItemPhase| phases.iter().filter(|s| s.as_str() == p.as_str()).count() as u64; Ok(RedriveReport { requeued: count(ItemPhase::Pending), failed: count(ItemPhase::Failed), done: count(ItemPhase::Done), }) } /// Return the in-flight items of finished campaigns whose leases lapsed to /// pending, as [`redrive_expired`] does for an unfinished one. Only an /// aborted campaign can have one: completion needs no item in flight. An aborted /// campaign keeps an item in flight until its worker's lease lapses, so no /// other campaign leases the subject while that worker may still be on it /// ([`lease_items`]); this tidies up after. Returns how many it released. pub async fn release_lapsed_in_finished(executor: impl Executor<'_>) -> Result { let partial_move_expired = ItemError::new(format!("{STARTED_HOLD_PREFIX}{LEASE_EXPIRED}")); Ok(sqlx::query(sql!( "UPDATE runtime_upgrade_items SET phase = $2, last_error = CASE WHEN last_error = $5 OR starts_with(last_error, $6) THEN $7 ELSE $3 END, lease_token = NULL, lease_expires_at = NULL WHERE phase = $1 AND lease_expires_at <= clock_timestamp() AND campaign_id IN ( SELECT id FROM runtime_upgrade_campaigns WHERE phase = $4)" )) .bind(ItemPhase::InFlight.as_str()) .bind(ItemPhase::Pending.as_str()) .bind(LEASE_EXPIRED) .bind(CampaignPhase::Aborted.as_str()) .bind(RUN_STARTED) .bind(STARTED_HOLD_PREFIX) .bind(partial_move_expired.as_deref()) .execute(executor.into_sqlx()) .await? .rows_affected()) }