LCOV - code coverage report
Current view: top level - storage_controller/src - tenant_shard.rs (source / functions) Coverage Total Hit
Test: 4be46b1c0003aa3bbac9ade362c676b419df4c20.info Lines: 69.1 % 1634 1129
Test Date: 2025-07-22 17:50:06 Functions: 54.9 % 122 67

            Line data    Source code
       1              : use std::collections::{HashMap, HashSet};
       2              : use std::sync::Arc;
       3              : use std::time::Duration;
       4              : 
       5              : use futures::future::{self, Either};
       6              : use itertools::Itertools;
       7              : use pageserver_api::controller_api::{AvailabilityZone, PlacementPolicy, ShardSchedulingPolicy};
       8              : use pageserver_api::models::{LocationConfig, LocationConfigMode, TenantConfig};
       9              : use pageserver_api::shard::{ShardIdentity, TenantShardId};
      10              : use serde::{Deserialize, Serialize};
      11              : use tokio::task::JoinHandle;
      12              : use tokio_util::sync::CancellationToken;
      13              : use tracing::{Instrument, instrument};
      14              : use utils::generation::Generation;
      15              : use utils::id::NodeId;
      16              : use utils::seqwait::{SeqWait, SeqWaitError};
      17              : use utils::shard::ShardCount;
      18              : use utils::sync::gate::GateGuard;
      19              : 
      20              : use crate::compute_hook::ComputeHook;
      21              : use crate::metrics::{
      22              :     self, ReconcileCompleteLabelGroup, ReconcileLongRunningLabelGroup, ReconcileOutcome,
      23              : };
      24              : use crate::node::Node;
      25              : use crate::persistence::split_state::SplitState;
      26              : use crate::persistence::{Persistence, TenantShardPersistence};
      27              : use crate::reconciler::{
      28              :     ReconcileError, ReconcileUnits, Reconciler, ReconcilerConfig, TargetState,
      29              :     attached_location_conf, secondary_location_conf,
      30              : };
      31              : use crate::scheduler::{
      32              :     AffinityScore, AttachedShardTag, NodeSchedulingScore, NodeSecondarySchedulingScore,
      33              :     RefCountUpdate, ScheduleContext, ScheduleError, Scheduler, SecondaryShardTag, ShardTag,
      34              : };
      35              : use crate::service::ReconcileResultRequest;
      36              : use crate::timeline_import::TimelineImportState;
      37              : use crate::{Sequence, service};
      38              : 
      39              : /// Serialization helper
      40            0 : fn read_last_error<S, T>(v: &std::sync::Mutex<Option<T>>, serializer: S) -> Result<S::Ok, S::Error>
      41            0 : where
      42            0 :     S: serde::ser::Serializer,
      43            0 :     T: std::fmt::Display,
      44              : {
      45            0 :     serializer.collect_str(
      46            0 :         &v.lock()
      47            0 :             .unwrap()
      48            0 :             .as_ref()
      49            0 :             .map(|e| format!("{e}"))
      50            0 :             .unwrap_or("".to_string()),
      51              :     )
      52            0 : }
      53              : 
      54              : /// In-memory state for a particular tenant shard.
      55              : ///
      56              : /// This struct implement Serialize for debugging purposes, but is _not_ persisted
      57              : /// itself: see [`crate::persistence`] for the subset of tenant shard state that is persisted.
      58              : #[derive(Serialize)]
      59              : pub(crate) struct TenantShard {
      60              :     pub(crate) tenant_shard_id: TenantShardId,
      61              : 
      62              :     pub(crate) shard: ShardIdentity,
      63              : 
      64              :     // Runtime only: sequence used to coordinate when updating this object while
      65              :     // with background reconcilers may be running.  A reconciler runs to a particular
      66              :     // sequence.
      67              :     pub(crate) sequence: Sequence,
      68              : 
      69              :     // Latest generation number: next time we attach, increment this
      70              :     // and use the incremented number when attaching.
      71              :     //
      72              :     // None represents an incompletely onboarded tenant via the [`Service::location_config`]
      73              :     // API, where this tenant may only run in PlacementPolicy::Secondary.
      74              :     pub(crate) generation: Option<Generation>,
      75              : 
      76              :     // High level description of how the tenant should be set up.  Provided
      77              :     // externally.
      78              :     pub(crate) policy: PlacementPolicy,
      79              : 
      80              :     // Low level description of exactly which pageservers should fulfil
      81              :     // which role.  Generated by `Self::schedule`.
      82              :     pub(crate) intent: IntentState,
      83              : 
      84              :     // Low level description of how the tenant is configured on pageservers:
      85              :     // if this does not match `Self::intent` then the tenant needs reconciliation
      86              :     // with `Self::reconcile`.
      87              :     pub(crate) observed: ObservedState,
      88              : 
      89              :     // Tenant configuration, passed through opaquely to the pageserver.  Identical
      90              :     // for all shards in a tenant.
      91              :     pub(crate) config: TenantConfig,
      92              : 
      93              :     /// If a reconcile task is currently in flight, it may be joined here (it is
      94              :     /// only safe to join if either the result has been received or the reconciler's
      95              :     /// cancellation token has been fired)
      96              :     #[serde(skip)]
      97              :     pub(crate) reconciler: Option<ReconcilerHandle>,
      98              : 
      99              :     /// If a tenant is being split, then all shards with that TenantId will have a
     100              :     /// SplitState set, this acts as a guard against other operations such as background
     101              :     /// reconciliation, and timeline creation.
     102              :     pub(crate) splitting: SplitState,
     103              : 
     104              :     /// Flag indicating whether the tenant has an in-progress timeline import.
     105              :     /// Used to disallow shard splits while an import is in progress.
     106              :     pub(crate) importing: TimelineImportState,
     107              : 
     108              :     /// If a tenant was enqueued for later reconcile due to hitting concurrency limit, this flag
     109              :     /// is set. This flag is cleared when the tenant is popped off the delay queue.
     110              :     pub(crate) delayed_reconcile: bool,
     111              : 
     112              :     /// Optionally wait for reconciliation to complete up to a particular
     113              :     /// sequence number.
     114              :     #[serde(skip)]
     115              :     pub(crate) waiter: std::sync::Arc<SeqWait<Sequence, Sequence>>,
     116              : 
     117              :     /// Indicates sequence number for which we have encountered an error reconciling.  If
     118              :     /// this advances ahead of [`Self::waiter`] then a reconciliation error has occurred,
     119              :     /// and callers should stop waiting for `waiter` and propagate the error.
     120              :     #[serde(skip)]
     121              :     pub(crate) error_waiter: std::sync::Arc<SeqWait<Sequence, Sequence>>,
     122              : 
     123              :     /// The most recent error from a reconcile on this tenant.  This is a nested Arc
     124              :     /// because:
     125              :     ///  - ReconcileWaiters need to Arc-clone the overall object to read it later
     126              :     ///  - ReconcileWaitError needs to use an `Arc<ReconcileError>` because we can construct
     127              :     ///    many waiters for one shard, and the underlying error types are not Clone.
     128              :     ///
     129              :     /// TODO: generalize to an array of recent events
     130              :     /// TOOD: use a ArcSwap instead of mutex for faster reads?
     131              :     #[serde(serialize_with = "read_last_error")]
     132              :     pub(crate) last_error: std::sync::Arc<std::sync::Mutex<Option<Arc<ReconcileError>>>>,
     133              : 
     134              :     /// Amount of consecutive [`crate::service::Service::reconcile_all`] iterations that have been
     135              :     /// scheduled a reconciliation for this shard.
     136              :     ///
     137              :     /// If this reaches `MAX_CONSECUTIVE_RECONCILES`, the shard is considered "stuck" and will be
     138              :     /// ignored when deciding whether optimizations can run. This includes both successful and failed
     139              :     /// reconciliations.
     140              :     ///
     141              :     /// Incremented in [`crate::service::Service::process_result`], and reset to 0 when
     142              :     /// [`crate::service::Service::reconcile_all`] determines no reconciliation is needed for this shard.
     143              :     pub(crate) consecutive_reconciles_count: usize,
     144              : 
     145              :     /// If we have a pending compute notification that for some reason we weren't able to send,
     146              :     /// set this to true. If this is set, calls to [`Self::get_reconcile_needed`] will return Yes
     147              :     /// and trigger a Reconciler run.  This is the mechanism by which compute notifications are included in the scope
     148              :     /// of state that we publish externally in an eventually consistent way.
     149              :     pub(crate) pending_compute_notification: bool,
     150              : 
     151              :     /// To do a graceful migration, set this field to the destination pageserver, and optimization
     152              :     /// functions will consider this node the best location and react appropriately.
     153              :     preferred_node: Option<NodeId>,
     154              : 
     155              :     // Support/debug tool: if something is going wrong or flapping with scheduling, this may
     156              :     // be set to a non-active state to avoid making changes while the issue is fixed.
     157              :     scheduling_policy: ShardSchedulingPolicy,
     158              : }
     159              : 
     160              : #[derive(Clone, Debug, Serialize)]
     161              : pub(crate) struct IntentState {
     162              :     attached: Option<NodeId>,
     163              :     secondary: Vec<NodeId>,
     164              : 
     165              :     // We should attempt to schedule this shard in the provided AZ to
     166              :     // decrease chances of cross-AZ compute.
     167              :     preferred_az_id: Option<AvailabilityZone>,
     168              : }
     169              : 
     170              : impl IntentState {
     171        12860 :     pub(crate) fn new(preferred_az_id: Option<AvailabilityZone>) -> Self {
     172        12860 :         Self {
     173        12860 :             attached: None,
     174        12860 :             secondary: vec![],
     175        12860 :             preferred_az_id,
     176        12860 :         }
     177        12860 :     }
     178            0 :     pub(crate) fn single(
     179            0 :         scheduler: &mut Scheduler,
     180            0 :         node_id: Option<NodeId>,
     181            0 :         preferred_az_id: Option<AvailabilityZone>,
     182            0 :     ) -> Self {
     183            0 :         if let Some(node_id) = node_id {
     184            0 :             scheduler.update_node_ref_counts(
     185            0 :                 node_id,
     186            0 :                 preferred_az_id.as_ref(),
     187            0 :                 RefCountUpdate::Attach,
     188            0 :             );
     189            0 :         }
     190            0 :         Self {
     191            0 :             attached: node_id,
     192            0 :             secondary: vec![],
     193            0 :             preferred_az_id,
     194            0 :         }
     195            0 :     }
     196              : 
     197        12859 :     pub(crate) fn set_attached(&mut self, scheduler: &mut Scheduler, new_attached: Option<NodeId>) {
     198        12859 :         if self.attached != new_attached {
     199        12859 :             if let Some(old_attached) = self.attached.take() {
     200            0 :                 scheduler.update_node_ref_counts(
     201            0 :                     old_attached,
     202            0 :                     self.preferred_az_id.as_ref(),
     203            0 :                     RefCountUpdate::Detach,
     204            0 :                 );
     205        12859 :             }
     206        12859 :             if let Some(new_attached) = &new_attached {
     207        12859 :                 scheduler.update_node_ref_counts(
     208        12859 :                     *new_attached,
     209        12859 :                     self.preferred_az_id.as_ref(),
     210        12859 :                     RefCountUpdate::Attach,
     211        12859 :                 );
     212        12859 :             }
     213        12859 :             self.attached = new_attached;
     214            0 :         }
     215              : 
     216        12859 :         if let Some(new_attached) = &new_attached {
     217        12859 :             assert!(!self.secondary.contains(new_attached));
     218            0 :         }
     219        12859 :     }
     220              : 
     221              :     /// Like set_attached, but the node is from [`Self::secondary`].  This swaps the node from
     222              :     /// secondary to attached while maintaining the scheduler's reference counts.
     223            7 :     pub(crate) fn promote_attached(
     224            7 :         &mut self,
     225            7 :         scheduler: &mut Scheduler,
     226            7 :         promote_secondary: NodeId,
     227            7 :     ) {
     228              :         // If we call this with a node that isn't in secondary, it would cause incorrect
     229              :         // scheduler reference counting, since we assume the node is already referenced as a secondary.
     230            7 :         debug_assert!(self.secondary.contains(&promote_secondary));
     231              : 
     232           16 :         self.secondary.retain(|n| n != &promote_secondary);
     233              : 
     234            7 :         let demoted = self.attached;
     235            7 :         self.attached = Some(promote_secondary);
     236              : 
     237            7 :         scheduler.update_node_ref_counts(
     238            7 :             promote_secondary,
     239            7 :             self.preferred_az_id.as_ref(),
     240            7 :             RefCountUpdate::PromoteSecondary,
     241              :         );
     242            7 :         if let Some(demoted) = demoted {
     243            0 :             scheduler.update_node_ref_counts(
     244            0 :                 demoted,
     245            0 :                 self.preferred_az_id.as_ref(),
     246            0 :                 RefCountUpdate::DemoteAttached,
     247            0 :             );
     248            7 :         }
     249            7 :     }
     250              : 
     251        12848 :     pub(crate) fn push_secondary(&mut self, scheduler: &mut Scheduler, new_secondary: NodeId) {
     252        12848 :         assert!(!self.secondary.contains(&new_secondary));
     253        12848 :         assert!(self.attached != Some(new_secondary));
     254        12848 :         scheduler.update_node_ref_counts(
     255        12848 :             new_secondary,
     256        12848 :             self.preferred_az_id.as_ref(),
     257        12848 :             RefCountUpdate::AddSecondary,
     258              :         );
     259        12848 :         self.secondary.push(new_secondary);
     260        12848 :     }
     261              : 
     262              :     /// It is legal to call this with a node that is not currently a secondary: that is a no-op
     263            9 :     pub(crate) fn remove_secondary(&mut self, scheduler: &mut Scheduler, node_id: NodeId) {
     264           13 :         let index = self.secondary.iter().position(|n| *n == node_id);
     265            9 :         if let Some(index) = index {
     266            9 :             scheduler.update_node_ref_counts(
     267            9 :                 node_id,
     268            9 :                 self.preferred_az_id.as_ref(),
     269            9 :                 RefCountUpdate::RemoveSecondary,
     270            9 :             );
     271            9 :             self.secondary.remove(index);
     272            9 :         }
     273            9 :     }
     274              : 
     275        12859 :     pub(crate) fn clear_secondary(&mut self, scheduler: &mut Scheduler) {
     276        12859 :         for secondary in self.secondary.drain(..) {
     277        12840 :             scheduler.update_node_ref_counts(
     278        12840 :                 secondary,
     279        12840 :                 self.preferred_az_id.as_ref(),
     280        12840 :                 RefCountUpdate::RemoveSecondary,
     281        12840 :             );
     282        12840 :         }
     283        12859 :     }
     284              : 
     285              :     /// Remove the last secondary node from the list of secondaries
     286            0 :     pub(crate) fn pop_secondary(&mut self, scheduler: &mut Scheduler) {
     287            0 :         if let Some(node_id) = self.secondary.pop() {
     288            0 :             scheduler.update_node_ref_counts(
     289            0 :                 node_id,
     290            0 :                 self.preferred_az_id.as_ref(),
     291            0 :                 RefCountUpdate::RemoveSecondary,
     292            0 :             );
     293            0 :         }
     294            0 :     }
     295              : 
     296        12859 :     pub(crate) fn clear(&mut self, scheduler: &mut Scheduler) {
     297        12859 :         if let Some(old_attached) = self.attached.take() {
     298        12857 :             scheduler.update_node_ref_counts(
     299        12857 :                 old_attached,
     300        12857 :                 self.preferred_az_id.as_ref(),
     301        12857 :                 RefCountUpdate::Detach,
     302        12857 :             );
     303        12857 :         }
     304              : 
     305        12859 :         self.clear_secondary(scheduler);
     306        12859 :     }
     307              : 
     308        12901 :     pub(crate) fn all_pageservers(&self) -> Vec<NodeId> {
     309        12901 :         let mut result = Vec::new();
     310        12901 :         if let Some(p) = self.attached {
     311        12896 :             result.push(p)
     312            5 :         }
     313              : 
     314        12901 :         result.extend(self.secondary.iter().copied());
     315              : 
     316        12901 :         result
     317        12901 :     }
     318              : 
     319        12624 :     pub(crate) fn get_attached(&self) -> &Option<NodeId> {
     320        12624 :         &self.attached
     321        12624 :     }
     322              : 
     323        12706 :     pub(crate) fn get_secondary(&self) -> &Vec<NodeId> {
     324        12706 :         &self.secondary
     325        12706 :     }
     326              : 
     327              :     /// If the node is in use as the attached location, demote it into
     328              :     /// the list of secondary locations.  This is used when a node goes offline,
     329              :     /// and we want to use a different node for attachment, but not permanently
     330              :     /// forget the location on the offline node.
     331              :     ///
     332              :     /// Returns true if a change was made
     333            8 :     pub(crate) fn demote_attached(&mut self, scheduler: &mut Scheduler, node_id: NodeId) -> bool {
     334            8 :         if self.attached == Some(node_id) {
     335            8 :             self.attached = None;
     336            8 :             self.secondary.push(node_id);
     337            8 :             scheduler.update_node_ref_counts(
     338            8 :                 node_id,
     339            8 :                 self.preferred_az_id.as_ref(),
     340            8 :                 RefCountUpdate::DemoteAttached,
     341              :             );
     342            8 :             true
     343              :         } else {
     344            0 :             false
     345              :         }
     346            8 :     }
     347              : 
     348            2 :     pub(crate) fn set_preferred_az(
     349            2 :         &mut self,
     350            2 :         scheduler: &mut Scheduler,
     351            2 :         preferred_az: Option<AvailabilityZone>,
     352            2 :     ) {
     353            2 :         let new_az = preferred_az.as_ref();
     354            2 :         let old_az = self.preferred_az_id.as_ref();
     355              : 
     356            2 :         if old_az != new_az {
     357            2 :             if let Some(node_id) = self.attached {
     358            2 :                 scheduler.update_node_ref_counts(
     359            2 :                     node_id,
     360            2 :                     new_az,
     361            2 :                     RefCountUpdate::ChangePreferredAzFrom(old_az),
     362            2 :                 );
     363            2 :             }
     364            4 :             for node_id in &self.secondary {
     365            2 :                 scheduler.update_node_ref_counts(
     366            2 :                     *node_id,
     367            2 :                     new_az,
     368            2 :                     RefCountUpdate::ChangePreferredAzFrom(old_az),
     369            2 :                 );
     370            2 :             }
     371            2 :             self.preferred_az_id = preferred_az;
     372            0 :         }
     373            2 :     }
     374              : 
     375        12508 :     pub(crate) fn get_preferred_az(&self) -> Option<&AvailabilityZone> {
     376        12508 :         self.preferred_az_id.as_ref()
     377        12508 :     }
     378              : }
     379              : 
     380              : impl Drop for IntentState {
     381        12860 :     fn drop(&mut self) {
     382              :         // Must clear before dropping, to avoid leaving stale refcounts in the Scheduler.
     383              :         // We do not check this while panicking, to avoid polluting unit test failures or
     384              :         // other assertions with this assertion's output.  It's still wrong to leak these,
     385              :         // but if we already have a panic then we don't need to independently flag this case.
     386        12860 :         if !(std::thread::panicking()) {
     387        12860 :             debug_assert!(self.attached.is_none() && self.secondary.is_empty());
     388            0 :         }
     389        12859 :     }
     390              : }
     391              : 
     392            0 : #[derive(Default, Clone, Serialize, Deserialize, Debug)]
     393              : pub(crate) struct ObservedState {
     394              :     pub(crate) locations: HashMap<NodeId, ObservedStateLocation>,
     395              : }
     396              : 
     397              : /// Our latest knowledge of how this tenant is configured in the outside world.
     398              : ///
     399              : /// Meaning:
     400              : ///     * No instance of this type exists for a node: we are certain that we have nothing configured on that
     401              : ///       node for this shard.
     402              : ///     * Instance exists with conf==None: we *might* have some state on that node, but we don't know
     403              : ///       what it is (e.g. we failed partway through configuring it)
     404              : ///     * Instance exists with conf==Some: this tells us what we last successfully configured on this node,
     405              : ///       and that configuration will still be present unless something external interfered.
     406            0 : #[derive(Clone, Serialize, Deserialize, Debug)]
     407              : pub(crate) struct ObservedStateLocation {
     408              :     /// If None, it means we do not know the status of this shard's location on this node, but
     409              :     /// we know that we might have some state on this node.
     410              :     pub(crate) conf: Option<LocationConfig>,
     411              : }
     412              : 
     413              : pub(crate) struct ReconcilerWaiter {
     414              :     // For observability purposes, remember the ID of the shard we're
     415              :     // waiting for.
     416              :     pub(crate) tenant_shard_id: TenantShardId,
     417              : 
     418              :     seq_wait: std::sync::Arc<SeqWait<Sequence, Sequence>>,
     419              :     error_seq_wait: std::sync::Arc<SeqWait<Sequence, Sequence>>,
     420              :     error: std::sync::Arc<std::sync::Mutex<Option<Arc<ReconcileError>>>>,
     421              :     seq: Sequence,
     422              : }
     423              : 
     424              : pub(crate) enum ReconcilerStatus {
     425              :     Done,
     426              :     Failed,
     427              :     InProgress,
     428              : }
     429              : 
     430              : #[derive(thiserror::Error, Debug)]
     431              : pub(crate) enum ReconcileWaitError {
     432              :     #[error("Timeout waiting for shard {0}")]
     433              :     Timeout(TenantShardId),
     434              :     #[error("shutting down")]
     435              :     Shutdown,
     436              :     #[error("Reconcile error on shard {0}: {1}")]
     437              :     Failed(TenantShardId, Arc<ReconcileError>),
     438              : }
     439              : 
     440              : #[derive(Eq, PartialEq, Debug, Clone)]
     441              : pub(crate) struct ReplaceSecondary {
     442              :     old_node_id: NodeId,
     443              :     new_node_id: NodeId,
     444              : }
     445              : 
     446              : #[derive(Eq, PartialEq, Debug, Clone)]
     447              : pub(crate) struct MigrateAttachment {
     448              :     pub(crate) old_attached_node_id: NodeId,
     449              :     pub(crate) new_attached_node_id: NodeId,
     450              : }
     451              : 
     452              : #[derive(Eq, PartialEq, Debug, Clone)]
     453              : pub(crate) enum ScheduleOptimizationAction {
     454              :     // Replace one of our secondary locations with a different node
     455              :     ReplaceSecondary(ReplaceSecondary),
     456              :     // Migrate attachment to an existing secondary location
     457              :     MigrateAttachment(MigrateAttachment),
     458              :     // Create a secondary location, with the intent of later migrating to it
     459              :     CreateSecondary(NodeId),
     460              :     // Remove a secondary location that we previously created to facilitate a migration
     461              :     RemoveSecondary(NodeId),
     462              : }
     463              : 
     464              : #[derive(Eq, PartialEq, Debug, Clone)]
     465              : pub(crate) struct ScheduleOptimization {
     466              :     // What was the reconcile sequence when we generated this optimization?  The optimization
     467              :     // should only be applied if the shard's sequence is still at this value, in case other changes
     468              :     // happened between planning the optimization and applying it.
     469              :     sequence: Sequence,
     470              : 
     471              :     pub(crate) action: ScheduleOptimizationAction,
     472              : }
     473              : 
     474              : impl ReconcilerWaiter {
     475            0 :     pub(crate) async fn wait_timeout(&self, timeout: Duration) -> Result<(), ReconcileWaitError> {
     476            0 :         tokio::select! {
     477            0 :             result = self.seq_wait.wait_for_timeout(self.seq, timeout)=> {
     478            0 :                 result.map_err(|e| match e {
     479            0 :                     SeqWaitError::Timeout => ReconcileWaitError::Timeout(self.tenant_shard_id),
     480            0 :                     SeqWaitError::Shutdown => ReconcileWaitError::Shutdown
     481            0 :                 })?;
     482              :             },
     483            0 :             result = self.error_seq_wait.wait_for(self.seq) => {
     484            0 :                 result.map_err(|e| match e {
     485            0 :                     SeqWaitError::Shutdown => ReconcileWaitError::Shutdown,
     486            0 :                     SeqWaitError::Timeout => unreachable!()
     487            0 :                 })?;
     488              : 
     489            0 :                 return Err(ReconcileWaitError::Failed(self.tenant_shard_id,
     490            0 :                     self.error.lock().unwrap().clone().expect("If error_seq_wait was advanced error was set").clone()))
     491              :             }
     492              :         }
     493              : 
     494            0 :         Ok(())
     495            0 :     }
     496              : 
     497            0 :     pub(crate) fn get_status(&self) -> ReconcilerStatus {
     498            0 :         if self.seq_wait.would_wait_for(self.seq).is_ok() {
     499            0 :             ReconcilerStatus::Done
     500            0 :         } else if self.error_seq_wait.would_wait_for(self.seq).is_ok() {
     501            0 :             ReconcilerStatus::Failed
     502              :         } else {
     503            0 :             ReconcilerStatus::InProgress
     504              :         }
     505            0 :     }
     506              : }
     507              : 
     508              : /// Having spawned a reconciler task, the tenant shard's state will carry enough
     509              : /// information to optionally cancel & await it later.
     510              : pub(crate) struct ReconcilerHandle {
     511              :     sequence: Sequence,
     512              :     handle: JoinHandle<()>,
     513              :     cancel: CancellationToken,
     514              : }
     515              : 
     516              : pub(crate) enum ReconcileNeeded {
     517              :     /// shard either doesn't need reconciliation, or is forbidden from spawning a reconciler
     518              :     /// in its current state (e.g. shard split in progress, or ShardSchedulingPolicy forbids it)
     519              :     No,
     520              :     /// shard has a reconciler running, and its intent hasn't changed since that one was
     521              :     /// spawned: wait for the existing reconciler rather than spawning a new one.
     522              :     WaitExisting(ReconcilerWaiter),
     523              :     /// shard needs reconciliation: call into [`TenantShard::spawn_reconciler`]
     524              :     Yes(ReconcileReason),
     525              : }
     526              : 
     527              : #[derive(Debug)]
     528              : pub(crate) enum ReconcileReason {
     529              :     ActiveNodesDirty,
     530              :     UnknownLocation,
     531              :     PendingComputeNotification,
     532              : }
     533              : 
     534              : /// Pending modification to the observed state of a tenant shard.
     535              : /// Produced by [`Reconciler::observed_deltas`] and applied in [`crate::service::Service::process_result`].
     536              : pub(crate) enum ObservedStateDelta {
     537              :     Upsert(Box<(NodeId, ObservedStateLocation)>),
     538              :     Delete(NodeId),
     539              : }
     540              : 
     541              : impl ObservedStateDelta {
     542            0 :     pub(crate) fn node_id(&self) -> &NodeId {
     543            0 :         match self {
     544            0 :             Self::Upsert(up) => &up.0,
     545            0 :             Self::Delete(nid) => nid,
     546              :         }
     547            0 :     }
     548              : }
     549              : 
     550              : /// When a reconcile task completes, it sends this result object
     551              : /// to be applied to the primary TenantShard.
     552              : pub(crate) struct ReconcileResult {
     553              :     pub(crate) sequence: Sequence,
     554              :     /// On errors, `observed` should be treated as an incompleted description
     555              :     /// of state (i.e. any nodes present in the result should override nodes
     556              :     /// present in the parent tenant state, but any unmentioned nodes should
     557              :     /// not be removed from parent tenant state)
     558              :     pub(crate) result: Result<(), ReconcileError>,
     559              : 
     560              :     pub(crate) tenant_shard_id: TenantShardId,
     561              :     pub(crate) generation: Option<Generation>,
     562              :     pub(crate) observed_deltas: Vec<ObservedStateDelta>,
     563              : 
     564              :     /// Set [`TenantShard::pending_compute_notification`] from this flag
     565              :     pub(crate) pending_compute_notification: bool,
     566              : }
     567              : 
     568              : impl ObservedState {
     569            0 :     pub(crate) fn new() -> Self {
     570            0 :         Self {
     571            0 :             locations: HashMap::new(),
     572            0 :         }
     573            0 :     }
     574              : 
     575            0 :     pub(crate) fn is_empty(&self) -> bool {
     576            0 :         self.locations.is_empty()
     577            0 :     }
     578              : }
     579              : 
     580              : impl TenantShard {
     581        12843 :     pub(crate) fn new(
     582        12843 :         tenant_shard_id: TenantShardId,
     583        12843 :         shard: ShardIdentity,
     584        12843 :         policy: PlacementPolicy,
     585        12843 :         preferred_az_id: Option<AvailabilityZone>,
     586        12843 :     ) -> Self {
     587        12843 :         metrics::METRICS_REGISTRY
     588        12843 :             .metrics_group
     589        12843 :             .storage_controller_tenant_shards
     590        12843 :             .inc();
     591              : 
     592        12843 :         Self {
     593        12843 :             tenant_shard_id,
     594        12843 :             policy,
     595        12843 :             intent: IntentState::new(preferred_az_id),
     596        12843 :             generation: Some(Generation::new(0)),
     597        12843 :             shard,
     598        12843 :             observed: ObservedState::default(),
     599        12843 :             config: TenantConfig::default(),
     600        12843 :             reconciler: None,
     601        12843 :             splitting: SplitState::Idle,
     602        12843 :             importing: TimelineImportState::Idle,
     603        12843 :             sequence: Sequence(1),
     604        12843 :             delayed_reconcile: false,
     605        12843 :             waiter: Arc::new(SeqWait::new(Sequence(0))),
     606        12843 :             error_waiter: Arc::new(SeqWait::new(Sequence(0))),
     607        12843 :             last_error: Arc::default(),
     608        12843 :             consecutive_reconciles_count: 0,
     609        12843 :             pending_compute_notification: false,
     610        12843 :             scheduling_policy: ShardSchedulingPolicy::default(),
     611        12843 :             preferred_node: None,
     612        12843 :         }
     613        12843 :     }
     614              : 
     615              :     /// For use on startup when learning state from pageservers: generate my [`IntentState`] from my
     616              :     /// [`ObservedState`], even if it violates my [`PlacementPolicy`].  Call [`Self::schedule`] next,
     617              :     /// to get an intent state that complies with placement policy.  The overall goal is to do scheduling
     618              :     /// in a way that makes use of any configured locations that already exist in the outside world.
     619            1 :     pub(crate) fn intent_from_observed(&mut self, scheduler: &mut Scheduler) {
     620              :         // Choose an attached location by filtering observed locations, and then sorting to get the highest
     621              :         // generation
     622            1 :         let mut attached_locs = self
     623            1 :             .observed
     624            1 :             .locations
     625            1 :             .iter()
     626            2 :             .filter_map(|(node_id, l)| {
     627            2 :                 if let Some(conf) = &l.conf {
     628            2 :                     if conf.mode == LocationConfigMode::AttachedMulti
     629            1 :                         || conf.mode == LocationConfigMode::AttachedSingle
     630            1 :                         || conf.mode == LocationConfigMode::AttachedStale
     631              :                     {
     632            2 :                         Some((node_id, conf.generation))
     633              :                     } else {
     634            0 :                         None
     635              :                     }
     636              :                 } else {
     637            0 :                     None
     638              :                 }
     639            2 :             })
     640            1 :             .collect::<Vec<_>>();
     641              : 
     642            1 :         attached_locs.sort_by_key(|i| i.1);
     643            1 :         if let Some((node_id, _gen)) = attached_locs.into_iter().next_back() {
     644            1 :             self.intent.set_attached(scheduler, Some(*node_id));
     645            1 :         }
     646              : 
     647              :         // All remaining observed locations generate secondary intents.  This includes None
     648              :         // observations, as these may well have some local content on disk that is usable (this
     649              :         // is an edge case that might occur if we restarted during a migration or other change)
     650              :         //
     651              :         // We may leave intent.attached empty if we didn't find any attached locations: [`Self::schedule`]
     652              :         // will take care of promoting one of these secondaries to be attached.
     653            2 :         self.observed.locations.keys().for_each(|node_id| {
     654            2 :             if Some(*node_id) != self.intent.attached {
     655            1 :                 self.intent.push_secondary(scheduler, *node_id);
     656            1 :             }
     657            2 :         });
     658            1 :     }
     659              : 
     660              :     /// Part of [`Self::schedule`] that is used to choose exactly one node to act as the
     661              :     /// attached pageserver for a shard.
     662              :     ///
     663              :     /// Returns whether we modified it, and the NodeId selected.
     664        12832 :     fn schedule_attached(
     665        12832 :         &mut self,
     666        12832 :         scheduler: &mut Scheduler,
     667        12832 :         context: &ScheduleContext,
     668        12832 :     ) -> Result<(bool, NodeId), ScheduleError> {
     669              :         // No work to do if we already have an attached tenant
     670        12832 :         if let Some(node_id) = self.intent.attached {
     671            0 :             return Ok((false, node_id));
     672        12832 :         }
     673              : 
     674        12832 :         if let Some(promote_secondary) = self.preferred_secondary(scheduler) {
     675              :             // Promote a secondary
     676            2 :             tracing::debug!("Promoted secondary {} to attached", promote_secondary);
     677            2 :             self.intent.promote_attached(scheduler, promote_secondary);
     678            2 :             Ok((true, promote_secondary))
     679              :         } else {
     680              :             // Pick a fresh node: either we had no secondaries or none were schedulable
     681        12830 :             let node_id = scheduler.schedule_shard::<AttachedShardTag>(
     682        12830 :                 &self.intent.secondary,
     683        12830 :                 &self.intent.preferred_az_id,
     684        12830 :                 context,
     685            0 :             )?;
     686        12830 :             tracing::debug!("Selected {} as attached", node_id);
     687        12830 :             self.intent.set_attached(scheduler, Some(node_id));
     688        12830 :             Ok((true, node_id))
     689              :         }
     690        12832 :     }
     691              : 
     692              :     #[instrument(skip_all, fields(
     693              :         tenant_id=%self.tenant_shard_id.tenant_id,
     694              :         shard_id=%self.tenant_shard_id.shard_slug(),
     695              :         sequence=%self.sequence
     696              :     ))]
     697              :     pub(crate) fn schedule(
     698              :         &mut self,
     699              :         scheduler: &mut Scheduler,
     700              :         context: &mut ScheduleContext,
     701              :     ) -> Result<(), ScheduleError> {
     702              :         let r = self.do_schedule(scheduler, context);
     703              : 
     704              :         context.avoid(&self.intent.all_pageservers());
     705              : 
     706              :         r
     707              :     }
     708              : 
     709        12836 :     pub(crate) fn do_schedule(
     710        12836 :         &mut self,
     711        12836 :         scheduler: &mut Scheduler,
     712        12836 :         context: &ScheduleContext,
     713        12836 :     ) -> Result<(), ScheduleError> {
     714              :         // TODO: before scheduling new nodes, check if any existing content in
     715              :         // self.intent refers to pageservers that are offline, and pick other
     716              :         // pageservers if so.
     717              : 
     718              :         // TODO: respect the splitting bit on tenants: if they are currently splitting then we may not
     719              :         // change their attach location.
     720              : 
     721        12836 :         match self.scheduling_policy {
     722        12835 :             ShardSchedulingPolicy::Active | ShardSchedulingPolicy::Essential => {}
     723              :             ShardSchedulingPolicy::Pause | ShardSchedulingPolicy::Stop => {
     724              :                 // Warn to make it obvious why other things aren't happening/working, if we skip scheduling
     725            1 :                 tracing::warn!(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(),
     726            0 :                     "Scheduling is disabled by policy {:?}", self.scheduling_policy);
     727            1 :                 return Ok(());
     728              :             }
     729              :         }
     730              : 
     731              :         // Build the set of pageservers already in use by this tenant, to avoid scheduling
     732              :         // more work on the same pageservers we're already using.
     733        12835 :         let mut modified = false;
     734              : 
     735              :         // Add/remove nodes to fulfil policy
     736              :         use PlacementPolicy::*;
     737        12835 :         match self.policy {
     738        12832 :             Attached(secondary_count) => {
     739              :                 // Should have exactly one attached, and at least N secondaries
     740        12832 :                 let (modified_attached, attached_node_id) =
     741        12832 :                     self.schedule_attached(scheduler, context)?;
     742        12832 :                 modified |= modified_attached;
     743              : 
     744        12832 :                 let mut used_pageservers = vec![attached_node_id];
     745        25663 :                 while self.intent.secondary.len() < secondary_count {
     746        12831 :                     let node_id = scheduler.schedule_shard::<SecondaryShardTag>(
     747        12831 :                         &used_pageservers,
     748        12831 :                         &self.intent.preferred_az_id,
     749        12831 :                         context,
     750            0 :                     )?;
     751        12831 :                     self.intent.push_secondary(scheduler, node_id);
     752        12831 :                     used_pageservers.push(node_id);
     753        12831 :                     modified = true;
     754              :                 }
     755              :             }
     756              :             Secondary => {
     757            3 :                 if let Some(node_id) = self.intent.get_attached() {
     758            2 :                     // Populate secondary by demoting the attached node
     759            2 :                     self.intent.demote_attached(scheduler, *node_id);
     760            2 : 
     761            2 :                     modified = true;
     762            2 :                 } else if self.intent.secondary.is_empty() {
     763              :                     // Populate secondary by scheduling a fresh node
     764              :                     //
     765              :                     // We use [`AttachedShardTag`] because when a secondary location is the only one
     766              :                     // a shard has, we expect that its next use will be as an attached location: we want
     767              :                     // the tenant to be ready to warm up and run fast in their preferred AZ.
     768            1 :                     let node_id = scheduler.schedule_shard::<AttachedShardTag>(
     769            1 :                         &[],
     770            1 :                         &self.intent.preferred_az_id,
     771            1 :                         context,
     772            0 :                     )?;
     773            1 :                     self.intent.push_secondary(scheduler, node_id);
     774            1 :                     modified = true;
     775            0 :                 }
     776            4 :                 while self.intent.secondary.len() > 1 {
     777              :                     // If we have multiple secondaries (e.g. when transitioning from Attached to Secondary and
     778              :                     // having just demoted our attached location), then we should prefer to keep the location
     779              :                     // in our preferred AZ.  Tenants in Secondary mode want to be in the preferred AZ so that
     780              :                     // they have a warm location to become attached when transitioning back into Attached.
     781              : 
     782            1 :                     let mut candidates = self.intent.get_secondary().clone();
     783              :                     // Sort to get secondaries outside preferred AZ last
     784            1 :                     candidates
     785            2 :                         .sort_by_key(|n| scheduler.get_node_az(n).as_ref() != self.preferred_az());
     786            1 :                     let secondary_to_remove = candidates.pop().unwrap();
     787            1 :                     self.intent.remove_secondary(scheduler, secondary_to_remove);
     788            1 :                     modified = true;
     789              :                 }
     790              :             }
     791              :             Detached => {
     792              :                 // Never add locations in this mode
     793            0 :                 if self.intent.get_attached().is_some() || !self.intent.get_secondary().is_empty() {
     794            0 :                     self.intent.clear(scheduler);
     795            0 :                     modified = true;
     796            0 :                 }
     797              :             }
     798              :         }
     799              : 
     800        12835 :         if modified {
     801        12835 :             self.sequence.0 += 1;
     802        12835 :         }
     803              : 
     804        12835 :         Ok(())
     805        12836 :     }
     806              : 
     807              :     /// Reschedule this tenant shard to one of its secondary locations. Returns a scheduling error
     808              :     /// if the swap is not possible and leaves the intent state in its original state.
     809              :     ///
     810              :     /// Arguments:
     811              :     /// `attached_to`: the currently attached location matching the intent state (may be None if the
     812              :     /// shard is not attached)
     813              :     /// `promote_to`: an optional secondary location of this tenant shard. If set to None, we ask
     814              :     /// the scheduler to recommend a node
     815            0 :     pub(crate) fn reschedule_to_secondary(
     816            0 :         &mut self,
     817            0 :         promote_to: Option<NodeId>,
     818            0 :         scheduler: &mut Scheduler,
     819            0 :     ) -> Result<(), ScheduleError> {
     820            0 :         let promote_to = match promote_to {
     821            0 :             Some(node) => node,
     822            0 :             None => match self.preferred_secondary(scheduler) {
     823            0 :                 Some(node) => node,
     824              :                 None => {
     825            0 :                     return Err(ScheduleError::ImpossibleConstraint);
     826              :                 }
     827              :             },
     828              :         };
     829              : 
     830            0 :         assert!(self.intent.get_secondary().contains(&promote_to));
     831              : 
     832            0 :         if let Some(node) = self.intent.get_attached() {
     833            0 :             let demoted = self.intent.demote_attached(scheduler, *node);
     834            0 :             if !demoted {
     835            0 :                 return Err(ScheduleError::ImpossibleConstraint);
     836            0 :             }
     837            0 :         }
     838              : 
     839            0 :         self.intent.promote_attached(scheduler, promote_to);
     840              : 
     841              :         // Increment the sequence number for the edge case where a
     842              :         // reconciler is already running to avoid waiting on the
     843              :         // current reconcile instead of spawning a new one.
     844            0 :         self.sequence = self.sequence.next();
     845              : 
     846            0 :         Ok(())
     847            0 :     }
     848              : 
     849              :     /// Returns None if the current location's score is unavailable, i.e. cannot draw a conclusion
     850           68 :     fn is_better_location<T: ShardTag>(
     851           68 :         &self,
     852           68 :         scheduler: &mut Scheduler,
     853           68 :         schedule_context: &ScheduleContext,
     854           68 :         current: NodeId,
     855           68 :         candidate: NodeId,
     856           68 :     ) -> Option<bool> {
     857           68 :         let Some(candidate_score) = scheduler.compute_node_score::<T::Score>(
     858           68 :             candidate,
     859           68 :             &self.intent.preferred_az_id,
     860           68 :             schedule_context,
     861           68 :         ) else {
     862              :             // The candidate node is unavailable for scheduling or otherwise couldn't get a score
     863            1 :             return None;
     864              :         };
     865              : 
     866              :         // If the candidate is our preferred node, then it is better than the current location, as long
     867              :         // as it is online -- the online check is part of the score calculation we did above, so it's
     868              :         // important that this check comes after that one.
     869           67 :         if let Some(preferred) = self.preferred_node.as_ref() {
     870            3 :             if preferred == &candidate {
     871            1 :                 return Some(true);
     872            2 :             }
     873           64 :         }
     874              : 
     875           66 :         match scheduler.compute_node_score::<T::Score>(
     876           66 :             current,
     877           66 :             &self.intent.preferred_az_id,
     878           66 :             schedule_context,
     879           66 :         ) {
     880           66 :             Some(current_score) => {
     881              :                 // Ignore utilization components when comparing scores: we don't want to migrate
     882              :                 // because of transient load variations, it risks making the system thrash, and
     883              :                 // migrating for utilization requires a separate high level view of the system to
     884              :                 // e.g. prioritize moving larger or smaller tenants, rather than arbitrarily
     885              :                 // moving things around in the order that we hit this function.
     886           66 :                 let candidate_score = candidate_score.for_optimization();
     887           66 :                 let current_score = current_score.for_optimization();
     888              : 
     889           66 :                 if candidate_score < current_score {
     890            8 :                     tracing::info!(
     891            0 :                         "Found a lower scoring location! {candidate} is better than {current} ({candidate_score:?} is better than {current_score:?})"
     892              :                     );
     893            8 :                     Some(true)
     894              :                 } else {
     895              :                     // The candidate node is no better than our current location, so don't migrate
     896           58 :                     tracing::debug!(
     897            0 :                         "Candidate node {candidate} is no better than our current location {current} (candidate {candidate_score:?} vs current {current_score:?})",
     898              :                     );
     899           58 :                     Some(false)
     900              :                 }
     901              :             }
     902              :             None => {
     903              :                 // The current node is unavailable for scheduling, so we can't make any sensible
     904              :                 // decisions about optimisation.  This should be a transient state -- if the node
     905              :                 // is offline then it will get evacuated, if is blocked by a scheduling mode
     906              :                 // then we will respect that mode by doing nothing.
     907            0 :                 tracing::debug!("Current node {current} is unavailable for scheduling");
     908            0 :                 None
     909              :             }
     910              :         }
     911           68 :     }
     912              : 
     913           48 :     pub(crate) fn find_better_location<T: ShardTag>(
     914           48 :         &self,
     915           48 :         scheduler: &mut Scheduler,
     916           48 :         schedule_context: &ScheduleContext,
     917           48 :         current: NodeId,
     918           48 :         hard_exclude: &[NodeId],
     919           48 :     ) -> Option<NodeId> {
     920              :         // If we have a migration hint, then that is our better location
     921           48 :         if let Some(hint) = self.preferred_node.as_ref() {
     922            1 :             if hint == &current {
     923            0 :                 return None;
     924            1 :             }
     925              : 
     926            1 :             return Some(*hint);
     927           47 :         }
     928              : 
     929              :         // Look for a lower-scoring location to attach to
     930           47 :         let Ok(candidate_node) = scheduler.schedule_shard::<T>(
     931           47 :             hard_exclude,
     932           47 :             &self.intent.preferred_az_id,
     933           47 :             schedule_context,
     934           47 :         ) else {
     935              :             // A scheduling error means we have no possible candidate replacements
     936            0 :             tracing::debug!("No candidate node found");
     937            0 :             return None;
     938              :         };
     939              : 
     940           47 :         if candidate_node == current {
     941              :             // We're already at the best possible location, so don't migrate
     942           24 :             tracing::debug!("Candidate node {candidate_node} is already in use");
     943           24 :             return None;
     944           23 :         }
     945              : 
     946           23 :         self.is_better_location::<T>(scheduler, schedule_context, current, candidate_node)
     947           23 :             .and_then(|better| if better { Some(candidate_node) } else { None })
     948           48 :     }
     949              : 
     950              :     /// This function is an optimization, used to avoid doing large numbers of scheduling operations
     951              :     /// when looking for optimizations.  This function uses knowledge of how scores work to do some
     952              :     /// fast checks for whether it may to be possible to improve a score.
     953              :     ///
     954              :     /// If we return true, it only means that optimization _might_ be possible, not that it necessarily is.  If we
     955              :     /// return no, it definitely means that calling [`Self::optimize_attachment`] or [`Self::optimize_secondary`] would do no
     956              :     /// work.
     957            3 :     pub(crate) fn maybe_optimizable(
     958            3 :         &self,
     959            3 :         scheduler: &mut Scheduler,
     960            3 :         schedule_context: &ScheduleContext,
     961            3 :     ) -> bool {
     962              :         // Tenant with preferred node: check if it is not already at the preferred node
     963            3 :         if let Some(preferred) = self.preferred_node.as_ref() {
     964            0 :             if Some(preferred) != self.intent.get_attached().as_ref() {
     965            0 :                 return true;
     966            0 :             }
     967            3 :         }
     968              : 
     969              :         // Sharded tenant: check if any locations have a nonzero affinity score
     970            3 :         if self.shard.count >= ShardCount(1) {
     971            3 :             let schedule_context = schedule_context.project_detach(self);
     972            5 :             for node in self.intent.all_pageservers() {
     973            5 :                 if let Some(af) = schedule_context.nodes.get(&node) {
     974            5 :                     if *af > AffinityScore(0) {
     975            3 :                         return true;
     976            2 :                     }
     977            0 :                 }
     978              :             }
     979            0 :         }
     980              : 
     981              :         // Attached tenant: check if the attachment is outside the preferred AZ
     982            0 :         if let PlacementPolicy::Attached(_) = self.policy {
     983            0 :             if let Some(attached) = self.intent.get_attached() {
     984            0 :                 if scheduler.get_node_az(attached) != self.intent.preferred_az_id {
     985            0 :                     return true;
     986            0 :                 }
     987            0 :             }
     988            0 :         }
     989              : 
     990              :         // Tenant with secondary locations: check if any are within the preferred AZ
     991            0 :         for secondary in self.intent.get_secondary() {
     992            0 :             if scheduler.get_node_az(secondary) == self.intent.preferred_az_id {
     993            0 :                 return true;
     994            0 :             }
     995              :         }
     996              : 
     997              :         // Does the tenant have excess secondaries?
     998            0 :         if self.intent.get_secondary().len() > self.policy.want_secondaries() {
     999            0 :             return true;
    1000            0 :         }
    1001              : 
    1002              :         // Fall through: no optimizations possible
    1003            0 :         false
    1004            3 :     }
    1005              : 
    1006              :     /// Optimize attachments: if a shard has a secondary location that is preferable to
    1007              :     /// its primary location based on soft constraints, switch that secondary location
    1008              :     /// to be attached.
    1009              :     ///
    1010              :     /// `schedule_context` should have been populated with all shards in the tenant, including
    1011              :     /// the one we're trying to optimize (this function will subtract its own contribution before making scoring decisions)
    1012              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    1013              :     pub(crate) fn optimize_attachment(
    1014              :         &self,
    1015              :         scheduler: &mut Scheduler,
    1016              :         schedule_context: &ScheduleContext,
    1017              :     ) -> Option<ScheduleOptimization> {
    1018              :         let attached = (*self.intent.get_attached())?;
    1019              : 
    1020              :         let schedule_context = schedule_context.project_detach(self);
    1021              : 
    1022              :         // If we already have a secondary that is higher-scoring than out current location,
    1023              :         // then simply migrate to it.
    1024              :         for secondary in self.intent.get_secondary() {
    1025              :             if let Some(true) = self.is_better_location::<AttachedShardTag>(
    1026              :                 scheduler,
    1027              :                 &schedule_context,
    1028              :                 attached,
    1029              :                 *secondary,
    1030              :             ) {
    1031              :                 return Some(ScheduleOptimization {
    1032              :                     sequence: self.sequence,
    1033              :                     action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    1034              :                         old_attached_node_id: attached,
    1035              :                         new_attached_node_id: *secondary,
    1036              :                     }),
    1037              :                 });
    1038              :             }
    1039              :         }
    1040              : 
    1041              :         // Given that none of our current secondaries is a better location than our current
    1042              :         // attached location (checked above), we may trim any secondaries that are not needed
    1043              :         // for the placement policy.
    1044              :         if self.intent.get_secondary().len() > self.policy.want_secondaries() {
    1045              :             // This code path cleans up extra secondaries after migrating, and/or
    1046              :             // trims extra secondaries after a PlacementPolicy::Attached(N) was
    1047              :             // modified to decrease N.
    1048              : 
    1049              :             let secondary_scores = self
    1050              :                 .intent
    1051              :                 .get_secondary()
    1052              :                 .iter()
    1053           12 :                 .map(|node_id| {
    1054           12 :                     (
    1055           12 :                         *node_id,
    1056           12 :                         scheduler.compute_node_score::<NodeSecondarySchedulingScore>(
    1057           12 :                             *node_id,
    1058           12 :                             &self.intent.preferred_az_id,
    1059           12 :                             &schedule_context,
    1060           12 :                         ),
    1061           12 :                     )
    1062           12 :                 })
    1063              :                 .collect::<HashMap<_, _>>();
    1064              : 
    1065           12 :             if secondary_scores.iter().any(|score| score.1.is_none()) {
    1066              :                 // Trivial case: if we only have one secondary, drop that one
    1067              :                 if self.intent.get_secondary().len() == 1 {
    1068              :                     return Some(ScheduleOptimization {
    1069              :                         sequence: self.sequence,
    1070              :                         action: ScheduleOptimizationAction::RemoveSecondary(
    1071              :                             *self.intent.get_secondary().first().unwrap(),
    1072              :                         ),
    1073              :                     });
    1074              :                 }
    1075              : 
    1076              :                 // Try to find a "good" secondary to keep, without relying on scores (one or more nodes is in a state
    1077              :                 // where its score can't be calculated), and drop the others.  This enables us to make progress in
    1078              :                 // most cases, even if some nodes are offline or have scheduling=pause set.
    1079              : 
    1080              :                 debug_assert!(self.intent.attached.is_some()); // We should not make it here unless attached -- this
    1081              :                 // logic presumes we are in a mode where we want secondaries to be in non-home AZ
    1082            1 :                 if let Some(retain_secondary) = self.intent.get_secondary().iter().find(|n| {
    1083            1 :                     let in_home_az = scheduler.get_node_az(n) == self.intent.preferred_az_id;
    1084            1 :                     let is_available = secondary_scores
    1085            1 :                         .get(n)
    1086            1 :                         .expect("Built from same list of nodes")
    1087            1 :                         .is_some();
    1088            1 :                     is_available && !in_home_az
    1089            1 :                 }) {
    1090              :                     // Great, we found one to retain.  Pick some other to drop.
    1091              :                     if let Some(victim) = self
    1092              :                         .intent
    1093              :                         .get_secondary()
    1094              :                         .iter()
    1095            2 :                         .find(|n| n != &retain_secondary)
    1096              :                     {
    1097              :                         return Some(ScheduleOptimization {
    1098              :                             sequence: self.sequence,
    1099              :                             action: ScheduleOptimizationAction::RemoveSecondary(*victim),
    1100              :                         });
    1101              :                     }
    1102              :                 }
    1103              : 
    1104              :                 // Fall through: we didn't identify one to remove.  This ought to be rare.
    1105              :                 tracing::warn!(
    1106              :                     "Keeping extra secondaries: can't determine which of {:?} to remove (some nodes offline?)",
    1107              :                     self.intent.get_secondary()
    1108              :                 );
    1109              :             } else {
    1110              :                 let victim = secondary_scores
    1111              :                     .iter()
    1112           10 :                     .max_by_key(|score| score.1.unwrap())
    1113              :                     .unwrap()
    1114              :                     .0;
    1115              :                 return Some(ScheduleOptimization {
    1116              :                     sequence: self.sequence,
    1117              :                     action: ScheduleOptimizationAction::RemoveSecondary(*victim),
    1118              :                 });
    1119              :             }
    1120              :         }
    1121              : 
    1122              :         let replacement = self.find_better_location::<AttachedShardTag>(
    1123              :             scheduler,
    1124              :             &schedule_context,
    1125              :             attached,
    1126              :             &[], // Don't exclude secondaries: our preferred attachment location may be a secondary
    1127              :         );
    1128              : 
    1129              :         // We have found a candidate and confirmed that its score is preferable
    1130              :         // to our current location. See if we have a secondary location in the preferred location already: if not,
    1131              :         // then create one.
    1132              :         if let Some(replacement) = replacement {
    1133              :             // If we are currently in non-preferred AZ, then the scheduler might suggest a location that is better, but still
    1134              :             // not in our preferred AZ.  Migration has a cost in resources an impact to the workload, so we want to avoid doing
    1135              :             // multiple hops where we might go to some other AZ before eventually finding a suitable location in our preferred
    1136              :             // AZ: skip this optimization if it is not in our final, preferred AZ.
    1137              :             //
    1138              :             // This should be a transient state, there should always be capacity eventually in our preferred AZ (even if nodes
    1139              :             // there are too overloaded for scheduler to suggest them, more should be provisioned eventually).
    1140              :             if self.preferred_node.is_none()
    1141              :                 && self.intent.preferred_az_id.is_some()
    1142              :                 && scheduler.get_node_az(&replacement) != self.intent.preferred_az_id
    1143              :             {
    1144              :                 tracing::debug!(
    1145              :                     "Candidate node {replacement} is not in preferred AZ {:?}",
    1146              :                     self.intent.preferred_az_id
    1147              :                 );
    1148              : 
    1149              :                 // This should only happen if our current location is not in the preferred AZ, otherwise
    1150              :                 // [`Self::find_better_location`]` should have rejected any other location outside the preferred Az, because
    1151              :                 // AZ is the highest priority part of NodeAttachmentSchedulingScore.
    1152              :                 debug_assert!(scheduler.get_node_az(&attached) != self.intent.preferred_az_id);
    1153              : 
    1154              :                 return None;
    1155              :             }
    1156              : 
    1157              :             if !self.intent.get_secondary().contains(&replacement) {
    1158              :                 Some(ScheduleOptimization {
    1159              :                     sequence: self.sequence,
    1160              :                     action: ScheduleOptimizationAction::CreateSecondary(replacement),
    1161              :                 })
    1162              :             } else {
    1163              :                 // We already have a secondary in the preferred location, let's try migrating to it.  Our caller
    1164              :                 // will check the warmth of the destination before deciding whether to really execute this.
    1165              :                 Some(ScheduleOptimization {
    1166              :                     sequence: self.sequence,
    1167              :                     action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    1168              :                         old_attached_node_id: attached,
    1169              :                         new_attached_node_id: replacement,
    1170              :                     }),
    1171              :                 })
    1172              :             }
    1173              :         } else {
    1174              :             // We didn't find somewhere we'd rather be, and we don't have any excess secondaries
    1175              :             // to clean up: no action required.
    1176              :             None
    1177              :         }
    1178              :     }
    1179              : 
    1180              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    1181              :     pub(crate) fn optimize_secondary(
    1182              :         &self,
    1183              :         scheduler: &mut Scheduler,
    1184              :         schedule_context: &ScheduleContext,
    1185              :     ) -> Option<ScheduleOptimization> {
    1186              :         if self.intent.get_secondary().len() > self.policy.want_secondaries() {
    1187              :             // We have extra secondaries, perhaps to facilitate a migration of the attached location:
    1188              :             // do nothing, it is up to [`Self::optimize_attachment`] to clean them up.  When that's done,
    1189              :             // and we are called again, we will proceed.
    1190              :             tracing::debug!("Too many secondaries: skipping");
    1191              :             return None;
    1192              :         }
    1193              : 
    1194              :         let schedule_context = schedule_context.project_detach(self);
    1195              : 
    1196              :         for secondary in self.intent.get_secondary() {
    1197              :             // Make sure we don't try to migrate a secondary to our attached location: this case happens
    1198              :             // easily in environments without multiple AZs.
    1199              :             let mut exclude = match self.intent.attached {
    1200              :                 Some(attached) => vec![attached],
    1201              :                 None => vec![],
    1202              :             };
    1203              : 
    1204              :             // Exclude all other secondaries from the scheduling process to avoid replacing
    1205              :             // one existing secondary with another existing secondary.
    1206              :             for another_secondary in self.intent.secondary.iter() {
    1207              :                 if another_secondary != secondary {
    1208              :                     exclude.push(*another_secondary);
    1209              :                 }
    1210              :             }
    1211              : 
    1212              :             let replacement = match &self.policy {
    1213              :                 PlacementPolicy::Attached(_) => {
    1214              :                     // Secondaries for an attached shard should be scheduled using `SecondaryShardTag`
    1215              :                     // to avoid placing them in the preferred AZ.
    1216              :                     self.find_better_location::<SecondaryShardTag>(
    1217              :                         scheduler,
    1218              :                         &schedule_context,
    1219              :                         *secondary,
    1220              :                         &exclude,
    1221              :                     )
    1222              :                 }
    1223              :                 PlacementPolicy::Secondary => {
    1224              :                     // In secondary-only mode, we want our secondary locations in the preferred AZ,
    1225              :                     // so that they're ready to take over as an attached location when we transition
    1226              :                     // into PlacementPolicy::Attached.
    1227              :                     self.find_better_location::<AttachedShardTag>(
    1228              :                         scheduler,
    1229              :                         &schedule_context,
    1230              :                         *secondary,
    1231              :                         &exclude,
    1232              :                     )
    1233              :                 }
    1234              :                 PlacementPolicy::Detached => None,
    1235              :             };
    1236              : 
    1237              :             assert!(replacement != Some(*secondary));
    1238              :             if let Some(replacement) = replacement {
    1239              :                 // We have found a candidate and confirmed that its score is preferable
    1240              :                 // to our current location. See if we have a secondary location in the preferred location already: if not,
    1241              :                 // then create one.
    1242              :                 return Some(ScheduleOptimization {
    1243              :                     sequence: self.sequence,
    1244              :                     action: ScheduleOptimizationAction::ReplaceSecondary(ReplaceSecondary {
    1245              :                         old_node_id: *secondary,
    1246              :                         new_node_id: replacement,
    1247              :                     }),
    1248              :                 });
    1249              :             }
    1250              :         }
    1251              : 
    1252              :         None
    1253              :     }
    1254              : 
    1255              :     /// Start or abort a graceful migration of this shard to another pageserver. This works on top of the
    1256              :     /// other optimisation functions, to bias them to move to the destination node.
    1257            0 :     pub(crate) fn set_preferred_node(&mut self, node: Option<NodeId>) {
    1258            0 :         if let Some(hint) = self.preferred_node.as_ref() {
    1259            0 :             if Some(hint) != node.as_ref() {
    1260              :                 // This is legal but a bit surprising: we expect that administrators wouldn't usually
    1261              :                 // change their mind about where to migrate something.
    1262            0 :                 tracing::warn!(
    1263            0 :                     "Changing migration destination from {hint} to {node:?} (current intent {:?})",
    1264              :                     self.intent
    1265              :                 );
    1266            0 :             }
    1267            0 :         }
    1268              : 
    1269            0 :         self.preferred_node = node;
    1270            0 :     }
    1271              : 
    1272            0 :     pub(crate) fn get_preferred_node(&self) -> Option<NodeId> {
    1273            0 :         self.preferred_node
    1274            0 :     }
    1275              : 
    1276              :     /// Return true if the optimization was really applied: it will not be applied if the optimization's
    1277              :     /// sequence is behind this tenant shard's or if the intent state proposed by the optimization
    1278              :     /// is not compatible with the current intent state. The later may happen when the background
    1279              :     /// reconcile loops runs concurrently with HTTP driven optimisations.
    1280           17 :     pub(crate) fn apply_optimization(
    1281           17 :         &mut self,
    1282           17 :         scheduler: &mut Scheduler,
    1283           17 :         optimization: ScheduleOptimization,
    1284           17 :     ) -> bool {
    1285           17 :         if optimization.sequence != self.sequence {
    1286            0 :             return false;
    1287           17 :         }
    1288              : 
    1289           17 :         if !self.validate_optimization(&optimization) {
    1290            0 :             tracing::info!(
    1291            0 :                 "Skipping optimization for {} because it does not match current intent: {:?}",
    1292              :                 self.tenant_shard_id,
    1293              :                 optimization,
    1294              :             );
    1295            0 :             return false;
    1296           17 :         }
    1297              : 
    1298           17 :         metrics::METRICS_REGISTRY
    1299           17 :             .metrics_group
    1300           17 :             .storage_controller_schedule_optimization
    1301           17 :             .inc();
    1302              : 
    1303           17 :         match optimization.action {
    1304              :             ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    1305            5 :                 old_attached_node_id,
    1306            5 :                 new_attached_node_id,
    1307              :             }) => {
    1308            5 :                 self.intent.demote_attached(scheduler, old_attached_node_id);
    1309            5 :                 self.intent
    1310            5 :                     .promote_attached(scheduler, new_attached_node_id);
    1311              : 
    1312            5 :                 if let Some(hint) = self.preferred_node.as_ref() {
    1313            1 :                     if hint == &new_attached_node_id {
    1314              :                         // The migration target is not a long term pin: once we are done with the migration, clear it.
    1315            1 :                         tracing::info!("Graceful migration to {hint} complete");
    1316            1 :                         self.preferred_node = None;
    1317            0 :                     }
    1318            4 :                 }
    1319              :             }
    1320              :             ScheduleOptimizationAction::ReplaceSecondary(ReplaceSecondary {
    1321            1 :                 old_node_id,
    1322            1 :                 new_node_id,
    1323            1 :             }) => {
    1324            1 :                 self.intent.remove_secondary(scheduler, old_node_id);
    1325            1 :                 self.intent.push_secondary(scheduler, new_node_id);
    1326            1 :             }
    1327            4 :             ScheduleOptimizationAction::CreateSecondary(new_node_id) => {
    1328            4 :                 self.intent.push_secondary(scheduler, new_node_id);
    1329            4 :             }
    1330            7 :             ScheduleOptimizationAction::RemoveSecondary(old_secondary) => {
    1331            7 :                 self.intent.remove_secondary(scheduler, old_secondary);
    1332            7 :             }
    1333              :         }
    1334              : 
    1335           17 :         true
    1336           17 :     }
    1337              : 
    1338              :     /// Check that the desired modifications to the intent state are compatible with
    1339              :     /// the current intent state
    1340           17 :     fn validate_optimization(&self, optimization: &ScheduleOptimization) -> bool {
    1341           17 :         match optimization.action {
    1342              :             ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    1343            5 :                 old_attached_node_id,
    1344            5 :                 new_attached_node_id,
    1345              :             }) => {
    1346            5 :                 self.intent.attached == Some(old_attached_node_id)
    1347            5 :                     && self.intent.secondary.contains(&new_attached_node_id)
    1348              :             }
    1349              :             ScheduleOptimizationAction::ReplaceSecondary(ReplaceSecondary {
    1350              :                 old_node_id: _,
    1351            1 :                 new_node_id,
    1352              :             }) => {
    1353              :                 // It's legal to remove a secondary that is not present in the intent state
    1354            1 :                 !self.intent.secondary.contains(&new_node_id)
    1355              :             }
    1356            4 :             ScheduleOptimizationAction::CreateSecondary(new_node_id) => {
    1357            4 :                 !self.intent.secondary.contains(&new_node_id)
    1358              :             }
    1359              :             ScheduleOptimizationAction::RemoveSecondary(_) => {
    1360              :                 // It's legal to remove a secondary that is not present in the intent state
    1361            7 :                 true
    1362              :             }
    1363              :         }
    1364           17 :     }
    1365              : 
    1366              :     /// When a shard has several secondary locations, we need to pick one in situations where
    1367              :     /// we promote one of them to an attached location:
    1368              :     ///  - When draining a node for restart
    1369              :     ///  - When responding to a node failure
    1370              :     ///
    1371              :     /// In this context, 'preferred' does not mean the node with the best scheduling score: instead
    1372              :     /// we want to pick the node which is best for use _temporarily_ while the previous attached location
    1373              :     /// is unavailable (e.g. because it's down or deploying).  That means we prefer to use secondary
    1374              :     /// locations in a non-preferred AZ, as they're more likely to have awarm cache than a temporary
    1375              :     /// secondary in the preferred AZ (which are usually only created for migrations, and if they exist
    1376              :     /// they're probably not warmed up yet). The latter behavior is based oni
    1377              :     ///
    1378              :     /// If the input is empty, or all the nodes are not elegible for scheduling, return None: the
    1379              :     /// caller needs to a pick a node some other way.
    1380        12832 :     pub(crate) fn preferred_secondary(&self, scheduler: &Scheduler) -> Option<NodeId> {
    1381        12832 :         let candidates = scheduler.filter_usable_nodes(&self.intent.secondary);
    1382              : 
    1383              :         // We will sort candidates to prefer nodes which are _not_ in our preferred AZ, i.e. we prefer
    1384              :         // to migrate to a long-lived secondary location (which would have been scheduled in a non-preferred AZ),
    1385              :         // rather than a short-lived secondary location being used for optimization/migration (which would have
    1386              :         // been scheduled in our preferred AZ).
    1387        12832 :         let mut candidates = candidates
    1388        12832 :             .iter()
    1389        12832 :             .map(|(node_id, node_az)| {
    1390            2 :                 if node_az == &self.intent.preferred_az_id {
    1391            1 :                     (1, *node_id)
    1392              :                 } else {
    1393            1 :                     (0, *node_id)
    1394              :                 }
    1395            2 :             })
    1396        12832 :             .collect::<Vec<_>>();
    1397              : 
    1398        12832 :         candidates.sort();
    1399              : 
    1400        12832 :         candidates.first().map(|i| i.1)
    1401        12832 :     }
    1402              : 
    1403              :     /// Query whether the tenant's observed state for attached node matches its intent state, and if so,
    1404              :     /// yield the node ID.  This is appropriate for emitting compute hook notifications: we are checking that
    1405              :     /// the node in question is not only where we intend to attach, but that the tenant is indeed already attached there.
    1406              :     ///
    1407              :     /// Reconciliation may still be needed for other aspects of state such as secondaries (see [`Self::dirty`]): this
    1408              :     /// funciton should not be used to decide whether to reconcile.
    1409            0 :     pub(crate) fn stably_attached(&self) -> Option<NodeId> {
    1410              :         // We have an intent to attach for this node
    1411            0 :         let attach_intent = self.intent.attached?;
    1412              :         // We have an observed state for this node
    1413            0 :         let location = self.observed.locations.get(&attach_intent)?;
    1414              :         // Our observed state is not None, i.e. not in flux
    1415            0 :         let location_config = location.conf.as_ref()?;
    1416              : 
    1417              :         // Check if our intent and observed state agree that this node is in an attached state.
    1418            0 :         match location_config.mode {
    1419              :             LocationConfigMode::AttachedMulti
    1420              :             | LocationConfigMode::AttachedSingle
    1421            0 :             | LocationConfigMode::AttachedStale => Some(attach_intent),
    1422            0 :             _ => None,
    1423              :         }
    1424            0 :     }
    1425              : 
    1426            0 :     fn dirty(&self, nodes: &Arc<HashMap<NodeId, Node>>) -> bool {
    1427            0 :         let mut dirty_nodes = HashSet::new();
    1428              : 
    1429            0 :         if let Some(node_id) = self.intent.attached {
    1430              :             // Maybe panic: it is a severe bug if we try to attach while generation is null.
    1431            0 :             let generation = self
    1432            0 :                 .generation
    1433            0 :                 .expect("Attempted to enter attached state without a generation");
    1434              : 
    1435            0 :             let wanted_conf = attached_location_conf(
    1436            0 :                 generation,
    1437            0 :                 &self.shard,
    1438            0 :                 &self.config,
    1439            0 :                 &self.policy,
    1440            0 :                 self.intent.get_secondary().len(),
    1441              :             );
    1442            0 :             match self.observed.locations.get(&node_id) {
    1443            0 :                 Some(conf) if conf.conf.as_ref() == Some(&wanted_conf) => {}
    1444            0 :                 Some(_) | None => {
    1445            0 :                     dirty_nodes.insert(node_id);
    1446            0 :                 }
    1447              :             }
    1448            0 :         }
    1449              : 
    1450            0 :         for node_id in &self.intent.secondary {
    1451            0 :             let wanted_conf = secondary_location_conf(&self.shard, &self.config);
    1452            0 :             match self.observed.locations.get(node_id) {
    1453            0 :                 Some(conf) if conf.conf.as_ref() == Some(&wanted_conf) => {}
    1454            0 :                 Some(_) | None => {
    1455            0 :                     dirty_nodes.insert(*node_id);
    1456            0 :                 }
    1457              :             }
    1458              :         }
    1459              : 
    1460            0 :         for node_id in self.observed.locations.keys() {
    1461            0 :             if self.intent.attached != Some(*node_id) && !self.intent.secondary.contains(node_id) {
    1462            0 :                 // We have observed state that isn't part of our intent: need to clean it up.
    1463            0 :                 dirty_nodes.insert(*node_id);
    1464            0 :             }
    1465              :         }
    1466              : 
    1467            0 :         dirty_nodes.retain(|node_id| {
    1468            0 :             nodes
    1469            0 :                 .get(node_id)
    1470            0 :                 .map(|n| n.is_available())
    1471            0 :                 .unwrap_or(false)
    1472            0 :         });
    1473              : 
    1474            0 :         !dirty_nodes.is_empty()
    1475            0 :     }
    1476              : 
    1477              :     #[allow(clippy::too_many_arguments)]
    1478              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    1479              :     pub(crate) fn get_reconcile_needed(
    1480              :         &mut self,
    1481              :         pageservers: &Arc<HashMap<NodeId, Node>>,
    1482              :     ) -> ReconcileNeeded {
    1483              :         // If there are any ambiguous observed states, and the nodes they refer to are available,
    1484              :         // we should reconcile to clean them up.
    1485              :         let mut dirty_observed = false;
    1486              :         for (node_id, observed_loc) in &self.observed.locations {
    1487              :             let node = pageservers
    1488              :                 .get(node_id)
    1489              :                 .expect("Nodes may not be removed while referenced");
    1490              :             if observed_loc.conf.is_none() && node.is_available() {
    1491              :                 dirty_observed = true;
    1492              :                 break;
    1493              :             }
    1494              :         }
    1495              : 
    1496              :         let active_nodes_dirty = self.dirty(pageservers);
    1497              : 
    1498              :         let reconcile_needed = match (
    1499              :             active_nodes_dirty,
    1500              :             dirty_observed,
    1501              :             self.pending_compute_notification,
    1502              :         ) {
    1503              :             (true, _, _) => ReconcileNeeded::Yes(ReconcileReason::ActiveNodesDirty),
    1504              :             (_, true, _) => ReconcileNeeded::Yes(ReconcileReason::UnknownLocation),
    1505              :             (_, _, true) => ReconcileNeeded::Yes(ReconcileReason::PendingComputeNotification),
    1506              :             _ => ReconcileNeeded::No,
    1507              :         };
    1508              : 
    1509              :         if matches!(reconcile_needed, ReconcileNeeded::No) {
    1510              :             tracing::debug!("Not dirty, no reconciliation needed.");
    1511              :             return ReconcileNeeded::No;
    1512              :         }
    1513              : 
    1514              :         // If we are currently splitting, then never start a reconciler task: the splitting logic
    1515              :         // requires that shards are not interfered with while it runs. Do this check here rather than
    1516              :         // up top, so that we only log this message if we would otherwise have done a reconciliation.
    1517              :         if !matches!(self.splitting, SplitState::Idle) {
    1518              :             tracing::info!("Refusing to reconcile, splitting in progress");
    1519              :             return ReconcileNeeded::No;
    1520              :         }
    1521              : 
    1522              :         // Reconcile already in flight for the current sequence?
    1523              :         if let Some(handle) = &self.reconciler {
    1524              :             if handle.sequence == self.sequence {
    1525              :                 tracing::info!(
    1526              :                     "Reconciliation already in progress for sequence {:?}",
    1527              :                     self.sequence,
    1528              :                 );
    1529              :                 return ReconcileNeeded::WaitExisting(ReconcilerWaiter {
    1530              :                     tenant_shard_id: self.tenant_shard_id,
    1531              :                     seq_wait: self.waiter.clone(),
    1532              :                     error_seq_wait: self.error_waiter.clone(),
    1533              :                     error: self.last_error.clone(),
    1534              :                     seq: self.sequence,
    1535              :                 });
    1536              :             }
    1537              :         }
    1538              : 
    1539              :         // Pre-checks done: finally check whether we may actually do the work
    1540              :         match self.scheduling_policy {
    1541              :             ShardSchedulingPolicy::Active
    1542              :             | ShardSchedulingPolicy::Essential
    1543              :             | ShardSchedulingPolicy::Pause => {}
    1544              :             ShardSchedulingPolicy::Stop => {
    1545              :                 // We only reach this point if there is work to do and we're going to skip
    1546              :                 // doing it: warn it obvious why this tenant isn't doing what it ought to.
    1547              :                 tracing::warn!("Skipping reconcile for policy {:?}", self.scheduling_policy);
    1548              :                 return ReconcileNeeded::No;
    1549              :             }
    1550              :         }
    1551              : 
    1552              :         reconcile_needed
    1553              :     }
    1554              : 
    1555              :     /// Ensure the sequence number is set to a value where waiting for this value will make us wait
    1556              :     /// for the next reconcile: i.e. it is ahead of all completed or running reconcilers.
    1557              :     ///
    1558              :     /// Constructing a ReconcilerWaiter with the resulting sequence number gives the property
    1559              :     /// that the waiter will not complete until some future Reconciler is constructed and run.
    1560            0 :     fn ensure_sequence_ahead(&mut self) {
    1561              :         // Find the highest sequence for which a Reconciler has previously run or is currently
    1562              :         // running
    1563            0 :         let max_seen = std::cmp::max(
    1564            0 :             self.reconciler
    1565            0 :                 .as_ref()
    1566            0 :                 .map(|r| r.sequence)
    1567            0 :                 .unwrap_or(Sequence(0)),
    1568            0 :             std::cmp::max(self.waiter.load(), self.error_waiter.load()),
    1569              :         );
    1570              : 
    1571            0 :         if self.sequence <= max_seen {
    1572            0 :             self.sequence = max_seen.next();
    1573            0 :         }
    1574            0 :     }
    1575              : 
    1576              :     /// Create a waiter that will wait for some future Reconciler that hasn't been spawned yet.
    1577              :     ///
    1578              :     /// This is appropriate when you can't spawn a reconciler (e.g. due to resource limits), but
    1579              :     /// you would like to wait on the next reconciler that gets spawned in the background.
    1580            0 :     pub(crate) fn future_reconcile_waiter(&mut self) -> ReconcilerWaiter {
    1581            0 :         self.ensure_sequence_ahead();
    1582              : 
    1583            0 :         ReconcilerWaiter {
    1584            0 :             tenant_shard_id: self.tenant_shard_id,
    1585            0 :             seq_wait: self.waiter.clone(),
    1586            0 :             error_seq_wait: self.error_waiter.clone(),
    1587            0 :             error: self.last_error.clone(),
    1588            0 :             seq: self.sequence,
    1589            0 :         }
    1590            0 :     }
    1591              : 
    1592            0 :     async fn reconcile(
    1593            0 :         sequence: Sequence,
    1594            0 :         mut reconciler: Reconciler,
    1595            0 :         must_notify: bool,
    1596            0 :     ) -> ReconcileResult {
    1597              :         // Attempt to make observed state match intent state
    1598            0 :         let result = reconciler.reconcile().await;
    1599              : 
    1600              :         // If we know we had a pending compute notification from some previous action, send a notification irrespective
    1601              :         // of whether the above reconcile() did any work.  It has to be Ok() though, because otherwise we might be
    1602              :         // sending a notification of a location that isn't really attached.
    1603            0 :         if result.is_ok() && must_notify {
    1604              :             // If this fails we will send the need to retry in [`ReconcileResult::pending_compute_notification`]
    1605            0 :             reconciler.compute_notify().await.ok();
    1606            0 :         } else if must_notify {
    1607            0 :             // Carry this flag so that the reconciler's result will indicate that it still needs to retry
    1608            0 :             // the compute hook notification eventually.
    1609            0 :             reconciler.compute_notify_failure = true;
    1610            0 :         }
    1611              : 
    1612              :         // Update result counter
    1613            0 :         let outcome_label = match &result {
    1614              :             Ok(_) => {
    1615            0 :                 if reconciler.compute_notify_failure {
    1616            0 :                     ReconcileOutcome::SuccessNoNotify
    1617              :                 } else {
    1618            0 :                     ReconcileOutcome::Success
    1619              :                 }
    1620              :             }
    1621            0 :             Err(ReconcileError::Cancel) => ReconcileOutcome::Cancel,
    1622            0 :             Err(_) => ReconcileOutcome::Error,
    1623              :         };
    1624              : 
    1625            0 :         metrics::METRICS_REGISTRY
    1626            0 :             .metrics_group
    1627            0 :             .storage_controller_reconcile_complete
    1628            0 :             .inc(ReconcileCompleteLabelGroup {
    1629            0 :                 status: outcome_label,
    1630            0 :             });
    1631              : 
    1632              :         // Constructing result implicitly drops Reconciler, freeing any ReconcileUnits before the Service might
    1633              :         // try and schedule more work in response to our result.
    1634            0 :         ReconcileResult {
    1635            0 :             sequence,
    1636            0 :             result,
    1637            0 :             tenant_shard_id: reconciler.tenant_shard_id,
    1638            0 :             generation: reconciler.generation,
    1639            0 :             observed_deltas: reconciler.observed_deltas(),
    1640            0 :             pending_compute_notification: reconciler.compute_notify_failure,
    1641            0 :         }
    1642            0 :     }
    1643              : 
    1644              :     #[allow(clippy::too_many_arguments)]
    1645              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    1646              :     pub(crate) fn spawn_reconciler(
    1647              :         &mut self,
    1648              :         reason: ReconcileReason,
    1649              :         result_tx: &tokio::sync::mpsc::UnboundedSender<ReconcileResultRequest>,
    1650              :         pageservers: &Arc<HashMap<NodeId, Node>>,
    1651              :         compute_hook: &Arc<ComputeHook>,
    1652              :         reconciler_config: ReconcilerConfig,
    1653              :         service_config: &service::Config,
    1654              :         persistence: &Arc<Persistence>,
    1655              :         units: ReconcileUnits,
    1656              :         gate_guard: GateGuard,
    1657              :         cancel: &CancellationToken,
    1658              :         http_client: reqwest::Client,
    1659              :     ) -> Option<ReconcilerWaiter> {
    1660              :         // Reconcile in flight for a stale sequence?  Our sequence's task will wait for it before
    1661              :         // doing our sequence's work.
    1662              :         let old_handle = self.reconciler.take();
    1663              : 
    1664              :         // Build list of nodes from which the reconciler should detach
    1665              :         let mut detach = Vec::new();
    1666              :         for node_id in self.observed.locations.keys() {
    1667              :             if self.intent.get_attached() != &Some(*node_id)
    1668              :                 && !self.intent.secondary.contains(node_id)
    1669              :             {
    1670              :                 detach.push(
    1671              :                     pageservers
    1672              :                         .get(node_id)
    1673              :                         .expect("Intent references non-existent pageserver")
    1674              :                         .clone(),
    1675              :                 )
    1676              :             }
    1677              :         }
    1678              : 
    1679              :         // Advance the sequence before spawning a reconciler, so that sequence waiters
    1680              :         // can distinguish between before+after the reconcile completes.
    1681              :         self.ensure_sequence_ahead();
    1682              : 
    1683              :         let reconciler_cancel = cancel.child_token();
    1684              :         let reconciler_intent = TargetState::from_intent(pageservers, &self.intent);
    1685              :         let reconciler = Reconciler {
    1686              :             tenant_shard_id: self.tenant_shard_id,
    1687              :             shard: self.shard,
    1688              :             placement_policy: self.policy.clone(),
    1689              :             generation: self.generation,
    1690              :             intent: reconciler_intent,
    1691              :             detach,
    1692              :             reconciler_config,
    1693              :             config: self.config.clone(),
    1694              :             preferred_az: self.intent.preferred_az_id.clone(),
    1695              :             observed: self.observed.clone(),
    1696              :             original_observed: self.observed.clone(),
    1697              :             compute_hook: compute_hook.clone(),
    1698              :             service_config: service_config.clone(),
    1699              :             _gate_guard: gate_guard,
    1700              :             _resource_units: units,
    1701              :             cancel: reconciler_cancel.clone(),
    1702              :             persistence: persistence.clone(),
    1703              :             compute_notify_failure: false,
    1704              :             http_client,
    1705              :         };
    1706              : 
    1707              :         let reconcile_seq = self.sequence;
    1708              :         let long_reconcile_threshold = service_config.long_reconcile_threshold;
    1709              : 
    1710              :         tracing::info!(seq=%reconcile_seq, "Spawning Reconciler ({reason:?})");
    1711              :         let must_notify = self.pending_compute_notification;
    1712              :         let reconciler_span = tracing::info_span!(parent: None, "reconciler", seq=%reconcile_seq,
    1713              :                                                         tenant_id=%reconciler.tenant_shard_id.tenant_id,
    1714              :                                                         shard_id=%reconciler.tenant_shard_id.shard_slug());
    1715              :         metrics::METRICS_REGISTRY
    1716              :             .metrics_group
    1717              :             .storage_controller_reconcile_spawn
    1718              :             .inc();
    1719              :         let result_tx = result_tx.clone();
    1720              :         let join_handle = tokio::task::spawn(
    1721            0 :             async move {
    1722              :                 // Wait for any previous reconcile task to complete before we start
    1723            0 :                 if let Some(old_handle) = old_handle {
    1724            0 :                     old_handle.cancel.cancel();
    1725            0 :                     if let Err(e) = old_handle.handle.await {
    1726              :                         // We can't do much with this other than log it: the task is done, so
    1727              :                         // we may proceed with our work.
    1728            0 :                         tracing::error!("Unexpected join error waiting for reconcile task: {e}");
    1729            0 :                     }
    1730            0 :                 }
    1731              : 
    1732              :                 // Early check for cancellation before doing any work
    1733              :                 // TODO: wrap all remote API operations in cancellation check
    1734              :                 // as well.
    1735            0 :                 if reconciler.cancel.is_cancelled() {
    1736            0 :                     metrics::METRICS_REGISTRY
    1737            0 :                         .metrics_group
    1738            0 :                         .storage_controller_reconcile_complete
    1739            0 :                         .inc(ReconcileCompleteLabelGroup {
    1740            0 :                             status: ReconcileOutcome::Cancel,
    1741            0 :                         });
    1742            0 :                     return;
    1743            0 :                 }
    1744              : 
    1745            0 :                 let (tenant_id_label, shard_number_label, sequence_label) = {
    1746            0 :                     (
    1747            0 :                         reconciler.tenant_shard_id.tenant_id.to_string(),
    1748            0 :                         reconciler.tenant_shard_id.shard_number.0.to_string(),
    1749            0 :                         reconcile_seq.to_string(),
    1750            0 :                     )
    1751            0 :                 };
    1752              : 
    1753            0 :                 let label_group = ReconcileLongRunningLabelGroup {
    1754            0 :                     tenant_id: &tenant_id_label,
    1755            0 :                     shard_number: &shard_number_label,
    1756            0 :                     sequence: &sequence_label,
    1757            0 :                 };
    1758              : 
    1759            0 :                 let reconcile_fut = Self::reconcile(reconcile_seq, reconciler, must_notify);
    1760            0 :                 let long_reconcile_fut = {
    1761            0 :                     let label_group = label_group.clone();
    1762            0 :                     async move {
    1763            0 :                         tokio::time::sleep(long_reconcile_threshold).await;
    1764              : 
    1765            0 :                         tracing::warn!("Reconcile passed the long running threshold of {long_reconcile_threshold:?}");
    1766              : 
    1767            0 :                         metrics::METRICS_REGISTRY
    1768            0 :                             .metrics_group
    1769            0 :                             .storage_controller_reconcile_long_running
    1770            0 :                             .inc(label_group);
    1771            0 :                     }
    1772              :                 };
    1773              : 
    1774            0 :                 let reconcile_fut = std::pin::pin!(reconcile_fut);
    1775            0 :                 let long_reconcile_fut = std::pin::pin!(long_reconcile_fut);
    1776              : 
    1777            0 :                 let (was_long, result) =
    1778            0 :                     match future::select(reconcile_fut, long_reconcile_fut).await {
    1779            0 :                         Either::Left((reconcile_result, _)) => (false, reconcile_result),
    1780            0 :                         Either::Right((_, reconcile_fut)) => (true, reconcile_fut.await),
    1781              :                     };
    1782              : 
    1783            0 :                 if was_long {
    1784            0 :                     let id = metrics::METRICS_REGISTRY
    1785            0 :                         .metrics_group
    1786            0 :                         .storage_controller_reconcile_long_running
    1787            0 :                         .with_labels(label_group);
    1788            0 :                     metrics::METRICS_REGISTRY
    1789            0 :                         .metrics_group
    1790            0 :                         .storage_controller_reconcile_long_running
    1791            0 :                         .remove_metric(id);
    1792            0 :                 }
    1793              : 
    1794            0 :                 result_tx
    1795            0 :                     .send(ReconcileResultRequest::ReconcileResult(result))
    1796            0 :                     .ok();
    1797            0 :             }
    1798              :             .instrument(reconciler_span),
    1799              :         );
    1800              : 
    1801              :         self.reconciler = Some(ReconcilerHandle {
    1802              :             sequence: self.sequence,
    1803              :             handle: join_handle,
    1804              :             cancel: reconciler_cancel,
    1805              :         });
    1806              : 
    1807              :         Some(ReconcilerWaiter {
    1808              :             tenant_shard_id: self.tenant_shard_id,
    1809              :             seq_wait: self.waiter.clone(),
    1810              :             error_seq_wait: self.error_waiter.clone(),
    1811              :             error: self.last_error.clone(),
    1812              :             seq: self.sequence,
    1813              :         })
    1814              :     }
    1815              : 
    1816            0 :     pub(crate) fn cancel_reconciler(&self) {
    1817            0 :         if let Some(handle) = self.reconciler.as_ref() {
    1818            0 :             handle.cancel.cancel()
    1819            0 :         }
    1820            0 :     }
    1821              : 
    1822              :     /// Get a waiter for any reconciliation in flight, but do not start reconciliation
    1823              :     /// if it is not already running
    1824            0 :     pub(crate) fn get_waiter(&self) -> Option<ReconcilerWaiter> {
    1825            0 :         if self.reconciler.is_some() {
    1826            0 :             Some(ReconcilerWaiter {
    1827            0 :                 tenant_shard_id: self.tenant_shard_id,
    1828            0 :                 seq_wait: self.waiter.clone(),
    1829            0 :                 error_seq_wait: self.error_waiter.clone(),
    1830            0 :                 error: self.last_error.clone(),
    1831            0 :                 seq: self.sequence,
    1832            0 :             })
    1833              :         } else {
    1834            0 :             None
    1835              :         }
    1836            0 :     }
    1837              : 
    1838              :     /// Called when a ReconcileResult has been emitted and the service is updating
    1839              :     /// our state: if the result is from a sequence >= my ReconcileHandle, then drop
    1840              :     /// the handle to indicate there is no longer a reconciliation in progress.
    1841            0 :     pub(crate) fn reconcile_complete(&mut self, sequence: Sequence) {
    1842            0 :         if let Some(reconcile_handle) = &self.reconciler {
    1843            0 :             if reconcile_handle.sequence <= sequence {
    1844            0 :                 self.reconciler = None;
    1845            0 :             }
    1846            0 :         }
    1847            0 :     }
    1848              : 
    1849              :     /// If we had any state at all referring to this node ID, drop it.  Does not
    1850              :     /// attempt to reschedule.
    1851              :     ///
    1852              :     /// Returns true if we modified the node's intent state.
    1853            0 :     pub(crate) fn deref_node(&mut self, node_id: NodeId) -> bool {
    1854            0 :         let mut intent_modified = false;
    1855              : 
    1856              :         // Drop if this node was our attached intent
    1857            0 :         if self.intent.attached == Some(node_id) {
    1858            0 :             self.intent.attached = None;
    1859            0 :             intent_modified = true;
    1860            0 :         }
    1861              : 
    1862              :         // Drop from the list of secondaries, and check if we modified it
    1863            0 :         let had_secondaries = self.intent.secondary.len();
    1864            0 :         self.intent.secondary.retain(|n| n != &node_id);
    1865            0 :         intent_modified |= self.intent.secondary.len() != had_secondaries;
    1866              : 
    1867            0 :         debug_assert!(!self.intent.all_pageservers().contains(&node_id));
    1868              : 
    1869            0 :         if self.preferred_node == Some(node_id) {
    1870            0 :             self.preferred_node = None;
    1871            0 :         }
    1872              : 
    1873            0 :         intent_modified
    1874            0 :     }
    1875              : 
    1876            0 :     pub(crate) fn set_scheduling_policy(&mut self, p: ShardSchedulingPolicy) {
    1877            0 :         self.scheduling_policy = p;
    1878            0 :     }
    1879              : 
    1880            0 :     pub(crate) fn get_scheduling_policy(&self) -> ShardSchedulingPolicy {
    1881            0 :         self.scheduling_policy
    1882            0 :     }
    1883              : 
    1884            0 :     pub(crate) fn set_last_error(&mut self, sequence: Sequence, error: ReconcileError) {
    1885              :         // Ordering: always set last_error before advancing sequence, so that sequence
    1886              :         // waiters are guaranteed to see a Some value when they see an error.
    1887            0 :         *(self.last_error.lock().unwrap()) = Some(Arc::new(error));
    1888            0 :         self.error_waiter.advance(sequence);
    1889            0 :     }
    1890              : 
    1891            0 :     pub(crate) fn from_persistent(
    1892            0 :         tsp: TenantShardPersistence,
    1893            0 :         intent: IntentState,
    1894            0 :     ) -> anyhow::Result<Self> {
    1895            0 :         let tenant_shard_id = tsp.get_tenant_shard_id()?;
    1896            0 :         let shard_identity = tsp.get_shard_identity()?;
    1897              : 
    1898            0 :         metrics::METRICS_REGISTRY
    1899            0 :             .metrics_group
    1900            0 :             .storage_controller_tenant_shards
    1901            0 :             .inc();
    1902              : 
    1903              :         Ok(Self {
    1904            0 :             tenant_shard_id,
    1905            0 :             shard: shard_identity,
    1906            0 :             sequence: Sequence::initial(),
    1907            0 :             generation: tsp.generation.map(|g| Generation::new(g as u32)),
    1908            0 :             policy: serde_json::from_str(&tsp.placement_policy).unwrap(),
    1909            0 :             intent,
    1910            0 :             observed: ObservedState::new(),
    1911            0 :             config: serde_json::from_str(&tsp.config).unwrap(),
    1912            0 :             reconciler: None,
    1913            0 :             splitting: tsp.splitting,
    1914              :             // Filled in during [`Service::startup_reconcile`]
    1915            0 :             importing: TimelineImportState::Idle,
    1916            0 :             waiter: Arc::new(SeqWait::new(Sequence::initial())),
    1917            0 :             error_waiter: Arc::new(SeqWait::new(Sequence::initial())),
    1918            0 :             last_error: Arc::default(),
    1919              :             consecutive_reconciles_count: 0,
    1920              :             pending_compute_notification: false,
    1921              :             delayed_reconcile: false,
    1922            0 :             scheduling_policy: serde_json::from_str(&tsp.scheduling_policy).unwrap(),
    1923            0 :             preferred_node: None,
    1924              :         })
    1925            0 :     }
    1926              : 
    1927            0 :     pub(crate) fn to_persistent(&self) -> TenantShardPersistence {
    1928              :         TenantShardPersistence {
    1929            0 :             tenant_id: self.tenant_shard_id.tenant_id.to_string(),
    1930            0 :             shard_number: self.tenant_shard_id.shard_number.0 as i32,
    1931            0 :             shard_count: self.tenant_shard_id.shard_count.literal() as i32,
    1932            0 :             shard_stripe_size: self.shard.stripe_size.0 as i32,
    1933            0 :             generation: self.generation.map(|g| g.into().unwrap_or(0) as i32),
    1934            0 :             generation_pageserver: self.intent.get_attached().map(|n| n.0 as i64),
    1935            0 :             placement_policy: serde_json::to_string(&self.policy).unwrap(),
    1936            0 :             config: serde_json::to_string(&self.config).unwrap(),
    1937            0 :             splitting: SplitState::default(),
    1938            0 :             scheduling_policy: serde_json::to_string(&self.scheduling_policy).unwrap(),
    1939            0 :             preferred_az_id: self.intent.preferred_az_id.as_ref().map(|az| az.0.clone()),
    1940              :         }
    1941            0 :     }
    1942              : 
    1943        12508 :     pub(crate) fn preferred_az(&self) -> Option<&AvailabilityZone> {
    1944        12508 :         self.intent.get_preferred_az()
    1945        12508 :     }
    1946              : 
    1947            2 :     pub(crate) fn set_preferred_az(
    1948            2 :         &mut self,
    1949            2 :         scheduler: &mut Scheduler,
    1950            2 :         preferred_az_id: Option<AvailabilityZone>,
    1951            2 :     ) {
    1952            2 :         self.intent.set_preferred_az(scheduler, preferred_az_id);
    1953            2 :     }
    1954              : 
    1955              :     /// Returns all the nodes to which this tenant shard is attached according to the
    1956              :     /// observed state and the generations. Return vector is sorted from latest generation
    1957              :     /// to earliest.
    1958            0 :     pub(crate) fn attached_locations(&self) -> Vec<(NodeId, Generation)> {
    1959            0 :         self.observed
    1960            0 :             .locations
    1961            0 :             .iter()
    1962            0 :             .filter_map(|(node_id, observed)| {
    1963              :                 use LocationConfigMode::{AttachedMulti, AttachedSingle, AttachedStale};
    1964              : 
    1965            0 :                 let conf = observed.conf.as_ref()?;
    1966              : 
    1967            0 :                 match (conf.generation, conf.mode) {
    1968            0 :                     (Some(gen_), AttachedMulti | AttachedSingle | AttachedStale) => {
    1969            0 :                         Some((*node_id, gen_))
    1970              :                     }
    1971            0 :                     _ => None,
    1972              :                 }
    1973            0 :             })
    1974            0 :             .sorted_by(|(_lhs_node_id, lhs_gen), (_rhs_node_id, rhs_gen)| {
    1975            0 :                 lhs_gen.cmp(rhs_gen).reverse()
    1976            0 :             })
    1977            0 :             .map(|(node_id, gen_)| (node_id, Generation::new(gen_)))
    1978            0 :             .collect()
    1979            0 :     }
    1980              : 
    1981              :     /// Update the observed state of the tenant by applying incremental deltas
    1982              :     ///
    1983              :     /// Deltas are generated by reconcilers via [`Reconciler::observed_deltas`].
    1984              :     /// They are then filtered in [`crate::service::Service::process_result`].
    1985            0 :     pub(crate) fn apply_observed_deltas(
    1986            0 :         &mut self,
    1987            0 :         deltas: impl Iterator<Item = ObservedStateDelta>,
    1988            0 :     ) {
    1989            0 :         for delta in deltas {
    1990            0 :             match delta {
    1991            0 :                 ObservedStateDelta::Upsert(ups) => {
    1992            0 :                     let (node_id, loc) = *ups;
    1993              : 
    1994              :                     // If the generation of the observed location in the delta is lagging
    1995              :                     // behind the current one, then we have a race condition and cannot
    1996              :                     // be certain about the true observed state. Set the observed state
    1997              :                     // to None in order to reflect this.
    1998            0 :                     let crnt_gen = self
    1999            0 :                         .observed
    2000            0 :                         .locations
    2001            0 :                         .get(&node_id)
    2002            0 :                         .and_then(|loc| loc.conf.as_ref())
    2003            0 :                         .and_then(|conf| conf.generation);
    2004            0 :                     let new_gen = loc.conf.as_ref().and_then(|conf| conf.generation);
    2005            0 :                     match (crnt_gen, new_gen) {
    2006            0 :                         (Some(crnt), Some(new)) if crnt_gen > new_gen => {
    2007            0 :                             tracing::warn!(
    2008            0 :                                 "Skipping observed state update {}: {:?} and using None due to stale generation ({} > {})",
    2009              :                                 node_id,
    2010              :                                 loc,
    2011              :                                 crnt,
    2012              :                                 new
    2013              :                             );
    2014              : 
    2015            0 :                             self.observed
    2016            0 :                                 .locations
    2017            0 :                                 .insert(node_id, ObservedStateLocation { conf: None });
    2018              : 
    2019            0 :                             continue;
    2020              :                         }
    2021            0 :                         _ => {}
    2022              :                     }
    2023              : 
    2024            0 :                     if let Some(conf) = &loc.conf {
    2025            0 :                         tracing::info!("Updating observed location {}: {:?}", node_id, conf);
    2026              :                     } else {
    2027            0 :                         tracing::info!("Setting observed location {} to None", node_id,)
    2028              :                     }
    2029              : 
    2030            0 :                     self.observed.locations.insert(node_id, loc);
    2031              :                 }
    2032            0 :                 ObservedStateDelta::Delete(node_id) => {
    2033            0 :                     tracing::info!("Deleting observed location {}", node_id);
    2034            0 :                     self.observed.locations.remove(&node_id);
    2035              :                 }
    2036              :             }
    2037              :         }
    2038            0 :     }
    2039              : 
    2040              :     /// Returns true if the tenant shard is attached to a node that is outside the preferred AZ.
    2041              :     ///
    2042              :     /// If the shard does not have a preferred AZ, returns false.
    2043            0 :     pub(crate) fn is_attached_outside_preferred_az(&self, nodes: &HashMap<NodeId, Node>) -> bool {
    2044            0 :         self.intent
    2045            0 :             .get_attached()
    2046            0 :             .map(|node_id| {
    2047            0 :                 Some(
    2048            0 :                     nodes
    2049            0 :                         .get(&node_id)
    2050            0 :                         .expect("referenced node exists")
    2051            0 :                         .get_availability_zone_id(),
    2052            0 :                 ) != self.intent.preferred_az_id.as_ref()
    2053            0 :             })
    2054            0 :             .unwrap_or(false)
    2055            0 :     }
    2056              : }
    2057              : 
    2058              : impl Drop for TenantShard {
    2059        12843 :     fn drop(&mut self) {
    2060        12843 :         metrics::METRICS_REGISTRY
    2061        12843 :             .metrics_group
    2062        12843 :             .storage_controller_tenant_shards
    2063        12843 :             .dec();
    2064        12843 :     }
    2065              : }
    2066              : 
    2067              : #[cfg(test)]
    2068              : pub(crate) mod tests {
    2069              :     use std::cell::RefCell;
    2070              :     use std::rc::Rc;
    2071              : 
    2072              :     use pageserver_api::controller_api::NodeAvailability;
    2073              :     use pageserver_api::shard::{DEFAULT_STRIPE_SIZE, ShardCount, ShardNumber};
    2074              :     use rand::SeedableRng;
    2075              :     use rand::rngs::StdRng;
    2076              :     use utils::id::TenantId;
    2077              : 
    2078              :     use super::*;
    2079              :     use crate::scheduler::test_utils::make_test_nodes;
    2080              : 
    2081           12 :     fn make_test_tenant_shard(policy: PlacementPolicy) -> TenantShard {
    2082           12 :         let tenant_id = TenantId::generate();
    2083           12 :         let shard_number = ShardNumber(0);
    2084           12 :         let shard_count = ShardCount::new(1);
    2085           12 :         let stripe_size = DEFAULT_STRIPE_SIZE;
    2086              : 
    2087           12 :         let tenant_shard_id = TenantShardId {
    2088           12 :             tenant_id,
    2089           12 :             shard_number,
    2090           12 :             shard_count,
    2091           12 :         };
    2092           12 :         TenantShard::new(
    2093           12 :             tenant_shard_id,
    2094           12 :             ShardIdentity::new(shard_number, shard_count, stripe_size).unwrap(),
    2095           12 :             policy,
    2096           12 :             None,
    2097              :         )
    2098           12 :     }
    2099              : 
    2100         5004 :     pub(crate) fn make_test_tenant(
    2101         5004 :         policy: PlacementPolicy,
    2102         5004 :         shard_count: ShardCount,
    2103         5004 :         preferred_az: Option<AvailabilityZone>,
    2104         5004 :     ) -> Vec<TenantShard> {
    2105         5004 :         make_test_tenant_with_id(TenantId::generate(), policy, shard_count, preferred_az)
    2106         5004 :     }
    2107              : 
    2108         5007 :     pub(crate) fn make_test_tenant_with_id(
    2109         5007 :         tenant_id: TenantId,
    2110         5007 :         policy: PlacementPolicy,
    2111         5007 :         shard_count: ShardCount,
    2112         5007 :         preferred_az: Option<AvailabilityZone>,
    2113         5007 :     ) -> Vec<TenantShard> {
    2114         5007 :         let stripe_size = DEFAULT_STRIPE_SIZE;
    2115         5007 :         (0..shard_count.count())
    2116        12522 :             .map(|i| {
    2117        12522 :                 let shard_number = ShardNumber(i);
    2118              : 
    2119        12522 :                 let tenant_shard_id = TenantShardId {
    2120        12522 :                     tenant_id,
    2121        12522 :                     shard_number,
    2122        12522 :                     shard_count,
    2123        12522 :                 };
    2124        12522 :                 TenantShard::new(
    2125        12522 :                     tenant_shard_id,
    2126        12522 :                     ShardIdentity::new(shard_number, shard_count, stripe_size).unwrap(),
    2127        12522 :                     policy.clone(),
    2128        12522 :                     preferred_az.clone(),
    2129              :                 )
    2130        12522 :             })
    2131         5007 :             .collect()
    2132         5007 :     }
    2133              : 
    2134              :     /// Test the scheduling behaviors used when a tenant configured for HA is subject
    2135              :     /// to nodes being marked offline.
    2136              :     #[test]
    2137            1 :     fn tenant_ha_scheduling() -> anyhow::Result<()> {
    2138              :         // Start with three nodes.  Our tenant will only use two.  The third one is
    2139              :         // expected to remain unused.
    2140            1 :         let mut nodes = make_test_nodes(3, &[]);
    2141              : 
    2142            1 :         let mut scheduler = Scheduler::new(nodes.values());
    2143            1 :         let mut context = ScheduleContext::default();
    2144              : 
    2145            1 :         let mut tenant_shard = make_test_tenant_shard(PlacementPolicy::Attached(1));
    2146            1 :         tenant_shard
    2147            1 :             .schedule(&mut scheduler, &mut context)
    2148            1 :             .expect("we have enough nodes, scheduling should work");
    2149              : 
    2150              :         // Expect to initially be schedule on to different nodes
    2151            1 :         assert_eq!(tenant_shard.intent.secondary.len(), 1);
    2152            1 :         assert!(tenant_shard.intent.attached.is_some());
    2153              : 
    2154            1 :         let attached_node_id = tenant_shard.intent.attached.unwrap();
    2155            1 :         let secondary_node_id = *tenant_shard.intent.secondary.iter().last().unwrap();
    2156            1 :         assert_ne!(attached_node_id, secondary_node_id);
    2157              : 
    2158              :         // Notifying the attached node is offline should demote it to a secondary
    2159            1 :         let changed = tenant_shard
    2160            1 :             .intent
    2161            1 :             .demote_attached(&mut scheduler, attached_node_id);
    2162            1 :         assert!(changed);
    2163            1 :         assert!(tenant_shard.intent.attached.is_none());
    2164            1 :         assert_eq!(tenant_shard.intent.secondary.len(), 2);
    2165              : 
    2166              :         // Update the scheduler state to indicate the node is offline
    2167            1 :         nodes
    2168            1 :             .get_mut(&attached_node_id)
    2169            1 :             .unwrap()
    2170            1 :             .set_availability(NodeAvailability::Offline);
    2171            1 :         scheduler.node_upsert(nodes.get(&attached_node_id).unwrap());
    2172              : 
    2173              :         // Scheduling the node should promote the still-available secondary node to attached
    2174            1 :         tenant_shard
    2175            1 :             .schedule(&mut scheduler, &mut context)
    2176            1 :             .expect("active nodes are available");
    2177            1 :         assert_eq!(tenant_shard.intent.attached.unwrap(), secondary_node_id);
    2178              : 
    2179              :         // The original attached node should have been retained as a secondary
    2180            1 :         assert_eq!(
    2181            1 :             *tenant_shard.intent.secondary.iter().last().unwrap(),
    2182              :             attached_node_id
    2183              :         );
    2184              : 
    2185            1 :         tenant_shard.intent.clear(&mut scheduler);
    2186              : 
    2187            1 :         Ok(())
    2188            1 :     }
    2189              : 
    2190              :     #[test]
    2191            1 :     fn intent_from_observed() -> anyhow::Result<()> {
    2192            1 :         let nodes = make_test_nodes(3, &[]);
    2193            1 :         let mut scheduler = Scheduler::new(nodes.values());
    2194              : 
    2195            1 :         let mut tenant_shard = make_test_tenant_shard(PlacementPolicy::Attached(1));
    2196              : 
    2197            1 :         tenant_shard.observed.locations.insert(
    2198            1 :             NodeId(3),
    2199            1 :             ObservedStateLocation {
    2200            1 :                 conf: Some(LocationConfig {
    2201            1 :                     mode: LocationConfigMode::AttachedMulti,
    2202            1 :                     generation: Some(2),
    2203            1 :                     secondary_conf: None,
    2204            1 :                     shard_number: tenant_shard.shard.number.0,
    2205            1 :                     shard_count: tenant_shard.shard.count.literal(),
    2206            1 :                     shard_stripe_size: tenant_shard.shard.stripe_size.0,
    2207            1 :                     tenant_conf: TenantConfig::default(),
    2208            1 :                 }),
    2209            1 :             },
    2210              :         );
    2211              : 
    2212            1 :         tenant_shard.observed.locations.insert(
    2213            1 :             NodeId(2),
    2214            1 :             ObservedStateLocation {
    2215            1 :                 conf: Some(LocationConfig {
    2216            1 :                     mode: LocationConfigMode::AttachedStale,
    2217            1 :                     generation: Some(1),
    2218            1 :                     secondary_conf: None,
    2219            1 :                     shard_number: tenant_shard.shard.number.0,
    2220            1 :                     shard_count: tenant_shard.shard.count.literal(),
    2221            1 :                     shard_stripe_size: tenant_shard.shard.stripe_size.0,
    2222            1 :                     tenant_conf: TenantConfig::default(),
    2223            1 :                 }),
    2224            1 :             },
    2225              :         );
    2226              : 
    2227            1 :         tenant_shard.intent_from_observed(&mut scheduler);
    2228              : 
    2229              :         // The highest generationed attached location gets used as attached
    2230            1 :         assert_eq!(tenant_shard.intent.attached, Some(NodeId(3)));
    2231              :         // Other locations get used as secondary
    2232            1 :         assert_eq!(tenant_shard.intent.secondary, vec![NodeId(2)]);
    2233              : 
    2234            1 :         scheduler.consistency_check(nodes.values(), [&tenant_shard].into_iter())?;
    2235              : 
    2236            1 :         tenant_shard.intent.clear(&mut scheduler);
    2237            1 :         Ok(())
    2238            1 :     }
    2239              : 
    2240              :     #[test]
    2241            1 :     fn scheduling_mode() -> anyhow::Result<()> {
    2242            1 :         let nodes = make_test_nodes(3, &[]);
    2243            1 :         let mut scheduler = Scheduler::new(nodes.values());
    2244              : 
    2245            1 :         let mut tenant_shard = make_test_tenant_shard(PlacementPolicy::Attached(1));
    2246              : 
    2247              :         // In pause mode, schedule() shouldn't do anything
    2248            1 :         tenant_shard.scheduling_policy = ShardSchedulingPolicy::Pause;
    2249            1 :         assert!(
    2250            1 :             tenant_shard
    2251            1 :                 .schedule(&mut scheduler, &mut ScheduleContext::default())
    2252            1 :                 .is_ok()
    2253              :         );
    2254            1 :         assert!(tenant_shard.intent.all_pageservers().is_empty());
    2255              : 
    2256              :         // In active mode, schedule() works
    2257            1 :         tenant_shard.scheduling_policy = ShardSchedulingPolicy::Active;
    2258            1 :         assert!(
    2259            1 :             tenant_shard
    2260            1 :                 .schedule(&mut scheduler, &mut ScheduleContext::default())
    2261            1 :                 .is_ok()
    2262              :         );
    2263            1 :         assert!(!tenant_shard.intent.all_pageservers().is_empty());
    2264              : 
    2265            1 :         tenant_shard.intent.clear(&mut scheduler);
    2266            1 :         Ok(())
    2267            1 :     }
    2268              : 
    2269              :     #[test]
    2270              :     /// Simple case: moving attachment to somewhere better where we already have a secondary
    2271            1 :     fn optimize_attachment_simple() -> anyhow::Result<()> {
    2272            1 :         let nodes = make_test_nodes(
    2273              :             3,
    2274            1 :             &[
    2275            1 :                 AvailabilityZone("az-a".to_string()),
    2276            1 :                 AvailabilityZone("az-b".to_string()),
    2277            1 :                 AvailabilityZone("az-c".to_string()),
    2278            1 :             ],
    2279              :         );
    2280            1 :         let mut scheduler = Scheduler::new(nodes.values());
    2281              : 
    2282            1 :         let mut shard_a = make_test_tenant_shard(PlacementPolicy::Attached(1));
    2283            1 :         shard_a.intent.preferred_az_id = Some(AvailabilityZone("az-a".to_string()));
    2284            1 :         let mut shard_b = make_test_tenant_shard(PlacementPolicy::Attached(1));
    2285            1 :         shard_b.intent.preferred_az_id = Some(AvailabilityZone("az-a".to_string()));
    2286              : 
    2287              :         // Initially: both nodes attached on shard 1, and both have secondary locations
    2288              :         // on different nodes.
    2289            1 :         shard_a.intent.set_attached(&mut scheduler, Some(NodeId(2)));
    2290            1 :         shard_a.intent.push_secondary(&mut scheduler, NodeId(1));
    2291            1 :         shard_b.intent.set_attached(&mut scheduler, Some(NodeId(1)));
    2292            1 :         shard_b.intent.push_secondary(&mut scheduler, NodeId(2));
    2293              : 
    2294            1 :         fn make_schedule_context(shard_a: &TenantShard, shard_b: &TenantShard) -> ScheduleContext {
    2295            1 :             let mut schedule_context = ScheduleContext::default();
    2296            1 :             schedule_context.avoid(&shard_a.intent.all_pageservers());
    2297            1 :             schedule_context.avoid(&shard_b.intent.all_pageservers());
    2298            1 :             schedule_context
    2299            1 :         }
    2300              : 
    2301            1 :         let schedule_context = make_schedule_context(&shard_a, &shard_b);
    2302            1 :         let optimization_a = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
    2303            1 :         assert_eq!(
    2304              :             optimization_a,
    2305            1 :             Some(ScheduleOptimization {
    2306            1 :                 sequence: shard_a.sequence,
    2307            1 :                 action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    2308            1 :                     old_attached_node_id: NodeId(2),
    2309            1 :                     new_attached_node_id: NodeId(1)
    2310            1 :                 })
    2311            1 :             })
    2312              :         );
    2313            1 :         shard_a.apply_optimization(&mut scheduler, optimization_a.unwrap());
    2314              : 
    2315              :         // // Either shard should recognize that it has the option to switch to a secondary location where there
    2316              :         // // would be no other shards from the same tenant, and request to do so.
    2317              :         // assert_eq!(
    2318              :         //     optimization_a_prepare,
    2319              :         //     Some(ScheduleOptimization {
    2320              :         //         sequence: shard_a.sequence,
    2321              :         //         action: ScheduleOptimizationAction::CreateSecondary(NodeId(2))
    2322              :         //     })
    2323              :         // );
    2324              :         // shard_a.apply_optimization(&mut scheduler, optimization_a_prepare.unwrap());
    2325              : 
    2326              :         // let schedule_context = make_schedule_context(&shard_a, &shard_b);
    2327              :         // let optimization_a_migrate = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
    2328              :         // assert_eq!(
    2329              :         //     optimization_a_migrate,
    2330              :         //     Some(ScheduleOptimization {
    2331              :         //         sequence: shard_a.sequence,
    2332              :         //         action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    2333              :         //             old_attached_node_id: NodeId(1),
    2334              :         //             new_attached_node_id: NodeId(2)
    2335              :         //         })
    2336              :         //     })
    2337              :         // );
    2338              :         // shard_a.apply_optimization(&mut scheduler, optimization_a_migrate.unwrap());
    2339              : 
    2340              :         // let schedule_context = make_schedule_context(&shard_a, &shard_b);
    2341              :         // let optimization_a_cleanup = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
    2342              :         // assert_eq!(
    2343              :         //     optimization_a_cleanup,
    2344              :         //     Some(ScheduleOptimization {
    2345              :         //         sequence: shard_a.sequence,
    2346              :         //         action: ScheduleOptimizationAction::RemoveSecondary(NodeId(1))
    2347              :         //     })
    2348              :         // );
    2349              :         // shard_a.apply_optimization(&mut scheduler, optimization_a_cleanup.unwrap());
    2350              : 
    2351              :         // // Shard B should not be moved anywhere, since the pressure on node 1 was relieved by moving shard A
    2352              :         // let schedule_context = make_schedule_context(&shard_a, &shard_b);
    2353              :         // assert_eq!(shard_b.optimize_attachment(&mut scheduler, &schedule_context), None);
    2354              : 
    2355            1 :         shard_a.intent.clear(&mut scheduler);
    2356            1 :         shard_b.intent.clear(&mut scheduler);
    2357              : 
    2358            1 :         Ok(())
    2359            1 :     }
    2360              : 
    2361              :     #[test]
    2362              :     /// Complicated case: moving attachment to somewhere better where we do not have a secondary
    2363              :     /// already, creating one as needed.
    2364            1 :     fn optimize_attachment_multistep() -> anyhow::Result<()> {
    2365            1 :         let nodes = make_test_nodes(
    2366              :             3,
    2367            1 :             &[
    2368            1 :                 AvailabilityZone("az-a".to_string()),
    2369            1 :                 AvailabilityZone("az-b".to_string()),
    2370            1 :                 AvailabilityZone("az-c".to_string()),
    2371            1 :             ],
    2372              :         );
    2373            1 :         let mut scheduler = Scheduler::new(nodes.values());
    2374              : 
    2375              :         // Two shards of a tenant that wants to be in AZ A
    2376            1 :         let mut shard_a = make_test_tenant_shard(PlacementPolicy::Attached(1));
    2377            1 :         shard_a.intent.preferred_az_id = Some(AvailabilityZone("az-a".to_string()));
    2378            1 :         let mut shard_b = make_test_tenant_shard(PlacementPolicy::Attached(1));
    2379            1 :         shard_b.intent.preferred_az_id = Some(AvailabilityZone("az-a".to_string()));
    2380              : 
    2381              :         // Both shards are initially attached in non-home AZ _and_ have secondaries in non-home AZs
    2382            1 :         shard_a.intent.set_attached(&mut scheduler, Some(NodeId(2)));
    2383            1 :         shard_a.intent.push_secondary(&mut scheduler, NodeId(3));
    2384            1 :         shard_b.intent.set_attached(&mut scheduler, Some(NodeId(3)));
    2385            1 :         shard_b.intent.push_secondary(&mut scheduler, NodeId(2));
    2386              : 
    2387            3 :         fn make_schedule_context(shard_a: &TenantShard, shard_b: &TenantShard) -> ScheduleContext {
    2388            3 :             let mut schedule_context = ScheduleContext::default();
    2389            3 :             schedule_context.avoid(&shard_a.intent.all_pageservers());
    2390            3 :             schedule_context.avoid(&shard_b.intent.all_pageservers());
    2391            3 :             schedule_context
    2392            3 :         }
    2393              : 
    2394            1 :         let schedule_context = make_schedule_context(&shard_a, &shard_b);
    2395            1 :         let optimization_a_prepare = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
    2396            1 :         assert_eq!(
    2397              :             optimization_a_prepare,
    2398            1 :             Some(ScheduleOptimization {
    2399            1 :                 sequence: shard_a.sequence,
    2400            1 :                 action: ScheduleOptimizationAction::CreateSecondary(NodeId(1))
    2401            1 :             })
    2402              :         );
    2403            1 :         shard_a.apply_optimization(&mut scheduler, optimization_a_prepare.unwrap());
    2404              : 
    2405            1 :         let schedule_context = make_schedule_context(&shard_a, &shard_b);
    2406            1 :         let optimization_a_migrate = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
    2407            1 :         assert_eq!(
    2408              :             optimization_a_migrate,
    2409            1 :             Some(ScheduleOptimization {
    2410            1 :                 sequence: shard_a.sequence,
    2411            1 :                 action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    2412            1 :                     old_attached_node_id: NodeId(2),
    2413            1 :                     new_attached_node_id: NodeId(1)
    2414            1 :                 })
    2415            1 :             })
    2416              :         );
    2417            1 :         shard_a.apply_optimization(&mut scheduler, optimization_a_migrate.unwrap());
    2418              : 
    2419            1 :         let schedule_context = make_schedule_context(&shard_a, &shard_b);
    2420            1 :         let optimization_a_cleanup = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
    2421            1 :         assert_eq!(
    2422              :             optimization_a_cleanup,
    2423            1 :             Some(ScheduleOptimization {
    2424            1 :                 sequence: shard_a.sequence,
    2425            1 :                 action: ScheduleOptimizationAction::RemoveSecondary(NodeId(3))
    2426            1 :             })
    2427              :         );
    2428            1 :         shard_a.apply_optimization(&mut scheduler, optimization_a_cleanup.unwrap());
    2429              : 
    2430              :         // // Shard B should not be moved anywhere, since the pressure on node 1 was relieved by moving shard A
    2431              :         // let schedule_context = make_schedule_context(&shard_a, &shard_b);
    2432              :         // assert_eq!(shard_b.optimize_attachment(&mut scheduler, &schedule_context), None);
    2433              : 
    2434            1 :         shard_a.intent.clear(&mut scheduler);
    2435            1 :         shard_b.intent.clear(&mut scheduler);
    2436              : 
    2437            1 :         Ok(())
    2438            1 :     }
    2439              : 
    2440              :     #[test]
    2441              :     /// How the optimisation code handles a shard with a preferred node set; this is an example
    2442              :     /// of the multi-step migration, but driven by a different input.
    2443            1 :     fn optimize_attachment_multi_preferred_node() -> anyhow::Result<()> {
    2444            1 :         let nodes = make_test_nodes(
    2445              :             4,
    2446            1 :             &[
    2447            1 :                 AvailabilityZone("az-a".to_string()),
    2448            1 :                 AvailabilityZone("az-a".to_string()),
    2449            1 :                 AvailabilityZone("az-b".to_string()),
    2450            1 :                 AvailabilityZone("az-b".to_string()),
    2451            1 :             ],
    2452              :         );
    2453            1 :         let mut scheduler = Scheduler::new(nodes.values());
    2454              : 
    2455              :         // Two shards of a tenant that wants to be in AZ A
    2456            1 :         let mut shard_a = make_test_tenant_shard(PlacementPolicy::Attached(1));
    2457            1 :         shard_a.intent.preferred_az_id = Some(AvailabilityZone("az-a".to_string()));
    2458              : 
    2459              :         // Initially attached in a stable location
    2460            1 :         shard_a.intent.set_attached(&mut scheduler, Some(NodeId(1)));
    2461            1 :         shard_a.intent.push_secondary(&mut scheduler, NodeId(3));
    2462              : 
    2463              :         // Set the preferred node to node 2, an equally high scoring node to its current location
    2464            1 :         shard_a.preferred_node = Some(NodeId(2));
    2465              : 
    2466            3 :         fn make_schedule_context(shard_a: &TenantShard) -> ScheduleContext {
    2467            3 :             let mut schedule_context = ScheduleContext::default();
    2468            3 :             schedule_context.avoid(&shard_a.intent.all_pageservers());
    2469            3 :             schedule_context
    2470            3 :         }
    2471              : 
    2472            1 :         let schedule_context = make_schedule_context(&shard_a);
    2473            1 :         let optimization_a_prepare = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
    2474            1 :         assert_eq!(
    2475              :             optimization_a_prepare,
    2476            1 :             Some(ScheduleOptimization {
    2477            1 :                 sequence: shard_a.sequence,
    2478            1 :                 action: ScheduleOptimizationAction::CreateSecondary(NodeId(2))
    2479            1 :             })
    2480              :         );
    2481            1 :         shard_a.apply_optimization(&mut scheduler, optimization_a_prepare.unwrap());
    2482              : 
    2483              :         // The first step of the optimisation should not have cleared the preferred node
    2484            1 :         assert_eq!(shard_a.preferred_node, Some(NodeId(2)));
    2485              : 
    2486            1 :         let schedule_context = make_schedule_context(&shard_a);
    2487            1 :         let optimization_a_migrate = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
    2488            1 :         assert_eq!(
    2489              :             optimization_a_migrate,
    2490            1 :             Some(ScheduleOptimization {
    2491            1 :                 sequence: shard_a.sequence,
    2492            1 :                 action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    2493            1 :                     old_attached_node_id: NodeId(1),
    2494            1 :                     new_attached_node_id: NodeId(2)
    2495            1 :                 })
    2496            1 :             })
    2497              :         );
    2498            1 :         shard_a.apply_optimization(&mut scheduler, optimization_a_migrate.unwrap());
    2499              : 
    2500              :         // The cutover step of the optimisation should have cleared the preferred node
    2501            1 :         assert_eq!(shard_a.preferred_node, None);
    2502              : 
    2503            1 :         let schedule_context = make_schedule_context(&shard_a);
    2504            1 :         let optimization_a_cleanup = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
    2505            1 :         assert_eq!(
    2506              :             optimization_a_cleanup,
    2507            1 :             Some(ScheduleOptimization {
    2508            1 :                 sequence: shard_a.sequence,
    2509            1 :                 action: ScheduleOptimizationAction::RemoveSecondary(NodeId(1))
    2510            1 :             })
    2511              :         );
    2512            1 :         shard_a.apply_optimization(&mut scheduler, optimization_a_cleanup.unwrap());
    2513              : 
    2514            1 :         shard_a.intent.clear(&mut scheduler);
    2515              : 
    2516            1 :         Ok(())
    2517            1 :     }
    2518              : 
    2519              :     #[test]
    2520              :     /// Check that multi-step migration works when moving to somewhere that is only better by
    2521              :     /// 1 AffinityScore -- this ensures that we don't have a bug like the intermediate secondary
    2522              :     /// counting toward the affinity score such that it prevents the rest of the migration from happening.
    2523            1 :     fn optimize_attachment_marginal() -> anyhow::Result<()> {
    2524            1 :         let nodes = make_test_nodes(2, &[]);
    2525            1 :         let mut scheduler = Scheduler::new(nodes.values());
    2526              : 
    2527              :         // Multi-sharded tenant, we will craft a situation where affinity
    2528              :         // scores differ only slightly
    2529            1 :         let mut shards = make_test_tenant(PlacementPolicy::Attached(0), ShardCount::new(4), None);
    2530              : 
    2531              :         // 1 attached on node 1
    2532            1 :         shards[0]
    2533            1 :             .intent
    2534            1 :             .set_attached(&mut scheduler, Some(NodeId(1)));
    2535              :         // 3 attached on node 2
    2536            1 :         shards[1]
    2537            1 :             .intent
    2538            1 :             .set_attached(&mut scheduler, Some(NodeId(2)));
    2539            1 :         shards[2]
    2540            1 :             .intent
    2541            1 :             .set_attached(&mut scheduler, Some(NodeId(2)));
    2542            1 :         shards[3]
    2543            1 :             .intent
    2544            1 :             .set_attached(&mut scheduler, Some(NodeId(2)));
    2545              : 
    2546              :         // The scheduler should figure out that we need to:
    2547              :         // - Create a secondary for shard 3 on node 1
    2548              :         // - Migrate shard 3 to node 1
    2549              :         // - Remove shard 3's location on node 2
    2550              : 
    2551            4 :         fn make_schedule_context(shards: &Vec<TenantShard>) -> ScheduleContext {
    2552            4 :             let mut schedule_context = ScheduleContext::default();
    2553           20 :             for shard in shards {
    2554           16 :                 schedule_context.avoid(&shard.intent.all_pageservers());
    2555           16 :             }
    2556            4 :             schedule_context
    2557            4 :         }
    2558              : 
    2559            1 :         let schedule_context = make_schedule_context(&shards);
    2560            1 :         let optimization_a_prepare =
    2561            1 :             shards[1].optimize_attachment(&mut scheduler, &schedule_context);
    2562            1 :         assert_eq!(
    2563              :             optimization_a_prepare,
    2564            1 :             Some(ScheduleOptimization {
    2565            1 :                 sequence: shards[1].sequence,
    2566            1 :                 action: ScheduleOptimizationAction::CreateSecondary(NodeId(1))
    2567            1 :             })
    2568              :         );
    2569            1 :         shards[1].apply_optimization(&mut scheduler, optimization_a_prepare.unwrap());
    2570              : 
    2571            1 :         let schedule_context = make_schedule_context(&shards);
    2572            1 :         let optimization_a_migrate =
    2573            1 :             shards[1].optimize_attachment(&mut scheduler, &schedule_context);
    2574            1 :         assert_eq!(
    2575              :             optimization_a_migrate,
    2576            1 :             Some(ScheduleOptimization {
    2577            1 :                 sequence: shards[1].sequence,
    2578            1 :                 action: ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    2579            1 :                     old_attached_node_id: NodeId(2),
    2580            1 :                     new_attached_node_id: NodeId(1)
    2581            1 :                 })
    2582            1 :             })
    2583              :         );
    2584            1 :         shards[1].apply_optimization(&mut scheduler, optimization_a_migrate.unwrap());
    2585              : 
    2586            1 :         let schedule_context = make_schedule_context(&shards);
    2587            1 :         let optimization_a_cleanup =
    2588            1 :             shards[1].optimize_attachment(&mut scheduler, &schedule_context);
    2589            1 :         assert_eq!(
    2590              :             optimization_a_cleanup,
    2591            1 :             Some(ScheduleOptimization {
    2592            1 :                 sequence: shards[1].sequence,
    2593            1 :                 action: ScheduleOptimizationAction::RemoveSecondary(NodeId(2))
    2594            1 :             })
    2595              :         );
    2596            1 :         shards[1].apply_optimization(&mut scheduler, optimization_a_cleanup.unwrap());
    2597              : 
    2598              :         // Everything should be stable now
    2599            1 :         let schedule_context = make_schedule_context(&shards);
    2600            1 :         assert_eq!(
    2601            1 :             shards[0].optimize_attachment(&mut scheduler, &schedule_context),
    2602              :             None
    2603              :         );
    2604            1 :         assert_eq!(
    2605            1 :             shards[1].optimize_attachment(&mut scheduler, &schedule_context),
    2606              :             None
    2607              :         );
    2608            1 :         assert_eq!(
    2609            1 :             shards[2].optimize_attachment(&mut scheduler, &schedule_context),
    2610              :             None
    2611              :         );
    2612            1 :         assert_eq!(
    2613            1 :             shards[3].optimize_attachment(&mut scheduler, &schedule_context),
    2614              :             None
    2615              :         );
    2616              : 
    2617            5 :         for mut shard in shards {
    2618            4 :             shard.intent.clear(&mut scheduler);
    2619            4 :         }
    2620              : 
    2621            1 :         Ok(())
    2622            1 :     }
    2623              : 
    2624              :     #[test]
    2625            1 :     fn optimize_secondary() -> anyhow::Result<()> {
    2626            1 :         let nodes = make_test_nodes(4, &[]);
    2627            1 :         let mut scheduler = Scheduler::new(nodes.values());
    2628              : 
    2629            1 :         let mut shard_a = make_test_tenant_shard(PlacementPolicy::Attached(1));
    2630            1 :         let mut shard_b = make_test_tenant_shard(PlacementPolicy::Attached(1));
    2631              : 
    2632              :         // Initially: both nodes attached on shard 1, and both have secondary locations
    2633              :         // on different nodes.
    2634            1 :         shard_a.intent.set_attached(&mut scheduler, Some(NodeId(1)));
    2635            1 :         shard_a.intent.push_secondary(&mut scheduler, NodeId(3));
    2636            1 :         shard_b.intent.set_attached(&mut scheduler, Some(NodeId(2)));
    2637            1 :         shard_b.intent.push_secondary(&mut scheduler, NodeId(3));
    2638              : 
    2639            1 :         let mut schedule_context = ScheduleContext::default();
    2640            1 :         schedule_context.avoid(&shard_a.intent.all_pageservers());
    2641            1 :         schedule_context.avoid(&shard_b.intent.all_pageservers());
    2642              : 
    2643            1 :         let optimization_a = shard_a.optimize_secondary(&mut scheduler, &schedule_context);
    2644              : 
    2645              :         // Since there is a node with no locations available, the node with two locations for the
    2646              :         // same tenant should generate an optimization to move one away
    2647            1 :         assert_eq!(
    2648              :             optimization_a,
    2649            1 :             Some(ScheduleOptimization {
    2650            1 :                 sequence: shard_a.sequence,
    2651            1 :                 action: ScheduleOptimizationAction::ReplaceSecondary(ReplaceSecondary {
    2652            1 :                     old_node_id: NodeId(3),
    2653            1 :                     new_node_id: NodeId(4)
    2654            1 :                 })
    2655            1 :             })
    2656              :         );
    2657              : 
    2658            1 :         shard_a.apply_optimization(&mut scheduler, optimization_a.unwrap());
    2659            1 :         assert_eq!(shard_a.intent.get_attached(), &Some(NodeId(1)));
    2660            1 :         assert_eq!(shard_a.intent.get_secondary(), &vec![NodeId(4)]);
    2661              : 
    2662            1 :         shard_a.intent.clear(&mut scheduler);
    2663            1 :         shard_b.intent.clear(&mut scheduler);
    2664              : 
    2665            1 :         Ok(())
    2666            1 :     }
    2667              : 
    2668              :     /// Test how the optimisation code behaves with an extra secondary
    2669              :     #[test]
    2670            1 :     fn optimize_removes_secondary() -> anyhow::Result<()> {
    2671            1 :         let az_a_tag = AvailabilityZone("az-a".to_string());
    2672            1 :         let az_b_tag = AvailabilityZone("az-b".to_string());
    2673            1 :         let mut nodes = make_test_nodes(
    2674              :             4,
    2675            1 :             &[
    2676            1 :                 az_a_tag.clone(),
    2677            1 :                 az_b_tag.clone(),
    2678            1 :                 az_a_tag.clone(),
    2679            1 :                 az_b_tag.clone(),
    2680            1 :             ],
    2681              :         );
    2682            1 :         let mut scheduler = Scheduler::new(nodes.values());
    2683              : 
    2684            1 :         let mut schedule_context = ScheduleContext::default();
    2685              : 
    2686            1 :         let mut shard_a = make_test_tenant_shard(PlacementPolicy::Attached(1));
    2687            1 :         shard_a.intent.preferred_az_id = Some(az_a_tag.clone());
    2688            1 :         shard_a
    2689            1 :             .schedule(&mut scheduler, &mut schedule_context)
    2690            1 :             .unwrap();
    2691              : 
    2692              :         // Attached on node 1, secondary on node 2
    2693            1 :         assert_eq!(shard_a.intent.get_attached(), &Some(NodeId(1)));
    2694            1 :         assert_eq!(shard_a.intent.get_secondary(), &vec![NodeId(2)]);
    2695              : 
    2696              :         // Initially optimiser is idle
    2697            1 :         assert_eq!(
    2698            1 :             shard_a.optimize_attachment(&mut scheduler, &schedule_context),
    2699              :             None
    2700              :         );
    2701            1 :         assert_eq!(
    2702            1 :             shard_a.optimize_secondary(&mut scheduler, &schedule_context),
    2703              :             None
    2704              :         );
    2705              : 
    2706              :         // A spare secondary in the home AZ: it should be removed -- this is the situation when we're midway through a graceful migration, after cutting over
    2707              :         // to our new location
    2708            1 :         shard_a.intent.push_secondary(&mut scheduler, NodeId(3));
    2709            1 :         let optimization = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
    2710            1 :         assert_eq!(
    2711              :             optimization,
    2712            1 :             Some(ScheduleOptimization {
    2713            1 :                 sequence: shard_a.sequence,
    2714            1 :                 action: ScheduleOptimizationAction::RemoveSecondary(NodeId(3))
    2715            1 :             })
    2716              :         );
    2717            1 :         shard_a.apply_optimization(&mut scheduler, optimization.unwrap());
    2718              : 
    2719              :         // A spare secondary in the non-home AZ, and one of them is offline
    2720            1 :         shard_a.intent.push_secondary(&mut scheduler, NodeId(4));
    2721            1 :         nodes
    2722            1 :             .get_mut(&NodeId(4))
    2723            1 :             .unwrap()
    2724            1 :             .set_availability(NodeAvailability::Offline);
    2725            1 :         scheduler.node_upsert(nodes.get(&NodeId(4)).unwrap());
    2726            1 :         let optimization = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
    2727            1 :         assert_eq!(
    2728              :             optimization,
    2729            1 :             Some(ScheduleOptimization {
    2730            1 :                 sequence: shard_a.sequence,
    2731            1 :                 action: ScheduleOptimizationAction::RemoveSecondary(NodeId(4))
    2732            1 :             })
    2733              :         );
    2734            1 :         shard_a.apply_optimization(&mut scheduler, optimization.unwrap());
    2735              : 
    2736              :         // A spare secondary when should have none
    2737            1 :         shard_a.policy = PlacementPolicy::Attached(0);
    2738            1 :         let optimization = shard_a.optimize_attachment(&mut scheduler, &schedule_context);
    2739            1 :         assert_eq!(
    2740              :             optimization,
    2741            1 :             Some(ScheduleOptimization {
    2742            1 :                 sequence: shard_a.sequence,
    2743            1 :                 action: ScheduleOptimizationAction::RemoveSecondary(NodeId(2))
    2744            1 :             })
    2745              :         );
    2746            1 :         shard_a.apply_optimization(&mut scheduler, optimization.unwrap());
    2747            1 :         assert_eq!(shard_a.intent.get_attached(), &Some(NodeId(1)));
    2748            1 :         assert_eq!(shard_a.intent.get_secondary(), &vec![]);
    2749              : 
    2750              :         // Check that in secondary mode, we preserve the secondary in the preferred AZ
    2751            1 :         let mut schedule_context = ScheduleContext::default(); // Fresh context, we're about to call schedule()
    2752            1 :         shard_a.policy = PlacementPolicy::Secondary;
    2753            1 :         shard_a
    2754            1 :             .schedule(&mut scheduler, &mut schedule_context)
    2755            1 :             .unwrap();
    2756            1 :         assert_eq!(shard_a.intent.get_attached(), &None);
    2757            1 :         assert_eq!(shard_a.intent.get_secondary(), &vec![NodeId(1)]);
    2758            1 :         assert_eq!(
    2759            1 :             shard_a.optimize_attachment(&mut scheduler, &schedule_context),
    2760              :             None
    2761              :         );
    2762            1 :         assert_eq!(
    2763            1 :             shard_a.optimize_secondary(&mut scheduler, &schedule_context),
    2764              :             None
    2765              :         );
    2766              : 
    2767            1 :         shard_a.intent.clear(&mut scheduler);
    2768              : 
    2769            1 :         Ok(())
    2770            1 :     }
    2771              : 
    2772              :     // Optimize til quiescent: this emulates what Service::optimize_all does, when
    2773              :     // called repeatedly in the background.
    2774              :     // Returns the applied optimizations
    2775            3 :     fn optimize_til_idle(
    2776            3 :         scheduler: &mut Scheduler,
    2777            3 :         shards: &mut [TenantShard],
    2778            3 :     ) -> Vec<ScheduleOptimization> {
    2779            3 :         let mut loop_n = 0;
    2780            3 :         let mut optimizations = Vec::default();
    2781              :         loop {
    2782            6 :             let mut schedule_context = ScheduleContext::default();
    2783            6 :             let mut any_changed = false;
    2784              : 
    2785           24 :             for shard in shards.iter() {
    2786           24 :                 schedule_context.avoid(&shard.intent.all_pageservers());
    2787           24 :             }
    2788              : 
    2789           15 :             for shard in shards.iter_mut() {
    2790           15 :                 let optimization = shard.optimize_attachment(scheduler, &schedule_context);
    2791           15 :                 tracing::info!(
    2792            0 :                     "optimize_attachment({})={:?}",
    2793              :                     shard.tenant_shard_id,
    2794              :                     optimization
    2795              :                 );
    2796           15 :                 if let Some(optimization) = optimization {
    2797              :                     // Check that maybe_optimizable wouldn't have wrongly claimed this optimization didn't exist
    2798            3 :                     assert!(shard.maybe_optimizable(scheduler, &schedule_context));
    2799            3 :                     optimizations.push(optimization.clone());
    2800            3 :                     shard.apply_optimization(scheduler, optimization);
    2801            3 :                     any_changed = true;
    2802            3 :                     break;
    2803           12 :                 }
    2804              : 
    2805           12 :                 let optimization = shard.optimize_secondary(scheduler, &schedule_context);
    2806           12 :                 tracing::info!(
    2807            0 :                     "optimize_secondary({})={:?}",
    2808              :                     shard.tenant_shard_id,
    2809              :                     optimization
    2810              :                 );
    2811           12 :                 if let Some(optimization) = optimization {
    2812              :                     // Check that maybe_optimizable wouldn't have wrongly claimed this optimization didn't exist
    2813            0 :                     assert!(shard.maybe_optimizable(scheduler, &schedule_context));
    2814              : 
    2815            0 :                     optimizations.push(optimization.clone());
    2816            0 :                     shard.apply_optimization(scheduler, optimization);
    2817            0 :                     any_changed = true;
    2818            0 :                     break;
    2819           12 :                 }
    2820              :             }
    2821              : 
    2822            6 :             if !any_changed {
    2823            3 :                 break;
    2824            3 :             }
    2825              : 
    2826              :             // Assert no infinite loop
    2827            3 :             loop_n += 1;
    2828            3 :             assert!(loop_n < 1000);
    2829              :         }
    2830              : 
    2831            3 :         optimizations
    2832            3 :     }
    2833              : 
    2834              :     /// Test the balancing behavior of shard scheduling: that it achieves a balance, and
    2835              :     /// that it converges.
    2836              :     #[test]
    2837            1 :     fn optimize_add_nodes() -> anyhow::Result<()> {
    2838            1 :         let nodes = make_test_nodes(
    2839              :             9,
    2840            1 :             &[
    2841            1 :                 // Initial 6 nodes
    2842            1 :                 AvailabilityZone("az-a".to_string()),
    2843            1 :                 AvailabilityZone("az-a".to_string()),
    2844            1 :                 AvailabilityZone("az-b".to_string()),
    2845            1 :                 AvailabilityZone("az-b".to_string()),
    2846            1 :                 AvailabilityZone("az-c".to_string()),
    2847            1 :                 AvailabilityZone("az-c".to_string()),
    2848            1 :                 // Three we will add later
    2849            1 :                 AvailabilityZone("az-a".to_string()),
    2850            1 :                 AvailabilityZone("az-b".to_string()),
    2851            1 :                 AvailabilityZone("az-c".to_string()),
    2852            1 :             ],
    2853              :         );
    2854              : 
    2855              :         // Only show the scheduler two nodes in each AZ to start with
    2856            1 :         let mut scheduler = Scheduler::new([].iter());
    2857            7 :         for i in 1..=6 {
    2858            6 :             scheduler.node_upsert(nodes.get(&NodeId(i)).unwrap());
    2859            6 :         }
    2860              : 
    2861            1 :         let mut shards = make_test_tenant(
    2862            1 :             PlacementPolicy::Attached(1),
    2863            1 :             ShardCount::new(4),
    2864            1 :             Some(AvailabilityZone("az-a".to_string())),
    2865              :         );
    2866            1 :         let mut schedule_context = ScheduleContext::default();
    2867            5 :         for shard in &mut shards {
    2868            4 :             assert!(
    2869            4 :                 shard
    2870            4 :                     .schedule(&mut scheduler, &mut schedule_context)
    2871            4 :                     .is_ok()
    2872              :             );
    2873              :         }
    2874              : 
    2875              :         // Initial: attached locations land in the tenant's home AZ.
    2876            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(1)), 2);
    2877            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(1)), 2);
    2878            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(2)), 2);
    2879            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(2)), 2);
    2880              : 
    2881              :         // Initial: secondary locations in a remote AZ
    2882            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(3)), 1);
    2883            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(3)), 0);
    2884            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(4)), 1);
    2885            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(4)), 0);
    2886            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(5)), 1);
    2887            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(5)), 0);
    2888            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(6)), 1);
    2889            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(6)), 0);
    2890              : 
    2891              :         // Add another three nodes: we should see the shards spread out when their optimize
    2892              :         // methods are called
    2893            1 :         scheduler.node_upsert(nodes.get(&NodeId(7)).unwrap());
    2894            1 :         scheduler.node_upsert(nodes.get(&NodeId(8)).unwrap());
    2895            1 :         scheduler.node_upsert(nodes.get(&NodeId(9)).unwrap());
    2896            1 :         optimize_til_idle(&mut scheduler, &mut shards);
    2897              : 
    2898              :         // We expect one attached location was moved to the new node in the tenant's home AZ
    2899            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(7)), 1);
    2900            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(7)), 1);
    2901              :         // The original node has one less attached shard
    2902            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(1)), 1);
    2903            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(1)), 1);
    2904              : 
    2905              :         // One of the original nodes still has two attachments, since there are an odd number of nodes
    2906            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(2)), 2);
    2907            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(2)), 2);
    2908              : 
    2909              :         // None of our secondaries moved, since we already had enough nodes for those to be
    2910              :         // scheduled perfectly
    2911            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(3)), 1);
    2912            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(3)), 0);
    2913            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(4)), 1);
    2914            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(4)), 0);
    2915            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(5)), 1);
    2916            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(5)), 0);
    2917            1 :         assert_eq!(scheduler.get_node_shard_count(NodeId(6)), 1);
    2918            1 :         assert_eq!(scheduler.get_node_attached_shard_count(NodeId(6)), 0);
    2919              : 
    2920            4 :         for shard in shards.iter_mut() {
    2921            4 :             shard.intent.clear(&mut scheduler);
    2922            4 :         }
    2923              : 
    2924            1 :         Ok(())
    2925            1 :     }
    2926              : 
    2927              :     /// Test that initial shard scheduling is optimal. By optimal we mean
    2928              :     /// that the optimizer cannot find a way to improve it.
    2929              :     ///
    2930              :     /// This test is an example of the scheduling issue described in
    2931              :     /// https://github.com/neondatabase/neon/issues/8969
    2932              :     #[test]
    2933            1 :     fn initial_scheduling_is_optimal() -> anyhow::Result<()> {
    2934              :         use itertools::Itertools;
    2935              : 
    2936            1 :         let nodes = make_test_nodes(2, &[]);
    2937              : 
    2938            1 :         let mut scheduler = Scheduler::new([].iter());
    2939            1 :         scheduler.node_upsert(nodes.get(&NodeId(1)).unwrap());
    2940            1 :         scheduler.node_upsert(nodes.get(&NodeId(2)).unwrap());
    2941              : 
    2942            1 :         let mut a = make_test_tenant(PlacementPolicy::Attached(1), ShardCount::new(4), None);
    2943            1 :         let a_context = Rc::new(RefCell::new(ScheduleContext::default()));
    2944              : 
    2945            1 :         let mut b = make_test_tenant(PlacementPolicy::Attached(1), ShardCount::new(4), None);
    2946            1 :         let b_context = Rc::new(RefCell::new(ScheduleContext::default()));
    2947              : 
    2948            4 :         let a_shards_with_context = a.iter_mut().map(|shard| (shard, a_context.clone()));
    2949            4 :         let b_shards_with_context = b.iter_mut().map(|shard| (shard, b_context.clone()));
    2950              : 
    2951            1 :         let schedule_order = a_shards_with_context.interleave(b_shards_with_context);
    2952              : 
    2953            9 :         for (shard, context) in schedule_order {
    2954            8 :             let context = &mut *context.borrow_mut();
    2955            8 :             shard.schedule(&mut scheduler, context).unwrap();
    2956            8 :         }
    2957              : 
    2958            1 :         let applied_to_a = optimize_til_idle(&mut scheduler, &mut a);
    2959            1 :         assert_eq!(applied_to_a, vec![]);
    2960              : 
    2961            1 :         let applied_to_b = optimize_til_idle(&mut scheduler, &mut b);
    2962            1 :         assert_eq!(applied_to_b, vec![]);
    2963              : 
    2964            8 :         for shard in a.iter_mut().chain(b.iter_mut()) {
    2965            8 :             shard.intent.clear(&mut scheduler);
    2966            8 :         }
    2967              : 
    2968            1 :         Ok(())
    2969            1 :     }
    2970              : 
    2971              :     #[test]
    2972            1 :     fn random_az_shard_scheduling() -> anyhow::Result<()> {
    2973              :         use rand::seq::SliceRandom;
    2974              : 
    2975           51 :         for seed in 0..50 {
    2976           50 :             eprintln!("Running test with seed {seed}");
    2977           50 :             let mut rng = StdRng::seed_from_u64(seed);
    2978              : 
    2979           50 :             let az_a_tag = AvailabilityZone("az-a".to_string());
    2980           50 :             let az_b_tag = AvailabilityZone("az-b".to_string());
    2981           50 :             let azs = [az_a_tag, az_b_tag];
    2982           50 :             let nodes = make_test_nodes(4, &azs);
    2983           50 :             let mut shards_per_az: HashMap<AvailabilityZone, u32> = HashMap::new();
    2984              : 
    2985           50 :             let mut scheduler = Scheduler::new([].iter());
    2986          200 :             for node in nodes.values() {
    2987          200 :                 scheduler.node_upsert(node);
    2988          200 :             }
    2989              : 
    2990           50 :             let mut shards = Vec::default();
    2991           50 :             let mut contexts = Vec::default();
    2992           50 :             let mut az_picker = azs.iter().cycle().cloned();
    2993         5050 :             for i in 0..100 {
    2994         5000 :                 let az = az_picker.next().unwrap();
    2995         5000 :                 let shard_count = i % 4 + 1;
    2996         5000 :                 *shards_per_az.entry(az.clone()).or_default() += shard_count;
    2997              : 
    2998         5000 :                 let tenant_shards = make_test_tenant(
    2999         5000 :                     PlacementPolicy::Attached(1),
    3000         5000 :                     ShardCount::new(shard_count.try_into().unwrap()),
    3001         5000 :                     Some(az),
    3002              :                 );
    3003         5000 :                 let context = Rc::new(RefCell::new(ScheduleContext::default()));
    3004              : 
    3005         5000 :                 contexts.push(context.clone());
    3006         5000 :                 let with_ctx = tenant_shards
    3007         5000 :                     .into_iter()
    3008        12500 :                     .map(|shard| (shard, context.clone()));
    3009        17500 :                 for shard_with_ctx in with_ctx {
    3010        12500 :                     shards.push(shard_with_ctx);
    3011        12500 :                 }
    3012              :             }
    3013              : 
    3014           50 :             shards.shuffle(&mut rng);
    3015              : 
    3016              :             #[derive(Default, Debug)]
    3017              :             struct NodeStats {
    3018              :                 attachments: u32,
    3019              :                 secondaries: u32,
    3020              :             }
    3021              : 
    3022           50 :             let mut node_stats: HashMap<NodeId, NodeStats> = HashMap::default();
    3023           50 :             let mut attachments_in_wrong_az = 0;
    3024           50 :             let mut secondaries_in_wrong_az = 0;
    3025              : 
    3026        12550 :             for (shard, context) in &mut shards {
    3027        12500 :                 let context = &mut *context.borrow_mut();
    3028        12500 :                 shard.schedule(&mut scheduler, context).unwrap();
    3029              : 
    3030        12500 :                 let attached_node = shard.intent.get_attached().unwrap();
    3031        12500 :                 let stats = node_stats.entry(attached_node).or_default();
    3032        12500 :                 stats.attachments += 1;
    3033              : 
    3034        12500 :                 let secondary_node = *shard.intent.get_secondary().first().unwrap();
    3035        12500 :                 let stats = node_stats.entry(secondary_node).or_default();
    3036        12500 :                 stats.secondaries += 1;
    3037              : 
    3038        12500 :                 let attached_node_az = nodes
    3039        12500 :                     .get(&attached_node)
    3040        12500 :                     .unwrap()
    3041        12500 :                     .get_availability_zone_id();
    3042        12500 :                 let secondary_node_az = nodes
    3043        12500 :                     .get(&secondary_node)
    3044        12500 :                     .unwrap()
    3045        12500 :                     .get_availability_zone_id();
    3046        12500 :                 let preferred_az = shard.preferred_az().unwrap();
    3047              : 
    3048        12500 :                 if attached_node_az != preferred_az {
    3049            0 :                     eprintln!(
    3050            0 :                         "{} attachment was scheduled in AZ {} but preferred AZ {}",
    3051            0 :                         shard.tenant_shard_id, attached_node_az, preferred_az
    3052            0 :                     );
    3053            0 :                     attachments_in_wrong_az += 1;
    3054        12500 :                 }
    3055              : 
    3056        12500 :                 if secondary_node_az == preferred_az {
    3057            0 :                     eprintln!(
    3058            0 :                         "{} secondary was scheduled in AZ {} which matches preference",
    3059            0 :                         shard.tenant_shard_id, attached_node_az
    3060            0 :                     );
    3061            0 :                     secondaries_in_wrong_az += 1;
    3062        12500 :                 }
    3063              :             }
    3064              : 
    3065           50 :             let mut violations = Vec::default();
    3066              : 
    3067           50 :             if attachments_in_wrong_az > 0 {
    3068            0 :                 violations.push(format!(
    3069            0 :                     "{attachments_in_wrong_az} attachments scheduled to the incorrect AZ"
    3070            0 :                 ));
    3071           50 :             }
    3072              : 
    3073           50 :             if secondaries_in_wrong_az > 0 {
    3074            0 :                 violations.push(format!(
    3075            0 :                     "{secondaries_in_wrong_az} secondaries scheduled to the incorrect AZ"
    3076            0 :                 ));
    3077           50 :             }
    3078              : 
    3079           50 :             eprintln!(
    3080           50 :                 "attachments_in_wrong_az={attachments_in_wrong_az} secondaries_in_wrong_az={secondaries_in_wrong_az}"
    3081              :             );
    3082              : 
    3083          250 :             for (node_id, stats) in &node_stats {
    3084          200 :                 let node_az = nodes.get(node_id).unwrap().get_availability_zone_id();
    3085          200 :                 let ideal_attachment_load = shards_per_az.get(node_az).unwrap() / 2;
    3086          200 :                 let allowed_attachment_load =
    3087          200 :                     (ideal_attachment_load - 1)..(ideal_attachment_load + 2);
    3088              : 
    3089          200 :                 if !allowed_attachment_load.contains(&stats.attachments) {
    3090            0 :                     violations.push(format!(
    3091            0 :                         "Found {} attachments on node {}, but expected {}",
    3092            0 :                         stats.attachments, node_id, ideal_attachment_load
    3093            0 :                     ));
    3094          200 :                 }
    3095              : 
    3096          200 :                 eprintln!(
    3097          200 :                     "{}: attachments={} secondaries={} ideal_attachment_load={}",
    3098              :                     node_id, stats.attachments, stats.secondaries, ideal_attachment_load
    3099              :                 );
    3100              :             }
    3101              : 
    3102           50 :             assert!(violations.is_empty(), "{violations:?}");
    3103              : 
    3104        12550 :             for (mut shard, _ctx) in shards {
    3105        12500 :                 shard.intent.clear(&mut scheduler);
    3106        12500 :             }
    3107              :         }
    3108            1 :         Ok(())
    3109            1 :     }
    3110              : 
    3111              :     /// Check how the shard's scheduling behaves when in PlacementPolicy::Secondary mode.
    3112              :     #[test]
    3113            1 :     fn tenant_secondary_scheduling() -> anyhow::Result<()> {
    3114            1 :         let az_a = AvailabilityZone("az-a".to_string());
    3115            1 :         let nodes = make_test_nodes(
    3116              :             3,
    3117            1 :             &[
    3118            1 :                 az_a.clone(),
    3119            1 :                 AvailabilityZone("az-b".to_string()),
    3120            1 :                 AvailabilityZone("az-c".to_string()),
    3121            1 :             ],
    3122              :         );
    3123              : 
    3124            1 :         let mut scheduler = Scheduler::new(nodes.values());
    3125            1 :         let mut context = ScheduleContext::default();
    3126              : 
    3127            1 :         let mut tenant_shard = make_test_tenant_shard(PlacementPolicy::Secondary);
    3128            1 :         tenant_shard.intent.preferred_az_id = Some(az_a.clone());
    3129            1 :         tenant_shard
    3130            1 :             .schedule(&mut scheduler, &mut context)
    3131            1 :             .expect("we have enough nodes, scheduling should work");
    3132            1 :         assert_eq!(tenant_shard.intent.secondary.len(), 1);
    3133            1 :         assert!(tenant_shard.intent.attached.is_none());
    3134              : 
    3135              :         // Should have scheduled into the preferred AZ
    3136            1 :         assert_eq!(
    3137            1 :             scheduler
    3138            1 :                 .get_node_az(&tenant_shard.intent.secondary[0])
    3139            1 :                 .as_ref(),
    3140            1 :             tenant_shard.preferred_az()
    3141              :         );
    3142              : 
    3143              :         // Optimizer should agree
    3144            1 :         assert_eq!(
    3145            1 :             tenant_shard.optimize_attachment(&mut scheduler, &context),
    3146              :             None
    3147              :         );
    3148            1 :         assert_eq!(
    3149            1 :             tenant_shard.optimize_secondary(&mut scheduler, &context),
    3150              :             None
    3151              :         );
    3152              : 
    3153              :         // Switch to PlacementPolicy::Attached
    3154            1 :         tenant_shard.policy = PlacementPolicy::Attached(1);
    3155            1 :         tenant_shard
    3156            1 :             .schedule(&mut scheduler, &mut context)
    3157            1 :             .expect("we have enough nodes, scheduling should work");
    3158            1 :         assert_eq!(tenant_shard.intent.secondary.len(), 1);
    3159            1 :         assert!(tenant_shard.intent.attached.is_some());
    3160              :         // Secondary should now be in non-preferred AZ
    3161            1 :         assert_ne!(
    3162            1 :             scheduler
    3163            1 :                 .get_node_az(&tenant_shard.intent.secondary[0])
    3164            1 :                 .as_ref(),
    3165            1 :             tenant_shard.preferred_az()
    3166              :         );
    3167              :         // Attached should be in preferred AZ
    3168            1 :         assert_eq!(
    3169            1 :             scheduler
    3170            1 :                 .get_node_az(&tenant_shard.intent.attached.unwrap())
    3171            1 :                 .as_ref(),
    3172            1 :             tenant_shard.preferred_az()
    3173              :         );
    3174              : 
    3175              :         // Optimizer should agree
    3176            1 :         assert_eq!(
    3177            1 :             tenant_shard.optimize_attachment(&mut scheduler, &context),
    3178              :             None
    3179              :         );
    3180            1 :         assert_eq!(
    3181            1 :             tenant_shard.optimize_secondary(&mut scheduler, &context),
    3182              :             None
    3183              :         );
    3184              : 
    3185              :         // Switch back to PlacementPolicy::Secondary
    3186            1 :         tenant_shard.policy = PlacementPolicy::Secondary;
    3187            1 :         tenant_shard
    3188            1 :             .schedule(&mut scheduler, &mut context)
    3189            1 :             .expect("we have enough nodes, scheduling should work");
    3190            1 :         assert_eq!(tenant_shard.intent.secondary.len(), 1);
    3191            1 :         assert!(tenant_shard.intent.attached.is_none());
    3192              :         // When we picked a location to keep, we should have kept the one in the preferred AZ
    3193            1 :         assert_eq!(
    3194            1 :             scheduler
    3195            1 :                 .get_node_az(&tenant_shard.intent.secondary[0])
    3196            1 :                 .as_ref(),
    3197            1 :             tenant_shard.preferred_az()
    3198              :         );
    3199              : 
    3200              :         // Optimizer should agree
    3201            1 :         assert_eq!(
    3202            1 :             tenant_shard.optimize_attachment(&mut scheduler, &context),
    3203              :             None
    3204              :         );
    3205            1 :         assert_eq!(
    3206            1 :             tenant_shard.optimize_secondary(&mut scheduler, &context),
    3207              :             None
    3208              :         );
    3209              : 
    3210            1 :         tenant_shard.intent.clear(&mut scheduler);
    3211              : 
    3212            1 :         Ok(())
    3213            1 :     }
    3214              : }
        

Generated by: LCOV version 2.1-beta