LCOV - code coverage report
Current view: top level - storage_controller/src - tenant_shard.rs (source / functions) Coverage Total Hit
Test: fabb29a6339542ee130cd1d32b534fafdc0be240.info Lines: 64.2 % 889 571
Test Date: 2024-06-25 13:20:00 Functions: 49.3 % 75 37

            Line data    Source code
       1              : use std::{
       2              :     collections::{HashMap, HashSet},
       3              :     sync::Arc,
       4              :     time::Duration,
       5              : };
       6              : 
       7              : use crate::{
       8              :     metrics::{self, ReconcileCompleteLabelGroup, ReconcileOutcome},
       9              :     persistence::TenantShardPersistence,
      10              :     reconciler::ReconcileUnits,
      11              :     scheduler::{AffinityScore, MaySchedule, RefCountUpdate, ScheduleContext},
      12              : };
      13              : use pageserver_api::controller_api::{
      14              :     NodeSchedulingPolicy, PlacementPolicy, ShardSchedulingPolicy,
      15              : };
      16              : use pageserver_api::{
      17              :     models::{LocationConfig, LocationConfigMode, TenantConfig},
      18              :     shard::{ShardIdentity, TenantShardId},
      19              : };
      20              : use serde::Serialize;
      21              : use tokio::task::JoinHandle;
      22              : use tokio_util::sync::CancellationToken;
      23              : use tracing::{instrument, Instrument};
      24              : use utils::{
      25              :     generation::Generation,
      26              :     id::NodeId,
      27              :     seqwait::{SeqWait, SeqWaitError},
      28              :     sync::gate::GateGuard,
      29              : };
      30              : 
      31              : use crate::{
      32              :     compute_hook::ComputeHook,
      33              :     node::Node,
      34              :     persistence::{split_state::SplitState, Persistence},
      35              :     reconciler::{
      36              :         attached_location_conf, secondary_location_conf, ReconcileError, Reconciler, TargetState,
      37              :     },
      38              :     scheduler::{ScheduleError, Scheduler},
      39              :     service, Sequence,
      40              : };
      41              : 
      42              : /// Serialization helper
      43            0 : fn read_last_error<S, T>(v: &std::sync::Mutex<Option<T>>, serializer: S) -> Result<S::Ok, S::Error>
      44            0 : where
      45            0 :     S: serde::ser::Serializer,
      46            0 :     T: std::fmt::Display,
      47            0 : {
      48            0 :     serializer.collect_str(
      49            0 :         &v.lock()
      50            0 :             .unwrap()
      51            0 :             .as_ref()
      52            0 :             .map(|e| format!("{e}"))
      53            0 :             .unwrap_or("".to_string()),
      54            0 :     )
      55            0 : }
      56              : 
      57              : /// In-memory state for a particular tenant shard.
      58              : ///
      59              : /// This struct implement Serialize for debugging purposes, but is _not_ persisted
      60              : /// itself: see [`crate::persistence`] for the subset of tenant shard state that is persisted.
      61            0 : #[derive(Serialize)]
      62              : pub(crate) struct TenantShard {
      63              :     pub(crate) tenant_shard_id: TenantShardId,
      64              : 
      65              :     pub(crate) shard: ShardIdentity,
      66              : 
      67              :     // Runtime only: sequence used to coordinate when updating this object while
      68              :     // with background reconcilers may be running.  A reconciler runs to a particular
      69              :     // sequence.
      70              :     pub(crate) sequence: Sequence,
      71              : 
      72              :     // Latest generation number: next time we attach, increment this
      73              :     // and use the incremented number when attaching.
      74              :     //
      75              :     // None represents an incompletely onboarded tenant via the [`Service::location_config`]
      76              :     // API, where this tenant may only run in PlacementPolicy::Secondary.
      77              :     pub(crate) generation: Option<Generation>,
      78              : 
      79              :     // High level description of how the tenant should be set up.  Provided
      80              :     // externally.
      81              :     pub(crate) policy: PlacementPolicy,
      82              : 
      83              :     // Low level description of exactly which pageservers should fulfil
      84              :     // which role.  Generated by `Self::schedule`.
      85              :     pub(crate) intent: IntentState,
      86              : 
      87              :     // Low level description of how the tenant is configured on pageservers:
      88              :     // if this does not match `Self::intent` then the tenant needs reconciliation
      89              :     // with `Self::reconcile`.
      90              :     pub(crate) observed: ObservedState,
      91              : 
      92              :     // Tenant configuration, passed through opaquely to the pageserver.  Identical
      93              :     // for all shards in a tenant.
      94              :     pub(crate) config: TenantConfig,
      95              : 
      96              :     /// If a reconcile task is currently in flight, it may be joined here (it is
      97              :     /// only safe to join if either the result has been received or the reconciler's
      98              :     /// cancellation token has been fired)
      99              :     #[serde(skip)]
     100              :     pub(crate) reconciler: Option<ReconcilerHandle>,
     101              : 
     102              :     /// If a tenant is being split, then all shards with that TenantId will have a
     103              :     /// SplitState set, this acts as a guard against other operations such as background
     104              :     /// reconciliation, and timeline creation.
     105              :     pub(crate) splitting: SplitState,
     106              : 
     107              :     /// If a tenant was enqueued for later reconcile due to hitting concurrency limit, this flag
     108              :     /// is set. This flag is cleared when the tenant is popped off the delay queue.
     109              :     pub(crate) delayed_reconcile: bool,
     110              : 
     111              :     /// Optionally wait for reconciliation to complete up to a particular
     112              :     /// sequence number.
     113              :     #[serde(skip)]
     114              :     pub(crate) waiter: std::sync::Arc<SeqWait<Sequence, Sequence>>,
     115              : 
     116              :     /// Indicates sequence number for which we have encountered an error reconciling.  If
     117              :     /// this advances ahead of [`Self::waiter`] then a reconciliation error has occurred,
     118              :     /// and callers should stop waiting for `waiter` and propagate the error.
     119              :     #[serde(skip)]
     120              :     pub(crate) error_waiter: std::sync::Arc<SeqWait<Sequence, Sequence>>,
     121              : 
     122              :     /// The most recent error from a reconcile on this tenant.  This is a nested Arc
     123              :     /// because:
     124              :     ///  - ReconcileWaiters need to Arc-clone the overall object to read it later
     125              :     ///  - ReconcileWaitError needs to use an `Arc<ReconcileError>` because we can construct
     126              :     ///    many waiters for one shard, and the underlying error types are not Clone.
     127              :     /// TODO: generalize to an array of recent events
     128              :     /// TOOD: use a ArcSwap instead of mutex for faster reads?
     129              :     #[serde(serialize_with = "read_last_error")]
     130              :     pub(crate) last_error: std::sync::Arc<std::sync::Mutex<Option<Arc<ReconcileError>>>>,
     131              : 
     132              :     /// If we have a pending compute notification that for some reason we weren't able to send,
     133              :     /// set this to true. If this is set, calls to [`Self::get_reconcile_needed`] will return Yes
     134              :     /// and trigger a Reconciler run.  This is the mechanism by which compute notifications are included in the scope
     135              :     /// of state that we publish externally in an eventually consistent way.
     136              :     pub(crate) pending_compute_notification: bool,
     137              : 
     138              :     // Support/debug tool: if something is going wrong or flapping with scheduling, this may
     139              :     // be set to a non-active state to avoid making changes while the issue is fixed.
     140              :     scheduling_policy: ShardSchedulingPolicy,
     141              : }
     142              : 
     143              : #[derive(Default, Clone, Debug, Serialize)]
     144              : pub(crate) struct IntentState {
     145              :     attached: Option<NodeId>,
     146              :     secondary: Vec<NodeId>,
     147              : }
     148              : 
     149              : impl IntentState {
     150            4 :     pub(crate) fn new() -> Self {
     151            4 :         Self {
     152            4 :             attached: None,
     153            4 :             secondary: vec![],
     154            4 :         }
     155            4 :     }
     156            0 :     pub(crate) fn single(scheduler: &mut Scheduler, node_id: Option<NodeId>) -> Self {
     157            0 :         if let Some(node_id) = node_id {
     158            0 :             scheduler.update_node_ref_counts(node_id, RefCountUpdate::Attach);
     159            0 :         }
     160            0 :         Self {
     161            0 :             attached: node_id,
     162            0 :             secondary: vec![],
     163            0 :         }
     164            0 :     }
     165              : 
     166           26 :     pub(crate) fn set_attached(&mut self, scheduler: &mut Scheduler, new_attached: Option<NodeId>) {
     167           26 :         if self.attached != new_attached {
     168           26 :             if let Some(old_attached) = self.attached.take() {
     169            0 :                 scheduler.update_node_ref_counts(old_attached, RefCountUpdate::Detach);
     170           26 :             }
     171           26 :             if let Some(new_attached) = &new_attached {
     172           26 :                 scheduler.update_node_ref_counts(*new_attached, RefCountUpdate::Attach);
     173           26 :             }
     174           26 :             self.attached = new_attached;
     175            0 :         }
     176           26 :     }
     177              : 
     178              :     /// Like set_attached, but the node is from [`Self::secondary`].  This swaps the node from
     179              :     /// secondary to attached while maintaining the scheduler's reference counts.
     180           10 :     pub(crate) fn promote_attached(
     181           10 :         &mut self,
     182           10 :         scheduler: &mut Scheduler,
     183           10 :         promote_secondary: NodeId,
     184           10 :     ) {
     185           10 :         // If we call this with a node that isn't in secondary, it would cause incorrect
     186           10 :         // scheduler reference counting, since we assume the node is already referenced as a secondary.
     187           10 :         debug_assert!(self.secondary.contains(&promote_secondary));
     188              : 
     189           20 :         self.secondary.retain(|n| n != &promote_secondary);
     190           10 : 
     191           10 :         let demoted = self.attached;
     192           10 :         self.attached = Some(promote_secondary);
     193           10 : 
     194           10 :         scheduler.update_node_ref_counts(promote_secondary, RefCountUpdate::PromoteSecondary);
     195           10 :         if let Some(demoted) = demoted {
     196            0 :             scheduler.update_node_ref_counts(demoted, RefCountUpdate::DemoteAttached);
     197           10 :         }
     198           10 :     }
     199              : 
     200           34 :     pub(crate) fn push_secondary(&mut self, scheduler: &mut Scheduler, new_secondary: NodeId) {
     201           34 :         debug_assert!(!self.secondary.contains(&new_secondary));
     202           34 :         scheduler.update_node_ref_counts(new_secondary, RefCountUpdate::AddSecondary);
     203           34 :         self.secondary.push(new_secondary);
     204           34 :     }
     205              : 
     206              :     /// It is legal to call this with a node that is not currently a secondary: that is a no-op
     207           10 :     pub(crate) fn remove_secondary(&mut self, scheduler: &mut Scheduler, node_id: NodeId) {
     208           10 :         let index = self.secondary.iter().position(|n| *n == node_id);
     209           10 :         if let Some(index) = index {
     210           10 :             scheduler.update_node_ref_counts(node_id, RefCountUpdate::RemoveSecondary);
     211           10 :             self.secondary.remove(index);
     212           10 :         }
     213           10 :     }
     214              : 
     215           24 :     pub(crate) fn clear_secondary(&mut self, scheduler: &mut Scheduler) {
     216           24 :         for secondary in self.secondary.drain(..) {
     217           24 :             scheduler.update_node_ref_counts(secondary, RefCountUpdate::RemoveSecondary);
     218           24 :         }
     219           24 :     }
     220              : 
     221              :     /// Remove the last secondary node from the list of secondaries
     222            0 :     pub(crate) fn pop_secondary(&mut self, scheduler: &mut Scheduler) {
     223            0 :         if let Some(node_id) = self.secondary.pop() {
     224            0 :             scheduler.update_node_ref_counts(node_id, RefCountUpdate::RemoveSecondary);
     225            0 :         }
     226            0 :     }
     227              : 
     228           24 :     pub(crate) fn clear(&mut self, scheduler: &mut Scheduler) {
     229           24 :         if let Some(old_attached) = self.attached.take() {
     230           24 :             scheduler.update_node_ref_counts(old_attached, RefCountUpdate::Detach);
     231           24 :         }
     232              : 
     233           24 :         self.clear_secondary(scheduler);
     234           24 :     }
     235              : 
     236          140 :     pub(crate) fn all_pageservers(&self) -> Vec<NodeId> {
     237          140 :         let mut result = Vec::new();
     238          140 :         if let Some(p) = self.attached {
     239          136 :             result.push(p)
     240            4 :         }
     241              : 
     242          140 :         result.extend(self.secondary.iter().copied());
     243          140 : 
     244          140 :         result
     245          140 :     }
     246              : 
     247          118 :     pub(crate) fn get_attached(&self) -> &Option<NodeId> {
     248          118 :         &self.attached
     249          118 :     }
     250              : 
     251           32 :     pub(crate) fn get_secondary(&self) -> &Vec<NodeId> {
     252           32 :         &self.secondary
     253           32 :     }
     254              : 
     255              :     /// If the node is in use as the attached location, demote it into
     256              :     /// the list of secondary locations.  This is used when a node goes offline,
     257              :     /// and we want to use a different node for attachment, but not permanently
     258              :     /// forget the location on the offline node.
     259              :     ///
     260              :     /// Returns true if a change was made
     261           10 :     pub(crate) fn demote_attached(&mut self, scheduler: &mut Scheduler, node_id: NodeId) -> bool {
     262           10 :         if self.attached == Some(node_id) {
     263           10 :             self.attached = None;
     264           10 :             self.secondary.push(node_id);
     265           10 :             scheduler.update_node_ref_counts(node_id, RefCountUpdate::DemoteAttached);
     266           10 :             true
     267              :         } else {
     268            0 :             false
     269              :         }
     270           10 :     }
     271              : }
     272              : 
     273              : impl Drop for IntentState {
     274           26 :     fn drop(&mut self) {
     275           26 :         // Must clear before dropping, to avoid leaving stale refcounts in the Scheduler.
     276           26 :         // We do not check this while panicking, to avoid polluting unit test failures or
     277           26 :         // other assertions with this assertion's output.  It's still wrong to leak these,
     278           26 :         // but if we already have a panic then we don't need to independently flag this case.
     279           26 :         if !(std::thread::panicking()) {
     280           26 :             debug_assert!(self.attached.is_none() && self.secondary.is_empty());
     281            0 :         }
     282           24 :     }
     283              : }
     284              : 
     285              : #[derive(Default, Clone, Serialize)]
     286              : pub(crate) struct ObservedState {
     287              :     pub(crate) locations: HashMap<NodeId, ObservedStateLocation>,
     288              : }
     289              : 
     290              : /// Our latest knowledge of how this tenant is configured in the outside world.
     291              : ///
     292              : /// Meaning:
     293              : ///     * No instance of this type exists for a node: we are certain that we have nothing configured on that
     294              : ///       node for this shard.
     295              : ///     * Instance exists with conf==None: we *might* have some state on that node, but we don't know
     296              : ///       what it is (e.g. we failed partway through configuring it)
     297              : ///     * Instance exists with conf==Some: this tells us what we last successfully configured on this node,
     298              : ///       and that configuration will still be present unless something external interfered.
     299              : #[derive(Clone, Serialize)]
     300              : pub(crate) struct ObservedStateLocation {
     301              :     /// If None, it means we do not know the status of this shard's location on this node, but
     302              :     /// we know that we might have some state on this node.
     303              :     pub(crate) conf: Option<LocationConfig>,
     304              : }
     305              : pub(crate) struct ReconcilerWaiter {
     306              :     // For observability purposes, remember the ID of the shard we're
     307              :     // waiting for.
     308              :     pub(crate) tenant_shard_id: TenantShardId,
     309              : 
     310              :     seq_wait: std::sync::Arc<SeqWait<Sequence, Sequence>>,
     311              :     error_seq_wait: std::sync::Arc<SeqWait<Sequence, Sequence>>,
     312              :     error: std::sync::Arc<std::sync::Mutex<Option<Arc<ReconcileError>>>>,
     313              :     seq: Sequence,
     314              : }
     315              : 
     316              : pub(crate) enum ReconcilerStatus {
     317              :     Done,
     318              :     Failed,
     319              :     InProgress,
     320              : }
     321              : 
     322            0 : #[derive(thiserror::Error, Debug)]
     323              : pub(crate) enum ReconcileWaitError {
     324              :     #[error("Timeout waiting for shard {0}")]
     325              :     Timeout(TenantShardId),
     326              :     #[error("shutting down")]
     327              :     Shutdown,
     328              :     #[error("Reconcile error on shard {0}: {1}")]
     329              :     Failed(TenantShardId, Arc<ReconcileError>),
     330              : }
     331              : 
     332              : #[derive(Eq, PartialEq, Debug)]
     333              : pub(crate) struct ReplaceSecondary {
     334              :     old_node_id: NodeId,
     335              :     new_node_id: NodeId,
     336              : }
     337              : 
     338              : #[derive(Eq, PartialEq, Debug)]
     339              : pub(crate) struct MigrateAttachment {
     340              :     pub(crate) old_attached_node_id: NodeId,
     341              :     pub(crate) new_attached_node_id: NodeId,
     342              : }
     343              : 
     344              : #[derive(Eq, PartialEq, Debug)]
     345              : pub(crate) enum ScheduleOptimizationAction {
     346              :     // Replace one of our secondary locations with a different node
     347              :     ReplaceSecondary(ReplaceSecondary),
     348              :     // Migrate attachment to an existing secondary location
     349              :     MigrateAttachment(MigrateAttachment),
     350              : }
     351              : 
     352              : #[derive(Eq, PartialEq, Debug)]
     353              : pub(crate) struct ScheduleOptimization {
     354              :     // What was the reconcile sequence when we generated this optimization?  The optimization
     355              :     // should only be applied if the shard's sequence is still at this value, in case other changes
     356              :     // happened between planning the optimization and applying it.
     357              :     sequence: Sequence,
     358              : 
     359              :     pub(crate) action: ScheduleOptimizationAction,
     360              : }
     361              : 
     362              : impl ReconcilerWaiter {
     363            0 :     pub(crate) async fn wait_timeout(&self, timeout: Duration) -> Result<(), ReconcileWaitError> {
     364              :         tokio::select! {
     365              :             result = self.seq_wait.wait_for_timeout(self.seq, timeout)=> {
     366            0 :                 result.map_err(|e| match e {
     367            0 :                     SeqWaitError::Timeout => ReconcileWaitError::Timeout(self.tenant_shard_id),
     368            0 :                     SeqWaitError::Shutdown => ReconcileWaitError::Shutdown
     369            0 :                 })?;
     370              :             },
     371              :             result = self.error_seq_wait.wait_for(self.seq) => {
     372            0 :                 result.map_err(|e| match e {
     373            0 :                     SeqWaitError::Shutdown => ReconcileWaitError::Shutdown,
     374            0 :                     SeqWaitError::Timeout => unreachable!()
     375            0 :                 })?;
     376              : 
     377              :                 return Err(ReconcileWaitError::Failed(self.tenant_shard_id,
     378              :                     self.error.lock().unwrap().clone().expect("If error_seq_wait was advanced error was set").clone()))
     379              :             }
     380              :         }
     381              : 
     382            0 :         Ok(())
     383            0 :     }
     384              : 
     385            0 :     pub(crate) fn get_status(&self) -> ReconcilerStatus {
     386            0 :         if self.seq_wait.would_wait_for(self.seq).is_err() {
     387            0 :             ReconcilerStatus::Done
     388            0 :         } else if self.error_seq_wait.would_wait_for(self.seq).is_err() {
     389            0 :             ReconcilerStatus::Failed
     390              :         } else {
     391            0 :             ReconcilerStatus::InProgress
     392              :         }
     393            0 :     }
     394              : }
     395              : 
     396              : /// Having spawned a reconciler task, the tenant shard's state will carry enough
     397              : /// information to optionally cancel & await it later.
     398              : pub(crate) struct ReconcilerHandle {
     399              :     sequence: Sequence,
     400              :     handle: JoinHandle<()>,
     401              :     cancel: CancellationToken,
     402              : }
     403              : 
     404              : pub(crate) enum ReconcileNeeded {
     405              :     /// shard either doesn't need reconciliation, or is forbidden from spawning a reconciler
     406              :     /// in its current state (e.g. shard split in progress, or ShardSchedulingPolicy forbids it)
     407              :     No,
     408              :     /// shard has a reconciler running, and its intent hasn't changed since that one was
     409              :     /// spawned: wait for the existing reconciler rather than spawning a new one.
     410              :     WaitExisting(ReconcilerWaiter),
     411              :     /// shard needs reconciliation: call into [`TenantShard::spawn_reconciler`]
     412              :     Yes,
     413              : }
     414              : 
     415              : /// When a reconcile task completes, it sends this result object
     416              : /// to be applied to the primary TenantShard.
     417              : pub(crate) struct ReconcileResult {
     418              :     pub(crate) sequence: Sequence,
     419              :     /// On errors, `observed` should be treated as an incompleted description
     420              :     /// of state (i.e. any nodes present in the result should override nodes
     421              :     /// present in the parent tenant state, but any unmentioned nodes should
     422              :     /// not be removed from parent tenant state)
     423              :     pub(crate) result: Result<(), ReconcileError>,
     424              : 
     425              :     pub(crate) tenant_shard_id: TenantShardId,
     426              :     pub(crate) generation: Option<Generation>,
     427              :     pub(crate) observed: ObservedState,
     428              : 
     429              :     /// Set [`TenantShard::pending_compute_notification`] from this flag
     430              :     pub(crate) pending_compute_notification: bool,
     431              : }
     432              : 
     433              : impl ObservedState {
     434            0 :     pub(crate) fn new() -> Self {
     435            0 :         Self {
     436            0 :             locations: HashMap::new(),
     437            0 :         }
     438            0 :     }
     439              : }
     440              : 
     441              : impl TenantShard {
     442           22 :     pub(crate) fn new(
     443           22 :         tenant_shard_id: TenantShardId,
     444           22 :         shard: ShardIdentity,
     445           22 :         policy: PlacementPolicy,
     446           22 :     ) -> Self {
     447           22 :         Self {
     448           22 :             tenant_shard_id,
     449           22 :             policy,
     450           22 :             intent: IntentState::default(),
     451           22 :             generation: Some(Generation::new(0)),
     452           22 :             shard,
     453           22 :             observed: ObservedState::default(),
     454           22 :             config: TenantConfig::default(),
     455           22 :             reconciler: None,
     456           22 :             splitting: SplitState::Idle,
     457           22 :             sequence: Sequence(1),
     458           22 :             delayed_reconcile: false,
     459           22 :             waiter: Arc::new(SeqWait::new(Sequence(0))),
     460           22 :             error_waiter: Arc::new(SeqWait::new(Sequence(0))),
     461           22 :             last_error: Arc::default(),
     462           22 :             pending_compute_notification: false,
     463           22 :             scheduling_policy: ShardSchedulingPolicy::default(),
     464           22 :         }
     465           22 :     }
     466              : 
     467              :     /// For use on startup when learning state from pageservers: generate my [`IntentState`] from my
     468              :     /// [`ObservedState`], even if it violates my [`PlacementPolicy`].  Call [`Self::schedule`] next,
     469              :     /// to get an intent state that complies with placement policy.  The overall goal is to do scheduling
     470              :     /// in a way that makes use of any configured locations that already exist in the outside world.
     471            2 :     pub(crate) fn intent_from_observed(&mut self, scheduler: &mut Scheduler) {
     472            2 :         // Choose an attached location by filtering observed locations, and then sorting to get the highest
     473            2 :         // generation
     474            2 :         let mut attached_locs = self
     475            2 :             .observed
     476            2 :             .locations
     477            2 :             .iter()
     478            4 :             .filter_map(|(node_id, l)| {
     479            4 :                 if let Some(conf) = &l.conf {
     480            4 :                     if conf.mode == LocationConfigMode::AttachedMulti
     481            2 :                         || conf.mode == LocationConfigMode::AttachedSingle
     482            2 :                         || conf.mode == LocationConfigMode::AttachedStale
     483              :                     {
     484            4 :                         Some((node_id, conf.generation))
     485              :                     } else {
     486            0 :                         None
     487              :                     }
     488              :                 } else {
     489            0 :                     None
     490              :                 }
     491            4 :             })
     492            2 :             .collect::<Vec<_>>();
     493            2 : 
     494            4 :         attached_locs.sort_by_key(|i| i.1);
     495            2 :         if let Some((node_id, _gen)) = attached_locs.into_iter().last() {
     496            2 :             self.intent.set_attached(scheduler, Some(*node_id));
     497            2 :         }
     498              : 
     499              :         // All remaining observed locations generate secondary intents.  This includes None
     500              :         // observations, as these may well have some local content on disk that is usable (this
     501              :         // is an edge case that might occur if we restarted during a migration or other change)
     502              :         //
     503              :         // We may leave intent.attached empty if we didn't find any attached locations: [`Self::schedule`]
     504              :         // will take care of promoting one of these secondaries to be attached.
     505            4 :         self.observed.locations.keys().for_each(|node_id| {
     506            4 :             if Some(*node_id) != self.intent.attached {
     507            2 :                 self.intent.push_secondary(scheduler, *node_id);
     508            2 :             }
     509            4 :         });
     510            2 :     }
     511              : 
     512              :     /// Part of [`Self::schedule`] that is used to choose exactly one node to act as the
     513              :     /// attached pageserver for a shard.
     514              :     ///
     515              :     /// Returns whether we modified it, and the NodeId selected.
     516           14 :     fn schedule_attached(
     517           14 :         &mut self,
     518           14 :         scheduler: &mut Scheduler,
     519           14 :         context: &ScheduleContext,
     520           14 :     ) -> Result<(bool, NodeId), ScheduleError> {
     521              :         // No work to do if we already have an attached tenant
     522           14 :         if let Some(node_id) = self.intent.attached {
     523            0 :             return Ok((false, node_id));
     524           14 :         }
     525              : 
     526           14 :         if let Some(promote_secondary) = scheduler.node_preferred(&self.intent.secondary) {
     527              :             // Promote a secondary
     528            2 :             tracing::debug!("Promoted secondary {} to attached", promote_secondary);
     529            2 :             self.intent.promote_attached(scheduler, promote_secondary);
     530            2 :             Ok((true, promote_secondary))
     531              :         } else {
     532              :             // Pick a fresh node: either we had no secondaries or none were schedulable
     533           12 :             let node_id = scheduler.schedule_shard(&self.intent.secondary, context)?;
     534           12 :             tracing::debug!("Selected {} as attached", node_id);
     535           12 :             self.intent.set_attached(scheduler, Some(node_id));
     536           12 :             Ok((true, node_id))
     537              :         }
     538           14 :     }
     539              : 
     540           16 :     pub(crate) fn schedule(
     541           16 :         &mut self,
     542           16 :         scheduler: &mut Scheduler,
     543           16 :         context: &mut ScheduleContext,
     544           16 :     ) -> Result<(), ScheduleError> {
     545           16 :         let r = self.do_schedule(scheduler, context);
     546           16 : 
     547           16 :         context.avoid(&self.intent.all_pageservers());
     548           16 :         if let Some(attached) = self.intent.get_attached() {
     549           14 :             context.push_attached(*attached);
     550           14 :         }
     551              : 
     552           16 :         r
     553           16 :     }
     554              : 
     555           16 :     pub(crate) fn do_schedule(
     556           16 :         &mut self,
     557           16 :         scheduler: &mut Scheduler,
     558           16 :         context: &ScheduleContext,
     559           16 :     ) -> Result<(), ScheduleError> {
     560           16 :         // TODO: before scheduling new nodes, check if any existing content in
     561           16 :         // self.intent refers to pageservers that are offline, and pick other
     562           16 :         // pageservers if so.
     563           16 : 
     564           16 :         // TODO: respect the splitting bit on tenants: if they are currently splitting then we may not
     565           16 :         // change their attach location.
     566           16 : 
     567           16 :         match self.scheduling_policy {
     568           14 :             ShardSchedulingPolicy::Active | ShardSchedulingPolicy::Essential => {}
     569              :             ShardSchedulingPolicy::Pause | ShardSchedulingPolicy::Stop => {
     570              :                 // Warn to make it obvious why other things aren't happening/working, if we skip scheduling
     571            2 :                 tracing::warn!(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(),
     572            0 :                     "Scheduling is disabled by policy {:?}", self.scheduling_policy);
     573            2 :                 return Ok(());
     574              :             }
     575              :         }
     576              : 
     577              :         // Build the set of pageservers already in use by this tenant, to avoid scheduling
     578              :         // more work on the same pageservers we're already using.
     579           14 :         let mut modified = false;
     580           14 : 
     581           14 :         // Add/remove nodes to fulfil policy
     582           14 :         use PlacementPolicy::*;
     583           14 :         match self.policy {
     584           14 :             Attached(secondary_count) => {
     585           14 :                 let retain_secondaries = if self.intent.attached.is_none()
     586           14 :                     && scheduler.node_preferred(&self.intent.secondary).is_some()
     587              :                 {
     588              :                     // If we have no attached, and one of the secondaries is elegible to be promoted, retain
     589              :                     // one more secondary than we usually would, as one of them will become attached futher down this function.
     590            2 :                     secondary_count + 1
     591              :                 } else {
     592           12 :                     secondary_count
     593              :                 };
     594              : 
     595           14 :                 while self.intent.secondary.len() > retain_secondaries {
     596            0 :                     // We have no particular preference for one secondary location over another: just
     597            0 :                     // arbitrarily drop from the end
     598            0 :                     self.intent.pop_secondary(scheduler);
     599            0 :                     modified = true;
     600            0 :                 }
     601              : 
     602              :                 // Should have exactly one attached, and N secondaries
     603           14 :                 let (modified_attached, attached_node_id) =
     604           14 :                     self.schedule_attached(scheduler, context)?;
     605           14 :                 modified |= modified_attached;
     606           14 : 
     607           14 :                 let mut used_pageservers = vec![attached_node_id];
     608           26 :                 while self.intent.secondary.len() < secondary_count {
     609           12 :                     let node_id = scheduler.schedule_shard(&used_pageservers, context)?;
     610           12 :                     self.intent.push_secondary(scheduler, node_id);
     611           12 :                     used_pageservers.push(node_id);
     612           12 :                     modified = true;
     613              :                 }
     614              :             }
     615              :             Secondary => {
     616            0 :                 if let Some(node_id) = self.intent.get_attached() {
     617            0 :                     // Populate secondary by demoting the attached node
     618            0 :                     self.intent.demote_attached(scheduler, *node_id);
     619            0 :                     modified = true;
     620            0 :                 } else if self.intent.secondary.is_empty() {
     621            0 :                     // Populate secondary by scheduling a fresh node
     622            0 :                     let node_id = scheduler.schedule_shard(&[], context)?;
     623            0 :                     self.intent.push_secondary(scheduler, node_id);
     624            0 :                     modified = true;
     625            0 :                 }
     626            0 :                 while self.intent.secondary.len() > 1 {
     627            0 :                     // We have no particular preference for one secondary location over another: just
     628            0 :                     // arbitrarily drop from the end
     629            0 :                     self.intent.pop_secondary(scheduler);
     630            0 :                     modified = true;
     631            0 :                 }
     632              :             }
     633              :             Detached => {
     634              :                 // Never add locations in this mode
     635            0 :                 if self.intent.get_attached().is_some() || !self.intent.get_secondary().is_empty() {
     636            0 :                     self.intent.clear(scheduler);
     637            0 :                     modified = true;
     638            0 :                 }
     639              :             }
     640              :         }
     641              : 
     642           14 :         if modified {
     643           14 :             self.sequence.0 += 1;
     644           14 :         }
     645              : 
     646           14 :         Ok(())
     647           16 :     }
     648              : 
     649              :     /// Reschedule this tenant shard to one of its secondary locations. Returns a scheduling error
     650              :     /// if the swap is not possible and leaves the intent state in its original state.
     651              :     ///
     652              :     /// Arguments:
     653              :     /// `attached_to`: the currently attached location matching the intent state (may be None if the
     654              :     /// shard is not attached)
     655              :     /// `promote_to`: an optional secondary location of this tenant shard. If set to None, we ask
     656              :     /// the scheduler to recommend a node
     657            0 :     pub(crate) fn reschedule_to_secondary(
     658            0 :         &mut self,
     659            0 :         promote_to: Option<NodeId>,
     660            0 :         scheduler: &mut Scheduler,
     661            0 :     ) -> Result<(), ScheduleError> {
     662            0 :         let promote_to = match promote_to {
     663            0 :             Some(node) => node,
     664            0 :             None => match scheduler.node_preferred(self.intent.get_secondary()) {
     665            0 :                 Some(node) => node,
     666              :                 None => {
     667            0 :                     return Err(ScheduleError::ImpossibleConstraint);
     668              :                 }
     669              :             },
     670              :         };
     671              : 
     672            0 :         assert!(self.intent.get_secondary().contains(&promote_to));
     673              : 
     674            0 :         if let Some(node) = self.intent.get_attached() {
     675            0 :             let demoted = self.intent.demote_attached(scheduler, *node);
     676            0 :             if !demoted {
     677            0 :                 return Err(ScheduleError::ImpossibleConstraint);
     678            0 :             }
     679            0 :         }
     680              : 
     681            0 :         self.intent.promote_attached(scheduler, promote_to);
     682            0 : 
     683            0 :         // Increment the sequence number for the edge case where a
     684            0 :         // reconciler is already running to avoid waiting on the
     685            0 :         // current reconcile instead of spawning a new one.
     686            0 :         self.sequence = self.sequence.next();
     687            0 : 
     688            0 :         Ok(())
     689            0 :     }
     690              : 
     691              :     /// Optimize attachments: if a shard has a secondary location that is preferable to
     692              :     /// its primary location based on soft constraints, switch that secondary location
     693              :     /// to be attached.
     694           30 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
     695              :     pub(crate) fn optimize_attachment(
     696              :         &self,
     697              :         nodes: &HashMap<NodeId, Node>,
     698              :         schedule_context: &ScheduleContext,
     699              :     ) -> Option<ScheduleOptimization> {
     700              :         let attached = (*self.intent.get_attached())?;
     701              :         if self.intent.secondary.is_empty() {
     702              :             // We can only do useful work if we have both attached and secondary locations: this
     703              :             // function doesn't schedule new locations, only swaps between attached and secondaries.
     704              :             return None;
     705              :         }
     706              : 
     707              :         let current_affinity_score = schedule_context.get_node_affinity(attached);
     708              :         let current_attachment_count = schedule_context.get_node_attachments(attached);
     709              : 
     710              :         // Generate score for each node, dropping any un-schedulable nodes.
     711              :         let all_pageservers = self.intent.all_pageservers();
     712              :         let mut scores = all_pageservers
     713              :             .iter()
     714           60 :             .flat_map(|node_id| {
     715           60 :                 let node = nodes.get(node_id);
     716           60 :                 if node.is_none() {
     717            0 :                     None
     718           60 :                 } else if matches!(
     719           60 :                     node.unwrap().get_scheduling(),
     720              :                     NodeSchedulingPolicy::Filling
     721              :                 ) {
     722              :                     // If the node is currently filling, don't count it as a candidate to avoid,
     723              :                     // racing with the background fill.
     724            0 :                     None
     725           60 :                 } else if matches!(node.unwrap().may_schedule(), MaySchedule::No) {
     726            0 :                     None
     727              :                 } else {
     728           60 :                     let affinity_score = schedule_context.get_node_affinity(*node_id);
     729           60 :                     let attachment_count = schedule_context.get_node_attachments(*node_id);
     730           60 :                     Some((*node_id, affinity_score, attachment_count))
     731              :                 }
     732           60 :             })
     733              :             .collect::<Vec<_>>();
     734              : 
     735              :         // Sort precedence:
     736              :         //  1st - prefer nodes with the lowest total affinity score
     737              :         //  2nd - prefer nodes with the lowest number of attachments in this context
     738              :         //  3rd - if all else is equal, sort by node ID for determinism in tests.
     739           60 :         scores.sort_by_key(|i| (i.1, i.2, i.0));
     740              : 
     741              :         if let Some((preferred_node, preferred_affinity_score, preferred_attachment_count)) =
     742              :             scores.first()
     743              :         {
     744              :             if attached != *preferred_node {
     745              :                 // The best alternative must be more than 1 better than us, otherwise we could end
     746              :                 // up flapping back next time we're called (e.g. there's no point migrating from
     747              :                 // a location with score 1 to a score zero, because on next location the situation
     748              :                 // would be the same, but in reverse).
     749              :                 if current_affinity_score > *preferred_affinity_score + AffinityScore(1)
     750              :                     || current_attachment_count > *preferred_attachment_count + 1
     751              :                 {
     752              :                     tracing::info!(
     753              :                         "Identified optimization: migrate attachment {attached}->{preferred_node} (secondaries {:?})",
     754              :                         self.intent.get_secondary()
     755              :                     );
     756              :                     return Some(ScheduleOptimization {
     757              :                         sequence: self.sequence,
     758              :                         action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
     759              :                             old_attached_node_id: attached,
     760              :                             new_attached_node_id: *preferred_node,
     761              :                         }),
     762              :                     });
     763              :                 }
     764              :             } else {
     765              :                 tracing::debug!(
     766              :                     "Node {} is already preferred (score {:?})",
     767              :                     preferred_node,
     768              :                     preferred_affinity_score
     769              :                 );
     770              :             }
     771              :         }
     772              : 
     773              :         // Fall-through: we didn't find an optimization
     774              :         None
     775              :     }
     776              : 
     777           24 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
     778              :     pub(crate) fn optimize_secondary(
     779              :         &self,
     780              :         scheduler: &Scheduler,
     781              :         schedule_context: &ScheduleContext,
     782              :     ) -> Option<ScheduleOptimization> {
     783              :         if self.intent.secondary.is_empty() {
     784              :             // We can only do useful work if we have both attached and secondary locations: this
     785              :             // function doesn't schedule new locations, only swaps between attached and secondaries.
     786              :             return None;
     787              :         }
     788              : 
     789              :         for secondary in self.intent.get_secondary() {
     790              :             let Some(affinity_score) = schedule_context.nodes.get(secondary) else {
     791              :                 // We're already on a node unaffected any affinity constraints,
     792              :                 // so we won't change it.
     793              :                 continue;
     794              :             };
     795              : 
     796              :             // Let the scheduler suggest a node, where it would put us if we were scheduling afresh
     797              :             // This implicitly limits the choice to nodes that are available, and prefers nodes
     798              :             // with lower utilization.
     799              :             let Ok(candidate_node) =
     800              :                 scheduler.schedule_shard(&self.intent.all_pageservers(), schedule_context)
     801              :             else {
     802              :                 // A scheduling error means we have no possible candidate replacements
     803              :                 continue;
     804              :             };
     805              : 
     806              :             let candidate_affinity_score = schedule_context
     807              :                 .nodes
     808              :                 .get(&candidate_node)
     809              :                 .unwrap_or(&AffinityScore::FREE);
     810              : 
     811              :             // The best alternative must be more than 1 better than us, otherwise we could end
     812              :             // up flapping back next time we're called.
     813              :             if *candidate_affinity_score + AffinityScore(1) < *affinity_score {
     814              :                 // If some other node is available and has a lower score than this node, then
     815              :                 // that other node is a good place to migrate to.
     816              :                 tracing::info!(
     817              :                     "Identified optimization: replace secondary {secondary}->{candidate_node} (current secondaries {:?})",
     818              :                     self.intent.get_secondary()
     819              :                 );
     820              :                 return Some(ScheduleOptimization {
     821              :                     sequence: self.sequence,
     822              :                     action: ScheduleOptimizationAction::ReplaceSecondary(ReplaceSecondary {
     823              :                         old_node_id: *secondary,
     824              :                         new_node_id: candidate_node,
     825              :                     }),
     826              :                 });
     827              :             }
     828              :         }
     829              : 
     830              :         None
     831              :     }
     832              : 
     833              :     /// Return true if the optimization was really applied: it will not be applied if the optimization's
     834              :     /// sequence is behind this tenant shard's
     835           18 :     pub(crate) fn apply_optimization(
     836           18 :         &mut self,
     837           18 :         scheduler: &mut Scheduler,
     838           18 :         optimization: ScheduleOptimization,
     839           18 :     ) -> bool {
     840           18 :         if optimization.sequence != self.sequence {
     841            0 :             return false;
     842           18 :         }
     843           18 : 
     844           18 :         metrics::METRICS_REGISTRY
     845           18 :             .metrics_group
     846           18 :             .storage_controller_schedule_optimization
     847           18 :             .inc();
     848           18 : 
     849           18 :         match optimization.action {
     850              :             ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
     851            8 :                 old_attached_node_id,
     852            8 :                 new_attached_node_id,
     853            8 :             }) => {
     854            8 :                 self.intent.demote_attached(scheduler, old_attached_node_id);
     855            8 :                 self.intent
     856            8 :                     .promote_attached(scheduler, new_attached_node_id);
     857            8 :             }
     858              :             ScheduleOptimizationAction::ReplaceSecondary(ReplaceSecondary {
     859           10 :                 old_node_id,
     860           10 :                 new_node_id,
     861           10 :             }) => {
     862           10 :                 self.intent.remove_secondary(scheduler, old_node_id);
     863           10 :                 self.intent.push_secondary(scheduler, new_node_id);
     864           10 :             }
     865              :         }
     866              : 
     867           18 :         true
     868           18 :     }
     869              : 
     870              :     /// Query whether the tenant's observed state for attached node matches its intent state, and if so,
     871              :     /// yield the node ID.  This is appropriate for emitting compute hook notifications: we are checking that
     872              :     /// the node in question is not only where we intend to attach, but that the tenant is indeed already attached there.
     873              :     ///
     874              :     /// Reconciliation may still be needed for other aspects of state such as secondaries (see [`Self::dirty`]): this
     875              :     /// funciton should not be used to decide whether to reconcile.
     876            0 :     pub(crate) fn stably_attached(&self) -> Option<NodeId> {
     877            0 :         if let Some(attach_intent) = self.intent.attached {
     878            0 :             match self.observed.locations.get(&attach_intent) {
     879            0 :                 Some(loc) => match &loc.conf {
     880            0 :                     Some(conf) => match conf.mode {
     881              :                         LocationConfigMode::AttachedMulti
     882              :                         | LocationConfigMode::AttachedSingle
     883              :                         | LocationConfigMode::AttachedStale => {
     884              :                             // Our intent and observed state agree that this node is in an attached state.
     885            0 :                             Some(attach_intent)
     886              :                         }
     887              :                         // Our observed config is not an attached state
     888            0 :                         _ => None,
     889              :                     },
     890              :                     // Our observed state is None, i.e. in flux
     891            0 :                     None => None,
     892              :                 },
     893              :                 // We have no observed state for this node
     894            0 :                 None => None,
     895              :             }
     896              :         } else {
     897              :             // Our intent is not to attach
     898            0 :             None
     899              :         }
     900            0 :     }
     901              : 
     902            0 :     fn dirty(&self, nodes: &Arc<HashMap<NodeId, Node>>) -> bool {
     903            0 :         let mut dirty_nodes = HashSet::new();
     904              : 
     905            0 :         if let Some(node_id) = self.intent.attached {
     906              :             // Maybe panic: it is a severe bug if we try to attach while generation is null.
     907            0 :             let generation = self
     908            0 :                 .generation
     909            0 :                 .expect("Attempted to enter attached state without a generation");
     910            0 : 
     911            0 :             let wanted_conf = attached_location_conf(
     912            0 :                 generation,
     913            0 :                 &self.shard,
     914            0 :                 &self.config,
     915            0 :                 !self.intent.secondary.is_empty(),
     916            0 :             );
     917            0 :             match self.observed.locations.get(&node_id) {
     918            0 :                 Some(conf) if conf.conf.as_ref() == Some(&wanted_conf) => {}
     919            0 :                 Some(_) | None => {
     920            0 :                     dirty_nodes.insert(node_id);
     921            0 :                 }
     922              :             }
     923            0 :         }
     924              : 
     925            0 :         for node_id in &self.intent.secondary {
     926            0 :             let wanted_conf = secondary_location_conf(&self.shard, &self.config);
     927            0 :             match self.observed.locations.get(node_id) {
     928            0 :                 Some(conf) if conf.conf.as_ref() == Some(&wanted_conf) => {}
     929            0 :                 Some(_) | None => {
     930            0 :                     dirty_nodes.insert(*node_id);
     931            0 :                 }
     932              :             }
     933              :         }
     934              : 
     935            0 :         for node_id in self.observed.locations.keys() {
     936            0 :             if self.intent.attached != Some(*node_id) && !self.intent.secondary.contains(node_id) {
     937            0 :                 // We have observed state that isn't part of our intent: need to clean it up.
     938            0 :                 dirty_nodes.insert(*node_id);
     939            0 :             }
     940              :         }
     941              : 
     942            0 :         dirty_nodes.retain(|node_id| {
     943            0 :             nodes
     944            0 :                 .get(node_id)
     945            0 :                 .map(|n| n.is_available())
     946            0 :                 .unwrap_or(false)
     947            0 :         });
     948            0 : 
     949            0 :         !dirty_nodes.is_empty()
     950            0 :     }
     951              : 
     952              :     #[allow(clippy::too_many_arguments)]
     953            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
     954              :     pub(crate) fn get_reconcile_needed(
     955              :         &mut self,
     956              :         pageservers: &Arc<HashMap<NodeId, Node>>,
     957              :     ) -> ReconcileNeeded {
     958              :         // If there are any ambiguous observed states, and the nodes they refer to are available,
     959              :         // we should reconcile to clean them up.
     960              :         let mut dirty_observed = false;
     961              :         for (node_id, observed_loc) in &self.observed.locations {
     962              :             let node = pageservers
     963              :                 .get(node_id)
     964              :                 .expect("Nodes may not be removed while referenced");
     965              :             if observed_loc.conf.is_none() && node.is_available() {
     966              :                 dirty_observed = true;
     967              :                 break;
     968              :             }
     969              :         }
     970              : 
     971              :         let active_nodes_dirty = self.dirty(pageservers);
     972              : 
     973              :         // Even if there is no pageserver work to be done, if we have a pending notification to computes,
     974              :         // wake up a reconciler to send it.
     975              :         let do_reconcile =
     976              :             active_nodes_dirty || dirty_observed || self.pending_compute_notification;
     977              : 
     978              :         if !do_reconcile {
     979              :             tracing::debug!("Not dirty, no reconciliation needed.");
     980              :             return ReconcileNeeded::No;
     981              :         }
     982              : 
     983              :         // If we are currently splitting, then never start a reconciler task: the splitting logic
     984              :         // requires that shards are not interfered with while it runs. Do this check here rather than
     985              :         // up top, so that we only log this message if we would otherwise have done a reconciliation.
     986              :         if !matches!(self.splitting, SplitState::Idle) {
     987              :             tracing::info!("Refusing to reconcile, splitting in progress");
     988              :             return ReconcileNeeded::No;
     989              :         }
     990              : 
     991              :         // Reconcile already in flight for the current sequence?
     992              :         if let Some(handle) = &self.reconciler {
     993              :             if handle.sequence == self.sequence {
     994              :                 tracing::info!(
     995              :                     "Reconciliation already in progress for sequence {:?}",
     996              :                     self.sequence,
     997              :                 );
     998              :                 return ReconcileNeeded::WaitExisting(ReconcilerWaiter {
     999              :                     tenant_shard_id: self.tenant_shard_id,
    1000              :                     seq_wait: self.waiter.clone(),
    1001              :                     error_seq_wait: self.error_waiter.clone(),
    1002              :                     error: self.last_error.clone(),
    1003              :                     seq: self.sequence,
    1004              :                 });
    1005              :             }
    1006              :         }
    1007              : 
    1008              :         // Pre-checks done: finally check whether we may actually do the work
    1009              :         match self.scheduling_policy {
    1010              :             ShardSchedulingPolicy::Active
    1011              :             | ShardSchedulingPolicy::Essential
    1012              :             | ShardSchedulingPolicy::Pause => {}
    1013              :             ShardSchedulingPolicy::Stop => {
    1014              :                 // We only reach this point if there is work to do and we're going to skip
    1015              :                 // doing it: warn it obvious why this tenant isn't doing what it ought to.
    1016              :                 tracing::warn!("Skipping reconcile for policy {:?}", self.scheduling_policy);
    1017              :                 return ReconcileNeeded::No;
    1018              :             }
    1019              :         }
    1020              : 
    1021              :         ReconcileNeeded::Yes
    1022              :     }
    1023              : 
    1024              :     /// Ensure the sequence number is set to a value where waiting for this value will make us wait
    1025              :     /// for the next reconcile: i.e. it is ahead of all completed or running reconcilers.
    1026              :     ///
    1027              :     /// Constructing a ReconcilerWaiter with the resulting sequence number gives the property
    1028              :     /// that the waiter will not complete until some future Reconciler is constructed and run.
    1029            0 :     fn ensure_sequence_ahead(&mut self) {
    1030            0 :         // Find the highest sequence for which a Reconciler has previously run or is currently
    1031            0 :         // running
    1032            0 :         let max_seen = std::cmp::max(
    1033            0 :             self.reconciler
    1034            0 :                 .as_ref()
    1035            0 :                 .map(|r| r.sequence)
    1036            0 :                 .unwrap_or(Sequence(0)),
    1037            0 :             std::cmp::max(self.waiter.load(), self.error_waiter.load()),
    1038            0 :         );
    1039            0 : 
    1040            0 :         if self.sequence <= max_seen {
    1041            0 :             self.sequence = max_seen.next();
    1042            0 :         }
    1043            0 :     }
    1044              : 
    1045              :     /// Create a waiter that will wait for some future Reconciler that hasn't been spawned yet.
    1046              :     ///
    1047              :     /// This is appropriate when you can't spawn a reconciler (e.g. due to resource limits), but
    1048              :     /// you would like to wait on the next reconciler that gets spawned in the background.
    1049            0 :     pub(crate) fn future_reconcile_waiter(&mut self) -> ReconcilerWaiter {
    1050            0 :         self.ensure_sequence_ahead();
    1051            0 : 
    1052            0 :         ReconcilerWaiter {
    1053            0 :             tenant_shard_id: self.tenant_shard_id,
    1054            0 :             seq_wait: self.waiter.clone(),
    1055            0 :             error_seq_wait: self.error_waiter.clone(),
    1056            0 :             error: self.last_error.clone(),
    1057            0 :             seq: self.sequence,
    1058            0 :         }
    1059            0 :     }
    1060              : 
    1061              :     #[allow(clippy::too_many_arguments)]
    1062            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    1063              :     pub(crate) fn spawn_reconciler(
    1064              :         &mut self,
    1065              :         result_tx: &tokio::sync::mpsc::UnboundedSender<ReconcileResult>,
    1066              :         pageservers: &Arc<HashMap<NodeId, Node>>,
    1067              :         compute_hook: &Arc<ComputeHook>,
    1068              :         service_config: &service::Config,
    1069              :         persistence: &Arc<Persistence>,
    1070              :         units: ReconcileUnits,
    1071              :         gate_guard: GateGuard,
    1072              :         cancel: &CancellationToken,
    1073              :     ) -> Option<ReconcilerWaiter> {
    1074              :         // Reconcile in flight for a stale sequence?  Our sequence's task will wait for it before
    1075              :         // doing our sequence's work.
    1076              :         let old_handle = self.reconciler.take();
    1077              : 
    1078              :         // Build list of nodes from which the reconciler should detach
    1079              :         let mut detach = Vec::new();
    1080              :         for node_id in self.observed.locations.keys() {
    1081              :             if self.intent.get_attached() != &Some(*node_id)
    1082              :                 && !self.intent.secondary.contains(node_id)
    1083              :             {
    1084              :                 detach.push(
    1085              :                     pageservers
    1086              :                         .get(node_id)
    1087              :                         .expect("Intent references non-existent pageserver")
    1088              :                         .clone(),
    1089              :                 )
    1090              :             }
    1091              :         }
    1092              : 
    1093              :         // Advance the sequence before spawning a reconciler, so that sequence waiters
    1094              :         // can distinguish between before+after the reconcile completes.
    1095              :         self.ensure_sequence_ahead();
    1096              : 
    1097              :         let reconciler_cancel = cancel.child_token();
    1098              :         let reconciler_intent = TargetState::from_intent(pageservers, &self.intent);
    1099              :         let mut reconciler = Reconciler {
    1100              :             tenant_shard_id: self.tenant_shard_id,
    1101              :             shard: self.shard,
    1102              :             generation: self.generation,
    1103              :             intent: reconciler_intent,
    1104              :             detach,
    1105              :             config: self.config.clone(),
    1106              :             observed: self.observed.clone(),
    1107              :             compute_hook: compute_hook.clone(),
    1108              :             service_config: service_config.clone(),
    1109              :             _gate_guard: gate_guard,
    1110              :             _resource_units: units,
    1111              :             cancel: reconciler_cancel.clone(),
    1112              :             persistence: persistence.clone(),
    1113              :             compute_notify_failure: false,
    1114              :         };
    1115              : 
    1116              :         let reconcile_seq = self.sequence;
    1117              : 
    1118              :         tracing::info!(seq=%reconcile_seq, "Spawning Reconciler for sequence {}", self.sequence);
    1119              :         let must_notify = self.pending_compute_notification;
    1120              :         let reconciler_span = tracing::info_span!(parent: None, "reconciler", seq=%reconcile_seq,
    1121              :                                                         tenant_id=%reconciler.tenant_shard_id.tenant_id,
    1122              :                                                         shard_id=%reconciler.tenant_shard_id.shard_slug());
    1123              :         metrics::METRICS_REGISTRY
    1124              :             .metrics_group
    1125              :             .storage_controller_reconcile_spawn
    1126              :             .inc();
    1127              :         let result_tx = result_tx.clone();
    1128              :         let join_handle = tokio::task::spawn(
    1129            0 :             async move {
    1130              :                 // Wait for any previous reconcile task to complete before we start
    1131            0 :                 if let Some(old_handle) = old_handle {
    1132            0 :                     old_handle.cancel.cancel();
    1133            0 :                     if let Err(e) = old_handle.handle.await {
    1134              :                         // We can't do much with this other than log it: the task is done, so
    1135              :                         // we may proceed with our work.
    1136            0 :                         tracing::error!("Unexpected join error waiting for reconcile task: {e}");
    1137            0 :                     }
    1138            0 :                 }
    1139              : 
    1140              :                 // Early check for cancellation before doing any work
    1141              :                 // TODO: wrap all remote API operations in cancellation check
    1142              :                 // as well.
    1143            0 :                 if reconciler.cancel.is_cancelled() {
    1144            0 :                     metrics::METRICS_REGISTRY
    1145            0 :                         .metrics_group
    1146            0 :                         .storage_controller_reconcile_complete
    1147            0 :                         .inc(ReconcileCompleteLabelGroup {
    1148            0 :                             status: ReconcileOutcome::Cancel,
    1149            0 :                         });
    1150            0 :                     return;
    1151            0 :                 }
    1152              : 
    1153              :                 // Attempt to make observed state match intent state
    1154            0 :                 let result = reconciler.reconcile().await;
    1155              : 
    1156              :                 // If we know we had a pending compute notification from some previous action, send a notification irrespective
    1157              :                 // of whether the above reconcile() did any work
    1158            0 :                 if result.is_ok() && must_notify {
    1159              :                     // If this fails we will send the need to retry in [`ReconcileResult::pending_compute_notification`]
    1160            0 :                     reconciler.compute_notify().await.ok();
    1161            0 :                 }
    1162              : 
    1163              :                 // Update result counter
    1164            0 :                 let outcome_label = match &result {
    1165            0 :                     Ok(_) => ReconcileOutcome::Success,
    1166            0 :                     Err(ReconcileError::Cancel) => ReconcileOutcome::Cancel,
    1167            0 :                     Err(_) => ReconcileOutcome::Error,
    1168              :                 };
    1169              : 
    1170            0 :                 metrics::METRICS_REGISTRY
    1171            0 :                     .metrics_group
    1172            0 :                     .storage_controller_reconcile_complete
    1173            0 :                     .inc(ReconcileCompleteLabelGroup {
    1174            0 :                         status: outcome_label,
    1175            0 :                     });
    1176            0 : 
    1177            0 :                 // Constructing result implicitly drops Reconciler, freeing any ReconcileUnits before the Service might
    1178            0 :                 // try and schedule more work in response to our result.
    1179            0 :                 let result = ReconcileResult {
    1180            0 :                     sequence: reconcile_seq,
    1181            0 :                     result,
    1182            0 :                     tenant_shard_id: reconciler.tenant_shard_id,
    1183            0 :                     generation: reconciler.generation,
    1184            0 :                     observed: reconciler.observed,
    1185            0 :                     pending_compute_notification: reconciler.compute_notify_failure,
    1186            0 :                 };
    1187            0 : 
    1188            0 :                 result_tx.send(result).ok();
    1189            0 :             }
    1190              :             .instrument(reconciler_span),
    1191              :         );
    1192              : 
    1193              :         self.reconciler = Some(ReconcilerHandle {
    1194              :             sequence: self.sequence,
    1195              :             handle: join_handle,
    1196              :             cancel: reconciler_cancel,
    1197              :         });
    1198              : 
    1199              :         Some(ReconcilerWaiter {
    1200              :             tenant_shard_id: self.tenant_shard_id,
    1201              :             seq_wait: self.waiter.clone(),
    1202              :             error_seq_wait: self.error_waiter.clone(),
    1203              :             error: self.last_error.clone(),
    1204              :             seq: self.sequence,
    1205              :         })
    1206              :     }
    1207              : 
    1208              :     /// Get a waiter for any reconciliation in flight, but do not start reconciliation
    1209              :     /// if it is not already running
    1210            0 :     pub(crate) fn get_waiter(&self) -> Option<ReconcilerWaiter> {
    1211            0 :         if self.reconciler.is_some() {
    1212            0 :             Some(ReconcilerWaiter {
    1213            0 :                 tenant_shard_id: self.tenant_shard_id,
    1214            0 :                 seq_wait: self.waiter.clone(),
    1215            0 :                 error_seq_wait: self.error_waiter.clone(),
    1216            0 :                 error: self.last_error.clone(),
    1217            0 :                 seq: self.sequence,
    1218            0 :             })
    1219              :         } else {
    1220            0 :             None
    1221              :         }
    1222            0 :     }
    1223              : 
    1224              :     /// Called when a ReconcileResult has been emitted and the service is updating
    1225              :     /// our state: if the result is from a sequence >= my ReconcileHandle, then drop
    1226              :     /// the handle to indicate there is no longer a reconciliation in progress.
    1227            0 :     pub(crate) fn reconcile_complete(&mut self, sequence: Sequence) {
    1228            0 :         if let Some(reconcile_handle) = &self.reconciler {
    1229            0 :             if reconcile_handle.sequence <= sequence {
    1230            0 :                 self.reconciler = None;
    1231            0 :             }
    1232            0 :         }
    1233            0 :     }
    1234              : 
    1235              :     // If we had any state at all referring to this node ID, drop it.  Does not
    1236              :     // attempt to reschedule.
    1237            0 :     pub(crate) fn deref_node(&mut self, node_id: NodeId) {
    1238            0 :         if self.intent.attached == Some(node_id) {
    1239            0 :             self.intent.attached = None;
    1240            0 :         }
    1241              : 
    1242            0 :         self.intent.secondary.retain(|n| n != &node_id);
    1243            0 : 
    1244            0 :         self.observed.locations.remove(&node_id);
    1245            0 : 
    1246            0 :         debug_assert!(!self.intent.all_pageservers().contains(&node_id));
    1247            0 :     }
    1248              : 
    1249            0 :     pub(crate) fn set_scheduling_policy(&mut self, p: ShardSchedulingPolicy) {
    1250            0 :         self.scheduling_policy = p;
    1251            0 :     }
    1252              : 
    1253            0 :     pub(crate) fn get_scheduling_policy(&self) -> &ShardSchedulingPolicy {
    1254            0 :         &self.scheduling_policy
    1255            0 :     }
    1256              : 
    1257            0 :     pub(crate) fn set_last_error(&mut self, sequence: Sequence, error: ReconcileError) {
    1258            0 :         // Ordering: always set last_error before advancing sequence, so that sequence
    1259            0 :         // waiters are guaranteed to see a Some value when they see an error.
    1260            0 :         *(self.last_error.lock().unwrap()) = Some(Arc::new(error));
    1261            0 :         self.error_waiter.advance(sequence);
    1262            0 :     }
    1263              : 
    1264            0 :     pub(crate) fn from_persistent(
    1265            0 :         tsp: TenantShardPersistence,
    1266            0 :         intent: IntentState,
    1267            0 :     ) -> anyhow::Result<Self> {
    1268            0 :         let tenant_shard_id = tsp.get_tenant_shard_id()?;
    1269            0 :         let shard_identity = tsp.get_shard_identity()?;
    1270              : 
    1271            0 :         Ok(Self {
    1272            0 :             tenant_shard_id,
    1273            0 :             shard: shard_identity,
    1274            0 :             sequence: Sequence::initial(),
    1275            0 :             generation: tsp.generation.map(|g| Generation::new(g as u32)),
    1276            0 :             policy: serde_json::from_str(&tsp.placement_policy).unwrap(),
    1277            0 :             intent,
    1278            0 :             observed: ObservedState::new(),
    1279            0 :             config: serde_json::from_str(&tsp.config).unwrap(),
    1280            0 :             reconciler: None,
    1281            0 :             splitting: tsp.splitting,
    1282            0 :             waiter: Arc::new(SeqWait::new(Sequence::initial())),
    1283            0 :             error_waiter: Arc::new(SeqWait::new(Sequence::initial())),
    1284            0 :             last_error: Arc::default(),
    1285            0 :             pending_compute_notification: false,
    1286            0 :             delayed_reconcile: false,
    1287            0 :             scheduling_policy: serde_json::from_str(&tsp.scheduling_policy).unwrap(),
    1288            0 :         })
    1289            0 :     }
    1290              : 
    1291            0 :     pub(crate) fn to_persistent(&self) -> TenantShardPersistence {
    1292            0 :         TenantShardPersistence {
    1293            0 :             tenant_id: self.tenant_shard_id.tenant_id.to_string(),
    1294            0 :             shard_number: self.tenant_shard_id.shard_number.0 as i32,
    1295            0 :             shard_count: self.tenant_shard_id.shard_count.literal() as i32,
    1296            0 :             shard_stripe_size: self.shard.stripe_size.0 as i32,
    1297            0 :             generation: self.generation.map(|g| g.into().unwrap_or(0) as i32),
    1298            0 :             generation_pageserver: self.intent.get_attached().map(|n| n.0 as i64),
    1299            0 :             placement_policy: serde_json::to_string(&self.policy).unwrap(),
    1300            0 :             config: serde_json::to_string(&self.config).unwrap(),
    1301            0 :             splitting: SplitState::default(),
    1302            0 :             scheduling_policy: serde_json::to_string(&self.scheduling_policy).unwrap(),
    1303            0 :         }
    1304            0 :     }
    1305              : }
    1306              : 
    1307              : #[cfg(test)]
    1308              : pub(crate) mod tests {
    1309              :     use pageserver_api::{
    1310              :         controller_api::NodeAvailability,
    1311              :         shard::{ShardCount, ShardNumber},
    1312              :     };
    1313              :     use utils::id::TenantId;
    1314              : 
    1315              :     use crate::scheduler::test_utils::make_test_nodes;
    1316              : 
    1317              :     use super::*;
    1318              : 
    1319           14 :     fn make_test_tenant_shard(policy: PlacementPolicy) -> TenantShard {
    1320           14 :         let tenant_id = TenantId::generate();
    1321           14 :         let shard_number = ShardNumber(0);
    1322           14 :         let shard_count = ShardCount::new(1);
    1323           14 : 
    1324           14 :         let tenant_shard_id = TenantShardId {
    1325           14 :             tenant_id,
    1326           14 :             shard_number,
    1327           14 :             shard_count,
    1328           14 :         };
    1329           14 :         TenantShard::new(
    1330           14 :             tenant_shard_id,
    1331           14 :             ShardIdentity::new(
    1332           14 :                 shard_number,
    1333           14 :                 shard_count,
    1334           14 :                 pageserver_api::shard::ShardStripeSize(32768),
    1335           14 :             )
    1336           14 :             .unwrap(),
    1337           14 :             policy,
    1338           14 :         )
    1339           14 :     }
    1340              : 
    1341            2 :     fn make_test_tenant(policy: PlacementPolicy, shard_count: ShardCount) -> Vec<TenantShard> {
    1342            2 :         let tenant_id = TenantId::generate();
    1343            2 : 
    1344            2 :         (0..shard_count.count())
    1345            8 :             .map(|i| {
    1346            8 :                 let shard_number = ShardNumber(i);
    1347            8 : 
    1348            8 :                 let tenant_shard_id = TenantShardId {
    1349            8 :                     tenant_id,
    1350            8 :                     shard_number,
    1351            8 :                     shard_count,
    1352            8 :                 };
    1353            8 :                 TenantShard::new(
    1354            8 :                     tenant_shard_id,
    1355            8 :                     ShardIdentity::new(
    1356            8 :                         shard_number,
    1357            8 :                         shard_count,
    1358            8 :                         pageserver_api::shard::ShardStripeSize(32768),
    1359            8 :                     )
    1360            8 :                     .unwrap(),
    1361            8 :                     policy.clone(),
    1362            8 :                 )
    1363            8 :             })
    1364            2 :             .collect()
    1365            2 :     }
    1366              : 
    1367              :     /// Test the scheduling behaviors used when a tenant configured for HA is subject
    1368              :     /// to nodes being marked offline.
    1369              :     #[test]
    1370            2 :     fn tenant_ha_scheduling() -> anyhow::Result<()> {
    1371            2 :         // Start with three nodes.  Our tenant will only use two.  The third one is
    1372            2 :         // expected to remain unused.
    1373            2 :         let mut nodes = make_test_nodes(3);
    1374            2 : 
    1375            2 :         let mut scheduler = Scheduler::new(nodes.values());
    1376            2 :         let mut context = ScheduleContext::default();
    1377            2 : 
    1378            2 :         let mut tenant_shard = make_test_tenant_shard(PlacementPolicy::Attached(1));
    1379            2 :         tenant_shard
    1380            2 :             .schedule(&mut scheduler, &mut context)
    1381            2 :             .expect("we have enough nodes, scheduling should work");
    1382            2 : 
    1383            2 :         // Expect to initially be schedule on to different nodes
    1384            2 :         assert_eq!(tenant_shard.intent.secondary.len(), 1);
    1385            2 :         assert!(tenant_shard.intent.attached.is_some());
    1386              : 
    1387            2 :         let attached_node_id = tenant_shard.intent.attached.unwrap();
    1388            2 :         let secondary_node_id = *tenant_shard.intent.secondary.iter().last().unwrap();
    1389            2 :         assert_ne!(attached_node_id, secondary_node_id);
    1390              : 
    1391              :         // Notifying the attached node is offline should demote it to a secondary
    1392            2 :         let changed = tenant_shard
    1393            2 :             .intent
    1394            2 :             .demote_attached(&mut scheduler, attached_node_id);
    1395            2 :         assert!(changed);
    1396            2 :         assert!(tenant_shard.intent.attached.is_none());
    1397            2 :         assert_eq!(tenant_shard.intent.secondary.len(), 2);
    1398              : 
    1399              :         // Update the scheduler state to indicate the node is offline
    1400            2 :         nodes
    1401            2 :             .get_mut(&attached_node_id)
    1402            2 :             .unwrap()
    1403            2 :             .set_availability(NodeAvailability::Offline);
    1404            2 :         scheduler.node_upsert(nodes.get(&attached_node_id).unwrap());
    1405            2 : 
    1406            2 :         // Scheduling the node should promote the still-available secondary node to attached
    1407            2 :         tenant_shard
    1408            2 :             .schedule(&mut scheduler, &mut context)
    1409            2 :             .expect("active nodes are available");
    1410            2 :         assert_eq!(tenant_shard.intent.attached.unwrap(), secondary_node_id);
    1411              : 
    1412              :         // The original attached node should have been retained as a secondary
    1413            2 :         assert_eq!(
    1414            2 :             *tenant_shard.intent.secondary.iter().last().unwrap(),
    1415            2 :             attached_node_id
    1416            2 :         );
    1417              : 
    1418            2 :         tenant_shard.intent.clear(&mut scheduler);
    1419            2 : 
    1420            2 :         Ok(())
    1421            2 :     }
    1422              : 
    1423              :     #[test]
    1424            2 :     fn intent_from_observed() -> anyhow::Result<()> {
    1425            2 :         let nodes = make_test_nodes(3);
    1426            2 :         let mut scheduler = Scheduler::new(nodes.values());
    1427            2 : 
    1428            2 :         let mut tenant_shard = make_test_tenant_shard(PlacementPolicy::Attached(1));
    1429            2 : 
    1430            2 :         tenant_shard.observed.locations.insert(
    1431            2 :             NodeId(3),
    1432            2 :             ObservedStateLocation {
    1433            2 :                 conf: Some(LocationConfig {
    1434            2 :                     mode: LocationConfigMode::AttachedMulti,
    1435            2 :                     generation: Some(2),
    1436            2 :                     secondary_conf: None,
    1437            2 :                     shard_number: tenant_shard.shard.number.0,
    1438            2 :                     shard_count: tenant_shard.shard.count.literal(),
    1439            2 :                     shard_stripe_size: tenant_shard.shard.stripe_size.0,
    1440            2 :                     tenant_conf: TenantConfig::default(),
    1441            2 :                 }),
    1442            2 :             },
    1443            2 :         );
    1444            2 : 
    1445            2 :         tenant_shard.observed.locations.insert(
    1446            2 :             NodeId(2),
    1447            2 :             ObservedStateLocation {
    1448            2 :                 conf: Some(LocationConfig {
    1449            2 :                     mode: LocationConfigMode::AttachedStale,
    1450            2 :                     generation: Some(1),
    1451            2 :                     secondary_conf: None,
    1452            2 :                     shard_number: tenant_shard.shard.number.0,
    1453            2 :                     shard_count: tenant_shard.shard.count.literal(),
    1454            2 :                     shard_stripe_size: tenant_shard.shard.stripe_size.0,
    1455            2 :                     tenant_conf: TenantConfig::default(),
    1456            2 :                 }),
    1457            2 :             },
    1458            2 :         );
    1459            2 : 
    1460            2 :         tenant_shard.intent_from_observed(&mut scheduler);
    1461            2 : 
    1462            2 :         // The highest generationed attached location gets used as attached
    1463            2 :         assert_eq!(tenant_shard.intent.attached, Some(NodeId(3)));
    1464              :         // Other locations get used as secondary
    1465            2 :         assert_eq!(tenant_shard.intent.secondary, vec![NodeId(2)]);
    1466              : 
    1467            2 :         scheduler.consistency_check(nodes.values(), [&tenant_shard].into_iter())?;
    1468              : 
    1469            2 :         tenant_shard.intent.clear(&mut scheduler);
    1470            2 :         Ok(())
    1471            2 :     }
    1472              : 
    1473              :     #[test]
    1474            2 :     fn scheduling_mode() -> anyhow::Result<()> {
    1475            2 :         let nodes = make_test_nodes(3);
    1476            2 :         let mut scheduler = Scheduler::new(nodes.values());
    1477            2 : 
    1478            2 :         let mut tenant_shard = make_test_tenant_shard(PlacementPolicy::Attached(1));
    1479            2 : 
    1480            2 :         // In pause mode, schedule() shouldn't do anything
    1481            2 :         tenant_shard.scheduling_policy = ShardSchedulingPolicy::Pause;
    1482            2 :         assert!(tenant_shard
    1483            2 :             .schedule(&mut scheduler, &mut ScheduleContext::default())
    1484            2 :             .is_ok());
    1485            2 :         assert!(tenant_shard.intent.all_pageservers().is_empty());
    1486              : 
    1487              :         // In active mode, schedule() works
    1488            2 :         tenant_shard.scheduling_policy = ShardSchedulingPolicy::Active;
    1489            2 :         assert!(tenant_shard
    1490            2 :             .schedule(&mut scheduler, &mut ScheduleContext::default())
    1491            2 :             .is_ok());
    1492            2 :         assert!(!tenant_shard.intent.all_pageservers().is_empty());
    1493              : 
    1494            2 :         tenant_shard.intent.clear(&mut scheduler);
    1495            2 :         Ok(())
    1496            2 :     }
    1497              : 
    1498              :     #[test]
    1499            2 :     fn optimize_attachment() -> anyhow::Result<()> {
    1500            2 :         let nodes = make_test_nodes(3);
    1501            2 :         let mut scheduler = Scheduler::new(nodes.values());
    1502            2 : 
    1503            2 :         let mut shard_a = make_test_tenant_shard(PlacementPolicy::Attached(1));
    1504            2 :         let mut shard_b = make_test_tenant_shard(PlacementPolicy::Attached(1));
    1505            2 : 
    1506            2 :         // Initially: both nodes attached on shard 1, and both have secondary locations
    1507            2 :         // on different nodes.
    1508            2 :         shard_a.intent.set_attached(&mut scheduler, Some(NodeId(1)));
    1509            2 :         shard_a.intent.push_secondary(&mut scheduler, NodeId(2));
    1510            2 :         shard_b.intent.set_attached(&mut scheduler, Some(NodeId(1)));
    1511            2 :         shard_b.intent.push_secondary(&mut scheduler, NodeId(3));
    1512            2 : 
    1513            2 :         let mut schedule_context = ScheduleContext::default();
    1514            2 :         schedule_context.avoid(&shard_a.intent.all_pageservers());
    1515            2 :         schedule_context.push_attached(shard_a.intent.get_attached().unwrap());
    1516            2 :         schedule_context.avoid(&shard_b.intent.all_pageservers());
    1517            2 :         schedule_context.push_attached(shard_b.intent.get_attached().unwrap());
    1518            2 : 
    1519            2 :         let optimization_a = shard_a.optimize_attachment(&nodes, &schedule_context);
    1520            2 : 
    1521            2 :         // Either shard should recognize that it has the option to switch to a secondary location where there
    1522            2 :         // would be no other shards from the same tenant, and request to do so.
    1523            2 :         assert_eq!(
    1524            2 :             optimization_a,
    1525            2 :             Some(ScheduleOptimization {
    1526            2 :                 sequence: shard_a.sequence,
    1527            2 :                 action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    1528            2 :                     old_attached_node_id: NodeId(1),
    1529            2 :                     new_attached_node_id: NodeId(2)
    1530            2 :                 })
    1531            2 :             })
    1532            2 :         );
    1533              : 
    1534              :         // Note that these optimizing two shards in the same tenant with the same ScheduleContext is
    1535              :         // mutually exclusive (the optimization of one invalidates the stats) -- it is the responsibility
    1536              :         // of [`Service::optimize_all`] to avoid trying
    1537              :         // to do optimizations for multiple shards in the same tenant at the same time.  Generating
    1538              :         // both optimizations is just done for test purposes
    1539            2 :         let optimization_b = shard_b.optimize_attachment(&nodes, &schedule_context);
    1540            2 :         assert_eq!(
    1541            2 :             optimization_b,
    1542            2 :             Some(ScheduleOptimization {
    1543            2 :                 sequence: shard_b.sequence,
    1544            2 :                 action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    1545            2 :                     old_attached_node_id: NodeId(1),
    1546            2 :                     new_attached_node_id: NodeId(3)
    1547            2 :                 })
    1548            2 :             })
    1549            2 :         );
    1550              : 
    1551              :         // Applying these optimizations should result in the end state proposed
    1552            2 :         shard_a.apply_optimization(&mut scheduler, optimization_a.unwrap());
    1553            2 :         assert_eq!(shard_a.intent.get_attached(), &Some(NodeId(2)));
    1554            2 :         assert_eq!(shard_a.intent.get_secondary(), &vec![NodeId(1)]);
    1555            2 :         shard_b.apply_optimization(&mut scheduler, optimization_b.unwrap());
    1556            2 :         assert_eq!(shard_b.intent.get_attached(), &Some(NodeId(3)));
    1557            2 :         assert_eq!(shard_b.intent.get_secondary(), &vec![NodeId(1)]);
    1558              : 
    1559            2 :         shard_a.intent.clear(&mut scheduler);
    1560            2 :         shard_b.intent.clear(&mut scheduler);
    1561            2 : 
    1562            2 :         Ok(())
    1563            2 :     }
    1564              : 
    1565              :     #[test]
    1566            2 :     fn optimize_secondary() -> anyhow::Result<()> {
    1567            2 :         let nodes = make_test_nodes(4);
    1568            2 :         let mut scheduler = Scheduler::new(nodes.values());
    1569            2 : 
    1570            2 :         let mut shard_a = make_test_tenant_shard(PlacementPolicy::Attached(1));
    1571            2 :         let mut shard_b = make_test_tenant_shard(PlacementPolicy::Attached(1));
    1572            2 : 
    1573            2 :         // Initially: both nodes attached on shard 1, and both have secondary locations
    1574            2 :         // on different nodes.
    1575            2 :         shard_a.intent.set_attached(&mut scheduler, Some(NodeId(1)));
    1576            2 :         shard_a.intent.push_secondary(&mut scheduler, NodeId(3));
    1577            2 :         shard_b.intent.set_attached(&mut scheduler, Some(NodeId(2)));
    1578            2 :         shard_b.intent.push_secondary(&mut scheduler, NodeId(3));
    1579            2 : 
    1580            2 :         let mut schedule_context = ScheduleContext::default();
    1581            2 :         schedule_context.avoid(&shard_a.intent.all_pageservers());
    1582            2 :         schedule_context.push_attached(shard_a.intent.get_attached().unwrap());
    1583            2 :         schedule_context.avoid(&shard_b.intent.all_pageservers());
    1584            2 :         schedule_context.push_attached(shard_b.intent.get_attached().unwrap());
    1585            2 : 
    1586            2 :         let optimization_a = shard_a.optimize_secondary(&scheduler, &schedule_context);
    1587            2 : 
    1588            2 :         // Since there is a node with no locations available, the node with two locations for the
    1589            2 :         // same tenant should generate an optimization to move one away
    1590            2 :         assert_eq!(
    1591            2 :             optimization_a,
    1592            2 :             Some(ScheduleOptimization {
    1593            2 :                 sequence: shard_a.sequence,
    1594            2 :                 action: ScheduleOptimizationAction::ReplaceSecondary(ReplaceSecondary {
    1595            2 :                     old_node_id: NodeId(3),
    1596            2 :                     new_node_id: NodeId(4)
    1597            2 :                 })
    1598            2 :             })
    1599            2 :         );
    1600              : 
    1601            2 :         shard_a.apply_optimization(&mut scheduler, optimization_a.unwrap());
    1602            2 :         assert_eq!(shard_a.intent.get_attached(), &Some(NodeId(1)));
    1603            2 :         assert_eq!(shard_a.intent.get_secondary(), &vec![NodeId(4)]);
    1604              : 
    1605            2 :         shard_a.intent.clear(&mut scheduler);
    1606            2 :         shard_b.intent.clear(&mut scheduler);
    1607            2 : 
    1608            2 :         Ok(())
    1609            2 :     }
    1610              : 
    1611              :     // Optimize til quiescent: this emulates what Service::optimize_all does, when
    1612              :     // called repeatedly in the background.
    1613            2 :     fn optimize_til_idle(
    1614            2 :         nodes: &HashMap<NodeId, Node>,
    1615            2 :         scheduler: &mut Scheduler,
    1616            2 :         shards: &mut [TenantShard],
    1617            2 :     ) {
    1618            2 :         let mut loop_n = 0;
    1619              :         loop {
    1620           14 :             let mut schedule_context = ScheduleContext::default();
    1621           14 :             let mut any_changed = false;
    1622              : 
    1623           56 :             for shard in shards.iter() {
    1624           56 :                 schedule_context.avoid(&shard.intent.all_pageservers());
    1625           56 :                 if let Some(attached) = shard.intent.get_attached() {
    1626           56 :                     schedule_context.push_attached(*attached);
    1627           56 :                 }
    1628              :             }
    1629              : 
    1630           26 :             for shard in shards.iter_mut() {
    1631           26 :                 let optimization = shard.optimize_attachment(nodes, &schedule_context);
    1632           26 :                 if let Some(optimization) = optimization {
    1633            4 :                     shard.apply_optimization(scheduler, optimization);
    1634            4 :                     any_changed = true;
    1635            4 :                     break;
    1636           22 :                 }
    1637           22 : 
    1638           22 :                 let optimization = shard.optimize_secondary(scheduler, &schedule_context);
    1639           22 :                 if let Some(optimization) = optimization {
    1640            8 :                     shard.apply_optimization(scheduler, optimization);
    1641            8 :                     any_changed = true;
    1642            8 :                     break;
    1643           14 :                 }
    1644              :             }
    1645              : 
    1646           14 :             if !any_changed {
    1647            2 :                 break;
    1648           12 :             }
    1649           12 : 
    1650           12 :             // Assert no infinite loop
    1651           12 :             loop_n += 1;
    1652           12 :             assert!(loop_n < 1000);
    1653              :         }
    1654            2 :     }
    1655              : 
    1656              :     /// Test the balancing behavior of shard scheduling: that it achieves a balance, and
    1657              :     /// that it converges.
    1658              :     #[test]
    1659            2 :     fn optimize_add_nodes() -> anyhow::Result<()> {
    1660            2 :         let nodes = make_test_nodes(4);
    1661            2 : 
    1662            2 :         // Only show the scheduler a couple of nodes
    1663            2 :         let mut scheduler = Scheduler::new([].iter());
    1664            2 :         scheduler.node_upsert(nodes.get(&NodeId(1)).unwrap());
    1665            2 :         scheduler.node_upsert(nodes.get(&NodeId(2)).unwrap());
    1666            2 : 
    1667            2 :         let mut shards = make_test_tenant(PlacementPolicy::Attached(1), ShardCount::new(4));
    1668            2 :         let mut schedule_context = ScheduleContext::default();
    1669           10 :         for shard in &mut shards {
    1670            8 :             assert!(shard
    1671            8 :                 .schedule(&mut scheduler, &mut schedule_context)
    1672            8 :                 .is_ok());
    1673              :         }
    1674              : 
    1675              :         // We should see equal number of locations on the two nodes.
    1676            2 :         assert_eq!(scheduler.get_node_shard_count(NodeId(1)), 4);
    1677            2 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(1)), 2);
    1678              : 
    1679            2 :         assert_eq!(scheduler.get_node_shard_count(NodeId(2)), 4);
    1680            2 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(2)), 2);
    1681              : 
    1682              :         // Add another two nodes: we should see the shards spread out when their optimize
    1683              :         // methods are called
    1684            2 :         scheduler.node_upsert(nodes.get(&NodeId(3)).unwrap());
    1685            2 :         scheduler.node_upsert(nodes.get(&NodeId(4)).unwrap());
    1686            2 :         optimize_til_idle(&nodes, &mut scheduler, &mut shards);
    1687            2 : 
    1688            2 :         assert_eq!(scheduler.get_node_shard_count(NodeId(1)), 2);
    1689            2 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(1)), 1);
    1690              : 
    1691            2 :         assert_eq!(scheduler.get_node_shard_count(NodeId(2)), 2);
    1692            2 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(2)), 1);
    1693              : 
    1694            2 :         assert_eq!(scheduler.get_node_shard_count(NodeId(3)), 2);
    1695            2 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(3)), 1);
    1696              : 
    1697            2 :         assert_eq!(scheduler.get_node_shard_count(NodeId(4)), 2);
    1698            2 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(4)), 1);
    1699              : 
    1700            8 :         for shard in shards.iter_mut() {
    1701            8 :             shard.intent.clear(&mut scheduler);
    1702            8 :         }
    1703              : 
    1704            2 :         Ok(())
    1705            2 :     }
    1706              : }
        

Generated by: LCOV version 2.1-beta