LCOV - code coverage report
Current view: top level - storage_controller/src - tenant_shard.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 69.0 % 1615 1115
Test Date: 2025-07-16 12:29:03 Functions: 54.5 % 121 66

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

Generated by: LCOV version 2.1-beta