LCOV - code coverage report
Current view: top level - storage_controller/src - tenant_shard.rs (source / functions) Coverage Total Hit
Test: 07bee600374ccd486c69370d0972d9035964fe68.info Lines: 71.1 % 1794 1276
Test Date: 2025-02-20 13:11:02 Functions: 46.3 % 136 63

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

Generated by: LCOV version 2.1-beta