LCOV - code coverage report
Current view: top level - storage_controller/src - service.rs (source / functions) Coverage Total Hit
Test: 2620485e474b48c32427149a5d91ef8fc2cd649e.info Lines: 5.5 % 5816 321
Test Date: 2025-05-01 22:50:11 Functions: 0.4 % 517 2

            Line data    Source code
       1              : pub mod chaos_injector;
       2              : mod context_iterator;
       3              : pub(crate) mod safekeeper_reconciler;
       4              : mod safekeeper_service;
       5              : 
       6              : use std::borrow::Cow;
       7              : use std::cmp::Ordering;
       8              : use std::collections::{BTreeMap, HashMap, HashSet};
       9              : use std::error::Error;
      10              : use std::num::NonZeroU32;
      11              : use std::ops::{Deref, DerefMut};
      12              : use std::path::PathBuf;
      13              : use std::str::FromStr;
      14              : use std::sync::{Arc, OnceLock};
      15              : use std::time::{Duration, Instant, SystemTime};
      16              : 
      17              : use anyhow::Context;
      18              : use context_iterator::TenantShardContextIterator;
      19              : use control_plane::storage_controller::{
      20              :     AttachHookRequest, AttachHookResponse, InspectRequest, InspectResponse,
      21              : };
      22              : use diesel::result::DatabaseErrorKind;
      23              : use futures::StreamExt;
      24              : use futures::stream::FuturesUnordered;
      25              : use http_utils::error::ApiError;
      26              : use hyper::Uri;
      27              : use itertools::Itertools;
      28              : use pageserver_api::controller_api::{
      29              :     AvailabilityZone, MetadataHealthRecord, MetadataHealthUpdateRequest, NodeAvailability,
      30              :     NodeRegisterRequest, NodeSchedulingPolicy, NodeShard, NodeShardResponse, PlacementPolicy,
      31              :     ShardSchedulingPolicy, ShardsPreferredAzsRequest, ShardsPreferredAzsResponse,
      32              :     TenantCreateRequest, TenantCreateResponse, TenantCreateResponseShard, TenantDescribeResponse,
      33              :     TenantDescribeResponseShard, TenantLocateResponse, TenantPolicyRequest,
      34              :     TenantShardMigrateRequest, TenantShardMigrateResponse,
      35              : };
      36              : use pageserver_api::models::{
      37              :     self, DetachBehavior, LocationConfig, LocationConfigListResponse, LocationConfigMode, LsnLease,
      38              :     PageserverUtilization, SecondaryProgress, ShardParameters, TenantConfig,
      39              :     TenantConfigPatchRequest, TenantConfigRequest, TenantLocationConfigRequest,
      40              :     TenantLocationConfigResponse, TenantShardLocation, TenantShardSplitRequest,
      41              :     TenantShardSplitResponse, TenantSorting, TenantTimeTravelRequest,
      42              :     TimelineArchivalConfigRequest, TimelineCreateRequest, TimelineCreateResponseStorcon,
      43              :     TimelineInfo, TimelineState, TopTenantShardItem, TopTenantShardsRequest,
      44              : };
      45              : use pageserver_api::shard::{
      46              :     DEFAULT_STRIPE_SIZE, ShardCount, ShardIdentity, ShardNumber, ShardStripeSize, TenantShardId,
      47              : };
      48              : use pageserver_api::upcall_api::{
      49              :     PutTimelineImportStatusRequest, ReAttachRequest, ReAttachResponse, ReAttachResponseTenant,
      50              :     ValidateRequest, ValidateResponse, ValidateResponseTenant,
      51              : };
      52              : use pageserver_client::{BlockUnblock, mgmt_api};
      53              : use reqwest::{Certificate, StatusCode};
      54              : use safekeeper_api::models::SafekeeperUtilization;
      55              : use safekeeper_reconciler::SafekeeperReconcilers;
      56              : use tokio::sync::TryAcquireError;
      57              : use tokio::sync::mpsc::error::TrySendError;
      58              : use tokio_util::sync::CancellationToken;
      59              : use tracing::{Instrument, debug, error, info, info_span, instrument, warn};
      60              : use utils::completion::Barrier;
      61              : use utils::generation::Generation;
      62              : use utils::id::{NodeId, TenantId, TimelineId};
      63              : use utils::lsn::Lsn;
      64              : use utils::sync::gate::{Gate, GateGuard};
      65              : use utils::{failpoint_support, pausable_failpoint};
      66              : 
      67              : use crate::background_node_operations::{
      68              :     Drain, Fill, MAX_RECONCILES_PER_OPERATION, Operation, OperationError, OperationHandler,
      69              : };
      70              : use crate::compute_hook::{self, ComputeHook, NotifyError};
      71              : use crate::drain_utils::{self, TenantShardDrain, TenantShardIterator};
      72              : use crate::heartbeater::{Heartbeater, PageserverState, SafekeeperState};
      73              : use crate::id_lock_map::{
      74              :     IdLockMap, TracingExclusiveGuard, trace_exclusive_lock, trace_shared_lock,
      75              : };
      76              : use crate::leadership::Leadership;
      77              : use crate::metrics;
      78              : use crate::node::{AvailabilityTransition, Node};
      79              : use crate::pageserver_client::PageserverClient;
      80              : use crate::peer_client::GlobalObservedState;
      81              : use crate::persistence::split_state::SplitState;
      82              : use crate::persistence::{
      83              :     AbortShardSplitStatus, ControllerPersistence, DatabaseError, DatabaseResult,
      84              :     MetadataHealthPersistence, Persistence, ShardGenerationState, TenantFilter,
      85              :     TenantShardPersistence,
      86              : };
      87              : use crate::reconciler::{
      88              :     ReconcileError, ReconcileUnits, ReconcilerConfig, ReconcilerConfigBuilder, ReconcilerPriority,
      89              :     attached_location_conf,
      90              : };
      91              : use crate::safekeeper::Safekeeper;
      92              : use crate::scheduler::{
      93              :     AttachedShardTag, MaySchedule, ScheduleContext, ScheduleError, ScheduleMode, Scheduler,
      94              : };
      95              : use crate::tenant_shard::{
      96              :     IntentState, MigrateAttachment, ObservedState, ObservedStateDelta, ObservedStateLocation,
      97              :     ReconcileNeeded, ReconcileResult, ReconcileWaitError, ReconcilerStatus, ReconcilerWaiter,
      98              :     ScheduleOptimization, ScheduleOptimizationAction, TenantShard,
      99              : };
     100              : use crate::timeline_import::{
     101              :     ShardImportStatuses, TimelineImport, TimelineImportState, UpcallClient,
     102              : };
     103              : 
     104              : const WAITER_FILL_DRAIN_POLL_TIMEOUT: Duration = Duration::from_millis(500);
     105              : 
     106              : // For operations that should be quick, like attaching a new tenant
     107              : const SHORT_RECONCILE_TIMEOUT: Duration = Duration::from_secs(5);
     108              : 
     109              : // For operations that might be slow, like migrating a tenant with
     110              : // some data in it.
     111              : pub const RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
     112              : 
     113              : // If we receive a call using Secondary mode initially, it will omit generation.  We will initialize
     114              : // tenant shards into this generation, and as long as it remains in this generation, we will accept
     115              : // input generation from future requests as authoritative.
     116              : const INITIAL_GENERATION: Generation = Generation::new(0);
     117              : 
     118              : /// How long [`Service::startup_reconcile`] is allowed to take before it should give
     119              : /// up on unresponsive pageservers and proceed.
     120              : pub(crate) const STARTUP_RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
     121              : 
     122              : /// How long a node may be unresponsive to heartbeats before we declare it offline.
     123              : /// This must be long enough to cover node restarts as well as normal operations: in future
     124              : pub const MAX_OFFLINE_INTERVAL_DEFAULT: Duration = Duration::from_secs(30);
     125              : 
     126              : /// How long a node may be unresponsive to heartbeats during start up before we declare it
     127              : /// offline.
     128              : ///
     129              : /// This is much more lenient than [`MAX_OFFLINE_INTERVAL_DEFAULT`] since the pageserver's
     130              : /// handling of the re-attach response may take a long time and blocks heartbeats from
     131              : /// being handled on the pageserver side.
     132              : pub const MAX_WARMING_UP_INTERVAL_DEFAULT: Duration = Duration::from_secs(300);
     133              : 
     134              : /// How often to send heartbeats to registered nodes?
     135              : pub const HEARTBEAT_INTERVAL_DEFAULT: Duration = Duration::from_secs(5);
     136              : 
     137              : /// How long is too long for a reconciliation?
     138              : pub const LONG_RECONCILE_THRESHOLD_DEFAULT: Duration = Duration::from_secs(120);
     139              : 
     140              : #[derive(Clone, strum_macros::Display)]
     141              : enum TenantOperations {
     142              :     Create,
     143              :     LocationConfig,
     144              :     ConfigSet,
     145              :     ConfigPatch,
     146              :     TimeTravelRemoteStorage,
     147              :     Delete,
     148              :     UpdatePolicy,
     149              :     ShardSplit,
     150              :     SecondaryDownload,
     151              :     TimelineCreate,
     152              :     TimelineDelete,
     153              :     AttachHook,
     154              :     TimelineArchivalConfig,
     155              :     TimelineDetachAncestor,
     156              :     TimelineGcBlockUnblock,
     157              :     DropDetached,
     158              :     DownloadHeatmapLayers,
     159              :     TimelineLsnLease,
     160              : }
     161              : 
     162              : #[derive(Clone, strum_macros::Display)]
     163              : enum NodeOperations {
     164              :     Register,
     165              :     Configure,
     166              :     Delete,
     167              : }
     168              : 
     169              : /// The leadership status for the storage controller process.
     170              : /// Allowed transitions are:
     171              : /// 1. Leader -> SteppedDown
     172              : /// 2. Candidate -> Leader
     173              : #[derive(
     174              :     Eq,
     175              :     PartialEq,
     176              :     Copy,
     177              :     Clone,
     178              :     strum_macros::Display,
     179            0 :     strum_macros::EnumIter,
     180              :     measured::FixedCardinalityLabel,
     181              : )]
     182              : #[strum(serialize_all = "snake_case")]
     183              : pub(crate) enum LeadershipStatus {
     184              :     /// This is the steady state where the storage controller can produce
     185              :     /// side effects in the cluster.
     186              :     Leader,
     187              :     /// We've been notified to step down by another candidate. No reconciliations
     188              :     /// take place in this state.
     189              :     SteppedDown,
     190              :     /// Initial state for a new storage controller instance. Will attempt to assume leadership.
     191              :     #[allow(unused)]
     192              :     Candidate,
     193              : }
     194              : 
     195              : pub const RECONCILER_CONCURRENCY_DEFAULT: usize = 128;
     196              : pub const PRIORITY_RECONCILER_CONCURRENCY_DEFAULT: usize = 256;
     197              : pub const SAFEKEEPER_RECONCILER_CONCURRENCY_DEFAULT: usize = 32;
     198              : 
     199              : // Depth of the channel used to enqueue shards for reconciliation when they can't do it immediately.
     200              : // This channel is finite-size to avoid using excessive memory if we get into a state where reconciles are finishing more slowly
     201              : // than they're being pushed onto the queue.
     202              : const MAX_DELAYED_RECONCILES: usize = 10000;
     203              : 
     204              : // Top level state available to all HTTP handlers
     205              : struct ServiceState {
     206              :     leadership_status: LeadershipStatus,
     207              : 
     208              :     tenants: BTreeMap<TenantShardId, TenantShard>,
     209              : 
     210              :     nodes: Arc<HashMap<NodeId, Node>>,
     211              : 
     212              :     safekeepers: Arc<HashMap<NodeId, Safekeeper>>,
     213              : 
     214              :     safekeeper_reconcilers: SafekeeperReconcilers,
     215              : 
     216              :     scheduler: Scheduler,
     217              : 
     218              :     /// Ongoing background operation on the cluster if any is running.
     219              :     /// Note that only one such operation may run at any given time,
     220              :     /// hence the type choice.
     221              :     ongoing_operation: Option<OperationHandler>,
     222              : 
     223              :     /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
     224              :     delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
     225              : }
     226              : 
     227              : /// Transform an error from a pageserver into an error to return to callers of a storage
     228              : /// controller API.
     229            0 : fn passthrough_api_error(node: &Node, e: mgmt_api::Error) -> ApiError {
     230            0 :     match e {
     231            0 :         mgmt_api::Error::SendRequest(e) => {
     232            0 :             // Presume errors sending requests are connectivity/availability issues
     233            0 :             ApiError::ResourceUnavailable(format!("{node} error sending request: {e}").into())
     234              :         }
     235            0 :         mgmt_api::Error::ReceiveErrorBody(str) => {
     236            0 :             // Presume errors receiving body are connectivity/availability issues
     237            0 :             ApiError::ResourceUnavailable(
     238            0 :                 format!("{node} error receiving error body: {str}").into(),
     239            0 :             )
     240              :         }
     241            0 :         mgmt_api::Error::ReceiveBody(err) if err.is_decode() => {
     242            0 :             // Return 500 for decoding errors.
     243            0 :             ApiError::InternalServerError(anyhow::Error::from(err).context("error decoding body"))
     244              :         }
     245            0 :         mgmt_api::Error::ReceiveBody(err) => {
     246            0 :             // Presume errors receiving body are connectivity/availability issues except for decoding errors
     247            0 :             let src_str = err.source().map(|e| e.to_string()).unwrap_or_default();
     248            0 :             ApiError::ResourceUnavailable(
     249            0 :                 format!("{node} error receiving error body: {err} {}", src_str).into(),
     250            0 :             )
     251              :         }
     252            0 :         mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, msg) => {
     253            0 :             ApiError::NotFound(anyhow::anyhow!(format!("{node}: {msg}")).into())
     254              :         }
     255            0 :         mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg) => {
     256            0 :             ApiError::ResourceUnavailable(format!("{node}: {msg}").into())
     257              :         }
     258            0 :         mgmt_api::Error::ApiError(status @ StatusCode::UNAUTHORIZED, msg)
     259            0 :         | mgmt_api::Error::ApiError(status @ StatusCode::FORBIDDEN, msg) => {
     260              :             // Auth errors talking to a pageserver are not auth errors for the caller: they are
     261              :             // internal server errors, showing that something is wrong with the pageserver or
     262              :             // storage controller's auth configuration.
     263            0 :             ApiError::InternalServerError(anyhow::anyhow!("{node} {status}: {msg}"))
     264              :         }
     265            0 :         mgmt_api::Error::ApiError(status @ StatusCode::TOO_MANY_REQUESTS, msg) => {
     266            0 :             // Pass through 429 errors: if pageserver is asking us to wait + retry, we in
     267            0 :             // turn ask our clients to wait + retry
     268            0 :             ApiError::Conflict(format!("{node} {status}: {status} {msg}"))
     269              :         }
     270            0 :         mgmt_api::Error::ApiError(status, msg) => {
     271            0 :             // Presume general case of pageserver API errors is that we tried to do something
     272            0 :             // that can't be done right now.
     273            0 :             ApiError::Conflict(format!("{node} {status}: {status} {msg}"))
     274              :         }
     275            0 :         mgmt_api::Error::Cancelled => ApiError::ShuttingDown,
     276            0 :         mgmt_api::Error::Timeout(e) => ApiError::Timeout(e.into()),
     277              :     }
     278            0 : }
     279              : 
     280              : impl ServiceState {
     281            0 :     fn new(
     282            0 :         nodes: HashMap<NodeId, Node>,
     283            0 :         safekeepers: HashMap<NodeId, Safekeeper>,
     284            0 :         tenants: BTreeMap<TenantShardId, TenantShard>,
     285            0 :         scheduler: Scheduler,
     286            0 :         delayed_reconcile_rx: tokio::sync::mpsc::Receiver<TenantShardId>,
     287            0 :         initial_leadership_status: LeadershipStatus,
     288            0 :         reconcilers_cancel: CancellationToken,
     289            0 :     ) -> Self {
     290            0 :         metrics::update_leadership_status(initial_leadership_status);
     291            0 : 
     292            0 :         Self {
     293            0 :             leadership_status: initial_leadership_status,
     294            0 :             tenants,
     295            0 :             nodes: Arc::new(nodes),
     296            0 :             safekeepers: Arc::new(safekeepers),
     297            0 :             safekeeper_reconcilers: SafekeeperReconcilers::new(reconcilers_cancel),
     298            0 :             scheduler,
     299            0 :             ongoing_operation: None,
     300            0 :             delayed_reconcile_rx,
     301            0 :         }
     302            0 :     }
     303              : 
     304            0 :     fn parts_mut(
     305            0 :         &mut self,
     306            0 :     ) -> (
     307            0 :         &mut Arc<HashMap<NodeId, Node>>,
     308            0 :         &mut BTreeMap<TenantShardId, TenantShard>,
     309            0 :         &mut Scheduler,
     310            0 :     ) {
     311            0 :         (&mut self.nodes, &mut self.tenants, &mut self.scheduler)
     312            0 :     }
     313              : 
     314              :     #[allow(clippy::type_complexity)]
     315            0 :     fn parts_mut_sk(
     316            0 :         &mut self,
     317            0 :     ) -> (
     318            0 :         &mut Arc<HashMap<NodeId, Node>>,
     319            0 :         &mut Arc<HashMap<NodeId, Safekeeper>>,
     320            0 :         &mut BTreeMap<TenantShardId, TenantShard>,
     321            0 :         &mut Scheduler,
     322            0 :     ) {
     323            0 :         (
     324            0 :             &mut self.nodes,
     325            0 :             &mut self.safekeepers,
     326            0 :             &mut self.tenants,
     327            0 :             &mut self.scheduler,
     328            0 :         )
     329            0 :     }
     330              : 
     331            0 :     fn get_leadership_status(&self) -> LeadershipStatus {
     332            0 :         self.leadership_status
     333            0 :     }
     334              : 
     335            0 :     fn step_down(&mut self) {
     336            0 :         self.leadership_status = LeadershipStatus::SteppedDown;
     337            0 :         metrics::update_leadership_status(self.leadership_status);
     338            0 :     }
     339              : 
     340            0 :     fn become_leader(&mut self) {
     341            0 :         self.leadership_status = LeadershipStatus::Leader;
     342            0 :         metrics::update_leadership_status(self.leadership_status);
     343            0 :     }
     344              : }
     345              : 
     346              : #[derive(Clone)]
     347              : pub struct Config {
     348              :     // All pageservers managed by one instance of this service must have
     349              :     // the same public key.  This JWT token will be used to authenticate
     350              :     // this service to the pageservers it manages.
     351              :     pub pageserver_jwt_token: Option<String>,
     352              : 
     353              :     // All safekeepers managed by one instance of this service must have
     354              :     // the same public key. This JWT token will be used to authenticate
     355              :     // this service to the safekeepers it manages.
     356              :     pub safekeeper_jwt_token: Option<String>,
     357              : 
     358              :     // This JWT token will be used to authenticate this service to the control plane.
     359              :     pub control_plane_jwt_token: Option<String>,
     360              : 
     361              :     // This JWT token will be used to authenticate with other storage controller instances
     362              :     pub peer_jwt_token: Option<String>,
     363              : 
     364              :     /// Prefix for storage API endpoints of the control plane. We use this prefix to compute
     365              :     /// URLs that we use to send pageserver and safekeeper attachment locations.
     366              :     /// If this is None, the compute hook will assume it is running in a test environment
     367              :     /// and try to invoke neon_local instead.
     368              :     pub control_plane_url: Option<String>,
     369              : 
     370              :     /// Grace period within which a pageserver does not respond to heartbeats, but is still
     371              :     /// considered active. Once the grace period elapses, the next heartbeat failure will
     372              :     /// mark the pagseserver offline.
     373              :     pub max_offline_interval: Duration,
     374              : 
     375              :     /// Extended grace period within which pageserver may not respond to heartbeats.
     376              :     /// This extended grace period kicks in after the node has been drained for restart
     377              :     /// and/or upon handling the re-attach request from a node.
     378              :     pub max_warming_up_interval: Duration,
     379              : 
     380              :     /// How many normal-priority Reconcilers may be spawned concurrently
     381              :     pub reconciler_concurrency: usize,
     382              : 
     383              :     /// How many high-priority Reconcilers may be spawned concurrently
     384              :     pub priority_reconciler_concurrency: usize,
     385              : 
     386              :     /// How many safekeeper reconciles may happen concurrently (per safekeeper)
     387              :     pub safekeeper_reconciler_concurrency: usize,
     388              : 
     389              :     /// How many API requests per second to allow per tenant, across all
     390              :     /// tenant-scoped API endpoints. Further API requests queue until ready.
     391              :     pub tenant_rate_limit: NonZeroU32,
     392              : 
     393              :     /// If a tenant shard's largest timeline (max_logical_size) exceeds this value, all tenant
     394              :     /// shards will be split in 2 until they fall below split_threshold (up to max_split_shards).
     395              :     ///
     396              :     /// This will greedily split into as many shards as necessary to fall below split_threshold, as
     397              :     /// powers of 2: if a tenant shard is 7 times larger than split_threshold, it will split into 8
     398              :     /// immediately, rather than first 2 then 4 then 8.
     399              :     ///
     400              :     /// None or 0 disables auto-splitting.
     401              :     ///
     402              :     /// TODO: consider using total logical size of all timelines instead.
     403              :     pub split_threshold: Option<u64>,
     404              : 
     405              :     /// The maximum number of shards a tenant can be split into during autosplits. Does not affect
     406              :     /// manual split requests. 0 or 1 disables autosplits, as we already have 1 shard.
     407              :     pub max_split_shards: u8,
     408              : 
     409              :     /// The size at which an unsharded tenant should initially split. Ingestion is significantly
     410              :     /// faster with multiple shards, so eagerly splitting below split_threshold will typically speed
     411              :     /// up initial ingestion of large tenants.
     412              :     ///
     413              :     /// This should be below split_threshold, but it is not required. If both split_threshold and
     414              :     /// initial_split_threshold qualify, the largest number of target shards will be used.
     415              :     ///
     416              :     /// Does not apply to already sharded tenants: changing initial_split_threshold or
     417              :     /// initial_split_shards is not retroactive for already-sharded tenants.
     418              :     ///
     419              :     /// None or 0 disables initial splits.
     420              :     pub initial_split_threshold: Option<u64>,
     421              : 
     422              :     /// The number of shards to split into when reaching initial_split_threshold. Will
     423              :     /// be clamped to max_split_shards.
     424              :     ///
     425              :     /// 0 or 1 disables initial splits. Has no effect if initial_split_threshold is disabled.
     426              :     pub initial_split_shards: u8,
     427              : 
     428              :     // TODO: make this cfg(feature  = "testing")
     429              :     pub neon_local_repo_dir: Option<PathBuf>,
     430              : 
     431              :     // Maximum acceptable download lag for the secondary location
     432              :     // while draining a node. If the secondary location is lagging
     433              :     // by more than the configured amount, then the secondary is not
     434              :     // upgraded to primary.
     435              :     pub max_secondary_lag_bytes: Option<u64>,
     436              : 
     437              :     pub heartbeat_interval: Duration,
     438              : 
     439              :     pub address_for_peers: Option<Uri>,
     440              : 
     441              :     pub start_as_candidate: bool,
     442              : 
     443              :     pub long_reconcile_threshold: Duration,
     444              : 
     445              :     pub use_https_pageserver_api: bool,
     446              : 
     447              :     pub use_https_safekeeper_api: bool,
     448              : 
     449              :     pub ssl_ca_certs: Vec<Certificate>,
     450              : 
     451              :     pub timelines_onto_safekeepers: bool,
     452              : 
     453              :     pub use_local_compute_notifications: bool,
     454              : }
     455              : 
     456              : impl From<DatabaseError> for ApiError {
     457            0 :     fn from(err: DatabaseError) -> ApiError {
     458            0 :         match err {
     459            0 :             DatabaseError::Query(e) => ApiError::InternalServerError(e.into()),
     460              :             // FIXME: ApiError doesn't have an Unavailable variant, but ShuttingDown maps to 503.
     461              :             DatabaseError::Connection(_) | DatabaseError::ConnectionPool(_) => {
     462            0 :                 ApiError::ShuttingDown
     463              :             }
     464            0 :             DatabaseError::Logical(reason) | DatabaseError::Migration(reason) => {
     465            0 :                 ApiError::InternalServerError(anyhow::anyhow!(reason))
     466              :             }
     467              :         }
     468            0 :     }
     469              : }
     470              : 
     471              : enum InitialShardScheduleOutcome {
     472              :     Scheduled(TenantCreateResponseShard),
     473              :     NotScheduled,
     474              :     ShardScheduleError(ScheduleError),
     475              : }
     476              : 
     477              : pub struct Service {
     478              :     inner: Arc<std::sync::RwLock<ServiceState>>,
     479              :     config: Config,
     480              :     persistence: Arc<Persistence>,
     481              :     compute_hook: Arc<ComputeHook>,
     482              :     result_tx: tokio::sync::mpsc::UnboundedSender<ReconcileResultRequest>,
     483              : 
     484              :     heartbeater_ps: Heartbeater<Node, PageserverState>,
     485              :     heartbeater_sk: Heartbeater<Safekeeper, SafekeeperState>,
     486              : 
     487              :     // Channel for background cleanup from failed operations that require cleanup, such as shard split
     488              :     abort_tx: tokio::sync::mpsc::UnboundedSender<TenantShardSplitAbort>,
     489              : 
     490              :     // Locking on a tenant granularity (covers all shards in the tenant):
     491              :     // - Take exclusively for rare operations that mutate the tenant's persistent state (e.g. create/delete/split)
     492              :     // - Take in shared mode for operations that need the set of shards to stay the same to complete reliably (e.g. timeline CRUD)
     493              :     tenant_op_locks: IdLockMap<TenantId, TenantOperations>,
     494              : 
     495              :     // Locking for node-mutating operations: take exclusively for operations that modify the node's persistent state, or
     496              :     // that transition it to/from Active.
     497              :     node_op_locks: IdLockMap<NodeId, NodeOperations>,
     498              : 
     499              :     // Limit how many Reconcilers we will spawn concurrently for normal-priority tasks such as background reconciliations
     500              :     // and reconciliation on startup.
     501              :     reconciler_concurrency: Arc<tokio::sync::Semaphore>,
     502              : 
     503              :     // Limit how many Reconcilers we will spawn concurrently for high-priority tasks such as tenant/timeline CRUD, which
     504              :     // a human user might be waiting for.
     505              :     priority_reconciler_concurrency: Arc<tokio::sync::Semaphore>,
     506              : 
     507              :     /// Queue of tenants who are waiting for concurrency limits to permit them to reconcile
     508              :     /// Send into this queue to promptly attempt to reconcile this shard next time units are available.
     509              :     ///
     510              :     /// Note that this state logically lives inside ServiceState, but carrying Sender here makes the code simpler
     511              :     /// by avoiding needing a &mut ref to something inside the ServiceState.  This could be optimized to
     512              :     /// use a VecDeque instead of a channel to reduce synchronization overhead, at the cost of some code complexity.
     513              :     delayed_reconcile_tx: tokio::sync::mpsc::Sender<TenantShardId>,
     514              : 
     515              :     // Process shutdown will fire this token
     516              :     cancel: CancellationToken,
     517              : 
     518              :     // Child token of [`Service::cancel`] used by reconcilers
     519              :     reconcilers_cancel: CancellationToken,
     520              : 
     521              :     // Background tasks will hold this gate
     522              :     gate: Gate,
     523              : 
     524              :     // Reconcilers background tasks will hold this gate
     525              :     reconcilers_gate: Gate,
     526              : 
     527              :     /// This waits for initial reconciliation with pageservers to complete.  Until this barrier
     528              :     /// passes, it isn't safe to do any actions that mutate tenants.
     529              :     pub(crate) startup_complete: Barrier,
     530              : 
     531              :     /// HTTP client with proper CA certs.
     532              :     http_client: reqwest::Client,
     533              : 
     534              :     /// Handle for the step down background task if one was ever requested
     535              :     step_down_barrier: OnceLock<tokio::sync::watch::Receiver<Option<GlobalObservedState>>>,
     536              : }
     537              : 
     538              : impl From<ReconcileWaitError> for ApiError {
     539            0 :     fn from(value: ReconcileWaitError) -> Self {
     540            0 :         match value {
     541            0 :             ReconcileWaitError::Shutdown => ApiError::ShuttingDown,
     542            0 :             e @ ReconcileWaitError::Timeout(_) => ApiError::Timeout(format!("{e}").into()),
     543            0 :             e @ ReconcileWaitError::Failed(..) => ApiError::InternalServerError(anyhow::anyhow!(e)),
     544              :         }
     545            0 :     }
     546              : }
     547              : 
     548              : impl From<OperationError> for ApiError {
     549            0 :     fn from(value: OperationError) -> Self {
     550            0 :         match value {
     551            0 :             OperationError::NodeStateChanged(err) | OperationError::FinalizeError(err) => {
     552            0 :                 ApiError::InternalServerError(anyhow::anyhow!(err))
     553              :             }
     554            0 :             OperationError::Cancelled => ApiError::Conflict("Operation was cancelled".into()),
     555              :         }
     556            0 :     }
     557              : }
     558              : 
     559              : #[allow(clippy::large_enum_variant)]
     560              : enum TenantCreateOrUpdate {
     561              :     Create(TenantCreateRequest),
     562              :     Update(Vec<ShardUpdate>),
     563              : }
     564              : 
     565              : struct ShardSplitParams {
     566              :     old_shard_count: ShardCount,
     567              :     new_shard_count: ShardCount,
     568              :     new_stripe_size: Option<ShardStripeSize>,
     569              :     targets: Vec<ShardSplitTarget>,
     570              :     policy: PlacementPolicy,
     571              :     config: TenantConfig,
     572              :     shard_ident: ShardIdentity,
     573              :     preferred_az_id: Option<AvailabilityZone>,
     574              : }
     575              : 
     576              : // When preparing for a shard split, we may either choose to proceed with the split,
     577              : // or find that the work is already done and return NoOp.
     578              : enum ShardSplitAction {
     579              :     Split(Box<ShardSplitParams>),
     580              :     NoOp(TenantShardSplitResponse),
     581              : }
     582              : 
     583              : // A parent shard which will be split
     584              : struct ShardSplitTarget {
     585              :     parent_id: TenantShardId,
     586              :     node: Node,
     587              :     child_ids: Vec<TenantShardId>,
     588              : }
     589              : 
     590              : /// When we tenant shard split operation fails, we may not be able to clean up immediately, because nodes
     591              : /// might not be available.  We therefore use a queue of abort operations processed in the background.
     592              : struct TenantShardSplitAbort {
     593              :     tenant_id: TenantId,
     594              :     /// The target values from the request that failed
     595              :     new_shard_count: ShardCount,
     596              :     new_stripe_size: Option<ShardStripeSize>,
     597              :     /// Until this abort op is complete, no other operations may be done on the tenant
     598              :     _tenant_lock: TracingExclusiveGuard<TenantOperations>,
     599              :     /// The reconciler gate for the duration of the split operation, and any included abort.
     600              :     _gate: GateGuard,
     601              : }
     602              : 
     603              : #[derive(thiserror::Error, Debug)]
     604              : enum TenantShardSplitAbortError {
     605              :     #[error(transparent)]
     606              :     Database(#[from] DatabaseError),
     607              :     #[error(transparent)]
     608              :     Remote(#[from] mgmt_api::Error),
     609              :     #[error("Unavailable")]
     610              :     Unavailable,
     611              : }
     612              : 
     613              : /// Inputs for computing a target shard count for a tenant.
     614              : struct ShardSplitInputs {
     615              :     /// Current shard count.
     616              :     shard_count: ShardCount,
     617              :     /// Total size of largest timeline summed across all shards.
     618              :     max_logical_size: u64,
     619              :     /// Size-based split threshold. Zero if size-based splits are disabled.
     620              :     split_threshold: u64,
     621              :     /// Upper bound on target shards. 0 or 1 disables splits.
     622              :     max_split_shards: u8,
     623              :     /// Initial split threshold. Zero if initial splits are disabled.
     624              :     initial_split_threshold: u64,
     625              :     /// Number of shards for initial splits. 0 or 1 disables initial splits.
     626              :     initial_split_shards: u8,
     627              : }
     628              : 
     629              : struct ShardUpdate {
     630              :     tenant_shard_id: TenantShardId,
     631              :     placement_policy: PlacementPolicy,
     632              :     tenant_config: TenantConfig,
     633              : 
     634              :     /// If this is None, generation is not updated.
     635              :     generation: Option<Generation>,
     636              : 
     637              :     /// If this is None, scheduling policy is not updated.
     638              :     scheduling_policy: Option<ShardSchedulingPolicy>,
     639              : }
     640              : 
     641              : enum StopReconciliationsReason {
     642              :     ShuttingDown,
     643              :     SteppingDown,
     644              : }
     645              : 
     646              : impl std::fmt::Display for StopReconciliationsReason {
     647            0 :     fn fmt(&self, writer: &mut std::fmt::Formatter) -> std::fmt::Result {
     648            0 :         let s = match self {
     649            0 :             Self::ShuttingDown => "Shutting down",
     650            0 :             Self::SteppingDown => "Stepping down",
     651              :         };
     652            0 :         write!(writer, "{}", s)
     653            0 :     }
     654              : }
     655              : 
     656              : pub(crate) enum ReconcileResultRequest {
     657              :     ReconcileResult(ReconcileResult),
     658              :     Stop,
     659              : }
     660              : 
     661              : #[derive(Clone)]
     662              : struct MutationLocation {
     663              :     node: Node,
     664              :     generation: Generation,
     665              : }
     666              : 
     667              : #[derive(Clone)]
     668              : struct ShardMutationLocations {
     669              :     latest: MutationLocation,
     670              :     other: Vec<MutationLocation>,
     671              : }
     672              : 
     673              : #[derive(Default, Clone)]
     674              : struct TenantMutationLocations(BTreeMap<TenantShardId, ShardMutationLocations>);
     675              : 
     676              : impl Service {
     677            0 :     pub fn get_config(&self) -> &Config {
     678            0 :         &self.config
     679            0 :     }
     680              : 
     681            0 :     pub fn get_http_client(&self) -> &reqwest::Client {
     682            0 :         &self.http_client
     683            0 :     }
     684              : 
     685              :     /// Called once on startup, this function attempts to contact all pageservers to build an up-to-date
     686              :     /// view of the world, and determine which pageservers are responsive.
     687              :     #[instrument(skip_all)]
     688              :     async fn startup_reconcile(
     689              :         self: &Arc<Service>,
     690              :         current_leader: Option<ControllerPersistence>,
     691              :         leader_step_down_state: Option<GlobalObservedState>,
     692              :         bg_compute_notify_result_tx: tokio::sync::mpsc::Sender<
     693              :             Result<(), (TenantShardId, NotifyError)>,
     694              :         >,
     695              :     ) {
     696              :         // Startup reconciliation does I/O to other services: whether they
     697              :         // are responsive or not, we should aim to finish within our deadline, because:
     698              :         // - If we don't, a k8s readiness hook watching /ready will kill us.
     699              :         // - While we're waiting for startup reconciliation, we are not fully
     700              :         //   available for end user operations like creating/deleting tenants and timelines.
     701              :         //
     702              :         // We set multiple deadlines to break up the time available between the phases of work: this is
     703              :         // arbitrary, but avoids a situation where the first phase could burn our entire timeout period.
     704              :         let start_at = Instant::now();
     705              :         let node_scan_deadline = start_at
     706              :             .checked_add(STARTUP_RECONCILE_TIMEOUT / 2)
     707              :             .expect("Reconcile timeout is a modest constant");
     708              : 
     709              :         let observed = if let Some(state) = leader_step_down_state {
     710              :             tracing::info!(
     711              :                 "Using observed state received from leader at {}",
     712              :                 current_leader.as_ref().unwrap().address
     713              :             );
     714              : 
     715              :             state
     716              :         } else {
     717              :             self.build_global_observed_state(node_scan_deadline).await
     718              :         };
     719              : 
     720              :         // Accumulate a list of any tenant locations that ought to be detached
     721              :         let mut cleanup = Vec::new();
     722              : 
     723              :         // Send initial heartbeat requests to all nodes loaded from the database
     724              :         let all_nodes = {
     725              :             let locked = self.inner.read().unwrap();
     726              :             locked.nodes.clone()
     727              :         };
     728              :         let (mut nodes_online, mut sks_online) =
     729              :             self.initial_heartbeat_round(all_nodes.keys()).await;
     730              : 
     731              :         // List of tenants for which we will attempt to notify compute of their location at startup
     732              :         let mut compute_notifications = Vec::new();
     733              : 
     734              :         // Populate intent and observed states for all tenants, based on reported state on pageservers
     735              :         tracing::info!("Populating tenant shards' states from initial pageserver scan...");
     736              :         let shard_count = {
     737              :             let mut locked = self.inner.write().unwrap();
     738              :             let (nodes, safekeepers, tenants, scheduler) = locked.parts_mut_sk();
     739              : 
     740              :             // Mark nodes online if they responded to us: nodes are offline by default after a restart.
     741              :             let mut new_nodes = (**nodes).clone();
     742              :             for (node_id, node) in new_nodes.iter_mut() {
     743              :                 if let Some(utilization) = nodes_online.remove(node_id) {
     744              :                     node.set_availability(NodeAvailability::Active(utilization));
     745              :                     scheduler.node_upsert(node);
     746              :                 }
     747              :             }
     748              :             *nodes = Arc::new(new_nodes);
     749              : 
     750              :             let mut new_sks = (**safekeepers).clone();
     751              :             for (node_id, node) in new_sks.iter_mut() {
     752              :                 if let Some((utilization, last_seen_at)) = sks_online.remove(node_id) {
     753              :                     node.set_availability(SafekeeperState::Available {
     754              :                         utilization,
     755              :                         last_seen_at,
     756              :                     });
     757              :                 }
     758              :             }
     759              :             *safekeepers = Arc::new(new_sks);
     760              : 
     761              :             for (tenant_shard_id, observed_state) in observed.0 {
     762              :                 let Some(tenant_shard) = tenants.get_mut(&tenant_shard_id) else {
     763              :                     for node_id in observed_state.locations.keys() {
     764              :                         cleanup.push((tenant_shard_id, *node_id));
     765              :                     }
     766              : 
     767              :                     continue;
     768              :                 };
     769              : 
     770              :                 tenant_shard.observed = observed_state;
     771              :             }
     772              : 
     773              :             // Populate each tenant's intent state
     774              :             let mut schedule_context = ScheduleContext::default();
     775              :             for (tenant_shard_id, tenant_shard) in tenants.iter_mut() {
     776              :                 if tenant_shard_id.shard_number == ShardNumber(0) {
     777              :                     // Reset scheduling context each time we advance to the next Tenant
     778              :                     schedule_context = ScheduleContext::default();
     779              :                 }
     780              : 
     781              :                 tenant_shard.intent_from_observed(scheduler);
     782              :                 if let Err(e) = tenant_shard.schedule(scheduler, &mut schedule_context) {
     783              :                     // Non-fatal error: we are unable to properly schedule the tenant, perhaps because
     784              :                     // not enough pageservers are available.  The tenant may well still be available
     785              :                     // to clients.
     786              :                     tracing::error!("Failed to schedule tenant {tenant_shard_id} at startup: {e}");
     787              :                 } else {
     788              :                     // If we're both intending and observed to be attached at a particular node, we will
     789              :                     // emit a compute notification for this. In the case where our observed state does not
     790              :                     // yet match our intent, we will eventually reconcile, and that will emit a compute notification.
     791              :                     if let Some(attached_at) = tenant_shard.stably_attached() {
     792              :                         compute_notifications.push(compute_hook::ShardUpdate {
     793              :                             tenant_shard_id: *tenant_shard_id,
     794              :                             node_id: attached_at,
     795              :                             stripe_size: tenant_shard.shard.stripe_size,
     796              :                             preferred_az: tenant_shard
     797              :                                 .preferred_az()
     798            0 :                                 .map(|az| Cow::Owned(az.clone())),
     799              :                         });
     800              :                     }
     801              :                 }
     802              :             }
     803              : 
     804              :             tenants.len()
     805              :         };
     806              : 
     807              :         // Before making any obeservable changes to the cluster, persist self
     808              :         // as leader in database and memory.
     809              :         let leadership = Leadership::new(
     810              :             self.persistence.clone(),
     811              :             self.config.clone(),
     812              :             self.cancel.child_token(),
     813              :         );
     814              : 
     815              :         if let Err(e) = leadership.become_leader(current_leader).await {
     816              :             tracing::error!("Failed to persist self as leader: {e}. Aborting start-up ...");
     817              :             std::process::exit(1);
     818              :         }
     819              : 
     820              :         let safekeepers = self.inner.read().unwrap().safekeepers.clone();
     821              :         let sk_schedule_requests =
     822              :             match safekeeper_reconciler::load_schedule_requests(self, &safekeepers).await {
     823              :                 Ok(v) => v,
     824              :                 Err(e) => {
     825              :                     tracing::warn!(
     826              :                         "Failed to load safekeeper pending ops at startup: {e}." // Don't abort for now: " Aborting start-up..."
     827              :                     );
     828              :                     // std::process::exit(1);
     829              :                     Vec::new()
     830              :                 }
     831              :             };
     832              : 
     833              :         {
     834              :             let mut locked = self.inner.write().unwrap();
     835              :             locked.become_leader();
     836              : 
     837              :             for (sk_id, _sk) in locked.safekeepers.clone().iter() {
     838              :                 locked.safekeeper_reconcilers.start_reconciler(*sk_id, self);
     839              :             }
     840              : 
     841              :             locked
     842              :                 .safekeeper_reconcilers
     843              :                 .schedule_request_vec(sk_schedule_requests);
     844              :         }
     845              : 
     846              :         // TODO: if any tenant's intent now differs from its loaded generation_pageserver, we should clear that
     847              :         // generation_pageserver in the database.
     848              : 
     849              :         // Emit compute hook notifications for all tenants which are already stably attached.  Other tenants
     850              :         // will emit compute hook notifications when they reconcile.
     851              :         //
     852              :         // Ordering: our calls to notify_background synchronously establish a relative order for these notifications vs. any later
     853              :         // calls into the ComputeHook for the same tenant: we can leave these to run to completion in the background and any later
     854              :         // calls will be correctly ordered wrt these.
     855              :         //
     856              :         // Concurrency: we call notify_background for all tenants, which will create O(N) tokio tasks, but almost all of them
     857              :         // will just wait on the ComputeHook::API_CONCURRENCY semaphore immediately, so very cheap until they get that semaphore
     858              :         // unit and start doing I/O.
     859              :         tracing::info!(
     860              :             "Sending {} compute notifications",
     861              :             compute_notifications.len()
     862              :         );
     863              :         self.compute_hook.notify_background(
     864              :             compute_notifications,
     865              :             bg_compute_notify_result_tx.clone(),
     866              :             &self.cancel,
     867              :         );
     868              : 
     869              :         // Finally, now that the service is up and running, launch reconcile operations for any tenants
     870              :         // which require it: under normal circumstances this should only include tenants that were in some
     871              :         // transient state before we restarted, or any tenants whose compute hooks failed above.
     872              :         tracing::info!("Checking for shards in need of reconciliation...");
     873              :         let reconcile_tasks = self.reconcile_all();
     874              :         // We will not wait for these reconciliation tasks to run here: we're now done with startup and
     875              :         // normal operations may proceed.
     876              : 
     877              :         // Clean up any tenants that were found on pageservers but are not known to us.  Do this in the
     878              :         // background because it does not need to complete in order to proceed with other work.
     879              :         if !cleanup.is_empty() {
     880              :             tracing::info!("Cleaning up {} locations in the background", cleanup.len());
     881              :             tokio::task::spawn({
     882              :                 let cleanup_self = self.clone();
     883            0 :                 async move { cleanup_self.cleanup_locations(cleanup).await }
     884              :             });
     885              :         }
     886              : 
     887              :         // Reconcile the timeline imports:
     888              :         // 1. Mark each tenant shard of tenants with an importing timeline as importing.
     889              :         // 2. Finalize the completed imports in the background. This handles the case where
     890              :         //    the previous storage controller instance shut down whilst finalizing imports.
     891              :         let imports = self.persistence.list_timeline_imports().await;
     892              :         match imports {
     893              :             Ok(mut imports) => {
     894              :                 {
     895              :                     let mut locked = self.inner.write().unwrap();
     896              :                     for import in &imports {
     897              :                         locked
     898              :                             .tenants
     899              :                             .range_mut(TenantShardId::tenant_range(import.tenant_id))
     900            0 :                             .for_each(|(_id, shard)| {
     901            0 :                                 shard.importing = TimelineImportState::Importing
     902            0 :                             });
     903              :                     }
     904              :                 }
     905              : 
     906            0 :                 imports.retain(|import| import.is_complete());
     907              :                 tokio::task::spawn({
     908              :                     let finalize_imports_self = self.clone();
     909            0 :                     async move {
     910            0 :                         finalize_imports_self
     911            0 :                             .finalize_timeline_imports(imports)
     912            0 :                             .await
     913            0 :                     }
     914              :                 });
     915              :             }
     916              :             Err(err) => {
     917              :                 tracing::error!("Could not retrieve completed imports from database: {err}");
     918              :             }
     919              :         }
     920              : 
     921              :         tracing::info!(
     922              :             "Startup complete, spawned {reconcile_tasks} reconciliation tasks ({shard_count} shards total)"
     923              :         );
     924              :     }
     925              : 
     926            0 :     async fn initial_heartbeat_round<'a>(
     927            0 :         &self,
     928            0 :         node_ids: impl Iterator<Item = &'a NodeId>,
     929            0 :     ) -> (
     930            0 :         HashMap<NodeId, PageserverUtilization>,
     931            0 :         HashMap<NodeId, (SafekeeperUtilization, Instant)>,
     932            0 :     ) {
     933            0 :         assert!(!self.startup_complete.is_ready());
     934              : 
     935            0 :         let all_nodes = {
     936            0 :             let locked = self.inner.read().unwrap();
     937            0 :             locked.nodes.clone()
     938            0 :         };
     939            0 : 
     940            0 :         let mut nodes_to_heartbeat = HashMap::new();
     941            0 :         for node_id in node_ids {
     942            0 :             match all_nodes.get(node_id) {
     943            0 :                 Some(node) => {
     944            0 :                     nodes_to_heartbeat.insert(*node_id, node.clone());
     945            0 :                 }
     946              :                 None => {
     947            0 :                     tracing::warn!("Node {node_id} was removed during start-up");
     948              :                 }
     949              :             }
     950              :         }
     951              : 
     952            0 :         let all_sks = {
     953            0 :             let locked = self.inner.read().unwrap();
     954            0 :             locked.safekeepers.clone()
     955            0 :         };
     956            0 : 
     957            0 :         tracing::info!("Sending initial heartbeats...");
     958            0 :         let (res_ps, res_sk) = tokio::join!(
     959            0 :             self.heartbeater_ps.heartbeat(Arc::new(nodes_to_heartbeat)),
     960            0 :             self.heartbeater_sk.heartbeat(all_sks)
     961            0 :         );
     962              : 
     963            0 :         let mut online_nodes = HashMap::new();
     964            0 :         if let Ok(deltas) = res_ps {
     965            0 :             for (node_id, status) in deltas.0 {
     966            0 :                 match status {
     967            0 :                     PageserverState::Available { utilization, .. } => {
     968            0 :                         online_nodes.insert(node_id, utilization);
     969            0 :                     }
     970            0 :                     PageserverState::Offline => {}
     971              :                     PageserverState::WarmingUp { .. } => {
     972            0 :                         unreachable!("Nodes are never marked warming-up during startup reconcile")
     973              :                     }
     974              :                 }
     975              :             }
     976            0 :         }
     977              : 
     978            0 :         let mut online_sks = HashMap::new();
     979            0 :         if let Ok(deltas) = res_sk {
     980            0 :             for (node_id, status) in deltas.0 {
     981            0 :                 match status {
     982              :                     SafekeeperState::Available {
     983            0 :                         utilization,
     984            0 :                         last_seen_at,
     985            0 :                     } => {
     986            0 :                         online_sks.insert(node_id, (utilization, last_seen_at));
     987            0 :                     }
     988            0 :                     SafekeeperState::Offline => {}
     989              :                 }
     990              :             }
     991            0 :         }
     992              : 
     993            0 :         (online_nodes, online_sks)
     994            0 :     }
     995              : 
     996              :     /// Used during [`Self::startup_reconcile`]: issue GETs to all nodes concurrently, with a deadline.
     997              :     ///
     998              :     /// The result includes only nodes which responded within the deadline
     999            0 :     async fn scan_node_locations(
    1000            0 :         &self,
    1001            0 :         deadline: Instant,
    1002            0 :     ) -> HashMap<NodeId, LocationConfigListResponse> {
    1003            0 :         let nodes = {
    1004            0 :             let locked = self.inner.read().unwrap();
    1005            0 :             locked.nodes.clone()
    1006            0 :         };
    1007            0 : 
    1008            0 :         let mut node_results = HashMap::new();
    1009            0 : 
    1010            0 :         let mut node_list_futs = FuturesUnordered::new();
    1011            0 : 
    1012            0 :         tracing::info!("Scanning shards on {} nodes...", nodes.len());
    1013            0 :         for node in nodes.values() {
    1014            0 :             node_list_futs.push({
    1015            0 :                 async move {
    1016            0 :                     tracing::info!("Scanning shards on node {node}...");
    1017            0 :                     let timeout = Duration::from_secs(5);
    1018            0 :                     let response = node
    1019            0 :                         .with_client_retries(
    1020            0 :                             |client| async move { client.list_location_config().await },
    1021            0 :                             &self.http_client,
    1022            0 :                             &self.config.pageserver_jwt_token,
    1023            0 :                             1,
    1024            0 :                             5,
    1025            0 :                             timeout,
    1026            0 :                             &self.cancel,
    1027            0 :                         )
    1028            0 :                         .await;
    1029            0 :                     (node.get_id(), response)
    1030            0 :                 }
    1031            0 :             });
    1032            0 :         }
    1033              : 
    1034              :         loop {
    1035            0 :             let (node_id, result) = tokio::select! {
    1036            0 :                 next = node_list_futs.next() => {
    1037            0 :                     match next {
    1038            0 :                         Some(result) => result,
    1039              :                         None =>{
    1040              :                             // We got results for all our nodes
    1041            0 :                             break;
    1042              :                         }
    1043              : 
    1044              :                     }
    1045              :                 },
    1046            0 :                 _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
    1047              :                     // Give up waiting for anyone who hasn't responded: we will yield the results that we have
    1048            0 :                     tracing::info!("Reached deadline while waiting for nodes to respond to location listing requests");
    1049            0 :                     break;
    1050              :                 }
    1051              :             };
    1052              : 
    1053            0 :             let Some(list_response) = result else {
    1054            0 :                 tracing::info!("Shutdown during startup_reconcile");
    1055            0 :                 break;
    1056              :             };
    1057              : 
    1058            0 :             match list_response {
    1059            0 :                 Err(e) => {
    1060            0 :                     tracing::warn!("Could not scan node {} ({e})", node_id);
    1061              :                 }
    1062            0 :                 Ok(listing) => {
    1063            0 :                     node_results.insert(node_id, listing);
    1064            0 :                 }
    1065              :             }
    1066              :         }
    1067              : 
    1068            0 :         node_results
    1069            0 :     }
    1070              : 
    1071            0 :     async fn build_global_observed_state(&self, deadline: Instant) -> GlobalObservedState {
    1072            0 :         let node_listings = self.scan_node_locations(deadline).await;
    1073            0 :         let mut observed = GlobalObservedState::default();
    1074              : 
    1075            0 :         for (node_id, location_confs) in node_listings {
    1076            0 :             tracing::info!(
    1077            0 :                 "Received {} shard statuses from pageserver {}",
    1078            0 :                 location_confs.tenant_shards.len(),
    1079              :                 node_id
    1080              :             );
    1081              : 
    1082            0 :             for (tid, location_conf) in location_confs.tenant_shards {
    1083            0 :                 let entry = observed.0.entry(tid).or_default();
    1084            0 :                 entry.locations.insert(
    1085            0 :                     node_id,
    1086            0 :                     ObservedStateLocation {
    1087            0 :                         conf: location_conf,
    1088            0 :                     },
    1089            0 :                 );
    1090            0 :             }
    1091              :         }
    1092              : 
    1093            0 :         observed
    1094            0 :     }
    1095              : 
    1096              :     /// Used during [`Self::startup_reconcile`]: detach a list of unknown-to-us tenants from pageservers.
    1097              :     ///
    1098              :     /// This is safe to run in the background, because if we don't have this TenantShardId in our map of
    1099              :     /// tenants, then it is probably something incompletely deleted before: we will not fight with any
    1100              :     /// other task trying to attach it.
    1101              :     #[instrument(skip_all)]
    1102              :     async fn cleanup_locations(&self, cleanup: Vec<(TenantShardId, NodeId)>) {
    1103              :         let nodes = self.inner.read().unwrap().nodes.clone();
    1104              : 
    1105              :         for (tenant_shard_id, node_id) in cleanup {
    1106              :             // A node reported a tenant_shard_id which is unknown to us: detach it.
    1107              :             let Some(node) = nodes.get(&node_id) else {
    1108              :                 // This is legitimate; we run in the background and [`Self::startup_reconcile`] might have identified
    1109              :                 // a location to clean up on a node that has since been removed.
    1110              :                 tracing::info!(
    1111              :                     "Not cleaning up location {node_id}/{tenant_shard_id}: node not found"
    1112              :                 );
    1113              :                 continue;
    1114              :             };
    1115              : 
    1116              :             if self.cancel.is_cancelled() {
    1117              :                 break;
    1118              :             }
    1119              : 
    1120              :             let client = PageserverClient::new(
    1121              :                 node.get_id(),
    1122              :                 self.http_client.clone(),
    1123              :                 node.base_url(),
    1124              :                 self.config.pageserver_jwt_token.as_deref(),
    1125              :             );
    1126              :             match client
    1127              :                 .location_config(
    1128              :                     tenant_shard_id,
    1129              :                     LocationConfig {
    1130              :                         mode: LocationConfigMode::Detached,
    1131              :                         generation: None,
    1132              :                         secondary_conf: None,
    1133              :                         shard_number: tenant_shard_id.shard_number.0,
    1134              :                         shard_count: tenant_shard_id.shard_count.literal(),
    1135              :                         shard_stripe_size: 0,
    1136              :                         tenant_conf: models::TenantConfig::default(),
    1137              :                     },
    1138              :                     None,
    1139              :                     false,
    1140              :                 )
    1141              :                 .await
    1142              :             {
    1143              :                 Ok(()) => {
    1144              :                     tracing::info!(
    1145              :                         "Detached unknown shard {tenant_shard_id} on pageserver {node_id}"
    1146              :                     );
    1147              :                 }
    1148              :                 Err(e) => {
    1149              :                     // Non-fatal error: leaving a tenant shard behind that we are not managing shouldn't
    1150              :                     // break anything.
    1151              :                     tracing::error!(
    1152              :                         "Failed to detach unknown shard {tenant_shard_id} on pageserver {node_id}: {e}"
    1153              :                     );
    1154              :                 }
    1155              :             }
    1156              :         }
    1157              :     }
    1158              : 
    1159              :     /// Long running background task that periodically wakes up and looks for shards that need
    1160              :     /// reconciliation.  Reconciliation is fallible, so any reconciliation tasks that fail during
    1161              :     /// e.g. a tenant create/attach/migrate must eventually be retried: this task is responsible
    1162              :     /// for those retries.
    1163              :     #[instrument(skip_all)]
    1164              :     async fn background_reconcile(self: &Arc<Self>) {
    1165              :         self.startup_complete.clone().wait().await;
    1166              : 
    1167              :         const BACKGROUND_RECONCILE_PERIOD: Duration = Duration::from_secs(20);
    1168              :         let mut interval = tokio::time::interval(BACKGROUND_RECONCILE_PERIOD);
    1169              :         while !self.reconcilers_cancel.is_cancelled() {
    1170              :             tokio::select! {
    1171              :               _ = interval.tick() => {
    1172              :                 let reconciles_spawned = self.reconcile_all();
    1173              :                 if reconciles_spawned == 0 {
    1174              :                     // Run optimizer only when we didn't find any other work to do
    1175              :                     self.optimize_all().await;
    1176              :                 }
    1177              :                 // Always attempt autosplits. Sharding is crucial for bulk ingest performance, so we
    1178              :                 // must be responsive when new projects begin ingesting and reach the threshold.
    1179              :                 self.autosplit_tenants().await;
    1180              :             }
    1181              :               _ = self.reconcilers_cancel.cancelled() => return
    1182              :             }
    1183              :         }
    1184              :     }
    1185              :     /// Heartbeat all storage nodes once in a while.
    1186              :     #[instrument(skip_all)]
    1187              :     async fn spawn_heartbeat_driver(&self) {
    1188              :         self.startup_complete.clone().wait().await;
    1189              : 
    1190              :         let mut interval = tokio::time::interval(self.config.heartbeat_interval);
    1191              :         while !self.cancel.is_cancelled() {
    1192              :             tokio::select! {
    1193              :               _ = interval.tick() => { }
    1194              :               _ = self.cancel.cancelled() => return
    1195              :             };
    1196              : 
    1197              :             let nodes = {
    1198              :                 let locked = self.inner.read().unwrap();
    1199              :                 locked.nodes.clone()
    1200              :             };
    1201              : 
    1202              :             let safekeepers = {
    1203              :                 let locked = self.inner.read().unwrap();
    1204              :                 locked.safekeepers.clone()
    1205              :             };
    1206              : 
    1207              :             let (res_ps, res_sk) = tokio::join!(
    1208              :                 self.heartbeater_ps.heartbeat(nodes),
    1209              :                 self.heartbeater_sk.heartbeat(safekeepers)
    1210              :             );
    1211              : 
    1212              :             if let Ok(deltas) = res_ps {
    1213              :                 let mut to_handle = Vec::default();
    1214              : 
    1215              :                 for (node_id, state) in deltas.0 {
    1216              :                     let new_availability = match state {
    1217              :                         PageserverState::Available { utilization, .. } => {
    1218              :                             NodeAvailability::Active(utilization)
    1219              :                         }
    1220              :                         PageserverState::WarmingUp { started_at } => {
    1221              :                             NodeAvailability::WarmingUp(started_at)
    1222              :                         }
    1223              :                         PageserverState::Offline => {
    1224              :                             // The node might have been placed in the WarmingUp state
    1225              :                             // while the heartbeat round was on-going. Hence, filter out
    1226              :                             // offline transitions for WarmingUp nodes that are still within
    1227              :                             // their grace period.
    1228              :                             if let Ok(NodeAvailability::WarmingUp(started_at)) = self
    1229              :                                 .get_node(node_id)
    1230              :                                 .await
    1231              :                                 .as_ref()
    1232            0 :                                 .map(|n| n.get_availability())
    1233              :                             {
    1234              :                                 let now = Instant::now();
    1235              :                                 if now - *started_at >= self.config.max_warming_up_interval {
    1236              :                                     NodeAvailability::Offline
    1237              :                                 } else {
    1238              :                                     NodeAvailability::WarmingUp(*started_at)
    1239              :                                 }
    1240              :                             } else {
    1241              :                                 NodeAvailability::Offline
    1242              :                             }
    1243              :                         }
    1244              :                     };
    1245              : 
    1246              :                     let node_lock = trace_exclusive_lock(
    1247              :                         &self.node_op_locks,
    1248              :                         node_id,
    1249              :                         NodeOperations::Configure,
    1250              :                     )
    1251              :                     .await;
    1252              : 
    1253              :                     pausable_failpoint!("heartbeat-pre-node-state-configure");
    1254              : 
    1255              :                     // This is the code path for geniune availability transitions (i.e node
    1256              :                     // goes unavailable and/or comes back online).
    1257              :                     let res = self
    1258              :                         .node_state_configure(node_id, Some(new_availability), None, &node_lock)
    1259              :                         .await;
    1260              : 
    1261              :                     match res {
    1262              :                         Ok(transition) => {
    1263              :                             // Keep hold of the lock until the availability transitions
    1264              :                             // have been handled in
    1265              :                             // [`Service::handle_node_availability_transitions`] in order avoid
    1266              :                             // racing with [`Service::external_node_configure`].
    1267              :                             to_handle.push((node_id, node_lock, transition));
    1268              :                         }
    1269              :                         Err(ApiError::NotFound(_)) => {
    1270              :                             // This should be rare, but legitimate since the heartbeats are done
    1271              :                             // on a snapshot of the nodes.
    1272              :                             tracing::info!("Node {} was not found after heartbeat round", node_id);
    1273              :                         }
    1274              :                         Err(ApiError::ShuttingDown) => {
    1275              :                             // No-op: we're shutting down, no need to try and update any nodes' statuses
    1276              :                         }
    1277              :                         Err(err) => {
    1278              :                             // Transition to active involves reconciling: if a node responds to a heartbeat then
    1279              :                             // becomes unavailable again, we may get an error here.
    1280              :                             tracing::error!(
    1281              :                                 "Failed to update node state {} after heartbeat round: {}",
    1282              :                                 node_id,
    1283              :                                 err
    1284              :                             );
    1285              :                         }
    1286              :                     }
    1287              :                 }
    1288              : 
    1289              :                 // We collected all the transitions above and now we handle them.
    1290              :                 let res = self.handle_node_availability_transitions(to_handle).await;
    1291              :                 if let Err(errs) = res {
    1292              :                     for (node_id, err) in errs {
    1293              :                         match err {
    1294              :                             ApiError::NotFound(_) => {
    1295              :                                 // This should be rare, but legitimate since the heartbeats are done
    1296              :                                 // on a snapshot of the nodes.
    1297              :                                 tracing::info!(
    1298              :                                     "Node {} was not found after heartbeat round",
    1299              :                                     node_id
    1300              :                                 );
    1301              :                             }
    1302              :                             err => {
    1303              :                                 tracing::error!(
    1304              :                                     "Failed to handle availability transition for {} after heartbeat round: {}",
    1305              :                                     node_id,
    1306              :                                     err
    1307              :                                 );
    1308              :                             }
    1309              :                         }
    1310              :                     }
    1311              :                 }
    1312              :             }
    1313              :             if let Ok(deltas) = res_sk {
    1314              :                 let mut locked = self.inner.write().unwrap();
    1315              :                 let mut safekeepers = (*locked.safekeepers).clone();
    1316              :                 for (id, state) in deltas.0 {
    1317              :                     let Some(sk) = safekeepers.get_mut(&id) else {
    1318              :                         tracing::info!(
    1319              :                             "Couldn't update safekeeper safekeeper state for id {id} from heartbeat={state:?}"
    1320              :                         );
    1321              :                         continue;
    1322              :                     };
    1323              :                     sk.set_availability(state);
    1324              :                 }
    1325              :                 locked.safekeepers = Arc::new(safekeepers);
    1326              :             }
    1327              :         }
    1328              :     }
    1329              : 
    1330              :     /// Apply the contents of a [`ReconcileResult`] to our in-memory state: if the reconciliation
    1331              :     /// was successful and intent hasn't changed since the Reconciler was spawned, this will update
    1332              :     /// the observed state of the tenant such that subsequent calls to [`TenantShard::get_reconcile_needed`]
    1333              :     /// will indicate that reconciliation is not needed.
    1334              :     #[instrument(skip_all, fields(
    1335              :         seq=%result.sequence,
    1336              :         tenant_id=%result.tenant_shard_id.tenant_id,
    1337              :         shard_id=%result.tenant_shard_id.shard_slug(),
    1338              :     ))]
    1339              :     fn process_result(&self, result: ReconcileResult) {
    1340              :         let mut locked = self.inner.write().unwrap();
    1341              :         let (nodes, tenants, _scheduler) = locked.parts_mut();
    1342              :         let Some(tenant) = tenants.get_mut(&result.tenant_shard_id) else {
    1343              :             // A reconciliation result might race with removing a tenant: drop results for
    1344              :             // tenants that aren't in our map.
    1345              :             return;
    1346              :         };
    1347              : 
    1348              :         // Usually generation should only be updated via this path, so the max() isn't
    1349              :         // needed, but it is used to handle out-of-band updates via. e.g. test hook.
    1350              :         tenant.generation = std::cmp::max(tenant.generation, result.generation);
    1351              : 
    1352              :         // If the reconciler signals that it failed to notify compute, set this state on
    1353              :         // the shard so that a future [`TenantShard::maybe_reconcile`] will try again.
    1354              :         tenant.pending_compute_notification = result.pending_compute_notification;
    1355              : 
    1356              :         // Let the TenantShard know it is idle.
    1357              :         tenant.reconcile_complete(result.sequence);
    1358              : 
    1359              :         // In case a node was deleted while this reconcile is in flight, filter it out of the update we will
    1360              :         // make to the tenant
    1361            0 :         let deltas = result.observed_deltas.into_iter().flat_map(|delta| {
    1362              :             // In case a node was deleted while this reconcile is in flight, filter it out of the update we will
    1363              :             // make to the tenant
    1364            0 :             let node = nodes.get(delta.node_id())?;
    1365              : 
    1366            0 :             if node.is_available() {
    1367            0 :                 return Some(delta);
    1368            0 :             }
    1369            0 : 
    1370            0 :             // In case a node became unavailable concurrently with the reconcile, observed
    1371            0 :             // locations on it are now uncertain. By convention, set them to None in order
    1372            0 :             // for them to get refreshed when the node comes back online.
    1373            0 :             Some(ObservedStateDelta::Upsert(Box::new((
    1374            0 :                 node.get_id(),
    1375            0 :                 ObservedStateLocation { conf: None },
    1376            0 :             ))))
    1377            0 :         });
    1378              : 
    1379              :         match result.result {
    1380              :             Ok(()) => {
    1381              :                 tenant.apply_observed_deltas(deltas);
    1382              :                 tenant.waiter.advance(result.sequence);
    1383              :             }
    1384              :             Err(e) => {
    1385              :                 match e {
    1386              :                     ReconcileError::Cancel => {
    1387              :                         tracing::info!("Reconciler was cancelled");
    1388              :                     }
    1389              :                     ReconcileError::Remote(mgmt_api::Error::Cancelled) => {
    1390              :                         // This might be due to the reconciler getting cancelled, or it might
    1391              :                         // be due to the `Node` being marked offline.
    1392              :                         tracing::info!("Reconciler cancelled during pageserver API call");
    1393              :                     }
    1394              :                     _ => {
    1395              :                         tracing::warn!("Reconcile error: {}", e);
    1396              :                     }
    1397              :                 }
    1398              : 
    1399              :                 // Ordering: populate last_error before advancing error_seq,
    1400              :                 // so that waiters will see the correct error after waiting.
    1401              :                 tenant.set_last_error(result.sequence, e);
    1402              : 
    1403              :                 // Skip deletions on reconcile failures
    1404              :                 let upsert_deltas =
    1405            0 :                     deltas.filter(|delta| matches!(delta, ObservedStateDelta::Upsert(_)));
    1406              :                 tenant.apply_observed_deltas(upsert_deltas);
    1407              :             }
    1408              :         }
    1409              : 
    1410              :         // If we just finished detaching all shards for a tenant, it might be time to drop it from memory.
    1411              :         if tenant.policy == PlacementPolicy::Detached {
    1412              :             // We may only drop a tenant from memory while holding the exclusive lock on the tenant ID: this protects us
    1413              :             // from concurrent execution wrt a request handler that might expect the tenant to remain in memory for the
    1414              :             // duration of the request.
    1415              :             let guard = self.tenant_op_locks.try_exclusive(
    1416              :                 tenant.tenant_shard_id.tenant_id,
    1417              :                 TenantOperations::DropDetached,
    1418              :             );
    1419              :             if let Some(guard) = guard {
    1420              :                 self.maybe_drop_tenant(tenant.tenant_shard_id.tenant_id, &mut locked, &guard);
    1421              :             }
    1422              :         }
    1423              : 
    1424              :         // Maybe some other work can proceed now that this job finished.
    1425              :         //
    1426              :         // Only bother with this if we have some semaphore units available in the normal-priority semaphore (these
    1427              :         // reconciles are scheduled at `[ReconcilerPriority::Normal]`).
    1428              :         if self.reconciler_concurrency.available_permits() > 0 {
    1429              :             while let Ok(tenant_shard_id) = locked.delayed_reconcile_rx.try_recv() {
    1430              :                 let (nodes, tenants, _scheduler) = locked.parts_mut();
    1431              :                 if let Some(shard) = tenants.get_mut(&tenant_shard_id) {
    1432              :                     shard.delayed_reconcile = false;
    1433              :                     self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal);
    1434              :                 }
    1435              : 
    1436              :                 if self.reconciler_concurrency.available_permits() == 0 {
    1437              :                     break;
    1438              :                 }
    1439              :             }
    1440              :         }
    1441              :     }
    1442              : 
    1443            0 :     async fn process_results(
    1444            0 :         &self,
    1445            0 :         mut result_rx: tokio::sync::mpsc::UnboundedReceiver<ReconcileResultRequest>,
    1446            0 :         mut bg_compute_hook_result_rx: tokio::sync::mpsc::Receiver<
    1447            0 :             Result<(), (TenantShardId, NotifyError)>,
    1448            0 :         >,
    1449            0 :     ) {
    1450              :         loop {
    1451              :             // Wait for the next result, or for cancellation
    1452            0 :             tokio::select! {
    1453            0 :                 r = result_rx.recv() => {
    1454            0 :                     match r {
    1455            0 :                         Some(ReconcileResultRequest::ReconcileResult(result)) => {self.process_result(result);},
    1456            0 :                         None | Some(ReconcileResultRequest::Stop) => {break;}
    1457              :                     }
    1458              :                 }
    1459            0 :                 _ = async{
    1460            0 :                     match bg_compute_hook_result_rx.recv().await {
    1461            0 :                         Some(result) => {
    1462            0 :                             if let Err((tenant_shard_id, notify_error)) = result {
    1463            0 :                                 tracing::warn!("Marking shard {tenant_shard_id} for notification retry, due to error {notify_error}");
    1464            0 :                                 let mut locked = self.inner.write().unwrap();
    1465            0 :                                 if let Some(shard) = locked.tenants.get_mut(&tenant_shard_id) {
    1466            0 :                                     shard.pending_compute_notification = true;
    1467            0 :                                 }
    1468              : 
    1469            0 :                             }
    1470              :                         },
    1471              :                         None => {
    1472              :                             // This channel is dead, but we don't want to terminate the outer loop{}: just wait for shutdown
    1473            0 :                             self.cancel.cancelled().await;
    1474              :                         }
    1475              :                     }
    1476            0 :                 } => {},
    1477            0 :                 _ = self.cancel.cancelled() => {
    1478            0 :                     break;
    1479              :                 }
    1480              :             };
    1481              :         }
    1482            0 :     }
    1483              : 
    1484            0 :     async fn process_aborts(
    1485            0 :         &self,
    1486            0 :         mut abort_rx: tokio::sync::mpsc::UnboundedReceiver<TenantShardSplitAbort>,
    1487            0 :     ) {
    1488              :         loop {
    1489              :             // Wait for the next result, or for cancellation
    1490            0 :             let op = tokio::select! {
    1491            0 :                 r = abort_rx.recv() => {
    1492            0 :                     match r {
    1493            0 :                         Some(op) => {op},
    1494            0 :                         None => {break;}
    1495              :                     }
    1496              :                 }
    1497            0 :                 _ = self.cancel.cancelled() => {
    1498            0 :                     break;
    1499              :                 }
    1500              :             };
    1501              : 
    1502              :             // Retry until shutdown: we must keep this request object alive until it is properly
    1503              :             // processed, as it holds a lock guard that prevents other operations trying to do things
    1504              :             // to the tenant while it is in a weird part-split state.
    1505            0 :             while !self.reconcilers_cancel.is_cancelled() {
    1506            0 :                 match self.abort_tenant_shard_split(&op).await {
    1507            0 :                     Ok(_) => break,
    1508            0 :                     Err(e) => {
    1509            0 :                         tracing::warn!(
    1510            0 :                             "Failed to abort shard split on {}, will retry: {e}",
    1511              :                             op.tenant_id
    1512              :                         );
    1513              : 
    1514              :                         // If a node is unavailable, we hope that it has been properly marked Offline
    1515              :                         // when we retry, so that the abort op will succeed.  If the abort op is failing
    1516              :                         // for some other reason, we will keep retrying forever, or until a human notices
    1517              :                         // and does something about it (either fixing a pageserver or restarting the controller).
    1518            0 :                         tokio::time::timeout(
    1519            0 :                             Duration::from_secs(5),
    1520            0 :                             self.reconcilers_cancel.cancelled(),
    1521            0 :                         )
    1522            0 :                         .await
    1523            0 :                         .ok();
    1524              :                     }
    1525              :                 }
    1526              :             }
    1527              :         }
    1528            0 :     }
    1529              : 
    1530            0 :     pub async fn spawn(config: Config, persistence: Arc<Persistence>) -> anyhow::Result<Arc<Self>> {
    1531            0 :         let (result_tx, result_rx) = tokio::sync::mpsc::unbounded_channel();
    1532            0 :         let (abort_tx, abort_rx) = tokio::sync::mpsc::unbounded_channel();
    1533            0 : 
    1534            0 :         let leadership_cancel = CancellationToken::new();
    1535            0 :         let leadership = Leadership::new(persistence.clone(), config.clone(), leadership_cancel);
    1536            0 :         let (leader, leader_step_down_state) = leadership.step_down_current_leader().await?;
    1537              : 
    1538              :         // Apply the migrations **after** the current leader has stepped down
    1539              :         // (or we've given up waiting for it), but **before** reading from the
    1540              :         // database. The only exception is reading the current leader before
    1541              :         // migrating.
    1542            0 :         persistence.migration_run().await?;
    1543              : 
    1544            0 :         tracing::info!("Loading nodes from database...");
    1545            0 :         let nodes = persistence
    1546            0 :             .list_nodes()
    1547            0 :             .await?
    1548            0 :             .into_iter()
    1549            0 :             .map(|x| Node::from_persistent(x, config.use_https_pageserver_api))
    1550            0 :             .collect::<anyhow::Result<Vec<Node>>>()?;
    1551            0 :         let nodes: HashMap<NodeId, Node> = nodes.into_iter().map(|n| (n.get_id(), n)).collect();
    1552            0 :         tracing::info!("Loaded {} nodes from database.", nodes.len());
    1553            0 :         metrics::METRICS_REGISTRY
    1554            0 :             .metrics_group
    1555            0 :             .storage_controller_pageserver_nodes
    1556            0 :             .set(nodes.len() as i64);
    1557            0 :         metrics::METRICS_REGISTRY
    1558            0 :             .metrics_group
    1559            0 :             .storage_controller_https_pageserver_nodes
    1560            0 :             .set(nodes.values().filter(|n| n.has_https_port()).count() as i64);
    1561            0 : 
    1562            0 :         tracing::info!("Loading safekeepers from database...");
    1563            0 :         let safekeepers = persistence
    1564            0 :             .list_safekeepers()
    1565            0 :             .await?
    1566            0 :             .into_iter()
    1567            0 :             .map(|skp| {
    1568            0 :                 Safekeeper::from_persistence(
    1569            0 :                     skp,
    1570            0 :                     CancellationToken::new(),
    1571            0 :                     config.use_https_safekeeper_api,
    1572            0 :                 )
    1573            0 :             })
    1574            0 :             .collect::<anyhow::Result<Vec<_>>>()?;
    1575            0 :         let safekeepers: HashMap<NodeId, Safekeeper> =
    1576            0 :             safekeepers.into_iter().map(|n| (n.get_id(), n)).collect();
    1577            0 :         tracing::info!("Loaded {} safekeepers from database.", safekeepers.len());
    1578            0 :         metrics::METRICS_REGISTRY
    1579            0 :             .metrics_group
    1580            0 :             .storage_controller_safekeeper_nodes
    1581            0 :             .set(safekeepers.len() as i64);
    1582            0 :         metrics::METRICS_REGISTRY
    1583            0 :             .metrics_group
    1584            0 :             .storage_controller_https_safekeeper_nodes
    1585            0 :             .set(safekeepers.values().filter(|s| s.has_https_port()).count() as i64);
    1586            0 : 
    1587            0 :         tracing::info!("Loading shards from database...");
    1588            0 :         let mut tenant_shard_persistence = persistence.load_active_tenant_shards().await?;
    1589            0 :         tracing::info!(
    1590            0 :             "Loaded {} shards from database.",
    1591            0 :             tenant_shard_persistence.len()
    1592              :         );
    1593              : 
    1594              :         // If any shard splits were in progress, reset the database state to abort them
    1595            0 :         let mut tenant_shard_count_min_max: HashMap<TenantId, (ShardCount, ShardCount)> =
    1596            0 :             HashMap::new();
    1597            0 :         for tsp in &mut tenant_shard_persistence {
    1598            0 :             let shard = tsp.get_shard_identity()?;
    1599            0 :             let tenant_shard_id = tsp.get_tenant_shard_id()?;
    1600            0 :             let entry = tenant_shard_count_min_max
    1601            0 :                 .entry(tenant_shard_id.tenant_id)
    1602            0 :                 .or_insert_with(|| (shard.count, shard.count));
    1603            0 :             entry.0 = std::cmp::min(entry.0, shard.count);
    1604            0 :             entry.1 = std::cmp::max(entry.1, shard.count);
    1605            0 :         }
    1606              : 
    1607            0 :         for (tenant_id, (count_min, count_max)) in tenant_shard_count_min_max {
    1608            0 :             if count_min != count_max {
    1609              :                 // Aborting the split in the database and dropping the child shards is sufficient: the reconciliation in
    1610              :                 // [`Self::startup_reconcile`] will implicitly drop the child shards on remote pageservers, or they'll
    1611              :                 // be dropped later in [`Self::node_activate_reconcile`] if it isn't available right now.
    1612            0 :                 tracing::info!("Aborting shard split {tenant_id} {count_min:?} -> {count_max:?}");
    1613            0 :                 let abort_status = persistence.abort_shard_split(tenant_id, count_max).await?;
    1614              : 
    1615              :                 // We may never see the Complete status here: if the split was complete, we wouldn't have
    1616              :                 // identified this tenant has having mismatching min/max counts.
    1617            0 :                 assert!(matches!(abort_status, AbortShardSplitStatus::Aborted));
    1618              : 
    1619              :                 // Clear the splitting status in-memory, to reflect that we just aborted in the database
    1620            0 :                 tenant_shard_persistence.iter_mut().for_each(|tsp| {
    1621            0 :                     // Set idle split state on those shards that we will retain.
    1622            0 :                     let tsp_tenant_id = TenantId::from_str(tsp.tenant_id.as_str()).unwrap();
    1623            0 :                     if tsp_tenant_id == tenant_id
    1624            0 :                         && tsp.get_shard_identity().unwrap().count == count_min
    1625            0 :                     {
    1626            0 :                         tsp.splitting = SplitState::Idle;
    1627            0 :                     } else if tsp_tenant_id == tenant_id {
    1628              :                         // Leave the splitting state on the child shards: this will be used next to
    1629              :                         // drop them.
    1630            0 :                         tracing::info!(
    1631            0 :                             "Shard {tsp_tenant_id} will be dropped after shard split abort",
    1632              :                         );
    1633            0 :                     }
    1634            0 :                 });
    1635            0 : 
    1636            0 :                 // Drop shards for this tenant which we didn't just mark idle (i.e. child shards of the aborted split)
    1637            0 :                 tenant_shard_persistence.retain(|tsp| {
    1638            0 :                     TenantId::from_str(tsp.tenant_id.as_str()).unwrap() != tenant_id
    1639            0 :                         || tsp.splitting == SplitState::Idle
    1640            0 :                 });
    1641            0 :             }
    1642              :         }
    1643              : 
    1644            0 :         let mut tenants = BTreeMap::new();
    1645            0 : 
    1646            0 :         let mut scheduler = Scheduler::new(nodes.values());
    1647              : 
    1648              :         #[cfg(feature = "testing")]
    1649              :         {
    1650              :             use pageserver_api::controller_api::AvailabilityZone;
    1651              : 
    1652              :             // Hack: insert scheduler state for all nodes referenced by shards, as compatibility
    1653              :             // tests only store the shards, not the nodes.  The nodes will be loaded shortly
    1654              :             // after when pageservers start up and register.
    1655            0 :             let mut node_ids = HashSet::new();
    1656            0 :             for tsp in &tenant_shard_persistence {
    1657            0 :                 if let Some(node_id) = tsp.generation_pageserver {
    1658            0 :                     node_ids.insert(node_id);
    1659            0 :                 }
    1660              :             }
    1661            0 :             for node_id in node_ids {
    1662            0 :                 tracing::info!("Creating node {} in scheduler for tests", node_id);
    1663            0 :                 let node = Node::new(
    1664            0 :                     NodeId(node_id as u64),
    1665            0 :                     "".to_string(),
    1666            0 :                     123,
    1667            0 :                     None,
    1668            0 :                     "".to_string(),
    1669            0 :                     123,
    1670            0 :                     AvailabilityZone("test_az".to_string()),
    1671            0 :                     false,
    1672            0 :                 )
    1673            0 :                 .unwrap();
    1674            0 : 
    1675            0 :                 scheduler.node_upsert(&node);
    1676              :             }
    1677              :         }
    1678            0 :         for tsp in tenant_shard_persistence {
    1679            0 :             let tenant_shard_id = tsp.get_tenant_shard_id()?;
    1680              : 
    1681              :             // We will populate intent properly later in [`Self::startup_reconcile`], initially populate
    1682              :             // it with what we can infer: the node for which a generation was most recently issued.
    1683            0 :             let mut intent = IntentState::new(
    1684            0 :                 tsp.preferred_az_id
    1685            0 :                     .as_ref()
    1686            0 :                     .map(|az| AvailabilityZone(az.clone())),
    1687            0 :             );
    1688            0 :             if let Some(generation_pageserver) = tsp.generation_pageserver.map(|n| NodeId(n as u64))
    1689              :             {
    1690            0 :                 if nodes.contains_key(&generation_pageserver) {
    1691            0 :                     intent.set_attached(&mut scheduler, Some(generation_pageserver));
    1692            0 :                 } else {
    1693              :                     // If a node was removed before being completely drained, it is legal for it to leave behind a `generation_pageserver` referring
    1694              :                     // to a non-existent node, because node deletion doesn't block on completing the reconciliations that will issue new generations
    1695              :                     // on different pageservers.
    1696            0 :                     tracing::warn!(
    1697            0 :                         "Tenant shard {tenant_shard_id} references non-existent node {generation_pageserver} in database, will be rescheduled"
    1698              :                     );
    1699              :                 }
    1700            0 :             }
    1701            0 :             let new_tenant = TenantShard::from_persistent(tsp, intent)?;
    1702              : 
    1703            0 :             tenants.insert(tenant_shard_id, new_tenant);
    1704              :         }
    1705              : 
    1706            0 :         let (startup_completion, startup_complete) = utils::completion::channel();
    1707            0 : 
    1708            0 :         // This channel is continuously consumed by process_results, so doesn't need to be very large.
    1709            0 :         let (bg_compute_notify_result_tx, bg_compute_notify_result_rx) =
    1710            0 :             tokio::sync::mpsc::channel(512);
    1711            0 : 
    1712            0 :         let (delayed_reconcile_tx, delayed_reconcile_rx) =
    1713            0 :             tokio::sync::mpsc::channel(MAX_DELAYED_RECONCILES);
    1714            0 : 
    1715            0 :         let cancel = CancellationToken::new();
    1716            0 :         let reconcilers_cancel = cancel.child_token();
    1717            0 : 
    1718            0 :         let mut http_client = reqwest::Client::builder();
    1719            0 :         // We intentionally disable the connection pool, so every request will create its own TCP connection.
    1720            0 :         // It's especially important for heartbeaters to notice more network problems.
    1721            0 :         //
    1722            0 :         // TODO: It makes sense to use this client only in heartbeaters and create a second one with
    1723            0 :         // connection pooling for everything else. But reqwest::Client may create a connection without
    1724            0 :         // ever using it (it uses hyper's Client under the hood):
    1725            0 :         // https://github.com/hyperium/hyper-util/blob/d51318df3461d40e5f5e5ca163cb3905ac960209/src/client/legacy/client.rs#L415
    1726            0 :         //
    1727            0 :         // Because of a bug in hyper0::Connection::graceful_shutdown such connections hang during
    1728            0 :         // graceful server shutdown: https://github.com/hyperium/hyper/issues/2730
    1729            0 :         //
    1730            0 :         // The bug has been fixed in hyper v1, so keep alive may be enabled only after we migrate to hyper1.
    1731            0 :         http_client = http_client.pool_max_idle_per_host(0);
    1732            0 :         for ssl_ca_cert in &config.ssl_ca_certs {
    1733            0 :             http_client = http_client.add_root_certificate(ssl_ca_cert.clone());
    1734            0 :         }
    1735            0 :         let http_client = http_client.build()?;
    1736              : 
    1737            0 :         let heartbeater_ps = Heartbeater::new(
    1738            0 :             http_client.clone(),
    1739            0 :             config.pageserver_jwt_token.clone(),
    1740            0 :             config.max_offline_interval,
    1741            0 :             config.max_warming_up_interval,
    1742            0 :             cancel.clone(),
    1743            0 :         );
    1744            0 : 
    1745            0 :         let heartbeater_sk = Heartbeater::new(
    1746            0 :             http_client.clone(),
    1747            0 :             config.safekeeper_jwt_token.clone(),
    1748            0 :             config.max_offline_interval,
    1749            0 :             config.max_warming_up_interval,
    1750            0 :             cancel.clone(),
    1751            0 :         );
    1752              : 
    1753            0 :         let initial_leadership_status = if config.start_as_candidate {
    1754            0 :             LeadershipStatus::Candidate
    1755              :         } else {
    1756            0 :             LeadershipStatus::Leader
    1757              :         };
    1758              : 
    1759            0 :         let this = Arc::new(Self {
    1760            0 :             inner: Arc::new(std::sync::RwLock::new(ServiceState::new(
    1761            0 :                 nodes,
    1762            0 :                 safekeepers,
    1763            0 :                 tenants,
    1764            0 :                 scheduler,
    1765            0 :                 delayed_reconcile_rx,
    1766            0 :                 initial_leadership_status,
    1767            0 :                 reconcilers_cancel.clone(),
    1768            0 :             ))),
    1769            0 :             config: config.clone(),
    1770            0 :             persistence,
    1771            0 :             compute_hook: Arc::new(ComputeHook::new(config.clone())?),
    1772            0 :             result_tx,
    1773            0 :             heartbeater_ps,
    1774            0 :             heartbeater_sk,
    1775            0 :             reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
    1776            0 :                 config.reconciler_concurrency,
    1777            0 :             )),
    1778            0 :             priority_reconciler_concurrency: Arc::new(tokio::sync::Semaphore::new(
    1779            0 :                 config.priority_reconciler_concurrency,
    1780            0 :             )),
    1781            0 :             delayed_reconcile_tx,
    1782            0 :             abort_tx,
    1783            0 :             startup_complete: startup_complete.clone(),
    1784            0 :             cancel,
    1785            0 :             reconcilers_cancel,
    1786            0 :             gate: Gate::default(),
    1787            0 :             reconcilers_gate: Gate::default(),
    1788            0 :             tenant_op_locks: Default::default(),
    1789            0 :             node_op_locks: Default::default(),
    1790            0 :             http_client,
    1791            0 :             step_down_barrier: Default::default(),
    1792            0 :         });
    1793            0 : 
    1794            0 :         let result_task_this = this.clone();
    1795            0 :         tokio::task::spawn(async move {
    1796              :             // Block shutdown until we're done (we must respect self.cancel)
    1797            0 :             if let Ok(_gate) = result_task_this.gate.enter() {
    1798            0 :                 result_task_this
    1799            0 :                     .process_results(result_rx, bg_compute_notify_result_rx)
    1800            0 :                     .await
    1801            0 :             }
    1802            0 :         });
    1803            0 : 
    1804            0 :         tokio::task::spawn({
    1805            0 :             let this = this.clone();
    1806            0 :             async move {
    1807              :                 // Block shutdown until we're done (we must respect self.cancel)
    1808            0 :                 if let Ok(_gate) = this.gate.enter() {
    1809            0 :                     this.process_aborts(abort_rx).await
    1810            0 :                 }
    1811            0 :             }
    1812            0 :         });
    1813            0 : 
    1814            0 :         tokio::task::spawn({
    1815            0 :             let this = this.clone();
    1816            0 :             async move {
    1817            0 :                 if let Ok(_gate) = this.gate.enter() {
    1818              :                     loop {
    1819            0 :                         tokio::select! {
    1820            0 :                             _ = this.cancel.cancelled() => {
    1821            0 :                                 break;
    1822              :                             },
    1823            0 :                             _ = tokio::time::sleep(Duration::from_secs(60)) => {}
    1824            0 :                         };
    1825            0 :                         this.tenant_op_locks.housekeeping();
    1826              :                     }
    1827            0 :                 }
    1828            0 :             }
    1829            0 :         });
    1830            0 : 
    1831            0 :         tokio::task::spawn({
    1832            0 :             let this = this.clone();
    1833            0 :             // We will block the [`Service::startup_complete`] barrier until [`Self::startup_reconcile`]
    1834            0 :             // is done.
    1835            0 :             let startup_completion = startup_completion.clone();
    1836            0 :             async move {
    1837              :                 // Block shutdown until we're done (we must respect self.cancel)
    1838            0 :                 let Ok(_gate) = this.gate.enter() else {
    1839            0 :                     return;
    1840              :                 };
    1841              : 
    1842            0 :                 this.startup_reconcile(leader, leader_step_down_state, bg_compute_notify_result_tx)
    1843            0 :                     .await;
    1844              : 
    1845            0 :                 drop(startup_completion);
    1846            0 :             }
    1847            0 :         });
    1848            0 : 
    1849            0 :         tokio::task::spawn({
    1850            0 :             let this = this.clone();
    1851            0 :             let startup_complete = startup_complete.clone();
    1852            0 :             async move {
    1853            0 :                 startup_complete.wait().await;
    1854            0 :                 this.background_reconcile().await;
    1855            0 :             }
    1856            0 :         });
    1857            0 : 
    1858            0 :         tokio::task::spawn({
    1859            0 :             let this = this.clone();
    1860            0 :             let startup_complete = startup_complete.clone();
    1861            0 :             async move {
    1862            0 :                 startup_complete.wait().await;
    1863            0 :                 this.spawn_heartbeat_driver().await;
    1864            0 :             }
    1865            0 :         });
    1866            0 : 
    1867            0 :         Ok(this)
    1868            0 :     }
    1869              : 
    1870            0 :     pub(crate) async fn attach_hook(
    1871            0 :         &self,
    1872            0 :         attach_req: AttachHookRequest,
    1873            0 :     ) -> anyhow::Result<AttachHookResponse> {
    1874            0 :         let _tenant_lock = trace_exclusive_lock(
    1875            0 :             &self.tenant_op_locks,
    1876            0 :             attach_req.tenant_shard_id.tenant_id,
    1877            0 :             TenantOperations::AttachHook,
    1878            0 :         )
    1879            0 :         .await;
    1880              : 
    1881              :         // This is a test hook.  To enable using it on tenants that were created directly with
    1882              :         // the pageserver API (not via this service), we will auto-create any missing tenant
    1883              :         // shards with default state.
    1884            0 :         let insert = {
    1885            0 :             match self
    1886            0 :                 .maybe_load_tenant(attach_req.tenant_shard_id.tenant_id, &_tenant_lock)
    1887            0 :                 .await
    1888              :             {
    1889            0 :                 Ok(_) => false,
    1890            0 :                 Err(ApiError::NotFound(_)) => true,
    1891            0 :                 Err(e) => return Err(e.into()),
    1892              :             }
    1893              :         };
    1894              : 
    1895            0 :         if insert {
    1896            0 :             let config = attach_req.config.clone().unwrap_or_default();
    1897            0 :             let tsp = TenantShardPersistence {
    1898            0 :                 tenant_id: attach_req.tenant_shard_id.tenant_id.to_string(),
    1899            0 :                 shard_number: attach_req.tenant_shard_id.shard_number.0 as i32,
    1900            0 :                 shard_count: attach_req.tenant_shard_id.shard_count.literal() as i32,
    1901            0 :                 shard_stripe_size: 0,
    1902            0 :                 generation: attach_req.generation_override.or(Some(0)),
    1903            0 :                 generation_pageserver: None,
    1904            0 :                 placement_policy: serde_json::to_string(&PlacementPolicy::Attached(0)).unwrap(),
    1905            0 :                 config: serde_json::to_string(&config).unwrap(),
    1906            0 :                 splitting: SplitState::default(),
    1907            0 :                 scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
    1908            0 :                     .unwrap(),
    1909            0 :                 preferred_az_id: None,
    1910            0 :             };
    1911            0 : 
    1912            0 :             match self.persistence.insert_tenant_shards(vec![tsp]).await {
    1913            0 :                 Err(e) => match e {
    1914              :                     DatabaseError::Query(diesel::result::Error::DatabaseError(
    1915              :                         DatabaseErrorKind::UniqueViolation,
    1916              :                         _,
    1917              :                     )) => {
    1918            0 :                         tracing::info!(
    1919            0 :                             "Raced with another request to insert tenant {}",
    1920              :                             attach_req.tenant_shard_id
    1921              :                         )
    1922              :                     }
    1923            0 :                     _ => return Err(e.into()),
    1924              :                 },
    1925              :                 Ok(()) => {
    1926            0 :                     tracing::info!("Inserted shard {} in database", attach_req.tenant_shard_id);
    1927              : 
    1928            0 :                     let mut shard = TenantShard::new(
    1929            0 :                         attach_req.tenant_shard_id,
    1930            0 :                         ShardIdentity::unsharded(),
    1931            0 :                         PlacementPolicy::Attached(0),
    1932            0 :                         None,
    1933            0 :                     );
    1934            0 :                     shard.config = config;
    1935            0 : 
    1936            0 :                     let mut locked = self.inner.write().unwrap();
    1937            0 :                     locked.tenants.insert(attach_req.tenant_shard_id, shard);
    1938            0 :                     tracing::info!("Inserted shard {} in memory", attach_req.tenant_shard_id);
    1939              :                 }
    1940              :             }
    1941            0 :         }
    1942              : 
    1943            0 :         let new_generation = if let Some(req_node_id) = attach_req.node_id {
    1944            0 :             let maybe_tenant_conf = {
    1945            0 :                 let locked = self.inner.write().unwrap();
    1946            0 :                 locked
    1947            0 :                     .tenants
    1948            0 :                     .get(&attach_req.tenant_shard_id)
    1949            0 :                     .map(|t| t.config.clone())
    1950            0 :             };
    1951            0 : 
    1952            0 :             match maybe_tenant_conf {
    1953            0 :                 Some(conf) => {
    1954            0 :                     let new_generation = self
    1955            0 :                         .persistence
    1956            0 :                         .increment_generation(attach_req.tenant_shard_id, req_node_id)
    1957            0 :                         .await?;
    1958              : 
    1959              :                     // Persist the placement policy update. This is required
    1960              :                     // when we reattaching a detached tenant.
    1961            0 :                     self.persistence
    1962            0 :                         .update_tenant_shard(
    1963            0 :                             TenantFilter::Shard(attach_req.tenant_shard_id),
    1964            0 :                             Some(PlacementPolicy::Attached(0)),
    1965            0 :                             Some(conf),
    1966            0 :                             None,
    1967            0 :                             None,
    1968            0 :                         )
    1969            0 :                         .await?;
    1970            0 :                     Some(new_generation)
    1971              :                 }
    1972              :                 None => {
    1973            0 :                     anyhow::bail!("Attach hook handling raced with tenant removal")
    1974              :                 }
    1975              :             }
    1976              :         } else {
    1977            0 :             self.persistence.detach(attach_req.tenant_shard_id).await?;
    1978            0 :             None
    1979              :         };
    1980              : 
    1981            0 :         let mut locked = self.inner.write().unwrap();
    1982            0 :         let (_nodes, tenants, scheduler) = locked.parts_mut();
    1983            0 : 
    1984            0 :         let tenant_shard = tenants
    1985            0 :             .get_mut(&attach_req.tenant_shard_id)
    1986            0 :             .expect("Checked for existence above");
    1987              : 
    1988            0 :         if let Some(new_generation) = new_generation {
    1989            0 :             tenant_shard.generation = Some(new_generation);
    1990            0 :             tenant_shard.policy = PlacementPolicy::Attached(0);
    1991            0 :         } else {
    1992              :             // This is a detach notification.  We must update placement policy to avoid re-attaching
    1993              :             // during background scheduling/reconciliation, or during storage controller restart.
    1994            0 :             assert!(attach_req.node_id.is_none());
    1995            0 :             tenant_shard.policy = PlacementPolicy::Detached;
    1996              :         }
    1997              : 
    1998            0 :         if let Some(attaching_pageserver) = attach_req.node_id.as_ref() {
    1999            0 :             tracing::info!(
    2000              :                 tenant_id = %attach_req.tenant_shard_id,
    2001              :                 ps_id = %attaching_pageserver,
    2002              :                 generation = ?tenant_shard.generation,
    2003            0 :                 "issuing",
    2004              :             );
    2005            0 :         } else if let Some(ps_id) = tenant_shard.intent.get_attached() {
    2006            0 :             tracing::info!(
    2007              :                 tenant_id = %attach_req.tenant_shard_id,
    2008              :                 %ps_id,
    2009              :                 generation = ?tenant_shard.generation,
    2010            0 :                 "dropping",
    2011              :             );
    2012              :         } else {
    2013            0 :             tracing::info!(
    2014              :             tenant_id = %attach_req.tenant_shard_id,
    2015            0 :             "no-op: tenant already has no pageserver");
    2016              :         }
    2017            0 :         tenant_shard
    2018            0 :             .intent
    2019            0 :             .set_attached(scheduler, attach_req.node_id);
    2020            0 : 
    2021            0 :         tracing::info!(
    2022            0 :             "attach_hook: tenant {} set generation {:?}, pageserver {}, config {:?}",
    2023            0 :             attach_req.tenant_shard_id,
    2024            0 :             tenant_shard.generation,
    2025            0 :             // TODO: this is an odd number of 0xf's
    2026            0 :             attach_req.node_id.unwrap_or(utils::id::NodeId(0xfffffff)),
    2027              :             attach_req.config,
    2028              :         );
    2029              : 
    2030              :         // Trick the reconciler into not doing anything for this tenant: this helps
    2031              :         // tests that manually configure a tenant on the pagesrever, and then call this
    2032              :         // attach hook: they don't want background reconciliation to modify what they
    2033              :         // did to the pageserver.
    2034              :         #[cfg(feature = "testing")]
    2035              :         {
    2036            0 :             if let Some(node_id) = attach_req.node_id {
    2037            0 :                 tenant_shard.observed.locations = HashMap::from([(
    2038            0 :                     node_id,
    2039            0 :                     ObservedStateLocation {
    2040            0 :                         conf: Some(attached_location_conf(
    2041            0 :                             tenant_shard.generation.unwrap(),
    2042            0 :                             &tenant_shard.shard,
    2043            0 :                             &tenant_shard.config,
    2044            0 :                             &PlacementPolicy::Attached(0),
    2045            0 :                         )),
    2046            0 :                     },
    2047            0 :                 )]);
    2048            0 :             } else {
    2049            0 :                 tenant_shard.observed.locations.clear();
    2050            0 :             }
    2051              :         }
    2052              : 
    2053            0 :         Ok(AttachHookResponse {
    2054            0 :             generation: attach_req
    2055            0 :                 .node_id
    2056            0 :                 .map(|_| tenant_shard.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap()),
    2057            0 :         })
    2058            0 :     }
    2059              : 
    2060            0 :     pub(crate) fn inspect(&self, inspect_req: InspectRequest) -> InspectResponse {
    2061            0 :         let locked = self.inner.read().unwrap();
    2062            0 : 
    2063            0 :         let tenant_shard = locked.tenants.get(&inspect_req.tenant_shard_id);
    2064            0 : 
    2065            0 :         InspectResponse {
    2066            0 :             attachment: tenant_shard.and_then(|s| {
    2067            0 :                 s.intent
    2068            0 :                     .get_attached()
    2069            0 :                     .map(|ps| (s.generation.expect("Test hook, not used on tenants that are mid-onboarding with a NULL generation").into().unwrap(), ps))
    2070            0 :             }),
    2071            0 :         }
    2072            0 :     }
    2073              : 
    2074              :     // When the availability state of a node transitions to active, we must do a full reconciliation
    2075              :     // of LocationConfigs on that node.  This is because while a node was offline:
    2076              :     // - we might have proceeded through startup_reconcile without checking for extraneous LocationConfigs on this node
    2077              :     // - aborting a tenant shard split might have left rogue child shards behind on this node.
    2078              :     //
    2079              :     // This function must complete _before_ setting a `Node` to Active: once it is set to Active, other
    2080              :     // Reconcilers might communicate with the node, and these must not overlap with the work we do in
    2081              :     // this function.
    2082              :     //
    2083              :     // The reconciliation logic in here is very similar to what [`Self::startup_reconcile`] does, but
    2084              :     // for written for a single node rather than as a batch job for all nodes.
    2085              :     #[tracing::instrument(skip_all, fields(node_id=%node.get_id()))]
    2086              :     async fn node_activate_reconcile(
    2087              :         &self,
    2088              :         mut node: Node,
    2089              :         _lock: &TracingExclusiveGuard<NodeOperations>,
    2090              :     ) -> Result<(), ApiError> {
    2091              :         // This Node is a mutable local copy: we will set it active so that we can use its
    2092              :         // API client to reconcile with the node.  The Node in [`Self::nodes`] will get updated
    2093              :         // later.
    2094              :         node.set_availability(NodeAvailability::Active(PageserverUtilization::full()));
    2095              : 
    2096              :         let configs = match node
    2097              :             .with_client_retries(
    2098            0 :                 |client| async move { client.list_location_config().await },
    2099              :                 &self.http_client,
    2100              :                 &self.config.pageserver_jwt_token,
    2101              :                 1,
    2102              :                 5,
    2103              :                 SHORT_RECONCILE_TIMEOUT,
    2104              :                 &self.cancel,
    2105              :             )
    2106              :             .await
    2107              :         {
    2108              :             None => {
    2109              :                 // We're shutting down (the Node's cancellation token can't have fired, because
    2110              :                 // we're the only scope that has a reference to it, and we didn't fire it).
    2111              :                 return Err(ApiError::ShuttingDown);
    2112              :             }
    2113              :             Some(Err(e)) => {
    2114              :                 // This node didn't succeed listing its locations: it may not proceed to active state
    2115              :                 // as it is apparently unavailable.
    2116              :                 return Err(ApiError::PreconditionFailed(
    2117              :                     format!("Failed to query node location configs, cannot activate ({e})").into(),
    2118              :                 ));
    2119              :             }
    2120              :             Some(Ok(configs)) => configs,
    2121              :         };
    2122              :         tracing::info!("Loaded {} LocationConfigs", configs.tenant_shards.len());
    2123              : 
    2124              :         let mut cleanup = Vec::new();
    2125              :         let mut mismatched_locations = 0;
    2126              :         {
    2127              :             let mut locked = self.inner.write().unwrap();
    2128              : 
    2129              :             for (tenant_shard_id, reported) in configs.tenant_shards {
    2130              :                 let Some(tenant_shard) = locked.tenants.get_mut(&tenant_shard_id) else {
    2131              :                     cleanup.push(tenant_shard_id);
    2132              :                     continue;
    2133              :                 };
    2134              : 
    2135              :                 let on_record = &mut tenant_shard
    2136              :                     .observed
    2137              :                     .locations
    2138              :                     .entry(node.get_id())
    2139            0 :                     .or_insert_with(|| ObservedStateLocation { conf: None })
    2140              :                     .conf;
    2141              : 
    2142              :                 // If the location reported by the node does not match our observed state,
    2143              :                 // then we mark it as uncertain and let the background reconciliation loop
    2144              :                 // deal with it.
    2145              :                 //
    2146              :                 // Note that this also covers net new locations reported by the node.
    2147              :                 if *on_record != reported {
    2148              :                     mismatched_locations += 1;
    2149              :                     *on_record = None;
    2150              :                 }
    2151              :             }
    2152              :         }
    2153              : 
    2154              :         if mismatched_locations > 0 {
    2155              :             tracing::info!(
    2156              :                 "Set observed state to None for {mismatched_locations} mismatched locations"
    2157              :             );
    2158              :         }
    2159              : 
    2160              :         for tenant_shard_id in cleanup {
    2161              :             tracing::info!("Detaching {tenant_shard_id}");
    2162              :             match node
    2163              :                 .with_client_retries(
    2164            0 :                     |client| async move {
    2165            0 :                         let config = LocationConfig {
    2166            0 :                             mode: LocationConfigMode::Detached,
    2167            0 :                             generation: None,
    2168            0 :                             secondary_conf: None,
    2169            0 :                             shard_number: tenant_shard_id.shard_number.0,
    2170            0 :                             shard_count: tenant_shard_id.shard_count.literal(),
    2171            0 :                             shard_stripe_size: 0,
    2172            0 :                             tenant_conf: models::TenantConfig::default(),
    2173            0 :                         };
    2174            0 :                         client
    2175            0 :                             .location_config(tenant_shard_id, config, None, false)
    2176            0 :                             .await
    2177            0 :                     },
    2178              :                     &self.http_client,
    2179              :                     &self.config.pageserver_jwt_token,
    2180              :                     1,
    2181              :                     5,
    2182              :                     SHORT_RECONCILE_TIMEOUT,
    2183              :                     &self.cancel,
    2184              :                 )
    2185              :                 .await
    2186              :             {
    2187              :                 None => {
    2188              :                     // We're shutting down (the Node's cancellation token can't have fired, because
    2189              :                     // we're the only scope that has a reference to it, and we didn't fire it).
    2190              :                     return Err(ApiError::ShuttingDown);
    2191              :                 }
    2192              :                 Some(Err(e)) => {
    2193              :                     // Do not let the node proceed to Active state if it is not responsive to requests
    2194              :                     // to detach.  This could happen if e.g. a shutdown bug in the pageserver is preventing
    2195              :                     // detach completing: we should not let this node back into the set of nodes considered
    2196              :                     // okay for scheduling.
    2197              :                     return Err(ApiError::Conflict(format!(
    2198              :                         "Node {node} failed to detach {tenant_shard_id}: {e}"
    2199              :                     )));
    2200              :                 }
    2201              :                 Some(Ok(_)) => {}
    2202              :             };
    2203              :         }
    2204              : 
    2205              :         Ok(())
    2206              :     }
    2207              : 
    2208            0 :     pub(crate) async fn re_attach(
    2209            0 :         &self,
    2210            0 :         reattach_req: ReAttachRequest,
    2211            0 :     ) -> Result<ReAttachResponse, ApiError> {
    2212            0 :         if let Some(register_req) = reattach_req.register {
    2213            0 :             self.node_register(register_req).await?;
    2214            0 :         }
    2215              : 
    2216              :         // Ordering: we must persist generation number updates before making them visible in the in-memory state
    2217            0 :         let incremented_generations = self.persistence.re_attach(reattach_req.node_id).await?;
    2218              : 
    2219            0 :         tracing::info!(
    2220              :             node_id=%reattach_req.node_id,
    2221            0 :             "Incremented {} tenant shards' generations",
    2222            0 :             incremented_generations.len()
    2223              :         );
    2224              : 
    2225              :         // Apply the updated generation to our in-memory state, and
    2226              :         // gather discover secondary locations.
    2227            0 :         let mut locked = self.inner.write().unwrap();
    2228            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    2229            0 : 
    2230            0 :         let mut response = ReAttachResponse {
    2231            0 :             tenants: Vec::new(),
    2232            0 :         };
    2233              : 
    2234              :         // TODO: cancel/restart any running reconciliation for this tenant, it might be trying
    2235              :         // to call location_conf API with an old generation.  Wait for cancellation to complete
    2236              :         // before responding to this request.  Requires well implemented CancellationToken logic
    2237              :         // all the way to where we call location_conf.  Even then, there can still be a location_conf
    2238              :         // request in flight over the network: TODO handle that by making location_conf API refuse
    2239              :         // to go backward in generations.
    2240              : 
    2241              :         // Scan through all shards, applying updates for ones where we updated generation
    2242              :         // and identifying shards that intend to have a secondary location on this node.
    2243            0 :         for (tenant_shard_id, shard) in tenants {
    2244            0 :             if let Some(new_gen) = incremented_generations.get(tenant_shard_id) {
    2245            0 :                 let new_gen = *new_gen;
    2246            0 :                 response.tenants.push(ReAttachResponseTenant {
    2247            0 :                     id: *tenant_shard_id,
    2248            0 :                     r#gen: Some(new_gen.into().unwrap()),
    2249            0 :                     // A tenant is only put into multi or stale modes in the middle of a [`Reconciler::live_migrate`]
    2250            0 :                     // execution.  If a pageserver is restarted during that process, then the reconcile pass will
    2251            0 :                     // fail, and start from scratch, so it doesn't make sense for us to try and preserve
    2252            0 :                     // the stale/multi states at this point.
    2253            0 :                     mode: LocationConfigMode::AttachedSingle,
    2254            0 :                 });
    2255            0 : 
    2256            0 :                 shard.generation = std::cmp::max(shard.generation, Some(new_gen));
    2257            0 :                 if let Some(observed) = shard.observed.locations.get_mut(&reattach_req.node_id) {
    2258              :                     // Why can we update `observed` even though we're not sure our response will be received
    2259              :                     // by the pageserver?  Because the pageserver will not proceed with startup until
    2260              :                     // it has processed response: if it loses it, we'll see another request and increment
    2261              :                     // generation again, avoiding any uncertainty about dirtiness of tenant's state.
    2262            0 :                     if let Some(conf) = observed.conf.as_mut() {
    2263            0 :                         conf.generation = new_gen.into();
    2264            0 :                     }
    2265            0 :                 } else {
    2266            0 :                     // This node has no observed state for the shard: perhaps it was offline
    2267            0 :                     // when the pageserver restarted.  Insert a None, so that the Reconciler
    2268            0 :                     // will be prompted to learn the location's state before it makes changes.
    2269            0 :                     shard
    2270            0 :                         .observed
    2271            0 :                         .locations
    2272            0 :                         .insert(reattach_req.node_id, ObservedStateLocation { conf: None });
    2273            0 :                 }
    2274            0 :             } else if shard.intent.get_secondary().contains(&reattach_req.node_id) {
    2275            0 :                 // Ordering: pageserver will not accept /location_config requests until it has
    2276            0 :                 // finished processing the response from re-attach.  So we can update our in-memory state
    2277            0 :                 // now, and be confident that we are not stamping on the result of some later location config.
    2278            0 :                 // TODO: however, we are not strictly ordered wrt ReconcileResults queue,
    2279            0 :                 // so we might update observed state here, and then get over-written by some racing
    2280            0 :                 // ReconcileResult.  The impact is low however, since we have set state on pageserver something
    2281            0 :                 // that matches intent, so worst case if we race then we end up doing a spurious reconcile.
    2282            0 : 
    2283            0 :                 response.tenants.push(ReAttachResponseTenant {
    2284            0 :                     id: *tenant_shard_id,
    2285            0 :                     r#gen: None,
    2286            0 :                     mode: LocationConfigMode::Secondary,
    2287            0 :                 });
    2288            0 : 
    2289            0 :                 // We must not update observed, because we have no guarantee that our
    2290            0 :                 // response will be received by the pageserver. This could leave it
    2291            0 :                 // falsely dirty, but the resulting reconcile should be idempotent.
    2292            0 :             }
    2293              :         }
    2294              : 
    2295              :         // We consider a node Active once we have composed a re-attach response, but we
    2296              :         // do not call [`Self::node_activate_reconcile`]: the handling of the re-attach response
    2297              :         // implicitly synchronizes the LocationConfigs on the node.
    2298              :         //
    2299              :         // Setting a node active unblocks any Reconcilers that might write to the location config API,
    2300              :         // but those requests will not be accepted by the node until it has finished processing
    2301              :         // the re-attach response.
    2302              :         //
    2303              :         // Additionally, reset the nodes scheduling policy to match the conditional update done
    2304              :         // in [`Persistence::re_attach`].
    2305            0 :         if let Some(node) = nodes.get(&reattach_req.node_id) {
    2306            0 :             let reset_scheduling = matches!(
    2307            0 :                 node.get_scheduling(),
    2308              :                 NodeSchedulingPolicy::PauseForRestart
    2309              :                     | NodeSchedulingPolicy::Draining
    2310              :                     | NodeSchedulingPolicy::Filling
    2311              :             );
    2312              : 
    2313            0 :             let mut new_nodes = (**nodes).clone();
    2314            0 :             if let Some(node) = new_nodes.get_mut(&reattach_req.node_id) {
    2315            0 :                 if reset_scheduling {
    2316            0 :                     node.set_scheduling(NodeSchedulingPolicy::Active);
    2317            0 :                 }
    2318              : 
    2319            0 :                 tracing::info!("Marking {} warming-up on reattach", reattach_req.node_id);
    2320            0 :                 node.set_availability(NodeAvailability::WarmingUp(std::time::Instant::now()));
    2321            0 : 
    2322            0 :                 scheduler.node_upsert(node);
    2323            0 :                 let new_nodes = Arc::new(new_nodes);
    2324            0 :                 *nodes = new_nodes;
    2325              :             } else {
    2326            0 :                 tracing::error!(
    2327            0 :                     "Reattaching node {} was removed while processing the request",
    2328              :                     reattach_req.node_id
    2329              :                 );
    2330              :             }
    2331            0 :         }
    2332              : 
    2333            0 :         Ok(response)
    2334            0 :     }
    2335              : 
    2336            0 :     pub(crate) async fn validate(
    2337            0 :         &self,
    2338            0 :         validate_req: ValidateRequest,
    2339            0 :     ) -> Result<ValidateResponse, DatabaseError> {
    2340              :         // Fast in-memory check: we may reject validation on anything that doesn't match our
    2341              :         // in-memory generation for a shard
    2342            0 :         let in_memory_result = {
    2343            0 :             let mut in_memory_result = Vec::new();
    2344            0 :             let locked = self.inner.read().unwrap();
    2345            0 :             for req_tenant in validate_req.tenants {
    2346            0 :                 if let Some(tenant_shard) = locked.tenants.get(&req_tenant.id) {
    2347            0 :                     let valid = tenant_shard.generation == Some(Generation::new(req_tenant.r#gen));
    2348            0 :                     tracing::info!(
    2349            0 :                         "handle_validate: {}(gen {}): valid={valid} (latest {:?})",
    2350              :                         req_tenant.id,
    2351              :                         req_tenant.r#gen,
    2352              :                         tenant_shard.generation
    2353              :                     );
    2354              : 
    2355            0 :                     in_memory_result.push((
    2356            0 :                         req_tenant.id,
    2357            0 :                         Generation::new(req_tenant.r#gen),
    2358            0 :                         valid,
    2359            0 :                     ));
    2360              :                 } else {
    2361              :                     // This is legal: for example during a shard split the pageserver may still
    2362              :                     // have deletions in its queue from the old pre-split shard, or after deletion
    2363              :                     // of a tenant that was busy with compaction/gc while being deleted.
    2364            0 :                     tracing::info!(
    2365            0 :                         "Refusing deletion validation for missing shard {}",
    2366              :                         req_tenant.id
    2367              :                     );
    2368              :                 }
    2369              :             }
    2370              : 
    2371            0 :             in_memory_result
    2372              :         };
    2373              : 
    2374              :         // Database calls to confirm validity for anything that passed the in-memory check.  We must do this
    2375              :         // in case of controller split-brain, where some other controller process might have incremented the generation.
    2376            0 :         let db_generations = self
    2377            0 :             .persistence
    2378            0 :             .shard_generations(
    2379            0 :                 in_memory_result
    2380            0 :                     .iter()
    2381            0 :                     .filter_map(|i| if i.2 { Some(&i.0) } else { None }),
    2382            0 :             )
    2383            0 :             .await?;
    2384            0 :         let db_generations = db_generations.into_iter().collect::<HashMap<_, _>>();
    2385            0 : 
    2386            0 :         let mut response = ValidateResponse {
    2387            0 :             tenants: Vec::new(),
    2388            0 :         };
    2389            0 :         for (tenant_shard_id, validate_generation, valid) in in_memory_result.into_iter() {
    2390            0 :             let valid = if valid {
    2391            0 :                 let db_generation = db_generations.get(&tenant_shard_id);
    2392            0 :                 db_generation == Some(&Some(validate_generation))
    2393              :             } else {
    2394              :                 // If in-memory state says it's invalid, trust that.  It's always safe to fail a validation, at worst
    2395              :                 // this prevents a pageserver from cleaning up an object in S3.
    2396            0 :                 false
    2397              :             };
    2398              : 
    2399            0 :             response.tenants.push(ValidateResponseTenant {
    2400            0 :                 id: tenant_shard_id,
    2401            0 :                 valid,
    2402            0 :             })
    2403              :         }
    2404              : 
    2405            0 :         Ok(response)
    2406            0 :     }
    2407              : 
    2408            0 :     pub(crate) async fn tenant_create(
    2409            0 :         &self,
    2410            0 :         create_req: TenantCreateRequest,
    2411            0 :     ) -> Result<TenantCreateResponse, ApiError> {
    2412            0 :         let tenant_id = create_req.new_tenant_id.tenant_id;
    2413              : 
    2414              :         // Exclude any concurrent attempts to create/access the same tenant ID
    2415            0 :         let _tenant_lock = trace_exclusive_lock(
    2416            0 :             &self.tenant_op_locks,
    2417            0 :             create_req.new_tenant_id.tenant_id,
    2418            0 :             TenantOperations::Create,
    2419            0 :         )
    2420            0 :         .await;
    2421            0 :         let (response, waiters) = self.do_tenant_create(create_req).await?;
    2422              : 
    2423            0 :         if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
    2424              :             // Avoid deadlock: reconcile may fail while notifying compute, if the cloud control plane refuses to
    2425              :             // accept compute notifications while it is in the process of creating.  Reconciliation will
    2426              :             // be retried in the background.
    2427            0 :             tracing::warn!(%tenant_id, "Reconcile not done yet while creating tenant ({e})");
    2428            0 :         }
    2429            0 :         Ok(response)
    2430            0 :     }
    2431              : 
    2432            0 :     pub(crate) async fn do_tenant_create(
    2433            0 :         &self,
    2434            0 :         create_req: TenantCreateRequest,
    2435            0 :     ) -> Result<(TenantCreateResponse, Vec<ReconcilerWaiter>), ApiError> {
    2436            0 :         let placement_policy = create_req
    2437            0 :             .placement_policy
    2438            0 :             .clone()
    2439            0 :             // As a default, zero secondaries is convenient for tests that don't choose a policy.
    2440            0 :             .unwrap_or(PlacementPolicy::Attached(0));
    2441              : 
    2442              :         // This service expects to handle sharding itself: it is an error to try and directly create
    2443              :         // a particular shard here.
    2444            0 :         let tenant_id = if !create_req.new_tenant_id.is_unsharded() {
    2445            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!(
    2446            0 :                 "Attempted to create a specific shard, this API is for creating the whole tenant"
    2447            0 :             )));
    2448              :         } else {
    2449            0 :             create_req.new_tenant_id.tenant_id
    2450            0 :         };
    2451            0 : 
    2452            0 :         tracing::info!(
    2453            0 :             "Creating tenant {}, shard_count={:?}",
    2454              :             create_req.new_tenant_id,
    2455              :             create_req.shard_parameters.count,
    2456              :         );
    2457              : 
    2458            0 :         let create_ids = (0..create_req.shard_parameters.count.count())
    2459            0 :             .map(|i| TenantShardId {
    2460            0 :                 tenant_id,
    2461            0 :                 shard_number: ShardNumber(i),
    2462            0 :                 shard_count: create_req.shard_parameters.count,
    2463            0 :             })
    2464            0 :             .collect::<Vec<_>>();
    2465              : 
    2466              :         // If the caller specifies a None generation, it means "start from default".  This is different
    2467              :         // to [`Self::tenant_location_config`], where a None generation is used to represent
    2468              :         // an incompletely-onboarded tenant.
    2469            0 :         let initial_generation = if matches!(placement_policy, PlacementPolicy::Secondary) {
    2470            0 :             tracing::info!(
    2471            0 :                 "tenant_create: secondary mode, generation is_some={}",
    2472            0 :                 create_req.generation.is_some()
    2473              :             );
    2474            0 :             create_req.generation.map(Generation::new)
    2475              :         } else {
    2476            0 :             tracing::info!(
    2477            0 :                 "tenant_create: not secondary mode, generation is_some={}",
    2478            0 :                 create_req.generation.is_some()
    2479              :             );
    2480            0 :             Some(
    2481            0 :                 create_req
    2482            0 :                     .generation
    2483            0 :                     .map(Generation::new)
    2484            0 :                     .unwrap_or(INITIAL_GENERATION),
    2485            0 :             )
    2486              :         };
    2487              : 
    2488            0 :         let preferred_az_id = {
    2489            0 :             let locked = self.inner.read().unwrap();
    2490              :             // Idempotency: take the existing value if the tenant already exists
    2491            0 :             if let Some(shard) = locked.tenants.get(create_ids.first().unwrap()) {
    2492            0 :                 shard.preferred_az().cloned()
    2493              :             } else {
    2494            0 :                 locked.scheduler.get_az_for_new_tenant()
    2495              :             }
    2496              :         };
    2497              : 
    2498              :         // Ordering: we persist tenant shards before creating them on the pageserver.  This enables a caller
    2499              :         // to clean up after themselves by issuing a tenant deletion if something goes wrong and we restart
    2500              :         // during the creation, rather than risking leaving orphan objects in S3.
    2501            0 :         let persist_tenant_shards = create_ids
    2502            0 :             .iter()
    2503            0 :             .map(|tenant_shard_id| TenantShardPersistence {
    2504            0 :                 tenant_id: tenant_shard_id.tenant_id.to_string(),
    2505            0 :                 shard_number: tenant_shard_id.shard_number.0 as i32,
    2506            0 :                 shard_count: tenant_shard_id.shard_count.literal() as i32,
    2507            0 :                 shard_stripe_size: create_req.shard_parameters.stripe_size.0 as i32,
    2508            0 :                 generation: initial_generation.map(|g| g.into().unwrap() as i32),
    2509            0 :                 // The pageserver is not known until scheduling happens: we will set this column when
    2510            0 :                 // incrementing the generation the first time we attach to a pageserver.
    2511            0 :                 generation_pageserver: None,
    2512            0 :                 placement_policy: serde_json::to_string(&placement_policy).unwrap(),
    2513            0 :                 config: serde_json::to_string(&create_req.config).unwrap(),
    2514            0 :                 splitting: SplitState::default(),
    2515            0 :                 scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
    2516            0 :                     .unwrap(),
    2517            0 :                 preferred_az_id: preferred_az_id.as_ref().map(|az| az.to_string()),
    2518            0 :             })
    2519            0 :             .collect();
    2520            0 : 
    2521            0 :         match self
    2522            0 :             .persistence
    2523            0 :             .insert_tenant_shards(persist_tenant_shards)
    2524            0 :             .await
    2525              :         {
    2526            0 :             Ok(_) => {}
    2527              :             Err(DatabaseError::Query(diesel::result::Error::DatabaseError(
    2528              :                 DatabaseErrorKind::UniqueViolation,
    2529              :                 _,
    2530              :             ))) => {
    2531              :                 // Unique key violation: this is probably a retry.  Because the shard count is part of the unique key,
    2532              :                 // if we see a unique key violation it means that the creation request's shard count matches the previous
    2533              :                 // creation's shard count.
    2534            0 :                 tracing::info!(
    2535            0 :                     "Tenant shards already present in database, proceeding with idempotent creation..."
    2536              :                 );
    2537              :             }
    2538              :             // Any other database error is unexpected and a bug.
    2539            0 :             Err(e) => return Err(ApiError::InternalServerError(anyhow::anyhow!(e))),
    2540              :         };
    2541              : 
    2542            0 :         let mut schedule_context = ScheduleContext::default();
    2543            0 :         let mut schedule_error = None;
    2544            0 :         let mut response_shards = Vec::new();
    2545            0 :         for tenant_shard_id in create_ids {
    2546            0 :             tracing::info!("Creating shard {tenant_shard_id}...");
    2547              : 
    2548            0 :             let outcome = self
    2549            0 :                 .do_initial_shard_scheduling(
    2550            0 :                     tenant_shard_id,
    2551            0 :                     initial_generation,
    2552            0 :                     &create_req.shard_parameters,
    2553            0 :                     create_req.config.clone(),
    2554            0 :                     placement_policy.clone(),
    2555            0 :                     preferred_az_id.as_ref(),
    2556            0 :                     &mut schedule_context,
    2557            0 :                 )
    2558            0 :                 .await;
    2559              : 
    2560            0 :             match outcome {
    2561            0 :                 InitialShardScheduleOutcome::Scheduled(resp) => response_shards.push(resp),
    2562            0 :                 InitialShardScheduleOutcome::NotScheduled => {}
    2563            0 :                 InitialShardScheduleOutcome::ShardScheduleError(err) => {
    2564            0 :                     schedule_error = Some(err);
    2565            0 :                 }
    2566              :             }
    2567              :         }
    2568              : 
    2569              :         // If we failed to schedule shards, then they are still created in the controller,
    2570              :         // but we return an error to the requester to avoid a silent failure when someone
    2571              :         // tries to e.g. create a tenant whose placement policy requires more nodes than
    2572              :         // are present in the system.  We do this here rather than in the above loop, to
    2573              :         // avoid situations where we only create a subset of shards in the tenant.
    2574            0 :         if let Some(e) = schedule_error {
    2575            0 :             return Err(ApiError::Conflict(format!(
    2576            0 :                 "Failed to schedule shard(s): {e}"
    2577            0 :             )));
    2578            0 :         }
    2579            0 : 
    2580            0 :         let waiters = {
    2581            0 :             let mut locked = self.inner.write().unwrap();
    2582            0 :             let (nodes, tenants, _scheduler) = locked.parts_mut();
    2583            0 :             let config = ReconcilerConfigBuilder::new(ReconcilerPriority::High)
    2584            0 :                 .tenant_creation_hint(true)
    2585            0 :                 .build();
    2586            0 :             tenants
    2587            0 :                 .range_mut(TenantShardId::tenant_range(tenant_id))
    2588            0 :                 .filter_map(|(_shard_id, shard)| {
    2589            0 :                     self.maybe_configured_reconcile_shard(shard, nodes, config)
    2590            0 :                 })
    2591            0 :                 .collect::<Vec<_>>()
    2592            0 :         };
    2593            0 : 
    2594            0 :         Ok((
    2595            0 :             TenantCreateResponse {
    2596            0 :                 shards: response_shards,
    2597            0 :             },
    2598            0 :             waiters,
    2599            0 :         ))
    2600            0 :     }
    2601              : 
    2602              :     /// Helper for tenant creation that does the scheduling for an individual shard. Covers both the
    2603              :     /// case of a new tenant and a pre-existing one.
    2604              :     #[allow(clippy::too_many_arguments)]
    2605            0 :     async fn do_initial_shard_scheduling(
    2606            0 :         &self,
    2607            0 :         tenant_shard_id: TenantShardId,
    2608            0 :         initial_generation: Option<Generation>,
    2609            0 :         shard_params: &ShardParameters,
    2610            0 :         config: TenantConfig,
    2611            0 :         placement_policy: PlacementPolicy,
    2612            0 :         preferred_az_id: Option<&AvailabilityZone>,
    2613            0 :         schedule_context: &mut ScheduleContext,
    2614            0 :     ) -> InitialShardScheduleOutcome {
    2615            0 :         let mut locked = self.inner.write().unwrap();
    2616            0 :         let (_nodes, tenants, scheduler) = locked.parts_mut();
    2617              : 
    2618              :         use std::collections::btree_map::Entry;
    2619            0 :         match tenants.entry(tenant_shard_id) {
    2620            0 :             Entry::Occupied(mut entry) => {
    2621            0 :                 tracing::info!("Tenant shard {tenant_shard_id} already exists while creating");
    2622              : 
    2623            0 :                 if let Err(err) = entry.get_mut().schedule(scheduler, schedule_context) {
    2624            0 :                     return InitialShardScheduleOutcome::ShardScheduleError(err);
    2625            0 :                 }
    2626              : 
    2627            0 :                 if let Some(node_id) = entry.get().intent.get_attached() {
    2628            0 :                     let generation = entry
    2629            0 :                         .get()
    2630            0 :                         .generation
    2631            0 :                         .expect("Generation is set when in attached mode");
    2632            0 :                     InitialShardScheduleOutcome::Scheduled(TenantCreateResponseShard {
    2633            0 :                         shard_id: tenant_shard_id,
    2634            0 :                         node_id: *node_id,
    2635            0 :                         generation: generation.into().unwrap(),
    2636            0 :                     })
    2637              :                 } else {
    2638            0 :                     InitialShardScheduleOutcome::NotScheduled
    2639              :                 }
    2640              :             }
    2641            0 :             Entry::Vacant(entry) => {
    2642            0 :                 let state = entry.insert(TenantShard::new(
    2643            0 :                     tenant_shard_id,
    2644            0 :                     ShardIdentity::from_params(tenant_shard_id.shard_number, shard_params),
    2645            0 :                     placement_policy,
    2646            0 :                     preferred_az_id.cloned(),
    2647            0 :                 ));
    2648            0 : 
    2649            0 :                 state.generation = initial_generation;
    2650            0 :                 state.config = config;
    2651            0 :                 if let Err(e) = state.schedule(scheduler, schedule_context) {
    2652            0 :                     return InitialShardScheduleOutcome::ShardScheduleError(e);
    2653            0 :                 }
    2654              : 
    2655              :                 // Only include shards in result if we are attaching: the purpose
    2656              :                 // of the response is to tell the caller where the shards are attached.
    2657            0 :                 if let Some(node_id) = state.intent.get_attached() {
    2658            0 :                     let generation = state
    2659            0 :                         .generation
    2660            0 :                         .expect("Generation is set when in attached mode");
    2661            0 :                     InitialShardScheduleOutcome::Scheduled(TenantCreateResponseShard {
    2662            0 :                         shard_id: tenant_shard_id,
    2663            0 :                         node_id: *node_id,
    2664            0 :                         generation: generation.into().unwrap(),
    2665            0 :                     })
    2666              :                 } else {
    2667            0 :                     InitialShardScheduleOutcome::NotScheduled
    2668              :                 }
    2669              :             }
    2670              :         }
    2671            0 :     }
    2672              : 
    2673              :     /// Helper for functions that reconcile a number of shards, and would like to do a timeout-bounded
    2674              :     /// wait for reconciliation to complete before responding.
    2675            0 :     async fn await_waiters(
    2676            0 :         &self,
    2677            0 :         waiters: Vec<ReconcilerWaiter>,
    2678            0 :         timeout: Duration,
    2679            0 :     ) -> Result<(), ReconcileWaitError> {
    2680            0 :         let deadline = Instant::now().checked_add(timeout).unwrap();
    2681            0 :         for waiter in waiters {
    2682            0 :             let timeout = deadline.duration_since(Instant::now());
    2683            0 :             waiter.wait_timeout(timeout).await?;
    2684              :         }
    2685              : 
    2686            0 :         Ok(())
    2687            0 :     }
    2688              : 
    2689              :     /// Same as [`Service::await_waiters`], but returns the waiters which are still
    2690              :     /// in progress
    2691            0 :     async fn await_waiters_remainder(
    2692            0 :         &self,
    2693            0 :         waiters: Vec<ReconcilerWaiter>,
    2694            0 :         timeout: Duration,
    2695            0 :     ) -> Vec<ReconcilerWaiter> {
    2696            0 :         let deadline = Instant::now().checked_add(timeout).unwrap();
    2697            0 :         for waiter in waiters.iter() {
    2698            0 :             let timeout = deadline.duration_since(Instant::now());
    2699            0 :             let _ = waiter.wait_timeout(timeout).await;
    2700              :         }
    2701              : 
    2702            0 :         waiters
    2703            0 :             .into_iter()
    2704            0 :             .filter(|waiter| matches!(waiter.get_status(), ReconcilerStatus::InProgress))
    2705            0 :             .collect::<Vec<_>>()
    2706            0 :     }
    2707              : 
    2708              :     /// Part of [`Self::tenant_location_config`]: dissect an incoming location config request,
    2709              :     /// and transform it into either a tenant creation of a series of shard updates.
    2710              :     ///
    2711              :     /// If the incoming request makes no changes, a [`TenantCreateOrUpdate::Update`] result will
    2712              :     /// still be returned.
    2713            0 :     fn tenant_location_config_prepare(
    2714            0 :         &self,
    2715            0 :         tenant_id: TenantId,
    2716            0 :         req: TenantLocationConfigRequest,
    2717            0 :     ) -> TenantCreateOrUpdate {
    2718            0 :         let mut updates = Vec::new();
    2719            0 :         let mut locked = self.inner.write().unwrap();
    2720            0 :         let (nodes, tenants, _scheduler) = locked.parts_mut();
    2721            0 :         let tenant_shard_id = TenantShardId::unsharded(tenant_id);
    2722              : 
    2723              :         // Use location config mode as an indicator of policy.
    2724            0 :         let placement_policy = match req.config.mode {
    2725            0 :             LocationConfigMode::Detached => PlacementPolicy::Detached,
    2726            0 :             LocationConfigMode::Secondary => PlacementPolicy::Secondary,
    2727              :             LocationConfigMode::AttachedMulti
    2728              :             | LocationConfigMode::AttachedSingle
    2729              :             | LocationConfigMode::AttachedStale => {
    2730            0 :                 if nodes.len() > 1 {
    2731            0 :                     PlacementPolicy::Attached(1)
    2732              :                 } else {
    2733              :                     // Convenience for dev/test: if we just have one pageserver, import
    2734              :                     // tenants into non-HA mode so that scheduling will succeed.
    2735            0 :                     PlacementPolicy::Attached(0)
    2736              :                 }
    2737              :             }
    2738              :         };
    2739              : 
    2740              :         // Ordinarily we do not update scheduling policy, but when making major changes
    2741              :         // like detaching or demoting to secondary-only, we need to force the scheduling
    2742              :         // mode to Active, or the caller's expected outcome (detach it) will not happen.
    2743            0 :         let scheduling_policy = match req.config.mode {
    2744              :             LocationConfigMode::Detached | LocationConfigMode::Secondary => {
    2745              :                 // Special case: when making major changes like detaching or demoting to secondary-only,
    2746              :                 // we need to force the scheduling mode to Active, or nothing will happen.
    2747            0 :                 Some(ShardSchedulingPolicy::Active)
    2748              :             }
    2749              :             LocationConfigMode::AttachedMulti
    2750              :             | LocationConfigMode::AttachedSingle
    2751              :             | LocationConfigMode::AttachedStale => {
    2752              :                 // While attached, continue to respect whatever the existing scheduling mode is.
    2753            0 :                 None
    2754              :             }
    2755              :         };
    2756              : 
    2757            0 :         let mut create = true;
    2758            0 :         for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    2759              :             // Saw an existing shard: this is not a creation
    2760            0 :             create = false;
    2761              : 
    2762              :             // Shards may have initially been created by a Secondary request, where we
    2763              :             // would have left generation as None.
    2764              :             //
    2765              :             // We only update generation the first time we see an attached-mode request,
    2766              :             // and if there is no existing generation set. The caller is responsible for
    2767              :             // ensuring that no non-storage-controller pageserver ever uses a higher
    2768              :             // generation than they passed in here.
    2769              :             use LocationConfigMode::*;
    2770            0 :             let set_generation = match req.config.mode {
    2771            0 :                 AttachedMulti | AttachedSingle | AttachedStale if shard.generation.is_none() => {
    2772            0 :                     req.config.generation.map(Generation::new)
    2773              :                 }
    2774            0 :                 _ => None,
    2775              :             };
    2776              : 
    2777            0 :             updates.push(ShardUpdate {
    2778            0 :                 tenant_shard_id: *shard_id,
    2779            0 :                 placement_policy: placement_policy.clone(),
    2780            0 :                 tenant_config: req.config.tenant_conf.clone(),
    2781            0 :                 generation: set_generation,
    2782            0 :                 scheduling_policy,
    2783            0 :             });
    2784              :         }
    2785              : 
    2786            0 :         if create {
    2787              :             use LocationConfigMode::*;
    2788            0 :             let generation = match req.config.mode {
    2789            0 :                 AttachedMulti | AttachedSingle | AttachedStale => req.config.generation,
    2790              :                 // If a caller provided a generation in a non-attached request, ignore it
    2791              :                 // and leave our generation as None: this enables a subsequent update to set
    2792              :                 // the generation when setting an attached mode for the first time.
    2793            0 :                 _ => None,
    2794              :             };
    2795              : 
    2796            0 :             TenantCreateOrUpdate::Create(
    2797            0 :                 // Synthesize a creation request
    2798            0 :                 TenantCreateRequest {
    2799            0 :                     new_tenant_id: tenant_shard_id,
    2800            0 :                     generation,
    2801            0 :                     shard_parameters: ShardParameters {
    2802            0 :                         count: tenant_shard_id.shard_count,
    2803            0 :                         // We only import un-sharded or single-sharded tenants, so stripe
    2804            0 :                         // size can be made up arbitrarily here.
    2805            0 :                         stripe_size: DEFAULT_STRIPE_SIZE,
    2806            0 :                     },
    2807            0 :                     placement_policy: Some(placement_policy),
    2808            0 :                     config: req.config.tenant_conf,
    2809            0 :                 },
    2810            0 :             )
    2811              :         } else {
    2812            0 :             assert!(!updates.is_empty());
    2813            0 :             TenantCreateOrUpdate::Update(updates)
    2814              :         }
    2815            0 :     }
    2816              : 
    2817              :     /// For APIs that might act on tenants with [`PlacementPolicy::Detached`], first check if
    2818              :     /// the tenant is present in memory. If not, load it from the database.  If it is found
    2819              :     /// in neither location, return a NotFound error.
    2820              :     ///
    2821              :     /// Caller must demonstrate they hold a lock guard, as otherwise two callers might try and load
    2822              :     /// it at the same time, or we might race with [`Self::maybe_drop_tenant`]
    2823            0 :     async fn maybe_load_tenant(
    2824            0 :         &self,
    2825            0 :         tenant_id: TenantId,
    2826            0 :         _guard: &TracingExclusiveGuard<TenantOperations>,
    2827            0 :     ) -> Result<(), ApiError> {
    2828              :         // Check if the tenant is present in memory, and select an AZ to use when loading
    2829              :         // if we will load it.
    2830            0 :         let load_in_az = {
    2831            0 :             let locked = self.inner.read().unwrap();
    2832            0 :             let existing = locked
    2833            0 :                 .tenants
    2834            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    2835            0 :                 .next();
    2836            0 : 
    2837            0 :             // If the tenant is not present in memory, we expect to load it from database,
    2838            0 :             // so let's figure out what AZ to load it into while we have self.inner locked.
    2839            0 :             if existing.is_none() {
    2840            0 :                 locked
    2841            0 :                     .scheduler
    2842            0 :                     .get_az_for_new_tenant()
    2843            0 :                     .ok_or(ApiError::BadRequest(anyhow::anyhow!(
    2844            0 :                         "No AZ with nodes found to load tenant"
    2845            0 :                     )))?
    2846              :             } else {
    2847              :                 // We already have this tenant in memory
    2848            0 :                 return Ok(());
    2849              :             }
    2850              :         };
    2851              : 
    2852            0 :         let tenant_shards = self.persistence.load_tenant(tenant_id).await?;
    2853            0 :         if tenant_shards.is_empty() {
    2854            0 :             return Err(ApiError::NotFound(
    2855            0 :                 anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
    2856            0 :             ));
    2857            0 :         }
    2858            0 : 
    2859            0 :         // Update the persistent shards with the AZ that we are about to apply to in-memory state
    2860            0 :         self.persistence
    2861            0 :             .set_tenant_shard_preferred_azs(
    2862            0 :                 tenant_shards
    2863            0 :                     .iter()
    2864            0 :                     .map(|t| {
    2865            0 :                         (
    2866            0 :                             t.get_tenant_shard_id().expect("Corrupt shard in database"),
    2867            0 :                             Some(load_in_az.clone()),
    2868            0 :                         )
    2869            0 :                     })
    2870            0 :                     .collect(),
    2871            0 :             )
    2872            0 :             .await?;
    2873              : 
    2874            0 :         let mut locked = self.inner.write().unwrap();
    2875            0 :         tracing::info!(
    2876            0 :             "Loaded {} shards for tenant {}",
    2877            0 :             tenant_shards.len(),
    2878              :             tenant_id
    2879              :         );
    2880              : 
    2881            0 :         locked.tenants.extend(tenant_shards.into_iter().map(|p| {
    2882            0 :             let intent = IntentState::new(Some(load_in_az.clone()));
    2883            0 :             let shard =
    2884            0 :                 TenantShard::from_persistent(p, intent).expect("Corrupt shard row in database");
    2885            0 : 
    2886            0 :             // Sanity check: when loading on-demand, we should always be loaded something Detached
    2887            0 :             debug_assert!(shard.policy == PlacementPolicy::Detached);
    2888            0 :             if shard.policy != PlacementPolicy::Detached {
    2889            0 :                 tracing::error!(
    2890            0 :                     "Tenant shard {} loaded on-demand, but has non-Detached policy {:?}",
    2891              :                     shard.tenant_shard_id,
    2892              :                     shard.policy
    2893              :                 );
    2894            0 :             }
    2895              : 
    2896            0 :             (shard.tenant_shard_id, shard)
    2897            0 :         }));
    2898            0 : 
    2899            0 :         Ok(())
    2900            0 :     }
    2901              : 
    2902              :     /// If all shards for a tenant are detached, and in a fully quiescent state (no observed locations on pageservers),
    2903              :     /// and have no reconciler running, then we can drop the tenant from memory.  It will be reloaded on-demand
    2904              :     /// if we are asked to attach it again (see [`Self::maybe_load_tenant`]).
    2905              :     ///
    2906              :     /// Caller must demonstrate they hold a lock guard, as otherwise it is unsafe to drop a tenant from
    2907              :     /// memory while some other function might assume it continues to exist while not holding the lock on Self::inner.
    2908            0 :     fn maybe_drop_tenant(
    2909            0 :         &self,
    2910            0 :         tenant_id: TenantId,
    2911            0 :         locked: &mut std::sync::RwLockWriteGuard<ServiceState>,
    2912            0 :         _guard: &TracingExclusiveGuard<TenantOperations>,
    2913            0 :     ) {
    2914            0 :         let mut tenant_shards = locked.tenants.range(TenantShardId::tenant_range(tenant_id));
    2915            0 :         if tenant_shards.all(|(_id, shard)| {
    2916            0 :             shard.policy == PlacementPolicy::Detached
    2917            0 :                 && shard.reconciler.is_none()
    2918            0 :                 && shard.observed.is_empty()
    2919            0 :         }) {
    2920            0 :             let keys = locked
    2921            0 :                 .tenants
    2922            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    2923            0 :                 .map(|(id, _)| id)
    2924            0 :                 .copied()
    2925            0 :                 .collect::<Vec<_>>();
    2926            0 :             for key in keys {
    2927            0 :                 tracing::info!("Dropping detached tenant shard {} from memory", key);
    2928            0 :                 locked.tenants.remove(&key);
    2929              :             }
    2930            0 :         }
    2931            0 :     }
    2932              : 
    2933              :     /// This API is used by the cloud control plane to migrate unsharded tenants that it created
    2934              :     /// directly with pageservers into this service.
    2935              :     ///
    2936              :     /// Cloud control plane MUST NOT continue issuing GENERATION NUMBERS for this tenant once it
    2937              :     /// has attempted to call this API. Failure to oblige to this rule may lead to S3 corruption.
    2938              :     /// Think of the first attempt to call this API as a transfer of absolute authority over the
    2939              :     /// tenant's source of generation numbers.
    2940              :     ///
    2941              :     /// The mode in this request coarse-grained control of tenants:
    2942              :     /// - Call with mode Attached* to upsert the tenant.
    2943              :     /// - Call with mode Secondary to either onboard a tenant without attaching it, or
    2944              :     ///   to set an existing tenant to PolicyMode::Secondary
    2945              :     /// - Call with mode Detached to switch to PolicyMode::Detached
    2946            0 :     pub(crate) async fn tenant_location_config(
    2947            0 :         &self,
    2948            0 :         tenant_shard_id: TenantShardId,
    2949            0 :         req: TenantLocationConfigRequest,
    2950            0 :     ) -> Result<TenantLocationConfigResponse, ApiError> {
    2951              :         // We require an exclusive lock, because we are updating both persistent and in-memory state
    2952            0 :         let _tenant_lock = trace_exclusive_lock(
    2953            0 :             &self.tenant_op_locks,
    2954            0 :             tenant_shard_id.tenant_id,
    2955            0 :             TenantOperations::LocationConfig,
    2956            0 :         )
    2957            0 :         .await;
    2958              : 
    2959            0 :         let tenant_id = if !tenant_shard_id.is_unsharded() {
    2960            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!(
    2961            0 :                 "This API is for importing single-sharded or unsharded tenants"
    2962            0 :             )));
    2963              :         } else {
    2964            0 :             tenant_shard_id.tenant_id
    2965            0 :         };
    2966            0 : 
    2967            0 :         // In case we are waking up a Detached tenant
    2968            0 :         match self.maybe_load_tenant(tenant_id, &_tenant_lock).await {
    2969            0 :             Ok(()) | Err(ApiError::NotFound(_)) => {
    2970            0 :                 // This is a creation or an update
    2971            0 :             }
    2972            0 :             Err(e) => {
    2973            0 :                 return Err(e);
    2974              :             }
    2975              :         };
    2976              : 
    2977              :         // First check if this is a creation or an update
    2978            0 :         let create_or_update = self.tenant_location_config_prepare(tenant_id, req);
    2979            0 : 
    2980            0 :         let mut result = TenantLocationConfigResponse {
    2981            0 :             shards: Vec::new(),
    2982            0 :             stripe_size: None,
    2983            0 :         };
    2984            0 :         let waiters = match create_or_update {
    2985            0 :             TenantCreateOrUpdate::Create(create_req) => {
    2986            0 :                 let (create_resp, waiters) = self.do_tenant_create(create_req).await?;
    2987            0 :                 result.shards = create_resp
    2988            0 :                     .shards
    2989            0 :                     .into_iter()
    2990            0 :                     .map(|s| TenantShardLocation {
    2991            0 :                         node_id: s.node_id,
    2992            0 :                         shard_id: s.shard_id,
    2993            0 :                     })
    2994            0 :                     .collect();
    2995            0 :                 waiters
    2996              :             }
    2997            0 :             TenantCreateOrUpdate::Update(updates) => {
    2998            0 :                 // Persist updates
    2999            0 :                 // Ordering: write to the database before applying changes in-memory, so that
    3000            0 :                 // we will not appear time-travel backwards on a restart.
    3001            0 : 
    3002            0 :                 let mut schedule_context = ScheduleContext::default();
    3003              :                 for ShardUpdate {
    3004            0 :                     tenant_shard_id,
    3005            0 :                     placement_policy,
    3006            0 :                     tenant_config,
    3007            0 :                     generation,
    3008            0 :                     scheduling_policy,
    3009            0 :                 } in &updates
    3010              :                 {
    3011            0 :                     self.persistence
    3012            0 :                         .update_tenant_shard(
    3013            0 :                             TenantFilter::Shard(*tenant_shard_id),
    3014            0 :                             Some(placement_policy.clone()),
    3015            0 :                             Some(tenant_config.clone()),
    3016            0 :                             *generation,
    3017            0 :                             *scheduling_policy,
    3018            0 :                         )
    3019            0 :                         .await?;
    3020              :                 }
    3021              : 
    3022              :                 // Apply updates in-memory
    3023            0 :                 let mut waiters = Vec::new();
    3024            0 :                 {
    3025            0 :                     let mut locked = self.inner.write().unwrap();
    3026            0 :                     let (nodes, tenants, scheduler) = locked.parts_mut();
    3027              : 
    3028              :                     for ShardUpdate {
    3029            0 :                         tenant_shard_id,
    3030            0 :                         placement_policy,
    3031            0 :                         tenant_config,
    3032            0 :                         generation: update_generation,
    3033            0 :                         scheduling_policy,
    3034            0 :                     } in updates
    3035              :                     {
    3036            0 :                         let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    3037            0 :                             tracing::warn!("Shard {tenant_shard_id} removed while updating");
    3038            0 :                             continue;
    3039              :                         };
    3040              : 
    3041              :                         // Update stripe size
    3042            0 :                         if result.stripe_size.is_none() && shard.shard.count.count() > 1 {
    3043            0 :                             result.stripe_size = Some(shard.shard.stripe_size);
    3044            0 :                         }
    3045              : 
    3046            0 :                         shard.policy = placement_policy;
    3047            0 :                         shard.config = tenant_config;
    3048            0 :                         if let Some(generation) = update_generation {
    3049            0 :                             shard.generation = Some(generation);
    3050            0 :                         }
    3051              : 
    3052            0 :                         if let Some(scheduling_policy) = scheduling_policy {
    3053            0 :                             shard.set_scheduling_policy(scheduling_policy);
    3054            0 :                         }
    3055              : 
    3056            0 :                         shard.schedule(scheduler, &mut schedule_context)?;
    3057              : 
    3058            0 :                         let maybe_waiter =
    3059            0 :                             self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
    3060            0 :                         if let Some(waiter) = maybe_waiter {
    3061            0 :                             waiters.push(waiter);
    3062            0 :                         }
    3063              : 
    3064            0 :                         if let Some(node_id) = shard.intent.get_attached() {
    3065            0 :                             result.shards.push(TenantShardLocation {
    3066            0 :                                 shard_id: tenant_shard_id,
    3067            0 :                                 node_id: *node_id,
    3068            0 :                             })
    3069            0 :                         }
    3070              :                     }
    3071              :                 }
    3072            0 :                 waiters
    3073              :             }
    3074              :         };
    3075              : 
    3076            0 :         if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
    3077              :             // Do not treat a reconcile error as fatal: we have already applied any requested
    3078              :             // Intent changes, and the reconcile can fail for external reasons like unavailable
    3079              :             // compute notification API.  In these cases, it is important that we do not
    3080              :             // cause the cloud control plane to retry forever on this API.
    3081            0 :             tracing::warn!(
    3082            0 :                 "Failed to reconcile after /location_config: {e}, returning success anyway"
    3083              :             );
    3084            0 :         }
    3085              : 
    3086              :         // Logging the full result is useful because it lets us cross-check what the cloud control
    3087              :         // plane's tenant_shards table should contain.
    3088            0 :         tracing::info!("Complete, returning {result:?}");
    3089              : 
    3090            0 :         Ok(result)
    3091            0 :     }
    3092              : 
    3093            0 :     pub(crate) async fn tenant_config_patch(
    3094            0 :         &self,
    3095            0 :         req: TenantConfigPatchRequest,
    3096            0 :     ) -> Result<(), ApiError> {
    3097            0 :         let _tenant_lock = trace_exclusive_lock(
    3098            0 :             &self.tenant_op_locks,
    3099            0 :             req.tenant_id,
    3100            0 :             TenantOperations::ConfigPatch,
    3101            0 :         )
    3102            0 :         .await;
    3103              : 
    3104            0 :         let tenant_id = req.tenant_id;
    3105            0 :         let patch = req.config;
    3106            0 : 
    3107            0 :         self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
    3108              : 
    3109            0 :         let base = {
    3110            0 :             let locked = self.inner.read().unwrap();
    3111            0 :             let shards = locked
    3112            0 :                 .tenants
    3113            0 :                 .range(TenantShardId::tenant_range(req.tenant_id));
    3114            0 : 
    3115            0 :             let mut configs = shards.map(|(_sid, shard)| &shard.config).peekable();
    3116              : 
    3117            0 :             let first = match configs.peek() {
    3118            0 :                 Some(first) => (*first).clone(),
    3119              :                 None => {
    3120            0 :                     return Err(ApiError::NotFound(
    3121            0 :                         anyhow::anyhow!("Tenant {} not found", req.tenant_id).into(),
    3122            0 :                     ));
    3123              :                 }
    3124              :             };
    3125              : 
    3126            0 :             if !configs.all_equal() {
    3127            0 :                 tracing::error!("Tenant configs for {} are mismatched. ", req.tenant_id);
    3128              :                 // This can't happen because we atomically update the database records
    3129              :                 // of all shards to the new value in [`Self::set_tenant_config_and_reconcile`].
    3130            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
    3131            0 :                     "Tenant configs for {} are mismatched",
    3132            0 :                     req.tenant_id
    3133            0 :                 )));
    3134            0 :             }
    3135            0 : 
    3136            0 :             first
    3137              :         };
    3138              : 
    3139            0 :         let updated_config = base
    3140            0 :             .apply_patch(patch)
    3141            0 :             .map_err(|err| ApiError::BadRequest(anyhow::anyhow!(err)))?;
    3142            0 :         self.set_tenant_config_and_reconcile(tenant_id, updated_config)
    3143            0 :             .await
    3144            0 :     }
    3145              : 
    3146            0 :     pub(crate) async fn tenant_config_set(&self, req: TenantConfigRequest) -> Result<(), ApiError> {
    3147              :         // We require an exclusive lock, because we are updating persistent and in-memory state
    3148            0 :         let _tenant_lock = trace_exclusive_lock(
    3149            0 :             &self.tenant_op_locks,
    3150            0 :             req.tenant_id,
    3151            0 :             TenantOperations::ConfigSet,
    3152            0 :         )
    3153            0 :         .await;
    3154              : 
    3155            0 :         self.maybe_load_tenant(req.tenant_id, &_tenant_lock).await?;
    3156              : 
    3157            0 :         self.set_tenant_config_and_reconcile(req.tenant_id, req.config)
    3158            0 :             .await
    3159            0 :     }
    3160              : 
    3161            0 :     async fn set_tenant_config_and_reconcile(
    3162            0 :         &self,
    3163            0 :         tenant_id: TenantId,
    3164            0 :         config: TenantConfig,
    3165            0 :     ) -> Result<(), ApiError> {
    3166            0 :         self.persistence
    3167            0 :             .update_tenant_shard(
    3168            0 :                 TenantFilter::Tenant(tenant_id),
    3169            0 :                 None,
    3170            0 :                 Some(config.clone()),
    3171            0 :                 None,
    3172            0 :                 None,
    3173            0 :             )
    3174            0 :             .await?;
    3175              : 
    3176            0 :         let waiters = {
    3177            0 :             let mut waiters = Vec::new();
    3178            0 :             let mut locked = self.inner.write().unwrap();
    3179            0 :             let (nodes, tenants, _scheduler) = locked.parts_mut();
    3180            0 :             for (_shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    3181            0 :                 shard.config = config.clone();
    3182            0 :                 if let Some(waiter) =
    3183            0 :                     self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
    3184            0 :                 {
    3185            0 :                     waiters.push(waiter);
    3186            0 :                 }
    3187              :             }
    3188            0 :             waiters
    3189              :         };
    3190              : 
    3191            0 :         if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
    3192              :             // Treat this as success because we have stored the configuration.  If e.g.
    3193              :             // a node was unavailable at this time, it should not stop us accepting a
    3194              :             // configuration change.
    3195            0 :             tracing::warn!(%tenant_id, "Accepted configuration update but reconciliation failed: {e}");
    3196            0 :         }
    3197              : 
    3198            0 :         Ok(())
    3199            0 :     }
    3200              : 
    3201            0 :     pub(crate) fn tenant_config_get(
    3202            0 :         &self,
    3203            0 :         tenant_id: TenantId,
    3204            0 :     ) -> Result<HashMap<&str, serde_json::Value>, ApiError> {
    3205            0 :         let config = {
    3206            0 :             let locked = self.inner.read().unwrap();
    3207            0 : 
    3208            0 :             match locked
    3209            0 :                 .tenants
    3210            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    3211            0 :                 .next()
    3212              :             {
    3213            0 :                 Some((_tenant_shard_id, shard)) => shard.config.clone(),
    3214              :                 None => {
    3215            0 :                     return Err(ApiError::NotFound(
    3216            0 :                         anyhow::anyhow!("Tenant not found").into(),
    3217            0 :                     ));
    3218              :                 }
    3219              :             }
    3220              :         };
    3221              : 
    3222              :         // Unlike the pageserver, we do not have a set of global defaults: the config is
    3223              :         // entirely per-tenant.  Therefore the distinction between `tenant_specific_overrides`
    3224              :         // and `effective_config` in the response is meaningless, but we retain that syntax
    3225              :         // in order to remain compatible with the pageserver API.
    3226              : 
    3227            0 :         let response = HashMap::from([
    3228              :             (
    3229              :                 "tenant_specific_overrides",
    3230            0 :                 serde_json::to_value(&config)
    3231            0 :                     .context("serializing tenant specific overrides")
    3232            0 :                     .map_err(ApiError::InternalServerError)?,
    3233              :             ),
    3234              :             (
    3235            0 :                 "effective_config",
    3236            0 :                 serde_json::to_value(&config)
    3237            0 :                     .context("serializing effective config")
    3238            0 :                     .map_err(ApiError::InternalServerError)?,
    3239              :             ),
    3240              :         ]);
    3241              : 
    3242            0 :         Ok(response)
    3243            0 :     }
    3244              : 
    3245            0 :     pub(crate) async fn tenant_time_travel_remote_storage(
    3246            0 :         &self,
    3247            0 :         time_travel_req: &TenantTimeTravelRequest,
    3248            0 :         tenant_id: TenantId,
    3249            0 :         timestamp: Cow<'_, str>,
    3250            0 :         done_if_after: Cow<'_, str>,
    3251            0 :     ) -> Result<(), ApiError> {
    3252            0 :         let _tenant_lock = trace_exclusive_lock(
    3253            0 :             &self.tenant_op_locks,
    3254            0 :             tenant_id,
    3255            0 :             TenantOperations::TimeTravelRemoteStorage,
    3256            0 :         )
    3257            0 :         .await;
    3258              : 
    3259            0 :         let node = {
    3260            0 :             let mut locked = self.inner.write().unwrap();
    3261              :             // Just a sanity check to prevent misuse: the API expects that the tenant is fully
    3262              :             // detached everywhere, and nothing writes to S3 storage. Here, we verify that,
    3263              :             // but only at the start of the process, so it's really just to prevent operator
    3264              :             // mistakes.
    3265            0 :             for (shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id)) {
    3266            0 :                 if shard.intent.get_attached().is_some() || !shard.intent.get_secondary().is_empty()
    3267              :                 {
    3268            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    3269            0 :                         "We want tenant to be attached in shard with tenant_shard_id={shard_id}"
    3270            0 :                     )));
    3271            0 :                 }
    3272            0 :                 let maybe_attached = shard
    3273            0 :                     .observed
    3274            0 :                     .locations
    3275            0 :                     .iter()
    3276            0 :                     .filter_map(|(node_id, observed_location)| {
    3277            0 :                         observed_location
    3278            0 :                             .conf
    3279            0 :                             .as_ref()
    3280            0 :                             .map(|loc| (node_id, observed_location, loc.mode))
    3281            0 :                     })
    3282            0 :                     .find(|(_, _, mode)| *mode != LocationConfigMode::Detached);
    3283            0 :                 if let Some((node_id, _observed_location, mode)) = maybe_attached {
    3284            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    3285            0 :                         "We observed attached={mode:?} tenant in node_id={node_id} shard with tenant_shard_id={shard_id}"
    3286            0 :                     )));
    3287            0 :                 }
    3288              :             }
    3289            0 :             let scheduler = &mut locked.scheduler;
    3290              :             // Right now we only perform the operation on a single node without parallelization
    3291              :             // TODO fan out the operation to multiple nodes for better performance
    3292            0 :             let node_id = scheduler.any_available_node()?;
    3293            0 :             let node = locked
    3294            0 :                 .nodes
    3295            0 :                 .get(&node_id)
    3296            0 :                 .expect("Pageservers may not be deleted while lock is active");
    3297            0 :             node.clone()
    3298            0 :         };
    3299            0 : 
    3300            0 :         // The shard count is encoded in the remote storage's URL, so we need to handle all historically used shard counts
    3301            0 :         let mut counts = time_travel_req
    3302            0 :             .shard_counts
    3303            0 :             .iter()
    3304            0 :             .copied()
    3305            0 :             .collect::<HashSet<_>>()
    3306            0 :             .into_iter()
    3307            0 :             .collect::<Vec<_>>();
    3308            0 :         counts.sort_unstable();
    3309              : 
    3310            0 :         for count in counts {
    3311            0 :             let shard_ids = (0..count.count())
    3312            0 :                 .map(|i| TenantShardId {
    3313            0 :                     tenant_id,
    3314            0 :                     shard_number: ShardNumber(i),
    3315            0 :                     shard_count: count,
    3316            0 :                 })
    3317            0 :                 .collect::<Vec<_>>();
    3318            0 :             for tenant_shard_id in shard_ids {
    3319            0 :                 let client = PageserverClient::new(
    3320            0 :                     node.get_id(),
    3321            0 :                     self.http_client.clone(),
    3322            0 :                     node.base_url(),
    3323            0 :                     self.config.pageserver_jwt_token.as_deref(),
    3324            0 :                 );
    3325            0 : 
    3326            0 :                 tracing::info!("Doing time travel recovery for shard {tenant_shard_id}",);
    3327              : 
    3328            0 :                 client
    3329            0 :                     .tenant_time_travel_remote_storage(
    3330            0 :                         tenant_shard_id,
    3331            0 :                         &timestamp,
    3332            0 :                         &done_if_after,
    3333            0 :                     )
    3334            0 :                     .await
    3335            0 :                     .map_err(|e| {
    3336            0 :                         ApiError::InternalServerError(anyhow::anyhow!(
    3337            0 :                             "Error doing time travel recovery for shard {tenant_shard_id} on node {}: {e}",
    3338            0 :                             node
    3339            0 :                         ))
    3340            0 :                     })?;
    3341              :             }
    3342              :         }
    3343            0 :         Ok(())
    3344            0 :     }
    3345              : 
    3346            0 :     pub(crate) async fn tenant_secondary_download(
    3347            0 :         &self,
    3348            0 :         tenant_id: TenantId,
    3349            0 :         wait: Option<Duration>,
    3350            0 :     ) -> Result<(StatusCode, SecondaryProgress), ApiError> {
    3351            0 :         let _tenant_lock = trace_shared_lock(
    3352            0 :             &self.tenant_op_locks,
    3353            0 :             tenant_id,
    3354            0 :             TenantOperations::SecondaryDownload,
    3355            0 :         )
    3356            0 :         .await;
    3357              : 
    3358              :         // Acquire lock and yield the collection of shard-node tuples which we will send requests onward to
    3359            0 :         let targets = {
    3360            0 :             let locked = self.inner.read().unwrap();
    3361            0 :             let mut targets = Vec::new();
    3362              : 
    3363            0 :             for (tenant_shard_id, shard) in
    3364            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    3365              :             {
    3366            0 :                 for node_id in shard.intent.get_secondary() {
    3367            0 :                     let node = locked
    3368            0 :                         .nodes
    3369            0 :                         .get(node_id)
    3370            0 :                         .expect("Pageservers may not be deleted while referenced");
    3371            0 : 
    3372            0 :                     targets.push((*tenant_shard_id, node.clone()));
    3373            0 :                 }
    3374              :             }
    3375            0 :             targets
    3376            0 :         };
    3377            0 : 
    3378            0 :         // Issue concurrent requests to all shards' locations
    3379            0 :         let mut futs = FuturesUnordered::new();
    3380            0 :         for (tenant_shard_id, node) in targets {
    3381            0 :             let client = PageserverClient::new(
    3382            0 :                 node.get_id(),
    3383            0 :                 self.http_client.clone(),
    3384            0 :                 node.base_url(),
    3385            0 :                 self.config.pageserver_jwt_token.as_deref(),
    3386            0 :             );
    3387            0 :             futs.push(async move {
    3388            0 :                 let result = client
    3389            0 :                     .tenant_secondary_download(tenant_shard_id, wait)
    3390            0 :                     .await;
    3391            0 :                 (result, node, tenant_shard_id)
    3392            0 :             })
    3393              :         }
    3394              : 
    3395              :         // Handle any errors returned by pageservers.  This includes cases like this request racing with
    3396              :         // a scheduling operation, such that the tenant shard we're calling doesn't exist on that pageserver any more, as
    3397              :         // well as more general cases like 503s, 500s, or timeouts.
    3398            0 :         let mut aggregate_progress = SecondaryProgress::default();
    3399            0 :         let mut aggregate_status: Option<StatusCode> = None;
    3400            0 :         let mut error: Option<mgmt_api::Error> = None;
    3401            0 :         while let Some((result, node, tenant_shard_id)) = futs.next().await {
    3402            0 :             match result {
    3403            0 :                 Err(e) => {
    3404            0 :                     // Secondary downloads are always advisory: if something fails, we nevertheless report success, so that whoever
    3405            0 :                     // is calling us will proceed with whatever migration they're doing, albeit with a slightly less warm cache
    3406            0 :                     // than they had hoped for.
    3407            0 :                     tracing::warn!("Secondary download error from pageserver {node}: {e}",);
    3408            0 :                     error = Some(e)
    3409              :                 }
    3410            0 :                 Ok((status_code, progress)) => {
    3411            0 :                     tracing::info!(%tenant_shard_id, "Shard status={status_code} progress: {progress:?}");
    3412            0 :                     aggregate_progress.layers_downloaded += progress.layers_downloaded;
    3413            0 :                     aggregate_progress.layers_total += progress.layers_total;
    3414            0 :                     aggregate_progress.bytes_downloaded += progress.bytes_downloaded;
    3415            0 :                     aggregate_progress.bytes_total += progress.bytes_total;
    3416            0 :                     aggregate_progress.heatmap_mtime =
    3417            0 :                         std::cmp::max(aggregate_progress.heatmap_mtime, progress.heatmap_mtime);
    3418            0 :                     aggregate_status = match aggregate_status {
    3419            0 :                         None => Some(status_code),
    3420            0 :                         Some(StatusCode::OK) => Some(status_code),
    3421            0 :                         Some(cur) => {
    3422            0 :                             // Other status codes (e.g. 202) -- do not overwrite.
    3423            0 :                             Some(cur)
    3424              :                         }
    3425              :                     };
    3426              :                 }
    3427              :             }
    3428              :         }
    3429              : 
    3430              :         // If any of the shards return 202, indicate our result as 202.
    3431            0 :         match aggregate_status {
    3432              :             None => {
    3433            0 :                 match error {
    3434            0 :                     Some(e) => {
    3435            0 :                         // No successes, and an error: surface it
    3436            0 :                         Err(ApiError::Conflict(format!("Error from pageserver: {e}")))
    3437              :                     }
    3438              :                     None => {
    3439              :                         // No shards found
    3440            0 :                         Err(ApiError::NotFound(
    3441            0 :                             anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
    3442            0 :                         ))
    3443              :                     }
    3444              :                 }
    3445              :             }
    3446            0 :             Some(aggregate_status) => Ok((aggregate_status, aggregate_progress)),
    3447              :         }
    3448            0 :     }
    3449              : 
    3450            0 :     pub(crate) async fn tenant_delete(
    3451            0 :         self: &Arc<Self>,
    3452            0 :         tenant_id: TenantId,
    3453            0 :     ) -> Result<StatusCode, ApiError> {
    3454            0 :         let _tenant_lock =
    3455            0 :             trace_exclusive_lock(&self.tenant_op_locks, tenant_id, TenantOperations::Delete).await;
    3456              : 
    3457            0 :         self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
    3458              : 
    3459              :         // Detach all shards. This also deletes local pageserver shard data.
    3460            0 :         let (detach_waiters, node) = {
    3461            0 :             let mut detach_waiters = Vec::new();
    3462            0 :             let mut locked = self.inner.write().unwrap();
    3463            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    3464            0 :             for (_, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    3465              :                 // Update the tenant's intent to remove all attachments
    3466            0 :                 shard.policy = PlacementPolicy::Detached;
    3467            0 :                 shard
    3468            0 :                     .schedule(scheduler, &mut ScheduleContext::default())
    3469            0 :                     .expect("De-scheduling is infallible");
    3470            0 :                 debug_assert!(shard.intent.get_attached().is_none());
    3471            0 :                 debug_assert!(shard.intent.get_secondary().is_empty());
    3472              : 
    3473            0 :                 if let Some(waiter) =
    3474            0 :                     self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
    3475            0 :                 {
    3476            0 :                     detach_waiters.push(waiter);
    3477            0 :                 }
    3478              :             }
    3479              : 
    3480              :             // Pick an arbitrary node to use for remote deletions (does not have to be where the tenant
    3481              :             // was attached, just has to be able to see the S3 content)
    3482            0 :             let node_id = scheduler.any_available_node()?;
    3483            0 :             let node = nodes
    3484            0 :                 .get(&node_id)
    3485            0 :                 .expect("Pageservers may not be deleted while lock is active");
    3486            0 :             (detach_waiters, node.clone())
    3487            0 :         };
    3488            0 : 
    3489            0 :         // This reconcile wait can fail in a few ways:
    3490            0 :         //  A there is a very long queue for the reconciler semaphore
    3491            0 :         //  B some pageserver is failing to handle a detach promptly
    3492            0 :         //  C some pageserver goes offline right at the moment we send it a request.
    3493            0 :         //
    3494            0 :         // A and C are transient: the semaphore will eventually become available, and once a node is marked offline
    3495            0 :         // the next attempt to reconcile will silently skip detaches for an offline node and succeed.  If B happens,
    3496            0 :         // it's a bug, and needs resolving at the pageserver level (we shouldn't just leave attachments behind while
    3497            0 :         // deleting the underlying data).
    3498            0 :         self.await_waiters(detach_waiters, RECONCILE_TIMEOUT)
    3499            0 :             .await?;
    3500              : 
    3501              :         // Delete the entire tenant (all shards) from remote storage via a random pageserver.
    3502              :         // Passing an unsharded tenant ID will cause the pageserver to remove all remote paths with
    3503              :         // the tenant ID prefix, including all shards (even possibly stale ones).
    3504            0 :         match node
    3505            0 :             .with_client_retries(
    3506            0 :                 |client| async move {
    3507            0 :                     client
    3508            0 :                         .tenant_delete(TenantShardId::unsharded(tenant_id))
    3509            0 :                         .await
    3510            0 :                 },
    3511            0 :                 &self.http_client,
    3512            0 :                 &self.config.pageserver_jwt_token,
    3513            0 :                 1,
    3514            0 :                 3,
    3515            0 :                 RECONCILE_TIMEOUT,
    3516            0 :                 &self.cancel,
    3517            0 :             )
    3518            0 :             .await
    3519            0 :             .unwrap_or(Err(mgmt_api::Error::Cancelled))
    3520              :         {
    3521            0 :             Ok(_) => {}
    3522              :             Err(mgmt_api::Error::Cancelled) => {
    3523            0 :                 return Err(ApiError::ShuttingDown);
    3524              :             }
    3525            0 :             Err(e) => {
    3526            0 :                 // This is unexpected: remote deletion should be infallible, unless the object store
    3527            0 :                 // at large is unavailable.
    3528            0 :                 tracing::error!("Error deleting via node {node}: {e}");
    3529            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(e)));
    3530              :             }
    3531              :         }
    3532              : 
    3533              :         // Fall through: deletion of the tenant on pageservers is complete, we may proceed to drop
    3534              :         // our in-memory state and database state.
    3535              : 
    3536              :         // Ordering: we delete persistent state first: if we then
    3537              :         // crash, we will drop the in-memory state.
    3538              : 
    3539              :         // Drop persistent state.
    3540            0 :         self.persistence.delete_tenant(tenant_id).await?;
    3541              : 
    3542              :         // Drop in-memory state
    3543              :         {
    3544            0 :             let mut locked = self.inner.write().unwrap();
    3545            0 :             let (_nodes, tenants, scheduler) = locked.parts_mut();
    3546              : 
    3547              :             // Dereference Scheduler from shards before dropping them
    3548            0 :             for (_tenant_shard_id, shard) in
    3549            0 :                 tenants.range_mut(TenantShardId::tenant_range(tenant_id))
    3550            0 :             {
    3551            0 :                 shard.intent.clear(scheduler);
    3552            0 :             }
    3553              : 
    3554            0 :             tenants.retain(|tenant_shard_id, _shard| tenant_shard_id.tenant_id != tenant_id);
    3555            0 :             tracing::info!(
    3556            0 :                 "Deleted tenant {tenant_id}, now have {} tenants",
    3557            0 :                 locked.tenants.len()
    3558              :             );
    3559              :         };
    3560              : 
    3561              :         // Delete the tenant from safekeepers (if needed)
    3562            0 :         self.tenant_delete_safekeepers(tenant_id)
    3563            0 :             .instrument(tracing::info_span!("tenant_delete_safekeepers", %tenant_id))
    3564            0 :             .await?;
    3565              : 
    3566              :         // Success is represented as 404, to imitate the existing pageserver deletion API
    3567            0 :         Ok(StatusCode::NOT_FOUND)
    3568            0 :     }
    3569              : 
    3570              :     /// Naming: this configures the storage controller's policies for a tenant, whereas [`Self::tenant_config_set`] is "set the TenantConfig"
    3571              :     /// for a tenant.  The TenantConfig is passed through to pageservers, whereas this function modifies
    3572              :     /// the tenant's policies (configuration) within the storage controller
    3573            0 :     pub(crate) async fn tenant_update_policy(
    3574            0 :         &self,
    3575            0 :         tenant_id: TenantId,
    3576            0 :         req: TenantPolicyRequest,
    3577            0 :     ) -> Result<(), ApiError> {
    3578              :         // We require an exclusive lock, because we are updating persistent and in-memory state
    3579            0 :         let _tenant_lock = trace_exclusive_lock(
    3580            0 :             &self.tenant_op_locks,
    3581            0 :             tenant_id,
    3582            0 :             TenantOperations::UpdatePolicy,
    3583            0 :         )
    3584            0 :         .await;
    3585              : 
    3586            0 :         self.maybe_load_tenant(tenant_id, &_tenant_lock).await?;
    3587              : 
    3588            0 :         failpoint_support::sleep_millis_async!("tenant-update-policy-exclusive-lock");
    3589              : 
    3590              :         let TenantPolicyRequest {
    3591            0 :             placement,
    3592            0 :             mut scheduling,
    3593            0 :         } = req;
    3594              : 
    3595            0 :         if let Some(PlacementPolicy::Detached | PlacementPolicy::Secondary) = placement {
    3596              :             // When someone configures a tenant to detach, we force the scheduling policy to enable
    3597              :             // this to take effect.
    3598            0 :             if scheduling.is_none() {
    3599            0 :                 scheduling = Some(ShardSchedulingPolicy::Active);
    3600            0 :             }
    3601            0 :         }
    3602              : 
    3603            0 :         self.persistence
    3604            0 :             .update_tenant_shard(
    3605            0 :                 TenantFilter::Tenant(tenant_id),
    3606            0 :                 placement.clone(),
    3607            0 :                 None,
    3608            0 :                 None,
    3609            0 :                 scheduling,
    3610            0 :             )
    3611            0 :             .await?;
    3612              : 
    3613            0 :         let mut schedule_context = ScheduleContext::default();
    3614            0 :         let mut locked = self.inner.write().unwrap();
    3615            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    3616            0 :         for (shard_id, shard) in tenants.range_mut(TenantShardId::tenant_range(tenant_id)) {
    3617            0 :             if let Some(placement) = &placement {
    3618            0 :                 shard.policy = placement.clone();
    3619            0 : 
    3620            0 :                 tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
    3621            0 :                                "Updated placement policy to {placement:?}");
    3622            0 :             }
    3623              : 
    3624            0 :             if let Some(scheduling) = &scheduling {
    3625            0 :                 shard.set_scheduling_policy(*scheduling);
    3626            0 : 
    3627            0 :                 tracing::info!(tenant_id=%shard_id.tenant_id, shard_id=%shard_id.shard_slug(),
    3628            0 :                                "Updated scheduling policy to {scheduling:?}");
    3629            0 :             }
    3630              : 
    3631              :             // In case scheduling is being switched back on, try it now.
    3632            0 :             shard.schedule(scheduler, &mut schedule_context).ok();
    3633            0 :             self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
    3634              :         }
    3635              : 
    3636            0 :         Ok(())
    3637            0 :     }
    3638              : 
    3639            0 :     pub(crate) async fn tenant_timeline_create_pageservers(
    3640            0 :         &self,
    3641            0 :         tenant_id: TenantId,
    3642            0 :         mut create_req: TimelineCreateRequest,
    3643            0 :     ) -> Result<TimelineInfo, ApiError> {
    3644            0 :         tracing::info!(
    3645            0 :             "Creating timeline {}/{}",
    3646              :             tenant_id,
    3647              :             create_req.new_timeline_id,
    3648              :         );
    3649              : 
    3650            0 :         self.tenant_remote_mutation(tenant_id, move |mut targets| async move {
    3651            0 :             if targets.0.is_empty() {
    3652            0 :                 return Err(ApiError::NotFound(
    3653            0 :                     anyhow::anyhow!("Tenant not found").into(),
    3654            0 :                 ));
    3655            0 :             };
    3656            0 : 
    3657            0 :             let (shard_zero_tid, shard_zero_locations) =
    3658            0 :                 targets.0.pop_first().expect("Must have at least one shard");
    3659            0 :             assert!(shard_zero_tid.is_shard_zero());
    3660              : 
    3661            0 :             async fn create_one(
    3662            0 :                 tenant_shard_id: TenantShardId,
    3663            0 :                 locations: ShardMutationLocations,
    3664            0 :                 http_client: reqwest::Client,
    3665            0 :                 jwt: Option<String>,
    3666            0 :                 mut create_req: TimelineCreateRequest,
    3667            0 :             ) -> Result<TimelineInfo, ApiError> {
    3668            0 :                 let latest = locations.latest.node;
    3669            0 : 
    3670            0 :                 tracing::info!(
    3671            0 :                     "Creating timeline on shard {}/{}, attached to node {latest} in generation {:?}",
    3672              :                     tenant_shard_id,
    3673              :                     create_req.new_timeline_id,
    3674              :                     locations.latest.generation
    3675              :                 );
    3676              : 
    3677            0 :                 let client =
    3678            0 :                     PageserverClient::new(latest.get_id(), http_client.clone(), latest.base_url(), jwt.as_deref());
    3679              : 
    3680            0 :                 let timeline_info = client
    3681            0 :                     .timeline_create(tenant_shard_id, &create_req)
    3682            0 :                     .await
    3683            0 :                     .map_err(|e| passthrough_api_error(&latest, e))?;
    3684              : 
    3685              :                 // If we are going to create the timeline on some stale locations for shard 0, then ask them to re-use
    3686              :                 // the initdb generated by the latest location, rather than generating their own.  This avoids racing uploads
    3687              :                 // of initdb to S3 which might not be binary-identical if different pageservers have different postgres binaries.
    3688            0 :                 if tenant_shard_id.is_shard_zero() {
    3689            0 :                     if let models::TimelineCreateRequestMode::Bootstrap { existing_initdb_timeline_id, .. } = &mut create_req.mode {
    3690            0 :                         *existing_initdb_timeline_id = Some(create_req.new_timeline_id);
    3691            0 :                     }
    3692            0 :                 }
    3693              : 
    3694              :                 // We propagate timeline creations to all attached locations such that a compute
    3695              :                 // for the new timeline is able to start regardless of the current state of the
    3696              :                 // tenant shard reconciliation.
    3697            0 :                 for location in locations.other {
    3698            0 :                     tracing::info!(
    3699            0 :                         "Creating timeline on shard {}/{}, stale attached to node {} in generation {:?}",
    3700              :                         tenant_shard_id,
    3701              :                         create_req.new_timeline_id,
    3702              :                         location.node,
    3703              :                         location.generation
    3704              :                     );
    3705              : 
    3706            0 :                     let client = PageserverClient::new(
    3707            0 :                         location.node.get_id(),
    3708            0 :                         http_client.clone(),
    3709            0 :                         location.node.base_url(),
    3710            0 :                         jwt.as_deref(),
    3711            0 :                     );
    3712              : 
    3713            0 :                     let res = client
    3714            0 :                         .timeline_create(tenant_shard_id, &create_req)
    3715            0 :                         .await;
    3716              : 
    3717            0 :                     if let Err(e) = res {
    3718            0 :                         match e {
    3719            0 :                             mgmt_api::Error::ApiError(StatusCode::NOT_FOUND, _) => {
    3720            0 :                                 // Tenant might have been detached from the stale location,
    3721            0 :                                 // so ignore 404s.
    3722            0 :                             },
    3723              :                             _ => {
    3724            0 :                                 return Err(passthrough_api_error(&location.node, e));
    3725              :                             }
    3726              :                         }
    3727            0 :                     }
    3728              :                 }
    3729              : 
    3730            0 :                 Ok(timeline_info)
    3731            0 :             }
    3732              : 
    3733              :             // Because the caller might not provide an explicit LSN, we must do the creation first on a single shard, and then
    3734              :             // use whatever LSN that shard picked when creating on subsequent shards.  We arbitrarily use shard zero as the shard
    3735              :             // that will get the first creation request, and propagate the LSN to all the >0 shards.
    3736              :             //
    3737              :             // This also enables non-zero shards to use the initdb that shard 0 generated and uploaded to S3, rather than
    3738              :             // independently generating their own initdb.  This guarantees that shards cannot end up with different initial
    3739              :             // states if e.g. they have different postgres binary versions.
    3740            0 :             let timeline_info = create_one(
    3741            0 :                 shard_zero_tid,
    3742            0 :                 shard_zero_locations,
    3743            0 :                 self.http_client.clone(),
    3744            0 :                 self.config.pageserver_jwt_token.clone(),
    3745            0 :                 create_req.clone(),
    3746            0 :             )
    3747            0 :             .await?;
    3748              : 
    3749              :             // Update the create request for shards >= 0
    3750            0 :             match &mut create_req.mode {
    3751            0 :                 models::TimelineCreateRequestMode::Branch { ancestor_start_lsn, .. } if ancestor_start_lsn.is_none() => {
    3752            0 :                     // Propagate the LSN that shard zero picked, if caller didn't provide one
    3753            0 :                     *ancestor_start_lsn = timeline_info.ancestor_lsn;
    3754            0 :                 },
    3755            0 :                 models::TimelineCreateRequestMode::Bootstrap { existing_initdb_timeline_id, .. } => {
    3756            0 :                     // For shards >= 0, do not run initdb: use the one that shard 0 uploaded to S3
    3757            0 :                     *existing_initdb_timeline_id = Some(create_req.new_timeline_id)
    3758              :                 }
    3759            0 :                 _ => {}
    3760              :             }
    3761              : 
    3762              :             // Create timeline on remaining shards with number >0
    3763            0 :             if !targets.0.is_empty() {
    3764              :                 // If we had multiple shards, issue requests for the remainder now.
    3765            0 :                 let jwt = &self.config.pageserver_jwt_token;
    3766            0 :                 self.tenant_for_shards(
    3767            0 :                     targets
    3768            0 :                         .0
    3769            0 :                         .iter()
    3770            0 :                         .map(|t| (*t.0, t.1.latest.node.clone()))
    3771            0 :                         .collect(),
    3772            0 :                     |tenant_shard_id: TenantShardId, _node: Node| {
    3773            0 :                         let create_req = create_req.clone();
    3774            0 :                         let mutation_locations = targets.0.remove(&tenant_shard_id).unwrap();
    3775            0 :                         Box::pin(create_one(
    3776            0 :                             tenant_shard_id,
    3777            0 :                             mutation_locations,
    3778            0 :                             self.http_client.clone(),
    3779            0 :                             jwt.clone(),
    3780            0 :                             create_req,
    3781            0 :                         ))
    3782            0 :                     },
    3783            0 :                 )
    3784            0 :                 .await?;
    3785            0 :             }
    3786              : 
    3787            0 :             Ok(timeline_info)
    3788            0 :         })
    3789            0 :         .await?
    3790            0 :     }
    3791              : 
    3792            0 :     pub(crate) async fn tenant_timeline_create(
    3793            0 :         self: &Arc<Self>,
    3794            0 :         tenant_id: TenantId,
    3795            0 :         create_req: TimelineCreateRequest,
    3796            0 :     ) -> Result<TimelineCreateResponseStorcon, ApiError> {
    3797            0 :         let safekeepers = self.config.timelines_onto_safekeepers;
    3798            0 :         let timeline_id = create_req.new_timeline_id;
    3799            0 : 
    3800            0 :         tracing::info!(
    3801            0 :             mode=%create_req.mode_tag(),
    3802            0 :             %safekeepers,
    3803            0 :             "Creating timeline {}/{}",
    3804              :             tenant_id,
    3805              :             timeline_id,
    3806              :         );
    3807              : 
    3808            0 :         let _tenant_lock = trace_shared_lock(
    3809            0 :             &self.tenant_op_locks,
    3810            0 :             tenant_id,
    3811            0 :             TenantOperations::TimelineCreate,
    3812            0 :         )
    3813            0 :         .await;
    3814            0 :         failpoint_support::sleep_millis_async!("tenant-create-timeline-shared-lock");
    3815            0 :         let is_import = create_req.is_import();
    3816            0 : 
    3817            0 :         if is_import {
    3818              :             // Ensure that there is no split on-going.
    3819              :             // [`Self::tenant_shard_split`] holds the exclusive tenant lock
    3820              :             // for the duration of the split, but here we handle the case
    3821              :             // where we restarted and the split is being aborted.
    3822            0 :             let locked = self.inner.read().unwrap();
    3823            0 :             let splitting = locked
    3824            0 :                 .tenants
    3825            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    3826            0 :                 .any(|(_id, shard)| shard.splitting != SplitState::Idle);
    3827            0 : 
    3828            0 :             if splitting {
    3829            0 :                 return Err(ApiError::Conflict("Tenant is splitting shard".to_string()));
    3830            0 :             }
    3831            0 :         }
    3832              : 
    3833            0 :         let timeline_info = self
    3834            0 :             .tenant_timeline_create_pageservers(tenant_id, create_req)
    3835            0 :             .await?;
    3836              : 
    3837            0 :         let selected_safekeepers = if is_import {
    3838            0 :             let shards = {
    3839            0 :                 let locked = self.inner.read().unwrap();
    3840            0 :                 locked
    3841            0 :                     .tenants
    3842            0 :                     .range(TenantShardId::tenant_range(tenant_id))
    3843            0 :                     .map(|(ts_id, _)| ts_id.to_index())
    3844            0 :                     .collect::<Vec<_>>()
    3845            0 :             };
    3846            0 : 
    3847            0 :             if !shards
    3848            0 :                 .iter()
    3849            0 :                 .map(|shard_index| shard_index.shard_count)
    3850            0 :                 .all_equal()
    3851              :             {
    3852            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
    3853            0 :                     "Inconsistent shard count"
    3854            0 :                 )));
    3855            0 :             }
    3856            0 : 
    3857            0 :             let import = TimelineImport {
    3858            0 :                 tenant_id,
    3859            0 :                 timeline_id,
    3860            0 :                 shard_statuses: ShardImportStatuses::new(shards),
    3861            0 :             };
    3862              : 
    3863            0 :             let inserted = self
    3864            0 :                 .persistence
    3865            0 :                 .insert_timeline_import(import.to_persistent())
    3866            0 :                 .await
    3867            0 :                 .context("timeline import insert")
    3868            0 :                 .map_err(ApiError::InternalServerError)?;
    3869              : 
    3870              :             // Set the importing flag on the tenant shards
    3871            0 :             self.inner
    3872            0 :                 .write()
    3873            0 :                 .unwrap()
    3874            0 :                 .tenants
    3875            0 :                 .range_mut(TenantShardId::tenant_range(tenant_id))
    3876            0 :                 .for_each(|(_id, shard)| shard.importing = TimelineImportState::Importing);
    3877            0 : 
    3878            0 :             match inserted {
    3879              :                 true => {
    3880            0 :                     tracing::info!(%tenant_id, %timeline_id, "Inserted timeline import");
    3881              :                 }
    3882              :                 false => {
    3883            0 :                     tracing::info!(%tenant_id, %timeline_id, "Timeline import entry already present");
    3884              :                 }
    3885              :             }
    3886              : 
    3887            0 :             None
    3888            0 :         } else if safekeepers {
    3889              :             // Note that we do not support creating the timeline on the safekeepers
    3890              :             // for imported timelines. The `start_lsn` of the timeline is not known
    3891              :             // until the import finshes.
    3892              :             // https://github.com/neondatabase/neon/issues/11569
    3893            0 :             let res = self
    3894            0 :                 .tenant_timeline_create_safekeepers(tenant_id, &timeline_info)
    3895            0 :                 .instrument(tracing::info_span!("timeline_create_safekeepers", %tenant_id, timeline_id=%timeline_info.timeline_id))
    3896            0 :                 .await?;
    3897            0 :             Some(res)
    3898              :         } else {
    3899            0 :             None
    3900              :         };
    3901              : 
    3902            0 :         Ok(TimelineCreateResponseStorcon {
    3903            0 :             timeline_info,
    3904            0 :             safekeepers: selected_safekeepers,
    3905            0 :         })
    3906            0 :     }
    3907              : 
    3908            0 :     pub(crate) async fn handle_timeline_shard_import_progress_upcall(
    3909            0 :         self: &Arc<Self>,
    3910            0 :         req: PutTimelineImportStatusRequest,
    3911            0 :     ) -> Result<(), ApiError> {
    3912            0 :         let res = self
    3913            0 :             .persistence
    3914            0 :             .update_timeline_import(req.tenant_shard_id, req.timeline_id, req.status)
    3915            0 :             .await;
    3916            0 :         let timeline_import = match res {
    3917            0 :             Ok(Ok(Some(timeline_import))) => timeline_import,
    3918              :             Ok(Ok(None)) => {
    3919              :                 // Idempotency: we've already seen and handled this update.
    3920            0 :                 return Ok(());
    3921              :             }
    3922            0 :             Ok(Err(logical_err)) => {
    3923            0 :                 return Err(logical_err.into());
    3924              :             }
    3925            0 :             Err(db_err) => {
    3926            0 :                 return Err(db_err.into());
    3927              :             }
    3928              :         };
    3929              : 
    3930            0 :         tracing::info!(
    3931              :             tenant_id=%req.tenant_shard_id.tenant_id,
    3932              :             timeline_id=%req.timeline_id,
    3933            0 :             shard_id=%req.tenant_shard_id.shard_slug(),
    3934            0 :             "Updated timeline import status to: {timeline_import:?}");
    3935              : 
    3936            0 :         if timeline_import.is_complete() {
    3937            0 :             tokio::task::spawn({
    3938            0 :                 let this = self.clone();
    3939            0 :                 async move { this.finalize_timeline_import(timeline_import).await }
    3940            0 :             });
    3941            0 :         }
    3942              : 
    3943            0 :         Ok(())
    3944            0 :     }
    3945              : 
    3946              :     #[instrument(skip_all, fields(
    3947              :         tenant_id=%import.tenant_id,
    3948              :         shard_id=%import.timeline_id,
    3949              :     ))]
    3950              :     async fn finalize_timeline_import(
    3951              :         self: &Arc<Self>,
    3952              :         import: TimelineImport,
    3953              :     ) -> anyhow::Result<()> {
    3954              :         tracing::info!("Finalizing timeline import");
    3955              : 
    3956              :         pausable_failpoint!("timeline-import-pre-cplane-notification");
    3957              : 
    3958              :         let import_failed = import.completion_error().is_some();
    3959              : 
    3960              :         if !import_failed {
    3961              :             loop {
    3962              :                 if self.cancel.is_cancelled() {
    3963              :                     anyhow::bail!("Shut down requested while finalizing import");
    3964              :                 }
    3965              : 
    3966              :                 let active = self.timeline_active_on_all_shards(&import).await?;
    3967              : 
    3968              :                 match active {
    3969              :                     true => {
    3970              :                         tracing::info!("Timeline became active on all shards");
    3971              :                         break;
    3972              :                     }
    3973              :                     false => {
    3974              :                         tracing::info!("Timeline not active on all shards yet");
    3975              : 
    3976              :                         tokio::select! {
    3977              :                             _ = self.cancel.cancelled() => {
    3978              :                                 anyhow::bail!("Shut down requested while finalizing import");
    3979              :                             },
    3980              :                             _ = tokio::time::sleep(Duration::from_secs(5)) => {}
    3981              :                         };
    3982              :                     }
    3983              :                 }
    3984              :             }
    3985              :         }
    3986              : 
    3987              :         tracing::info!(%import_failed, "Notifying cplane of import completion");
    3988              : 
    3989              :         let client = UpcallClient::new(self.get_config(), self.cancel.child_token());
    3990              :         client.notify_import_complete(&import).await?;
    3991              : 
    3992              :         if let Err(err) = self
    3993              :             .persistence
    3994              :             .delete_timeline_import(import.tenant_id, import.timeline_id)
    3995              :             .await
    3996              :         {
    3997              :             tracing::warn!("Failed to delete timeline import entry from database: {err}");
    3998              :         }
    3999              : 
    4000              :         self.inner
    4001              :             .write()
    4002              :             .unwrap()
    4003              :             .tenants
    4004              :             .range_mut(TenantShardId::tenant_range(import.tenant_id))
    4005            0 :             .for_each(|(_id, shard)| shard.importing = TimelineImportState::Idle);
    4006              : 
    4007              :         // TODO(vlad): Timeline creations in import mode do not return a correct initdb lsn,
    4008              :         // so we can't create the timeline on the safekeepers. Fix by moving creation here.
    4009              :         // https://github.com/neondatabase/neon/issues/11569
    4010              :         tracing::info!(%import_failed, "Timeline import complete");
    4011              : 
    4012              :         Ok(())
    4013              :     }
    4014              : 
    4015            0 :     async fn finalize_timeline_imports(self: &Arc<Self>, imports: Vec<TimelineImport>) {
    4016            0 :         futures::future::join_all(
    4017            0 :             imports
    4018            0 :                 .into_iter()
    4019            0 :                 .map(|import| self.finalize_timeline_import(import)),
    4020            0 :         )
    4021            0 :         .await;
    4022            0 :     }
    4023              : 
    4024            0 :     async fn timeline_active_on_all_shards(
    4025            0 :         self: &Arc<Self>,
    4026            0 :         import: &TimelineImport,
    4027            0 :     ) -> anyhow::Result<bool> {
    4028            0 :         let targets = {
    4029            0 :             let locked = self.inner.read().unwrap();
    4030            0 :             let mut targets = Vec::new();
    4031              : 
    4032            0 :             for (tenant_shard_id, shard) in locked
    4033            0 :                 .tenants
    4034            0 :                 .range(TenantShardId::tenant_range(import.tenant_id))
    4035              :             {
    4036            0 :                 if !import
    4037            0 :                     .shard_statuses
    4038            0 :                     .0
    4039            0 :                     .contains_key(&tenant_shard_id.to_index())
    4040              :                 {
    4041            0 :                     anyhow::bail!("Shard layout change detected on completion");
    4042            0 :                 }
    4043              : 
    4044            0 :                 if let Some(node_id) = shard.intent.get_attached() {
    4045            0 :                     let node = locked
    4046            0 :                         .nodes
    4047            0 :                         .get(node_id)
    4048            0 :                         .expect("Pageservers may not be deleted while referenced");
    4049            0 :                     targets.push((*tenant_shard_id, node.clone()));
    4050            0 :                 } else {
    4051            0 :                     return Ok(false);
    4052              :                 }
    4053              :             }
    4054              : 
    4055            0 :             targets
    4056              :         };
    4057              : 
    4058            0 :         let results = self
    4059            0 :             .tenant_for_shards_api(
    4060            0 :                 targets,
    4061            0 :                 |tenant_shard_id, client| async move {
    4062            0 :                     client
    4063            0 :                         .timeline_detail(tenant_shard_id, import.timeline_id)
    4064            0 :                         .await
    4065            0 :                 },
    4066            0 :                 1,
    4067            0 :                 1,
    4068            0 :                 SHORT_RECONCILE_TIMEOUT,
    4069            0 :                 &self.cancel,
    4070            0 :             )
    4071            0 :             .await;
    4072              : 
    4073            0 :         Ok(results.into_iter().all(|res| match res {
    4074            0 :             Ok(info) => info.state == TimelineState::Active,
    4075            0 :             Err(_) => false,
    4076            0 :         }))
    4077            0 :     }
    4078              : 
    4079            0 :     pub(crate) async fn tenant_timeline_archival_config(
    4080            0 :         &self,
    4081            0 :         tenant_id: TenantId,
    4082            0 :         timeline_id: TimelineId,
    4083            0 :         req: TimelineArchivalConfigRequest,
    4084            0 :     ) -> Result<(), ApiError> {
    4085            0 :         tracing::info!(
    4086            0 :             "Setting archival config of timeline {tenant_id}/{timeline_id} to '{:?}'",
    4087              :             req.state
    4088              :         );
    4089              : 
    4090            0 :         let _tenant_lock = trace_shared_lock(
    4091            0 :             &self.tenant_op_locks,
    4092            0 :             tenant_id,
    4093            0 :             TenantOperations::TimelineArchivalConfig,
    4094            0 :         )
    4095            0 :         .await;
    4096              : 
    4097            0 :         self.tenant_remote_mutation(tenant_id, move |targets| async move {
    4098            0 :             if targets.0.is_empty() {
    4099            0 :                 return Err(ApiError::NotFound(
    4100            0 :                     anyhow::anyhow!("Tenant not found").into(),
    4101            0 :                 ));
    4102            0 :             }
    4103            0 :             async fn config_one(
    4104            0 :                 tenant_shard_id: TenantShardId,
    4105            0 :                 timeline_id: TimelineId,
    4106            0 :                 node: Node,
    4107            0 :                 http_client: reqwest::Client,
    4108            0 :                 jwt: Option<String>,
    4109            0 :                 req: TimelineArchivalConfigRequest,
    4110            0 :             ) -> Result<(), ApiError> {
    4111            0 :                 tracing::info!(
    4112            0 :                     "Setting archival config of timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
    4113              :                 );
    4114              : 
    4115            0 :                 let client = PageserverClient::new(node.get_id(),  http_client, node.base_url(), jwt.as_deref());
    4116            0 : 
    4117            0 :                 client
    4118            0 :                     .timeline_archival_config(tenant_shard_id, timeline_id, &req)
    4119            0 :                     .await
    4120            0 :                     .map_err(|e| match e {
    4121            0 :                         mgmt_api::Error::ApiError(StatusCode::PRECONDITION_FAILED, msg) => {
    4122            0 :                             ApiError::PreconditionFailed(msg.into_boxed_str())
    4123              :                         }
    4124            0 :                         _ => passthrough_api_error(&node, e),
    4125            0 :                     })
    4126            0 :             }
    4127              : 
    4128              :             // no shard needs to go first/last; the operation should be idempotent
    4129              :             // TODO: it would be great to ensure that all shards return the same error
    4130            0 :             let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
    4131            0 :             let results = self
    4132            0 :                 .tenant_for_shards(locations, |tenant_shard_id, node| {
    4133            0 :                     futures::FutureExt::boxed(config_one(
    4134            0 :                         tenant_shard_id,
    4135            0 :                         timeline_id,
    4136            0 :                         node,
    4137            0 :                         self.http_client.clone(),
    4138            0 :                         self.config.pageserver_jwt_token.clone(),
    4139            0 :                         req.clone(),
    4140            0 :                     ))
    4141            0 :                 })
    4142            0 :                 .await?;
    4143            0 :             assert!(!results.is_empty(), "must have at least one result");
    4144              : 
    4145            0 :             Ok(())
    4146            0 :         }).await?
    4147            0 :     }
    4148              : 
    4149            0 :     pub(crate) async fn tenant_timeline_detach_ancestor(
    4150            0 :         &self,
    4151            0 :         tenant_id: TenantId,
    4152            0 :         timeline_id: TimelineId,
    4153            0 :         behavior: Option<DetachBehavior>,
    4154            0 :     ) -> Result<models::detach_ancestor::AncestorDetached, ApiError> {
    4155            0 :         tracing::info!("Detaching timeline {tenant_id}/{timeline_id}",);
    4156              : 
    4157            0 :         let _tenant_lock = trace_shared_lock(
    4158            0 :             &self.tenant_op_locks,
    4159            0 :             tenant_id,
    4160            0 :             TenantOperations::TimelineDetachAncestor,
    4161            0 :         )
    4162            0 :         .await;
    4163              : 
    4164            0 :         self.tenant_remote_mutation(tenant_id, move |targets| async move {
    4165            0 :             if targets.0.is_empty() {
    4166            0 :                 return Err(ApiError::NotFound(
    4167            0 :                     anyhow::anyhow!("Tenant not found").into(),
    4168            0 :                 ));
    4169            0 :             }
    4170              : 
    4171            0 :             async fn detach_one(
    4172            0 :                 tenant_shard_id: TenantShardId,
    4173            0 :                 timeline_id: TimelineId,
    4174            0 :                 node: Node,
    4175            0 :                 http_client: reqwest::Client,
    4176            0 :                 jwt: Option<String>,
    4177            0 :                 behavior: Option<DetachBehavior>,
    4178            0 :             ) -> Result<(ShardNumber, models::detach_ancestor::AncestorDetached), ApiError> {
    4179            0 :                 tracing::info!(
    4180            0 :                     "Detaching timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
    4181              :                 );
    4182              : 
    4183            0 :                 let client = PageserverClient::new(node.get_id(), http_client, node.base_url(), jwt.as_deref());
    4184            0 : 
    4185            0 :                 client
    4186            0 :                     .timeline_detach_ancestor(tenant_shard_id, timeline_id, behavior)
    4187            0 :                     .await
    4188            0 :                     .map_err(|e| {
    4189              :                         use mgmt_api::Error;
    4190              : 
    4191            0 :                         match e {
    4192              :                             // no ancestor (ever)
    4193            0 :                             Error::ApiError(StatusCode::CONFLICT, msg) => ApiError::Conflict(format!(
    4194            0 :                                 "{node}: {}",
    4195            0 :                                 msg.strip_prefix("Conflict: ").unwrap_or(&msg)
    4196            0 :                             )),
    4197              :                             // too many ancestors
    4198            0 :                             Error::ApiError(StatusCode::BAD_REQUEST, msg) => {
    4199            0 :                                 ApiError::BadRequest(anyhow::anyhow!("{node}: {msg}"))
    4200              :                             }
    4201            0 :                             Error::ApiError(StatusCode::INTERNAL_SERVER_ERROR, msg) => {
    4202            0 :                                 // avoid turning these into conflicts to remain compatible with
    4203            0 :                                 // pageservers, 500 errors are sadly retryable with timeline ancestor
    4204            0 :                                 // detach
    4205            0 :                                 ApiError::InternalServerError(anyhow::anyhow!("{node}: {msg}"))
    4206              :                             }
    4207              :                             // rest can be mapped as usual
    4208            0 :                             other => passthrough_api_error(&node, other),
    4209              :                         }
    4210            0 :                     })
    4211            0 :                     .map(|res| (tenant_shard_id.shard_number, res))
    4212            0 :             }
    4213              : 
    4214              :             // no shard needs to go first/last; the operation should be idempotent
    4215            0 :             let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
    4216            0 :             let mut results = self
    4217            0 :                 .tenant_for_shards(locations, |tenant_shard_id, node| {
    4218            0 :                     futures::FutureExt::boxed(detach_one(
    4219            0 :                         tenant_shard_id,
    4220            0 :                         timeline_id,
    4221            0 :                         node,
    4222            0 :                         self.http_client.clone(),
    4223            0 :                         self.config.pageserver_jwt_token.clone(),
    4224            0 :                         behavior,
    4225            0 :                     ))
    4226            0 :                 })
    4227            0 :                 .await?;
    4228              : 
    4229            0 :             let any = results.pop().expect("we must have at least one response");
    4230            0 : 
    4231            0 :             let mismatching = results
    4232            0 :                 .iter()
    4233            0 :                 .filter(|(_, res)| res != &any.1)
    4234            0 :                 .collect::<Vec<_>>();
    4235            0 :             if !mismatching.is_empty() {
    4236              :                 // this can be hit by races which should not happen because operation lock on cplane
    4237            0 :                 let matching = results.len() - mismatching.len();
    4238            0 :                 tracing::error!(
    4239              :                     matching,
    4240              :                     compared_against=?any,
    4241              :                     ?mismatching,
    4242            0 :                     "shards returned different results"
    4243              :                 );
    4244              : 
    4245            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!("pageservers returned mixed results for ancestor detach; manual intervention is required.")));
    4246            0 :             }
    4247            0 : 
    4248            0 :             Ok(any.1)
    4249            0 :         }).await?
    4250            0 :     }
    4251              : 
    4252            0 :     pub(crate) async fn tenant_timeline_block_unblock_gc(
    4253            0 :         &self,
    4254            0 :         tenant_id: TenantId,
    4255            0 :         timeline_id: TimelineId,
    4256            0 :         dir: BlockUnblock,
    4257            0 :     ) -> Result<(), ApiError> {
    4258            0 :         let _tenant_lock = trace_shared_lock(
    4259            0 :             &self.tenant_op_locks,
    4260            0 :             tenant_id,
    4261            0 :             TenantOperations::TimelineGcBlockUnblock,
    4262            0 :         )
    4263            0 :         .await;
    4264              : 
    4265            0 :         self.tenant_remote_mutation(tenant_id, move |targets| async move {
    4266            0 :             if targets.0.is_empty() {
    4267            0 :                 return Err(ApiError::NotFound(
    4268            0 :                     anyhow::anyhow!("Tenant not found").into(),
    4269            0 :                 ));
    4270            0 :             }
    4271              : 
    4272            0 :             async fn do_one(
    4273            0 :                 tenant_shard_id: TenantShardId,
    4274            0 :                 timeline_id: TimelineId,
    4275            0 :                 node: Node,
    4276            0 :                 http_client: reqwest::Client,
    4277            0 :                 jwt: Option<String>,
    4278            0 :                 dir: BlockUnblock,
    4279            0 :             ) -> Result<(), ApiError> {
    4280            0 :                 let client = PageserverClient::new(
    4281            0 :                     node.get_id(),
    4282            0 :                     http_client,
    4283            0 :                     node.base_url(),
    4284            0 :                     jwt.as_deref(),
    4285            0 :                 );
    4286            0 : 
    4287            0 :                 client
    4288            0 :                     .timeline_block_unblock_gc(tenant_shard_id, timeline_id, dir)
    4289            0 :                     .await
    4290            0 :                     .map_err(|e| passthrough_api_error(&node, e))
    4291            0 :             }
    4292              : 
    4293              :             // no shard needs to go first/last; the operation should be idempotent
    4294            0 :             let locations = targets
    4295            0 :                 .0
    4296            0 :                 .iter()
    4297            0 :                 .map(|t| (*t.0, t.1.latest.node.clone()))
    4298            0 :                 .collect();
    4299            0 :             self.tenant_for_shards(locations, |tenant_shard_id, node| {
    4300            0 :                 futures::FutureExt::boxed(do_one(
    4301            0 :                     tenant_shard_id,
    4302            0 :                     timeline_id,
    4303            0 :                     node,
    4304            0 :                     self.http_client.clone(),
    4305            0 :                     self.config.pageserver_jwt_token.clone(),
    4306            0 :                     dir,
    4307            0 :                 ))
    4308            0 :             })
    4309            0 :             .await
    4310            0 :         })
    4311            0 :         .await??;
    4312            0 :         Ok(())
    4313            0 :     }
    4314              : 
    4315            0 :     pub(crate) async fn tenant_timeline_lsn_lease(
    4316            0 :         &self,
    4317            0 :         tenant_id: TenantId,
    4318            0 :         timeline_id: TimelineId,
    4319            0 :         lsn: Lsn,
    4320            0 :     ) -> Result<LsnLease, ApiError> {
    4321            0 :         let _tenant_lock = trace_shared_lock(
    4322            0 :             &self.tenant_op_locks,
    4323            0 :             tenant_id,
    4324            0 :             TenantOperations::TimelineLsnLease,
    4325            0 :         )
    4326            0 :         .await;
    4327              : 
    4328            0 :         let targets = {
    4329            0 :             let locked = self.inner.read().unwrap();
    4330            0 :             let mut targets = Vec::new();
    4331            0 : 
    4332            0 :             // If the request got an unsharded tenant id, then apply
    4333            0 :             // the operation to all shards. Otherwise, apply it to a specific shard.
    4334            0 :             let shards_range = TenantShardId::tenant_range(tenant_id);
    4335              : 
    4336            0 :             for (tenant_shard_id, shard) in locked.tenants.range(shards_range) {
    4337            0 :                 if let Some(node_id) = shard.intent.get_attached() {
    4338            0 :                     let node = locked
    4339            0 :                         .nodes
    4340            0 :                         .get(node_id)
    4341            0 :                         .expect("Pageservers may not be deleted while referenced");
    4342            0 : 
    4343            0 :                     targets.push((*tenant_shard_id, node.clone()));
    4344            0 :                 }
    4345              :             }
    4346            0 :             targets
    4347              :         };
    4348              : 
    4349            0 :         let res = self
    4350            0 :             .tenant_for_shards_api(
    4351            0 :                 targets,
    4352            0 :                 |tenant_shard_id, client| async move {
    4353            0 :                     client
    4354            0 :                         .timeline_lease_lsn(tenant_shard_id, timeline_id, lsn)
    4355            0 :                         .await
    4356            0 :                 },
    4357            0 :                 1,
    4358            0 :                 1,
    4359            0 :                 SHORT_RECONCILE_TIMEOUT,
    4360            0 :                 &self.cancel,
    4361            0 :             )
    4362            0 :             .await;
    4363              : 
    4364            0 :         let mut valid_until = None;
    4365            0 :         for r in res {
    4366            0 :             match r {
    4367            0 :                 Ok(lease) => {
    4368            0 :                     if let Some(ref mut valid_until) = valid_until {
    4369            0 :                         *valid_until = std::cmp::min(*valid_until, lease.valid_until);
    4370            0 :                     } else {
    4371            0 :                         valid_until = Some(lease.valid_until);
    4372            0 :                     }
    4373              :                 }
    4374            0 :                 Err(e) => {
    4375            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(e)));
    4376              :                 }
    4377              :             }
    4378              :         }
    4379            0 :         Ok(LsnLease {
    4380            0 :             valid_until: valid_until.unwrap_or_else(SystemTime::now),
    4381            0 :         })
    4382            0 :     }
    4383              : 
    4384            0 :     pub(crate) async fn tenant_timeline_download_heatmap_layers(
    4385            0 :         &self,
    4386            0 :         tenant_shard_id: TenantShardId,
    4387            0 :         timeline_id: TimelineId,
    4388            0 :         concurrency: Option<usize>,
    4389            0 :         recurse: bool,
    4390            0 :     ) -> Result<(), ApiError> {
    4391            0 :         let _tenant_lock = trace_shared_lock(
    4392            0 :             &self.tenant_op_locks,
    4393            0 :             tenant_shard_id.tenant_id,
    4394            0 :             TenantOperations::DownloadHeatmapLayers,
    4395            0 :         )
    4396            0 :         .await;
    4397              : 
    4398            0 :         let targets = {
    4399            0 :             let locked = self.inner.read().unwrap();
    4400            0 :             let mut targets = Vec::new();
    4401              : 
    4402              :             // If the request got an unsharded tenant id, then apply
    4403              :             // the operation to all shards. Otherwise, apply it to a specific shard.
    4404            0 :             let shards_range = if tenant_shard_id.is_unsharded() {
    4405            0 :                 TenantShardId::tenant_range(tenant_shard_id.tenant_id)
    4406              :             } else {
    4407            0 :                 tenant_shard_id.range()
    4408              :             };
    4409              : 
    4410            0 :             for (tenant_shard_id, shard) in locked.tenants.range(shards_range) {
    4411            0 :                 if let Some(node_id) = shard.intent.get_attached() {
    4412            0 :                     let node = locked
    4413            0 :                         .nodes
    4414            0 :                         .get(node_id)
    4415            0 :                         .expect("Pageservers may not be deleted while referenced");
    4416            0 : 
    4417            0 :                     targets.push((*tenant_shard_id, node.clone()));
    4418            0 :                 }
    4419              :             }
    4420            0 :             targets
    4421            0 :         };
    4422            0 : 
    4423            0 :         self.tenant_for_shards_api(
    4424            0 :             targets,
    4425            0 :             |tenant_shard_id, client| async move {
    4426            0 :                 client
    4427            0 :                     .timeline_download_heatmap_layers(
    4428            0 :                         tenant_shard_id,
    4429            0 :                         timeline_id,
    4430            0 :                         concurrency,
    4431            0 :                         recurse,
    4432            0 :                     )
    4433            0 :                     .await
    4434            0 :             },
    4435            0 :             1,
    4436            0 :             1,
    4437            0 :             SHORT_RECONCILE_TIMEOUT,
    4438            0 :             &self.cancel,
    4439            0 :         )
    4440            0 :         .await;
    4441              : 
    4442            0 :         Ok(())
    4443            0 :     }
    4444              : 
    4445              :     /// Helper for concurrently calling a pageserver API on a number of shards, such as timeline creation.
    4446              :     ///
    4447              :     /// On success, the returned vector contains exactly the same number of elements as the input `locations`
    4448              :     /// and returned element at index `i` is the result for `req_fn(op(locations[i])`.
    4449            0 :     async fn tenant_for_shards<F, R>(
    4450            0 :         &self,
    4451            0 :         locations: Vec<(TenantShardId, Node)>,
    4452            0 :         mut req_fn: F,
    4453            0 :     ) -> Result<Vec<R>, ApiError>
    4454            0 :     where
    4455            0 :         F: FnMut(
    4456            0 :             TenantShardId,
    4457            0 :             Node,
    4458            0 :         )
    4459            0 :             -> std::pin::Pin<Box<dyn futures::Future<Output = Result<R, ApiError>> + Send>>,
    4460            0 :     {
    4461            0 :         let mut futs = FuturesUnordered::new();
    4462            0 :         let mut results = Vec::with_capacity(locations.len());
    4463              : 
    4464            0 :         for (idx, (tenant_shard_id, node)) in locations.into_iter().enumerate() {
    4465            0 :             let fut = req_fn(tenant_shard_id, node);
    4466            0 :             futs.push(async move { (idx, fut.await) });
    4467            0 :         }
    4468              : 
    4469            0 :         while let Some((idx, r)) = futs.next().await {
    4470            0 :             results.push((idx, r?));
    4471              :         }
    4472              : 
    4473            0 :         results.sort_by_key(|(idx, _)| *idx);
    4474            0 :         Ok(results.into_iter().map(|(_, r)| r).collect())
    4475            0 :     }
    4476              : 
    4477              :     /// Concurrently invoke a pageserver API call on many shards at once.
    4478              :     ///
    4479              :     /// The returned Vec has the same length as the `locations` Vec,
    4480              :     /// and returned element at index `i` is the result for `op(locations[i])`.
    4481            0 :     pub(crate) async fn tenant_for_shards_api<T, O, F>(
    4482            0 :         &self,
    4483            0 :         locations: Vec<(TenantShardId, Node)>,
    4484            0 :         op: O,
    4485            0 :         warn_threshold: u32,
    4486            0 :         max_retries: u32,
    4487            0 :         timeout: Duration,
    4488            0 :         cancel: &CancellationToken,
    4489            0 :     ) -> Vec<mgmt_api::Result<T>>
    4490            0 :     where
    4491            0 :         O: Fn(TenantShardId, PageserverClient) -> F + Copy,
    4492            0 :         F: std::future::Future<Output = mgmt_api::Result<T>>,
    4493            0 :     {
    4494            0 :         let mut futs = FuturesUnordered::new();
    4495            0 :         let mut results = Vec::with_capacity(locations.len());
    4496              : 
    4497            0 :         for (idx, (tenant_shard_id, node)) in locations.into_iter().enumerate() {
    4498            0 :             futs.push(async move {
    4499            0 :                 let r = node
    4500            0 :                     .with_client_retries(
    4501            0 :                         |client| op(tenant_shard_id, client),
    4502            0 :                         &self.http_client,
    4503            0 :                         &self.config.pageserver_jwt_token,
    4504            0 :                         warn_threshold,
    4505            0 :                         max_retries,
    4506            0 :                         timeout,
    4507            0 :                         cancel,
    4508            0 :                     )
    4509            0 :                     .await;
    4510            0 :                 (idx, r)
    4511            0 :             });
    4512            0 :         }
    4513              : 
    4514            0 :         while let Some((idx, r)) = futs.next().await {
    4515            0 :             results.push((idx, r.unwrap_or(Err(mgmt_api::Error::Cancelled))));
    4516            0 :         }
    4517              : 
    4518            0 :         results.sort_by_key(|(idx, _)| *idx);
    4519            0 :         results.into_iter().map(|(_, r)| r).collect()
    4520            0 :     }
    4521              : 
    4522              :     /// Helper for safely working with the shards in a tenant remotely on pageservers, for example
    4523              :     /// when creating and deleting timelines:
    4524              :     /// - Makes sure shards are attached somewhere if they weren't already
    4525              :     /// - Looks up the shards and the nodes where they were most recently attached
    4526              :     /// - Guarantees that after the inner function returns, the shards' generations haven't moved on: this
    4527              :     ///   ensures that the remote operation acted on the most recent generation, and is therefore durable.
    4528            0 :     async fn tenant_remote_mutation<R, O, F>(
    4529            0 :         &self,
    4530            0 :         tenant_id: TenantId,
    4531            0 :         op: O,
    4532            0 :     ) -> Result<R, ApiError>
    4533            0 :     where
    4534            0 :         O: FnOnce(TenantMutationLocations) -> F,
    4535            0 :         F: std::future::Future<Output = R>,
    4536            0 :     {
    4537            0 :         let mutation_locations = {
    4538            0 :             let mut locations = TenantMutationLocations::default();
    4539              : 
    4540              :             // Load the currently attached pageservers for the latest generation of each shard.  This can
    4541              :             // run concurrently with reconciliations, and it is not guaranteed that the node we find here
    4542              :             // will still be the latest when we're done: we will check generations again at the end of
    4543              :             // this function to handle that.
    4544            0 :             let generations = self.persistence.tenant_generations(tenant_id).await?;
    4545              : 
    4546            0 :             if generations
    4547            0 :                 .iter()
    4548            0 :                 .any(|i| i.generation.is_none() || i.generation_pageserver.is_none())
    4549              :             {
    4550            0 :                 let shard_generations = generations
    4551            0 :                     .into_iter()
    4552            0 :                     .map(|i| (i.tenant_shard_id, (i.generation, i.generation_pageserver)))
    4553            0 :                     .collect::<HashMap<_, _>>();
    4554            0 : 
    4555            0 :                 // One or more shards has not been attached to a pageserver.  Check if this is because it's configured
    4556            0 :                 // to be detached (409: caller should give up), or because it's meant to be attached but isn't yet (503: caller should retry)
    4557            0 :                 let locked = self.inner.read().unwrap();
    4558            0 :                 for (shard_id, shard) in
    4559            0 :                     locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    4560              :                 {
    4561            0 :                     match shard.policy {
    4562              :                         PlacementPolicy::Attached(_) => {
    4563              :                             // This shard is meant to be attached: the caller is not wrong to try and
    4564              :                             // use this function, but we can't service the request right now.
    4565            0 :                             let Some(generation) = shard_generations.get(shard_id) else {
    4566              :                                 // This can only happen if there is a split brain controller modifying the database.  This should
    4567              :                                 // never happen when testing, and if it happens in production we can only log the issue.
    4568            0 :                                 debug_assert!(false);
    4569            0 :                                 tracing::error!(
    4570            0 :                                     "Shard {shard_id} not found in generation state!  Is another rogue controller running?"
    4571              :                                 );
    4572            0 :                                 continue;
    4573              :                             };
    4574            0 :                             let (generation, generation_pageserver) = generation;
    4575            0 :                             if let Some(generation) = generation {
    4576            0 :                                 if generation_pageserver.is_none() {
    4577              :                                     // This is legitimate only in a very narrow window where the shard was only just configured into
    4578              :                                     // Attached mode after being created in Secondary or Detached mode, and it has had its generation
    4579              :                                     // set but not yet had a Reconciler run (reconciler is the only thing that sets generation_pageserver).
    4580            0 :                                     tracing::warn!(
    4581            0 :                                         "Shard {shard_id} generation is set ({generation:?}) but generation_pageserver is None, reconciler not run yet?"
    4582              :                                     );
    4583            0 :                                 }
    4584              :                             } else {
    4585              :                                 // This should never happen: a shard with no generation is only permitted when it was created in some state
    4586              :                                 // other than PlacementPolicy::Attached (and generation is always written to DB before setting Attached in memory)
    4587            0 :                                 debug_assert!(false);
    4588            0 :                                 tracing::error!(
    4589            0 :                                     "Shard {shard_id} generation is None, but it is in PlacementPolicy::Attached mode!"
    4590              :                                 );
    4591            0 :                                 continue;
    4592              :                             }
    4593              :                         }
    4594              :                         PlacementPolicy::Secondary | PlacementPolicy::Detached => {
    4595            0 :                             return Err(ApiError::Conflict(format!(
    4596            0 :                                 "Shard {shard_id} tenant has policy {:?}",
    4597            0 :                                 shard.policy
    4598            0 :                             )));
    4599              :                         }
    4600              :                     }
    4601              :                 }
    4602              : 
    4603            0 :                 return Err(ApiError::ResourceUnavailable(
    4604            0 :                     "One or more shards in tenant is not yet attached".into(),
    4605            0 :                 ));
    4606            0 :             }
    4607            0 : 
    4608            0 :             let locked = self.inner.read().unwrap();
    4609              :             for ShardGenerationState {
    4610            0 :                 tenant_shard_id,
    4611            0 :                 generation,
    4612            0 :                 generation_pageserver,
    4613            0 :             } in generations
    4614              :             {
    4615            0 :                 let node_id = generation_pageserver.expect("We checked for None above");
    4616            0 :                 let node = locked
    4617            0 :                     .nodes
    4618            0 :                     .get(&node_id)
    4619            0 :                     .ok_or(ApiError::Conflict(format!(
    4620            0 :                         "Raced with removal of node {node_id}"
    4621            0 :                     )))?;
    4622            0 :                 let generation = generation.expect("Checked above");
    4623            0 : 
    4624            0 :                 let tenant = locked.tenants.get(&tenant_shard_id);
    4625              : 
    4626              :                 // TODO(vlad): Abstract the logic that finds stale attached locations
    4627              :                 // from observed state into a [`Service`] method.
    4628            0 :                 let other_locations = match tenant {
    4629            0 :                     Some(tenant) => {
    4630            0 :                         let mut other = tenant.attached_locations();
    4631            0 :                         let latest_location_index =
    4632            0 :                             other.iter().position(|&l| l == (node.get_id(), generation));
    4633            0 :                         if let Some(idx) = latest_location_index {
    4634            0 :                             other.remove(idx);
    4635            0 :                         }
    4636              : 
    4637            0 :                         other
    4638              :                     }
    4639            0 :                     None => Vec::default(),
    4640              :                 };
    4641              : 
    4642            0 :                 let location = ShardMutationLocations {
    4643            0 :                     latest: MutationLocation {
    4644            0 :                         node: node.clone(),
    4645            0 :                         generation,
    4646            0 :                     },
    4647            0 :                     other: other_locations
    4648            0 :                         .into_iter()
    4649            0 :                         .filter_map(|(node_id, generation)| {
    4650            0 :                             let node = locked.nodes.get(&node_id)?;
    4651              : 
    4652            0 :                             Some(MutationLocation {
    4653            0 :                                 node: node.clone(),
    4654            0 :                                 generation,
    4655            0 :                             })
    4656            0 :                         })
    4657            0 :                         .collect(),
    4658            0 :                 };
    4659            0 :                 locations.0.insert(tenant_shard_id, location);
    4660            0 :             }
    4661              : 
    4662            0 :             locations
    4663              :         };
    4664              : 
    4665            0 :         let result = op(mutation_locations.clone()).await;
    4666              : 
    4667              :         // Post-check: are all the generations of all the shards the same as they were initially?  This proves that
    4668              :         // our remote operation executed on the latest generation and is therefore persistent.
    4669              :         {
    4670            0 :             let latest_generations = self.persistence.tenant_generations(tenant_id).await?;
    4671            0 :             if latest_generations
    4672            0 :                 .into_iter()
    4673            0 :                 .map(
    4674            0 :                     |ShardGenerationState {
    4675              :                          tenant_shard_id,
    4676              :                          generation,
    4677              :                          generation_pageserver: _,
    4678            0 :                      }| (tenant_shard_id, generation),
    4679            0 :                 )
    4680            0 :                 .collect::<Vec<_>>()
    4681            0 :                 != mutation_locations
    4682            0 :                     .0
    4683            0 :                     .into_iter()
    4684            0 :                     .map(|i| (i.0, Some(i.1.latest.generation)))
    4685            0 :                     .collect::<Vec<_>>()
    4686              :             {
    4687              :                 // We raced with something that incremented the generation, and therefore cannot be
    4688              :                 // confident that our actions are persistent (they might have hit an old generation).
    4689              :                 //
    4690              :                 // This is safe but requires a retry: ask the client to do that by giving them a 503 response.
    4691            0 :                 return Err(ApiError::ResourceUnavailable(
    4692            0 :                     "Tenant attachment changed, please retry".into(),
    4693            0 :                 ));
    4694            0 :             }
    4695            0 :         }
    4696            0 : 
    4697            0 :         Ok(result)
    4698            0 :     }
    4699              : 
    4700            0 :     pub(crate) async fn tenant_timeline_delete(
    4701            0 :         self: &Arc<Self>,
    4702            0 :         tenant_id: TenantId,
    4703            0 :         timeline_id: TimelineId,
    4704            0 :     ) -> Result<StatusCode, ApiError> {
    4705            0 :         tracing::info!("Deleting timeline {}/{}", tenant_id, timeline_id,);
    4706            0 :         let _tenant_lock = trace_shared_lock(
    4707            0 :             &self.tenant_op_locks,
    4708            0 :             tenant_id,
    4709            0 :             TenantOperations::TimelineDelete,
    4710            0 :         )
    4711            0 :         .await;
    4712              : 
    4713            0 :         let status_code = self.tenant_remote_mutation(tenant_id, move |mut targets| async move {
    4714            0 :             if targets.0.is_empty() {
    4715            0 :                 return Err(ApiError::NotFound(
    4716            0 :                     anyhow::anyhow!("Tenant not found").into(),
    4717            0 :                 ));
    4718            0 :             }
    4719            0 : 
    4720            0 :             let (shard_zero_tid, shard_zero_locations) = targets.0.pop_first().expect("Must have at least one shard");
    4721            0 :             assert!(shard_zero_tid.is_shard_zero());
    4722              : 
    4723            0 :             async fn delete_one(
    4724            0 :                 tenant_shard_id: TenantShardId,
    4725            0 :                 timeline_id: TimelineId,
    4726            0 :                 node: Node,
    4727            0 :                 http_client: reqwest::Client,
    4728            0 :                 jwt: Option<String>,
    4729            0 :             ) -> Result<StatusCode, ApiError> {
    4730            0 :                 tracing::info!(
    4731            0 :                     "Deleting timeline on shard {tenant_shard_id}/{timeline_id}, attached to node {node}",
    4732              :                 );
    4733              : 
    4734            0 :                 let client = PageserverClient::new(node.get_id(), http_client, node.base_url(), jwt.as_deref());
    4735            0 :                 let res = client
    4736            0 :                     .timeline_delete(tenant_shard_id, timeline_id)
    4737            0 :                     .await;
    4738              : 
    4739            0 :                 match res {
    4740            0 :                     Ok(ok) => Ok(ok),
    4741            0 :                     Err(mgmt_api::Error::ApiError(StatusCode::CONFLICT, _)) => Ok(StatusCode::CONFLICT),
    4742            0 :                     Err(mgmt_api::Error::ApiError(StatusCode::SERVICE_UNAVAILABLE, msg)) => Err(ApiError::ResourceUnavailable(msg.into())),
    4743            0 :                     Err(e) => {
    4744            0 :                         Err(
    4745            0 :                             ApiError::InternalServerError(anyhow::anyhow!(
    4746            0 :                                 "Error deleting timeline {timeline_id} on {tenant_shard_id} on node {node}: {e}",
    4747            0 :                             ))
    4748            0 :                         )
    4749              :                     }
    4750              :                 }
    4751            0 :             }
    4752              : 
    4753            0 :             let locations = targets.0.iter().map(|t| (*t.0, t.1.latest.node.clone())).collect();
    4754            0 :             let statuses = self
    4755            0 :                 .tenant_for_shards(locations, |tenant_shard_id: TenantShardId, node: Node| {
    4756            0 :                     Box::pin(delete_one(
    4757            0 :                         tenant_shard_id,
    4758            0 :                         timeline_id,
    4759            0 :                         node,
    4760            0 :                         self.http_client.clone(),
    4761            0 :                         self.config.pageserver_jwt_token.clone(),
    4762            0 :                     ))
    4763            0 :                 })
    4764            0 :                 .await?;
    4765              : 
    4766              :             // If any shards >0 haven't finished deletion yet, don't start deletion on shard zero.
    4767              :             // We return 409 (Conflict) if deletion was already in progress on any of the shards
    4768              :             // and 202 (Accepted) if deletion was not already in progress on any of the shards.
    4769            0 :             if statuses.iter().any(|s| s == &StatusCode::CONFLICT) {
    4770            0 :                 return Ok(StatusCode::CONFLICT);
    4771            0 :             }
    4772            0 : 
    4773            0 :             if statuses.iter().any(|s| s != &StatusCode::NOT_FOUND) {
    4774            0 :                 return Ok(StatusCode::ACCEPTED);
    4775            0 :             }
    4776              : 
    4777              :             // Delete shard zero last: this is not strictly necessary, but since a caller's GET on a timeline will be routed
    4778              :             // to shard zero, it gives a more obvious behavior that a GET returns 404 once the deletion is done.
    4779            0 :             let shard_zero_status = delete_one(
    4780            0 :                 shard_zero_tid,
    4781            0 :                 timeline_id,
    4782            0 :                 shard_zero_locations.latest.node,
    4783            0 :                 self.http_client.clone(),
    4784            0 :                 self.config.pageserver_jwt_token.clone(),
    4785            0 :             )
    4786            0 :             .await?;
    4787            0 :             Ok(shard_zero_status)
    4788            0 :         }).await?;
    4789              : 
    4790            0 :         self.tenant_timeline_delete_safekeepers(tenant_id, timeline_id)
    4791            0 :             .await?;
    4792              : 
    4793            0 :         status_code
    4794            0 :     }
    4795              :     /// When you know the TenantId but not a specific shard, and would like to get the node holding shard 0.
    4796            0 :     pub(crate) async fn tenant_shard0_node(
    4797            0 :         &self,
    4798            0 :         tenant_id: TenantId,
    4799            0 :     ) -> Result<(Node, TenantShardId), ApiError> {
    4800            0 :         let tenant_shard_id = {
    4801            0 :             let locked = self.inner.read().unwrap();
    4802            0 :             let Some((tenant_shard_id, _shard)) = locked
    4803            0 :                 .tenants
    4804            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    4805            0 :                 .next()
    4806              :             else {
    4807            0 :                 return Err(ApiError::NotFound(
    4808            0 :                     anyhow::anyhow!("Tenant {tenant_id} not found").into(),
    4809            0 :                 ));
    4810              :             };
    4811              : 
    4812            0 :             *tenant_shard_id
    4813            0 :         };
    4814            0 : 
    4815            0 :         self.tenant_shard_node(tenant_shard_id)
    4816            0 :             .await
    4817            0 :             .map(|node| (node, tenant_shard_id))
    4818            0 :     }
    4819              : 
    4820              :     /// When you need to send an HTTP request to the pageserver that holds a shard of a tenant, this
    4821              :     /// function looks up and returns node. If the shard isn't found, returns Err(ApiError::NotFound)
    4822            0 :     pub(crate) async fn tenant_shard_node(
    4823            0 :         &self,
    4824            0 :         tenant_shard_id: TenantShardId,
    4825            0 :     ) -> Result<Node, ApiError> {
    4826            0 :         // Look up in-memory state and maybe use the node from there.
    4827            0 :         {
    4828            0 :             let locked = self.inner.read().unwrap();
    4829            0 :             let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
    4830            0 :                 return Err(ApiError::NotFound(
    4831            0 :                     anyhow::anyhow!("Tenant shard {tenant_shard_id} not found").into(),
    4832            0 :                 ));
    4833              :             };
    4834              : 
    4835            0 :             let Some(intent_node_id) = shard.intent.get_attached() else {
    4836            0 :                 tracing::warn!(
    4837            0 :                     tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),
    4838            0 :                     "Shard not scheduled (policy {:?}), cannot generate pass-through URL",
    4839              :                     shard.policy
    4840              :                 );
    4841            0 :                 return Err(ApiError::Conflict(
    4842            0 :                     "Cannot call timeline API on non-attached tenant".to_string(),
    4843            0 :                 ));
    4844              :             };
    4845              : 
    4846            0 :             if shard.reconciler.is_none() {
    4847              :                 // Optimization: while no reconcile is in flight, we may trust our in-memory state
    4848              :                 // to tell us which pageserver to use. Otherwise we will fall through and hit the database
    4849            0 :                 let Some(node) = locked.nodes.get(intent_node_id) else {
    4850              :                     // This should never happen
    4851            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    4852            0 :                         "Shard refers to nonexistent node"
    4853            0 :                     )));
    4854              :                 };
    4855            0 :                 return Ok(node.clone());
    4856            0 :             }
    4857              :         };
    4858              : 
    4859              :         // Look up the latest attached pageserver location from the database
    4860              :         // generation state: this will reflect the progress of any ongoing migration.
    4861              :         // Note that it is not guaranteed to _stay_ here, our caller must still handle
    4862              :         // the case where they call through to the pageserver and get a 404.
    4863            0 :         let db_result = self
    4864            0 :             .persistence
    4865            0 :             .tenant_generations(tenant_shard_id.tenant_id)
    4866            0 :             .await?;
    4867              :         let Some(ShardGenerationState {
    4868              :             tenant_shard_id: _,
    4869              :             generation: _,
    4870            0 :             generation_pageserver: Some(node_id),
    4871            0 :         }) = db_result
    4872            0 :             .into_iter()
    4873            0 :             .find(|s| s.tenant_shard_id == tenant_shard_id)
    4874              :         else {
    4875              :             // This can happen if we raced with a tenant deletion or a shard split.  On a retry
    4876              :             // the caller will either succeed (shard split case), get a proper 404 (deletion case),
    4877              :             // or a conflict response (case where tenant was detached in background)
    4878            0 :             return Err(ApiError::ResourceUnavailable(
    4879            0 :                 format!("Shard {tenant_shard_id} not found in database, or is not attached").into(),
    4880            0 :             ));
    4881              :         };
    4882            0 :         let locked = self.inner.read().unwrap();
    4883            0 :         let Some(node) = locked.nodes.get(&node_id) else {
    4884              :             // This should never happen
    4885            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!(
    4886            0 :                 "Shard refers to nonexistent node"
    4887            0 :             )));
    4888              :         };
    4889              : 
    4890            0 :         Ok(node.clone())
    4891            0 :     }
    4892              : 
    4893            0 :     pub(crate) fn tenant_locate(
    4894            0 :         &self,
    4895            0 :         tenant_id: TenantId,
    4896            0 :     ) -> Result<TenantLocateResponse, ApiError> {
    4897            0 :         let locked = self.inner.read().unwrap();
    4898            0 :         tracing::info!("Locating shards for tenant {tenant_id}");
    4899              : 
    4900            0 :         let mut result = Vec::new();
    4901            0 :         let mut shard_params: Option<ShardParameters> = None;
    4902              : 
    4903            0 :         for (tenant_shard_id, shard) in locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    4904              :         {
    4905            0 :             let node_id =
    4906            0 :                 shard
    4907            0 :                     .intent
    4908            0 :                     .get_attached()
    4909            0 :                     .ok_or(ApiError::BadRequest(anyhow::anyhow!(
    4910            0 :                         "Cannot locate a tenant that is not attached"
    4911            0 :                     )))?;
    4912              : 
    4913            0 :             let node = locked
    4914            0 :                 .nodes
    4915            0 :                 .get(&node_id)
    4916            0 :                 .expect("Pageservers may not be deleted while referenced");
    4917            0 : 
    4918            0 :             result.push(node.shard_location(*tenant_shard_id));
    4919            0 : 
    4920            0 :             match &shard_params {
    4921            0 :                 None => {
    4922            0 :                     shard_params = Some(ShardParameters {
    4923            0 :                         stripe_size: shard.shard.stripe_size,
    4924            0 :                         count: shard.shard.count,
    4925            0 :                     });
    4926            0 :                 }
    4927            0 :                 Some(params) => {
    4928            0 :                     if params.stripe_size != shard.shard.stripe_size {
    4929              :                         // This should never happen.  We enforce at runtime because it's simpler than
    4930              :                         // adding an extra per-tenant data structure to store the things that should be the same
    4931            0 :                         return Err(ApiError::InternalServerError(anyhow::anyhow!(
    4932            0 :                             "Inconsistent shard stripe size parameters!"
    4933            0 :                         )));
    4934            0 :                     }
    4935              :                 }
    4936              :             }
    4937              :         }
    4938              : 
    4939            0 :         if result.is_empty() {
    4940            0 :             return Err(ApiError::NotFound(
    4941            0 :                 anyhow::anyhow!("No shards for this tenant ID found").into(),
    4942            0 :             ));
    4943            0 :         }
    4944            0 :         let shard_params = shard_params.expect("result is non-empty, therefore this is set");
    4945            0 :         tracing::info!(
    4946            0 :             "Located tenant {} with params {:?} on shards {}",
    4947            0 :             tenant_id,
    4948            0 :             shard_params,
    4949            0 :             result
    4950            0 :                 .iter()
    4951            0 :                 .map(|s| format!("{:?}", s))
    4952            0 :                 .collect::<Vec<_>>()
    4953            0 :                 .join(",")
    4954              :         );
    4955              : 
    4956            0 :         Ok(TenantLocateResponse {
    4957            0 :             shards: result,
    4958            0 :             shard_params,
    4959            0 :         })
    4960            0 :     }
    4961              : 
    4962              :     /// Returns None if the input iterator of shards does not include a shard with number=0
    4963            0 :     fn tenant_describe_impl<'a>(
    4964            0 :         &self,
    4965            0 :         shards: impl Iterator<Item = &'a TenantShard>,
    4966            0 :     ) -> Option<TenantDescribeResponse> {
    4967            0 :         let mut shard_zero = None;
    4968            0 :         let mut describe_shards = Vec::new();
    4969              : 
    4970            0 :         for shard in shards {
    4971            0 :             if shard.tenant_shard_id.is_shard_zero() {
    4972            0 :                 shard_zero = Some(shard);
    4973            0 :             }
    4974              : 
    4975            0 :             describe_shards.push(TenantDescribeResponseShard {
    4976            0 :                 tenant_shard_id: shard.tenant_shard_id,
    4977            0 :                 node_attached: *shard.intent.get_attached(),
    4978            0 :                 node_secondary: shard.intent.get_secondary().to_vec(),
    4979            0 :                 last_error: shard
    4980            0 :                     .last_error
    4981            0 :                     .lock()
    4982            0 :                     .unwrap()
    4983            0 :                     .as_ref()
    4984            0 :                     .map(|e| format!("{e}"))
    4985            0 :                     .unwrap_or("".to_string())
    4986            0 :                     .clone(),
    4987            0 :                 is_reconciling: shard.reconciler.is_some(),
    4988            0 :                 is_pending_compute_notification: shard.pending_compute_notification,
    4989            0 :                 is_splitting: matches!(shard.splitting, SplitState::Splitting),
    4990            0 :                 is_importing: shard.importing == TimelineImportState::Importing,
    4991            0 :                 scheduling_policy: shard.get_scheduling_policy(),
    4992            0 :                 preferred_az_id: shard.preferred_az().map(ToString::to_string),
    4993              :             })
    4994              :         }
    4995              : 
    4996            0 :         let shard_zero = shard_zero?;
    4997              : 
    4998            0 :         Some(TenantDescribeResponse {
    4999            0 :             tenant_id: shard_zero.tenant_shard_id.tenant_id,
    5000            0 :             shards: describe_shards,
    5001            0 :             stripe_size: shard_zero.shard.stripe_size,
    5002            0 :             policy: shard_zero.policy.clone(),
    5003            0 :             config: shard_zero.config.clone(),
    5004            0 :         })
    5005            0 :     }
    5006              : 
    5007            0 :     pub(crate) fn tenant_describe(
    5008            0 :         &self,
    5009            0 :         tenant_id: TenantId,
    5010            0 :     ) -> Result<TenantDescribeResponse, ApiError> {
    5011            0 :         let locked = self.inner.read().unwrap();
    5012            0 : 
    5013            0 :         self.tenant_describe_impl(
    5014            0 :             locked
    5015            0 :                 .tenants
    5016            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    5017            0 :                 .map(|(_k, v)| v),
    5018            0 :         )
    5019            0 :         .ok_or_else(|| ApiError::NotFound(anyhow::anyhow!("Tenant {tenant_id} not found").into()))
    5020            0 :     }
    5021              : 
    5022              :     /// limit & offset are pagination parameters. Since we are walking an in-memory HashMap, `offset` does not
    5023              :     /// avoid traversing data, it just avoid returning it. This is suitable for our purposes, since our in memory
    5024              :     /// maps are small enough to traverse fast, our pagination is just to avoid serializing huge JSON responses
    5025              :     /// in our external API.
    5026            0 :     pub(crate) fn tenant_list(
    5027            0 :         &self,
    5028            0 :         limit: Option<usize>,
    5029            0 :         start_after: Option<TenantId>,
    5030            0 :     ) -> Vec<TenantDescribeResponse> {
    5031            0 :         let locked = self.inner.read().unwrap();
    5032              : 
    5033              :         // Apply start_from parameter
    5034            0 :         let shard_range = match start_after {
    5035            0 :             None => locked.tenants.range(..),
    5036            0 :             Some(tenant_id) => locked.tenants.range(
    5037            0 :                 TenantShardId {
    5038            0 :                     tenant_id,
    5039            0 :                     shard_number: ShardNumber(u8::MAX),
    5040            0 :                     shard_count: ShardCount(u8::MAX),
    5041            0 :                 }..,
    5042            0 :             ),
    5043              :         };
    5044              : 
    5045            0 :         let mut result = Vec::new();
    5046            0 :         for (_tenant_id, tenant_shards) in &shard_range.group_by(|(id, _shard)| id.tenant_id) {
    5047            0 :             result.push(
    5048            0 :                 self.tenant_describe_impl(tenant_shards.map(|(_k, v)| v))
    5049            0 :                     .expect("Groups are always non-empty"),
    5050            0 :             );
    5051              : 
    5052              :             // Enforce `limit` parameter
    5053            0 :             if let Some(limit) = limit {
    5054            0 :                 if result.len() >= limit {
    5055            0 :                     break;
    5056            0 :                 }
    5057            0 :             }
    5058              :         }
    5059              : 
    5060            0 :         result
    5061            0 :     }
    5062              : 
    5063              :     #[instrument(skip_all, fields(tenant_id=%op.tenant_id))]
    5064              :     async fn abort_tenant_shard_split(
    5065              :         &self,
    5066              :         op: &TenantShardSplitAbort,
    5067              :     ) -> Result<(), TenantShardSplitAbortError> {
    5068              :         // Cleaning up a split:
    5069              :         // - Parent shards are not destroyed during a split, just detached.
    5070              :         // - Failed pageserver split API calls can leave the remote node with just the parent attached,
    5071              :         //   just the children attached, or both.
    5072              :         //
    5073              :         // Therefore our work to do is to:
    5074              :         // 1. Clean up storage controller's internal state to just refer to parents, no children
    5075              :         // 2. Call out to pageservers to ensure that children are detached
    5076              :         // 3. Call out to pageservers to ensure that parents are attached.
    5077              :         //
    5078              :         // Crash safety:
    5079              :         // - If the storage controller stops running during this cleanup *after* clearing the splitting state
    5080              :         //   from our database, then [`Self::startup_reconcile`] will regard child attachments as garbage
    5081              :         //   and detach them.
    5082              :         // - TODO: If the storage controller stops running during this cleanup *before* clearing the splitting state
    5083              :         //   from our database, then we will re-enter this cleanup routine on startup.
    5084              : 
    5085              :         let TenantShardSplitAbort {
    5086              :             tenant_id,
    5087              :             new_shard_count,
    5088              :             new_stripe_size,
    5089              :             ..
    5090              :         } = op;
    5091              : 
    5092              :         // First abort persistent state, if any exists.
    5093              :         match self
    5094              :             .persistence
    5095              :             .abort_shard_split(*tenant_id, *new_shard_count)
    5096              :             .await?
    5097              :         {
    5098              :             AbortShardSplitStatus::Aborted => {
    5099              :                 // Proceed to roll back any child shards created on pageservers
    5100              :             }
    5101              :             AbortShardSplitStatus::Complete => {
    5102              :                 // The split completed (we might hit that path if e.g. our database transaction
    5103              :                 // to write the completion landed in the database, but we dropped connection
    5104              :                 // before seeing the result).
    5105              :                 //
    5106              :                 // We must update in-memory state to reflect the successful split.
    5107              :                 self.tenant_shard_split_commit_inmem(
    5108              :                     *tenant_id,
    5109              :                     *new_shard_count,
    5110              :                     *new_stripe_size,
    5111              :                 );
    5112              :                 return Ok(());
    5113              :             }
    5114              :         }
    5115              : 
    5116              :         // Clean up in-memory state, and accumulate the list of child locations that need detaching
    5117              :         let detach_locations: Vec<(Node, TenantShardId)> = {
    5118              :             let mut detach_locations = Vec::new();
    5119              :             let mut locked = self.inner.write().unwrap();
    5120              :             let (nodes, tenants, scheduler) = locked.parts_mut();
    5121              : 
    5122              :             for (tenant_shard_id, shard) in
    5123              :                 tenants.range_mut(TenantShardId::tenant_range(op.tenant_id))
    5124              :             {
    5125              :                 if shard.shard.count == op.new_shard_count {
    5126              :                     // Surprising: the phase of [`Self::do_tenant_shard_split`] which inserts child shards in-memory
    5127              :                     // is infallible, so if we got an error we shouldn't have got that far.
    5128              :                     tracing::warn!(
    5129              :                         "During split abort, child shard {tenant_shard_id} found in-memory"
    5130              :                     );
    5131              :                     continue;
    5132              :                 }
    5133              : 
    5134              :                 // Add the children of this shard to this list of things to detach
    5135              :                 if let Some(node_id) = shard.intent.get_attached() {
    5136              :                     for child_id in tenant_shard_id.split(*new_shard_count) {
    5137              :                         detach_locations.push((
    5138              :                             nodes
    5139              :                                 .get(node_id)
    5140              :                                 .expect("Intent references nonexistent node")
    5141              :                                 .clone(),
    5142              :                             child_id,
    5143              :                         ));
    5144              :                     }
    5145              :                 } else {
    5146              :                     tracing::warn!(
    5147              :                         "During split abort, shard {tenant_shard_id} has no attached location"
    5148              :                     );
    5149              :                 }
    5150              : 
    5151              :                 tracing::info!("Restoring parent shard {tenant_shard_id}");
    5152              : 
    5153              :                 // Drop any intents that refer to unavailable nodes, to enable this abort to proceed even
    5154              :                 // if the original attachment location is offline.
    5155              :                 if let Some(node_id) = shard.intent.get_attached() {
    5156              :                     if !nodes.get(node_id).unwrap().is_available() {
    5157              :                         tracing::info!(
    5158              :                             "Demoting attached intent for {tenant_shard_id} on unavailable node {node_id}"
    5159              :                         );
    5160              :                         shard.intent.demote_attached(scheduler, *node_id);
    5161              :                     }
    5162              :                 }
    5163              :                 for node_id in shard.intent.get_secondary().clone() {
    5164              :                     if !nodes.get(&node_id).unwrap().is_available() {
    5165              :                         tracing::info!(
    5166              :                             "Dropping secondary intent for {tenant_shard_id} on unavailable node {node_id}"
    5167              :                         );
    5168              :                         shard.intent.remove_secondary(scheduler, node_id);
    5169              :                     }
    5170              :                 }
    5171              : 
    5172              :                 shard.splitting = SplitState::Idle;
    5173              :                 if let Err(e) = shard.schedule(scheduler, &mut ScheduleContext::default()) {
    5174              :                     // If this shard can't be scheduled now (perhaps due to offline nodes or
    5175              :                     // capacity issues), that must not prevent us rolling back a split.  In this
    5176              :                     // case it should be eventually scheduled in the background.
    5177              :                     tracing::warn!("Failed to schedule {tenant_shard_id} during shard abort: {e}")
    5178              :                 }
    5179              : 
    5180              :                 self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High);
    5181              :             }
    5182              : 
    5183              :             // We don't expect any new_shard_count shards to exist here, but drop them just in case
    5184            0 :             tenants.retain(|_id, s| s.shard.count != *new_shard_count);
    5185              : 
    5186              :             detach_locations
    5187              :         };
    5188              : 
    5189              :         for (node, child_id) in detach_locations {
    5190              :             if !node.is_available() {
    5191              :                 // An unavailable node cannot be cleaned up now: to avoid blocking forever, we will permit this, and
    5192              :                 // rely on the reconciliation that happens when a node transitions to Active to clean up. Since we have
    5193              :                 // removed child shards from our in-memory state and database, the reconciliation will implicitly remove
    5194              :                 // them from the node.
    5195              :                 tracing::warn!(
    5196              :                     "Node {node} unavailable, can't clean up during split abort. It will be cleaned up when it is reactivated."
    5197              :                 );
    5198              :                 continue;
    5199              :             }
    5200              : 
    5201              :             // Detach the remote child.  If the pageserver split API call is still in progress, this call will get
    5202              :             // a 503 and retry, up to our limit.
    5203              :             tracing::info!("Detaching {child_id} on {node}...");
    5204              :             match node
    5205              :                 .with_client_retries(
    5206            0 :                     |client| async move {
    5207            0 :                         let config = LocationConfig {
    5208            0 :                             mode: LocationConfigMode::Detached,
    5209            0 :                             generation: None,
    5210            0 :                             secondary_conf: None,
    5211            0 :                             shard_number: child_id.shard_number.0,
    5212            0 :                             shard_count: child_id.shard_count.literal(),
    5213            0 :                             // Stripe size and tenant config don't matter when detaching
    5214            0 :                             shard_stripe_size: 0,
    5215            0 :                             tenant_conf: TenantConfig::default(),
    5216            0 :                         };
    5217            0 : 
    5218            0 :                         client.location_config(child_id, config, None, false).await
    5219            0 :                     },
    5220              :                     &self.http_client,
    5221              :                     &self.config.pageserver_jwt_token,
    5222              :                     1,
    5223              :                     10,
    5224              :                     Duration::from_secs(5),
    5225              :                     &self.reconcilers_cancel,
    5226              :                 )
    5227              :                 .await
    5228              :             {
    5229              :                 Some(Ok(_)) => {}
    5230              :                 Some(Err(e)) => {
    5231              :                     // We failed to communicate with the remote node.  This is problematic: we may be
    5232              :                     // leaving it with a rogue child shard.
    5233              :                     tracing::warn!(
    5234              :                         "Failed to detach child {child_id} from node {node} during abort"
    5235              :                     );
    5236              :                     return Err(e.into());
    5237              :                 }
    5238              :                 None => {
    5239              :                     // Cancellation: we were shutdown or the node went offline. Shutdown is fine, we'll
    5240              :                     // clean up on restart. The node going offline requires a retry.
    5241              :                     return Err(TenantShardSplitAbortError::Unavailable);
    5242              :                 }
    5243              :             };
    5244              :         }
    5245              : 
    5246              :         tracing::info!("Successfully aborted split");
    5247              :         Ok(())
    5248              :     }
    5249              : 
    5250              :     /// Infallible final stage of [`Self::tenant_shard_split`]: update the contents
    5251              :     /// of the tenant map to reflect the child shards that exist after the split.
    5252            0 :     fn tenant_shard_split_commit_inmem(
    5253            0 :         &self,
    5254            0 :         tenant_id: TenantId,
    5255            0 :         new_shard_count: ShardCount,
    5256            0 :         new_stripe_size: Option<ShardStripeSize>,
    5257            0 :     ) -> (
    5258            0 :         TenantShardSplitResponse,
    5259            0 :         Vec<(TenantShardId, NodeId, ShardStripeSize)>,
    5260            0 :         Vec<ReconcilerWaiter>,
    5261            0 :     ) {
    5262            0 :         let mut response = TenantShardSplitResponse {
    5263            0 :             new_shards: Vec::new(),
    5264            0 :         };
    5265            0 :         let mut child_locations = Vec::new();
    5266            0 :         let mut waiters = Vec::new();
    5267            0 : 
    5268            0 :         {
    5269            0 :             let mut locked = self.inner.write().unwrap();
    5270            0 : 
    5271            0 :             let parent_ids = locked
    5272            0 :                 .tenants
    5273            0 :                 .range(TenantShardId::tenant_range(tenant_id))
    5274            0 :                 .map(|(shard_id, _)| *shard_id)
    5275            0 :                 .collect::<Vec<_>>();
    5276            0 : 
    5277            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    5278            0 :             for parent_id in parent_ids {
    5279            0 :                 let child_ids = parent_id.split(new_shard_count);
    5280              : 
    5281            0 :                 let (pageserver, generation, policy, parent_ident, config, preferred_az) = {
    5282            0 :                     let mut old_state = tenants
    5283            0 :                         .remove(&parent_id)
    5284            0 :                         .expect("It was present, we just split it");
    5285            0 : 
    5286            0 :                     // A non-splitting state is impossible, because [`Self::tenant_shard_split`] holds
    5287            0 :                     // a TenantId lock and passes it through to [`TenantShardSplitAbort`] in case of cleanup:
    5288            0 :                     // nothing else can clear this.
    5289            0 :                     assert!(matches!(old_state.splitting, SplitState::Splitting));
    5290              : 
    5291            0 :                     let old_attached = old_state.intent.get_attached().unwrap();
    5292            0 :                     old_state.intent.clear(scheduler);
    5293            0 :                     let generation = old_state.generation.expect("Shard must have been attached");
    5294            0 :                     (
    5295            0 :                         old_attached,
    5296            0 :                         generation,
    5297            0 :                         old_state.policy.clone(),
    5298            0 :                         old_state.shard,
    5299            0 :                         old_state.config.clone(),
    5300            0 :                         old_state.preferred_az().cloned(),
    5301            0 :                     )
    5302            0 :                 };
    5303            0 : 
    5304            0 :                 let mut schedule_context = ScheduleContext::default();
    5305            0 :                 for child in child_ids {
    5306            0 :                     let mut child_shard = parent_ident;
    5307            0 :                     child_shard.number = child.shard_number;
    5308            0 :                     child_shard.count = child.shard_count;
    5309            0 :                     if let Some(stripe_size) = new_stripe_size {
    5310            0 :                         child_shard.stripe_size = stripe_size;
    5311            0 :                     }
    5312              : 
    5313            0 :                     let mut child_observed: HashMap<NodeId, ObservedStateLocation> = HashMap::new();
    5314            0 :                     child_observed.insert(
    5315            0 :                         pageserver,
    5316            0 :                         ObservedStateLocation {
    5317            0 :                             conf: Some(attached_location_conf(
    5318            0 :                                 generation,
    5319            0 :                                 &child_shard,
    5320            0 :                                 &config,
    5321            0 :                                 &policy,
    5322            0 :                             )),
    5323            0 :                         },
    5324            0 :                     );
    5325            0 : 
    5326            0 :                     let mut child_state =
    5327            0 :                         TenantShard::new(child, child_shard, policy.clone(), preferred_az.clone());
    5328            0 :                     child_state.intent =
    5329            0 :                         IntentState::single(scheduler, Some(pageserver), preferred_az.clone());
    5330            0 :                     child_state.observed = ObservedState {
    5331            0 :                         locations: child_observed,
    5332            0 :                     };
    5333            0 :                     child_state.generation = Some(generation);
    5334            0 :                     child_state.config = config.clone();
    5335            0 : 
    5336            0 :                     // The child's TenantShard::splitting is intentionally left at the default value of Idle,
    5337            0 :                     // as at this point in the split process we have succeeded and this part is infallible:
    5338            0 :                     // we will never need to do any special recovery from this state.
    5339            0 : 
    5340            0 :                     child_locations.push((child, pageserver, child_shard.stripe_size));
    5341              : 
    5342            0 :                     if let Err(e) = child_state.schedule(scheduler, &mut schedule_context) {
    5343              :                         // This is not fatal, because we've implicitly already got an attached
    5344              :                         // location for the child shard.  Failure here just means we couldn't
    5345              :                         // find a secondary (e.g. because cluster is overloaded).
    5346            0 :                         tracing::warn!("Failed to schedule child shard {child}: {e}");
    5347            0 :                     }
    5348              :                     // In the background, attach secondary locations for the new shards
    5349            0 :                     if let Some(waiter) = self.maybe_reconcile_shard(
    5350            0 :                         &mut child_state,
    5351            0 :                         nodes,
    5352            0 :                         ReconcilerPriority::High,
    5353            0 :                     ) {
    5354            0 :                         waiters.push(waiter);
    5355            0 :                     }
    5356              : 
    5357            0 :                     tenants.insert(child, child_state);
    5358            0 :                     response.new_shards.push(child);
    5359              :                 }
    5360              :             }
    5361            0 :             (response, child_locations, waiters)
    5362            0 :         }
    5363            0 :     }
    5364              : 
    5365            0 :     async fn tenant_shard_split_start_secondaries(
    5366            0 :         &self,
    5367            0 :         tenant_id: TenantId,
    5368            0 :         waiters: Vec<ReconcilerWaiter>,
    5369            0 :     ) {
    5370              :         // Wait for initial reconcile of child shards, this creates the secondary locations
    5371            0 :         if let Err(e) = self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
    5372              :             // This is not a failure to split: it's some issue reconciling the new child shards, perhaps
    5373              :             // their secondaries couldn't be attached.
    5374            0 :             tracing::warn!("Failed to reconcile after split: {e}");
    5375            0 :             return;
    5376            0 :         }
    5377              : 
    5378              :         // Take the state lock to discover the attached & secondary intents for all shards
    5379            0 :         let (attached, secondary) = {
    5380            0 :             let locked = self.inner.read().unwrap();
    5381            0 :             let mut attached = Vec::new();
    5382            0 :             let mut secondary = Vec::new();
    5383              : 
    5384            0 :             for (tenant_shard_id, shard) in
    5385            0 :                 locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    5386              :             {
    5387            0 :                 let Some(node_id) = shard.intent.get_attached() else {
    5388              :                     // Unexpected.  Race with a PlacementPolicy change?
    5389            0 :                     tracing::warn!(
    5390            0 :                         "No attached node on {tenant_shard_id} immediately after shard split!"
    5391              :                     );
    5392            0 :                     continue;
    5393              :                 };
    5394              : 
    5395            0 :                 let Some(secondary_node_id) = shard.intent.get_secondary().first() else {
    5396              :                     // No secondary location.  Nothing for us to do.
    5397            0 :                     continue;
    5398              :                 };
    5399              : 
    5400            0 :                 let attached_node = locked
    5401            0 :                     .nodes
    5402            0 :                     .get(node_id)
    5403            0 :                     .expect("Pageservers may not be deleted while referenced");
    5404            0 : 
    5405            0 :                 let secondary_node = locked
    5406            0 :                     .nodes
    5407            0 :                     .get(secondary_node_id)
    5408            0 :                     .expect("Pageservers may not be deleted while referenced");
    5409            0 : 
    5410            0 :                 attached.push((*tenant_shard_id, attached_node.clone()));
    5411            0 :                 secondary.push((*tenant_shard_id, secondary_node.clone()));
    5412              :             }
    5413            0 :             (attached, secondary)
    5414            0 :         };
    5415            0 : 
    5416            0 :         if secondary.is_empty() {
    5417              :             // No secondary locations; nothing for us to do
    5418            0 :             return;
    5419            0 :         }
    5420              : 
    5421            0 :         for result in self
    5422            0 :             .tenant_for_shards_api(
    5423            0 :                 attached,
    5424            0 :                 |tenant_shard_id, client| async move {
    5425            0 :                     client.tenant_heatmap_upload(tenant_shard_id).await
    5426            0 :                 },
    5427            0 :                 1,
    5428            0 :                 1,
    5429            0 :                 SHORT_RECONCILE_TIMEOUT,
    5430            0 :                 &self.cancel,
    5431            0 :             )
    5432            0 :             .await
    5433              :         {
    5434            0 :             if let Err(e) = result {
    5435            0 :                 tracing::warn!("Error calling heatmap upload after shard split: {e}");
    5436            0 :                 return;
    5437            0 :             }
    5438              :         }
    5439              : 
    5440            0 :         for result in self
    5441            0 :             .tenant_for_shards_api(
    5442            0 :                 secondary,
    5443            0 :                 |tenant_shard_id, client| async move {
    5444            0 :                     client
    5445            0 :                         .tenant_secondary_download(tenant_shard_id, Some(Duration::ZERO))
    5446            0 :                         .await
    5447            0 :                 },
    5448            0 :                 1,
    5449            0 :                 1,
    5450            0 :                 SHORT_RECONCILE_TIMEOUT,
    5451            0 :                 &self.cancel,
    5452            0 :             )
    5453            0 :             .await
    5454              :         {
    5455            0 :             if let Err(e) = result {
    5456            0 :                 tracing::warn!("Error calling secondary download after shard split: {e}");
    5457            0 :                 return;
    5458            0 :             }
    5459              :         }
    5460            0 :     }
    5461              : 
    5462            0 :     pub(crate) async fn tenant_shard_split(
    5463            0 :         &self,
    5464            0 :         tenant_id: TenantId,
    5465            0 :         split_req: TenantShardSplitRequest,
    5466            0 :     ) -> Result<TenantShardSplitResponse, ApiError> {
    5467              :         // TODO: return 503 if we get stuck waiting for this lock
    5468              :         // (issue https://github.com/neondatabase/neon/issues/7108)
    5469            0 :         let _tenant_lock = trace_exclusive_lock(
    5470            0 :             &self.tenant_op_locks,
    5471            0 :             tenant_id,
    5472            0 :             TenantOperations::ShardSplit,
    5473            0 :         )
    5474            0 :         .await;
    5475              : 
    5476            0 :         let _gate = self
    5477            0 :             .reconcilers_gate
    5478            0 :             .enter()
    5479            0 :             .map_err(|_| ApiError::ShuttingDown)?;
    5480              : 
    5481              :         // Timeline imports on the pageserver side can't handle shard-splits.
    5482              :         // If the tenant is importing a timeline, dont't shard split it.
    5483            0 :         match self
    5484            0 :             .persistence
    5485            0 :             .is_tenant_importing_timeline(tenant_id)
    5486            0 :             .await
    5487              :         {
    5488            0 :             Ok(importing) => {
    5489            0 :                 if importing {
    5490            0 :                     return Err(ApiError::Conflict(
    5491            0 :                         "Cannot shard split during timeline import".to_string(),
    5492            0 :                     ));
    5493            0 :                 }
    5494              :             }
    5495            0 :             Err(err) => {
    5496            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
    5497            0 :                     "Failed to check for running imports: {err}"
    5498            0 :                 )));
    5499              :             }
    5500              :         }
    5501              : 
    5502            0 :         let new_shard_count = ShardCount::new(split_req.new_shard_count);
    5503            0 :         let new_stripe_size = split_req.new_stripe_size;
    5504              : 
    5505              :         // Validate the request and construct parameters.  This phase is fallible, but does not require
    5506              :         // rollback on errors, as it does no I/O and mutates no state.
    5507            0 :         let shard_split_params = match self.prepare_tenant_shard_split(tenant_id, split_req)? {
    5508            0 :             ShardSplitAction::NoOp(resp) => return Ok(resp),
    5509            0 :             ShardSplitAction::Split(params) => params,
    5510              :         };
    5511              : 
    5512              :         // Execute this split: this phase mutates state and does remote I/O on pageservers.  If it fails,
    5513              :         // we must roll back.
    5514            0 :         let r = self
    5515            0 :             .do_tenant_shard_split(tenant_id, shard_split_params)
    5516            0 :             .await;
    5517              : 
    5518            0 :         let (response, waiters) = match r {
    5519            0 :             Ok(r) => r,
    5520            0 :             Err(e) => {
    5521            0 :                 // Split might be part-done, we must do work to abort it.
    5522            0 :                 tracing::warn!("Enqueuing background abort of split on {tenant_id}");
    5523            0 :                 self.abort_tx
    5524            0 :                     .send(TenantShardSplitAbort {
    5525            0 :                         tenant_id,
    5526            0 :                         new_shard_count,
    5527            0 :                         new_stripe_size,
    5528            0 :                         _tenant_lock,
    5529            0 :                         _gate,
    5530            0 :                     })
    5531            0 :                     // Ignore error sending: that just means we're shutting down: aborts are ephemeral so it's fine to drop it.
    5532            0 :                     .ok();
    5533            0 :                 return Err(e);
    5534              :             }
    5535              :         };
    5536              : 
    5537              :         // The split is now complete.  As an optimization, we will trigger all the child shards to upload
    5538              :         // a heatmap immediately, and all their secondary locations to start downloading: this avoids waiting
    5539              :         // for the background heatmap/download interval before secondaries get warm enough to migrate shards
    5540              :         // in [`Self::optimize_all`]
    5541            0 :         self.tenant_shard_split_start_secondaries(tenant_id, waiters)
    5542            0 :             .await;
    5543            0 :         Ok(response)
    5544            0 :     }
    5545              : 
    5546            0 :     fn prepare_tenant_shard_split(
    5547            0 :         &self,
    5548            0 :         tenant_id: TenantId,
    5549            0 :         split_req: TenantShardSplitRequest,
    5550            0 :     ) -> Result<ShardSplitAction, ApiError> {
    5551            0 :         fail::fail_point!("shard-split-validation", |_| Err(ApiError::BadRequest(
    5552            0 :             anyhow::anyhow!("failpoint")
    5553            0 :         )));
    5554              : 
    5555            0 :         let mut policy = None;
    5556            0 :         let mut config = None;
    5557            0 :         let mut shard_ident = None;
    5558            0 :         let mut preferred_az_id = None;
    5559              :         // Validate input, and calculate which shards we will create
    5560            0 :         let (old_shard_count, targets) =
    5561              :             {
    5562            0 :                 let locked = self.inner.read().unwrap();
    5563            0 : 
    5564            0 :                 let pageservers = locked.nodes.clone();
    5565            0 : 
    5566            0 :                 let mut targets = Vec::new();
    5567            0 : 
    5568            0 :                 // In case this is a retry, count how many already-split shards we found
    5569            0 :                 let mut children_found = Vec::new();
    5570            0 :                 let mut old_shard_count = None;
    5571              : 
    5572            0 :                 for (tenant_shard_id, shard) in
    5573            0 :                     locked.tenants.range(TenantShardId::tenant_range(tenant_id))
    5574              :                 {
    5575            0 :                     match shard.shard.count.count().cmp(&split_req.new_shard_count) {
    5576              :                         Ordering::Equal => {
    5577              :                             //  Already split this
    5578            0 :                             children_found.push(*tenant_shard_id);
    5579            0 :                             continue;
    5580              :                         }
    5581              :                         Ordering::Greater => {
    5582            0 :                             return Err(ApiError::BadRequest(anyhow::anyhow!(
    5583            0 :                                 "Requested count {} but already have shards at count {}",
    5584            0 :                                 split_req.new_shard_count,
    5585            0 :                                 shard.shard.count.count()
    5586            0 :                             )));
    5587              :                         }
    5588            0 :                         Ordering::Less => {
    5589            0 :                             // Fall through: this shard has lower count than requested,
    5590            0 :                             // is a candidate for splitting.
    5591            0 :                         }
    5592            0 :                     }
    5593            0 : 
    5594            0 :                     match old_shard_count {
    5595            0 :                         None => old_shard_count = Some(shard.shard.count),
    5596            0 :                         Some(old_shard_count) => {
    5597            0 :                             if old_shard_count != shard.shard.count {
    5598              :                                 // We may hit this case if a caller asked for two splits to
    5599              :                                 // different sizes, before the first one is complete.
    5600              :                                 // e.g. 1->2, 2->4, where the 4 call comes while we have a mixture
    5601              :                                 // of shard_count=1 and shard_count=2 shards in the map.
    5602            0 :                                 return Err(ApiError::Conflict(
    5603            0 :                                     "Cannot split, currently mid-split".to_string(),
    5604            0 :                                 ));
    5605            0 :                             }
    5606              :                         }
    5607              :                     }
    5608            0 :                     if policy.is_none() {
    5609            0 :                         policy = Some(shard.policy.clone());
    5610            0 :                     }
    5611            0 :                     if shard_ident.is_none() {
    5612            0 :                         shard_ident = Some(shard.shard);
    5613            0 :                     }
    5614            0 :                     if config.is_none() {
    5615            0 :                         config = Some(shard.config.clone());
    5616            0 :                     }
    5617            0 :                     if preferred_az_id.is_none() {
    5618            0 :                         preferred_az_id = shard.preferred_az().cloned();
    5619            0 :                     }
    5620              : 
    5621            0 :                     if tenant_shard_id.shard_count.count() == split_req.new_shard_count {
    5622            0 :                         tracing::info!(
    5623            0 :                             "Tenant shard {} already has shard count {}",
    5624              :                             tenant_shard_id,
    5625              :                             split_req.new_shard_count
    5626              :                         );
    5627            0 :                         continue;
    5628            0 :                     }
    5629              : 
    5630            0 :                     let node_id = shard.intent.get_attached().ok_or(ApiError::BadRequest(
    5631            0 :                         anyhow::anyhow!("Cannot split a tenant that is not attached"),
    5632            0 :                     ))?;
    5633              : 
    5634            0 :                     let node = pageservers
    5635            0 :                         .get(&node_id)
    5636            0 :                         .expect("Pageservers may not be deleted while referenced");
    5637            0 : 
    5638            0 :                     targets.push(ShardSplitTarget {
    5639            0 :                         parent_id: *tenant_shard_id,
    5640            0 :                         node: node.clone(),
    5641            0 :                         child_ids: tenant_shard_id
    5642            0 :                             .split(ShardCount::new(split_req.new_shard_count)),
    5643            0 :                     });
    5644              :                 }
    5645              : 
    5646            0 :                 if targets.is_empty() {
    5647            0 :                     if children_found.len() == split_req.new_shard_count as usize {
    5648            0 :                         return Ok(ShardSplitAction::NoOp(TenantShardSplitResponse {
    5649            0 :                             new_shards: children_found,
    5650            0 :                         }));
    5651              :                     } else {
    5652              :                         // No shards found to split, and no existing children found: the
    5653              :                         // tenant doesn't exist at all.
    5654            0 :                         return Err(ApiError::NotFound(
    5655            0 :                             anyhow::anyhow!("Tenant {} not found", tenant_id).into(),
    5656            0 :                         ));
    5657              :                     }
    5658            0 :                 }
    5659            0 : 
    5660            0 :                 (old_shard_count, targets)
    5661            0 :             };
    5662            0 : 
    5663            0 :         // unwrap safety: we would have returned above if we didn't find at least one shard to split
    5664            0 :         let old_shard_count = old_shard_count.unwrap();
    5665            0 :         let shard_ident = if let Some(new_stripe_size) = split_req.new_stripe_size {
    5666              :             // This ShardIdentity will be used as the template for all children, so this implicitly
    5667              :             // applies the new stripe size to the children.
    5668            0 :             let mut shard_ident = shard_ident.unwrap();
    5669            0 :             if shard_ident.count.count() > 1 && shard_ident.stripe_size != new_stripe_size {
    5670            0 :                 return Err(ApiError::BadRequest(anyhow::anyhow!(
    5671            0 :                     "Attempted to change stripe size ({:?}->{new_stripe_size:?}) on a tenant with multiple shards",
    5672            0 :                     shard_ident.stripe_size
    5673            0 :                 )));
    5674            0 :             }
    5675            0 : 
    5676            0 :             shard_ident.stripe_size = new_stripe_size;
    5677            0 :             tracing::info!("applied  stripe size {}", shard_ident.stripe_size.0);
    5678            0 :             shard_ident
    5679              :         } else {
    5680            0 :             shard_ident.unwrap()
    5681              :         };
    5682            0 :         let policy = policy.unwrap();
    5683            0 :         let config = config.unwrap();
    5684            0 : 
    5685            0 :         Ok(ShardSplitAction::Split(Box::new(ShardSplitParams {
    5686            0 :             old_shard_count,
    5687            0 :             new_shard_count: ShardCount::new(split_req.new_shard_count),
    5688            0 :             new_stripe_size: split_req.new_stripe_size,
    5689            0 :             targets,
    5690            0 :             policy,
    5691            0 :             config,
    5692            0 :             shard_ident,
    5693            0 :             preferred_az_id,
    5694            0 :         })))
    5695            0 :     }
    5696              : 
    5697            0 :     async fn do_tenant_shard_split(
    5698            0 :         &self,
    5699            0 :         tenant_id: TenantId,
    5700            0 :         params: Box<ShardSplitParams>,
    5701            0 :     ) -> Result<(TenantShardSplitResponse, Vec<ReconcilerWaiter>), ApiError> {
    5702            0 :         // FIXME: we have dropped self.inner lock, and not yet written anything to the database: another
    5703            0 :         // request could occur here, deleting or mutating the tenant.  begin_shard_split checks that the
    5704            0 :         // parent shards exist as expected, but it would be neater to do the above pre-checks within the
    5705            0 :         // same database transaction rather than pre-check in-memory and then maybe-fail the database write.
    5706            0 :         // (https://github.com/neondatabase/neon/issues/6676)
    5707            0 : 
    5708            0 :         let ShardSplitParams {
    5709            0 :             old_shard_count,
    5710            0 :             new_shard_count,
    5711            0 :             new_stripe_size,
    5712            0 :             mut targets,
    5713            0 :             policy,
    5714            0 :             config,
    5715            0 :             shard_ident,
    5716            0 :             preferred_az_id,
    5717            0 :         } = *params;
    5718              : 
    5719              :         // Drop any secondary locations: pageservers do not support splitting these, and in any case the
    5720              :         // end-state for a split tenant will usually be to have secondary locations on different nodes.
    5721              :         // The reconciliation calls in this block also implicitly cancel+barrier wrt any ongoing reconciliation
    5722              :         // at the time of split.
    5723            0 :         let waiters = {
    5724            0 :             let mut locked = self.inner.write().unwrap();
    5725            0 :             let mut waiters = Vec::new();
    5726            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    5727            0 :             for target in &mut targets {
    5728            0 :                 let Some(shard) = tenants.get_mut(&target.parent_id) else {
    5729              :                     // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
    5730            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    5731            0 :                         "Shard {} not found",
    5732            0 :                         target.parent_id
    5733            0 :                     )));
    5734              :                 };
    5735              : 
    5736            0 :                 if shard.intent.get_attached() != &Some(target.node.get_id()) {
    5737              :                     // Paranoia check: this shouldn't happen: we have the oplock for this tenant ID.
    5738            0 :                     return Err(ApiError::Conflict(format!(
    5739            0 :                         "Shard {} unexpectedly rescheduled during split",
    5740            0 :                         target.parent_id
    5741            0 :                     )));
    5742            0 :                 }
    5743            0 : 
    5744            0 :                 // Irrespective of PlacementPolicy, clear secondary locations from intent
    5745            0 :                 shard.intent.clear_secondary(scheduler);
    5746              : 
    5747              :                 // Run Reconciler to execute detach fo secondary locations.
    5748            0 :                 if let Some(waiter) =
    5749            0 :                     self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
    5750            0 :                 {
    5751            0 :                     waiters.push(waiter);
    5752            0 :                 }
    5753              :             }
    5754            0 :             waiters
    5755            0 :         };
    5756            0 :         self.await_waiters(waiters, RECONCILE_TIMEOUT).await?;
    5757              : 
    5758              :         // Before creating any new child shards in memory or on the pageservers, persist them: this
    5759              :         // enables us to ensure that we will always be able to clean up if something goes wrong.  This also
    5760              :         // acts as the protection against two concurrent attempts to split: one of them will get a database
    5761              :         // error trying to insert the child shards.
    5762            0 :         let mut child_tsps = Vec::new();
    5763            0 :         for target in &targets {
    5764            0 :             let mut this_child_tsps = Vec::new();
    5765            0 :             for child in &target.child_ids {
    5766            0 :                 let mut child_shard = shard_ident;
    5767            0 :                 child_shard.number = child.shard_number;
    5768            0 :                 child_shard.count = child.shard_count;
    5769            0 : 
    5770            0 :                 tracing::info!(
    5771            0 :                     "Create child shard persistence with stripe size {}",
    5772              :                     shard_ident.stripe_size.0
    5773              :                 );
    5774              : 
    5775            0 :                 this_child_tsps.push(TenantShardPersistence {
    5776            0 :                     tenant_id: child.tenant_id.to_string(),
    5777            0 :                     shard_number: child.shard_number.0 as i32,
    5778            0 :                     shard_count: child.shard_count.literal() as i32,
    5779            0 :                     shard_stripe_size: shard_ident.stripe_size.0 as i32,
    5780            0 :                     // Note: this generation is a placeholder, [`Persistence::begin_shard_split`] will
    5781            0 :                     // populate the correct generation as part of its transaction, to protect us
    5782            0 :                     // against racing with changes in the state of the parent.
    5783            0 :                     generation: None,
    5784            0 :                     generation_pageserver: Some(target.node.get_id().0 as i64),
    5785            0 :                     placement_policy: serde_json::to_string(&policy).unwrap(),
    5786            0 :                     config: serde_json::to_string(&config).unwrap(),
    5787            0 :                     splitting: SplitState::Splitting,
    5788            0 : 
    5789            0 :                     // Scheduling policies and preferred AZ do not carry through to children
    5790            0 :                     scheduling_policy: serde_json::to_string(&ShardSchedulingPolicy::default())
    5791            0 :                         .unwrap(),
    5792            0 :                     preferred_az_id: preferred_az_id.as_ref().map(|az| az.0.clone()),
    5793            0 :                 });
    5794            0 :             }
    5795              : 
    5796            0 :             child_tsps.push((target.parent_id, this_child_tsps));
    5797              :         }
    5798              : 
    5799            0 :         if let Err(e) = self
    5800            0 :             .persistence
    5801            0 :             .begin_shard_split(old_shard_count, tenant_id, child_tsps)
    5802            0 :             .await
    5803              :         {
    5804            0 :             match e {
    5805              :                 DatabaseError::Query(diesel::result::Error::DatabaseError(
    5806              :                     DatabaseErrorKind::UniqueViolation,
    5807              :                     _,
    5808              :                 )) => {
    5809              :                     // Inserting a child shard violated a unique constraint: we raced with another call to
    5810              :                     // this function
    5811            0 :                     tracing::warn!("Conflicting attempt to split {tenant_id}: {e}");
    5812            0 :                     return Err(ApiError::Conflict("Tenant is already splitting".into()));
    5813              :                 }
    5814            0 :                 _ => return Err(ApiError::InternalServerError(e.into())),
    5815              :             }
    5816            0 :         }
    5817            0 :         fail::fail_point!("shard-split-post-begin", |_| Err(
    5818            0 :             ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
    5819            0 :         ));
    5820              : 
    5821              :         // Now that I have persisted the splitting state, apply it in-memory.  This is infallible, so
    5822              :         // callers may assume that if splitting is set in memory, then it was persisted, and if splitting
    5823              :         // is not set in memory, then it was not persisted.
    5824              :         {
    5825            0 :             let mut locked = self.inner.write().unwrap();
    5826            0 :             for target in &targets {
    5827            0 :                 if let Some(parent_shard) = locked.tenants.get_mut(&target.parent_id) {
    5828            0 :                     parent_shard.splitting = SplitState::Splitting;
    5829            0 :                     // Put the observed state to None, to reflect that it is indeterminate once we start the
    5830            0 :                     // split operation.
    5831            0 :                     parent_shard
    5832            0 :                         .observed
    5833            0 :                         .locations
    5834            0 :                         .insert(target.node.get_id(), ObservedStateLocation { conf: None });
    5835            0 :                 }
    5836              :             }
    5837              :         }
    5838              : 
    5839              :         // TODO: issue split calls concurrently (this only matters once we're splitting
    5840              :         // N>1 shards into M shards -- initially we're usually splitting 1 shard into N).
    5841              : 
    5842            0 :         for target in &targets {
    5843              :             let ShardSplitTarget {
    5844            0 :                 parent_id,
    5845            0 :                 node,
    5846            0 :                 child_ids,
    5847            0 :             } = target;
    5848            0 :             let client = PageserverClient::new(
    5849            0 :                 node.get_id(),
    5850            0 :                 self.http_client.clone(),
    5851            0 :                 node.base_url(),
    5852            0 :                 self.config.pageserver_jwt_token.as_deref(),
    5853            0 :             );
    5854            0 :             let response = client
    5855            0 :                 .tenant_shard_split(
    5856            0 :                     *parent_id,
    5857            0 :                     TenantShardSplitRequest {
    5858            0 :                         new_shard_count: new_shard_count.literal(),
    5859            0 :                         new_stripe_size,
    5860            0 :                     },
    5861            0 :                 )
    5862            0 :                 .await
    5863            0 :                 .map_err(|e| ApiError::Conflict(format!("Failed to split {}: {}", parent_id, e)))?;
    5864              : 
    5865            0 :             fail::fail_point!("shard-split-post-remote", |_| Err(ApiError::Conflict(
    5866            0 :                 "failpoint".to_string()
    5867            0 :             )));
    5868              : 
    5869            0 :             failpoint_support::sleep_millis_async!(
    5870              :                 "shard-split-post-remote-sleep",
    5871            0 :                 &self.reconcilers_cancel
    5872              :             );
    5873              : 
    5874            0 :             tracing::info!(
    5875            0 :                 "Split {} into {}",
    5876            0 :                 parent_id,
    5877            0 :                 response
    5878            0 :                     .new_shards
    5879            0 :                     .iter()
    5880            0 :                     .map(|s| format!("{:?}", s))
    5881            0 :                     .collect::<Vec<_>>()
    5882            0 :                     .join(",")
    5883              :             );
    5884              : 
    5885            0 :             if &response.new_shards != child_ids {
    5886              :                 // This should never happen: the pageserver should agree with us on how shard splits work.
    5887            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
    5888            0 :                     "Splitting shard {} resulted in unexpected IDs: {:?} (expected {:?})",
    5889            0 :                     parent_id,
    5890            0 :                     response.new_shards,
    5891            0 :                     child_ids
    5892            0 :                 )));
    5893            0 :             }
    5894              :         }
    5895              : 
    5896            0 :         pausable_failpoint!("shard-split-pre-complete");
    5897              : 
    5898              :         // TODO: if the pageserver restarted concurrently with our split API call,
    5899              :         // the actual generation of the child shard might differ from the generation
    5900              :         // we expect it to have.  In order for our in-database generation to end up
    5901              :         // correct, we should carry the child generation back in the response and apply it here
    5902              :         // in complete_shard_split (and apply the correct generation in memory)
    5903              :         // (or, we can carry generation in the request and reject the request if
    5904              :         //  it doesn't match, but that requires more retry logic on this side)
    5905              : 
    5906            0 :         self.persistence
    5907            0 :             .complete_shard_split(tenant_id, old_shard_count, new_shard_count)
    5908            0 :             .await?;
    5909              : 
    5910            0 :         fail::fail_point!("shard-split-post-complete", |_| Err(
    5911            0 :             ApiError::InternalServerError(anyhow::anyhow!("failpoint"))
    5912            0 :         ));
    5913              : 
    5914              :         // Replace all the shards we just split with their children: this phase is infallible.
    5915            0 :         let (response, child_locations, waiters) =
    5916            0 :             self.tenant_shard_split_commit_inmem(tenant_id, new_shard_count, new_stripe_size);
    5917            0 : 
    5918            0 :         // Send compute notifications for all the new shards
    5919            0 :         let mut failed_notifications = Vec::new();
    5920            0 :         for (child_id, child_ps, stripe_size) in child_locations {
    5921            0 :             if let Err(e) = self
    5922            0 :                 .compute_hook
    5923            0 :                 .notify(
    5924            0 :                     compute_hook::ShardUpdate {
    5925            0 :                         tenant_shard_id: child_id,
    5926            0 :                         node_id: child_ps,
    5927            0 :                         stripe_size,
    5928            0 :                         preferred_az: preferred_az_id.as_ref().map(Cow::Borrowed),
    5929            0 :                     },
    5930            0 :                     &self.reconcilers_cancel,
    5931            0 :                 )
    5932            0 :                 .await
    5933              :             {
    5934            0 :                 tracing::warn!(
    5935            0 :                     "Failed to update compute of {}->{} during split, proceeding anyway to complete split ({e})",
    5936              :                     child_id,
    5937              :                     child_ps
    5938              :                 );
    5939            0 :                 failed_notifications.push(child_id);
    5940            0 :             }
    5941              :         }
    5942              : 
    5943              :         // If we failed any compute notifications, make a note to retry later.
    5944            0 :         if !failed_notifications.is_empty() {
    5945            0 :             let mut locked = self.inner.write().unwrap();
    5946            0 :             for failed in failed_notifications {
    5947            0 :                 if let Some(shard) = locked.tenants.get_mut(&failed) {
    5948            0 :                     shard.pending_compute_notification = true;
    5949            0 :                 }
    5950              :             }
    5951            0 :         }
    5952              : 
    5953            0 :         Ok((response, waiters))
    5954            0 :     }
    5955              : 
    5956              :     /// A graceful migration: update the preferred node and let optimisation handle the migration
    5957              :     /// in the background (may take a long time as it will fully warm up a location before cutting over)
    5958              :     ///
    5959              :     /// Our external API calls this a 'prewarm=true' migration, but internally it isn't a special prewarm step: it's
    5960              :     /// just a migration that uses the same graceful procedure as our background scheduling optimisations would use.
    5961            0 :     fn tenant_shard_migrate_with_prewarm(
    5962            0 :         &self,
    5963            0 :         migrate_req: &TenantShardMigrateRequest,
    5964            0 :         shard: &mut TenantShard,
    5965            0 :         scheduler: &mut Scheduler,
    5966            0 :         schedule_context: ScheduleContext,
    5967            0 :     ) -> Result<Option<ScheduleOptimization>, ApiError> {
    5968            0 :         shard.set_preferred_node(Some(migrate_req.node_id));
    5969            0 : 
    5970            0 :         // Generate whatever the initial change to the intent is: this could be creation of a secondary, or
    5971            0 :         // cutting over to an existing secondary.  Caller is responsible for validating this before applying it,
    5972            0 :         // e.g. by checking secondary is warm enough.
    5973            0 :         Ok(shard.optimize_attachment(scheduler, &schedule_context))
    5974            0 :     }
    5975              : 
    5976              :     /// Immediate migration: directly update the intent state and kick off a reconciler
    5977            0 :     fn tenant_shard_migrate_immediate(
    5978            0 :         &self,
    5979            0 :         migrate_req: &TenantShardMigrateRequest,
    5980            0 :         nodes: &Arc<HashMap<NodeId, Node>>,
    5981            0 :         shard: &mut TenantShard,
    5982            0 :         scheduler: &mut Scheduler,
    5983            0 :     ) -> Result<Option<ReconcilerWaiter>, ApiError> {
    5984            0 :         // Non-graceful migration: update the intent state immediately
    5985            0 :         let old_attached = *shard.intent.get_attached();
    5986            0 :         match shard.policy {
    5987            0 :             PlacementPolicy::Attached(n) => {
    5988            0 :                 // If our new attached node was a secondary, it no longer should be.
    5989            0 :                 shard
    5990            0 :                     .intent
    5991            0 :                     .remove_secondary(scheduler, migrate_req.node_id);
    5992            0 : 
    5993            0 :                 shard
    5994            0 :                     .intent
    5995            0 :                     .set_attached(scheduler, Some(migrate_req.node_id));
    5996              : 
    5997              :                 // If we were already attached to something, demote that to a secondary
    5998            0 :                 if let Some(old_attached) = old_attached {
    5999            0 :                     if n > 0 {
    6000              :                         // Remove other secondaries to make room for the location we'll demote
    6001            0 :                         while shard.intent.get_secondary().len() >= n {
    6002            0 :                             shard.intent.pop_secondary(scheduler);
    6003            0 :                         }
    6004              : 
    6005            0 :                         shard.intent.push_secondary(scheduler, old_attached);
    6006            0 :                     }
    6007            0 :                 }
    6008              :             }
    6009            0 :             PlacementPolicy::Secondary => {
    6010            0 :                 shard.intent.clear(scheduler);
    6011            0 :                 shard.intent.push_secondary(scheduler, migrate_req.node_id);
    6012            0 :             }
    6013              :             PlacementPolicy::Detached => {
    6014            0 :                 return Err(ApiError::BadRequest(anyhow::anyhow!(
    6015            0 :                     "Cannot migrate a tenant that is PlacementPolicy::Detached: configure it to an attached policy first"
    6016            0 :                 )));
    6017              :             }
    6018              :         }
    6019              : 
    6020            0 :         tracing::info!("Migrating: new intent {:?}", shard.intent);
    6021            0 :         shard.sequence = shard.sequence.next();
    6022            0 :         shard.set_preferred_node(None); // Abort any in-flight graceful migration
    6023            0 :         Ok(self.maybe_configured_reconcile_shard(
    6024            0 :             shard,
    6025            0 :             nodes,
    6026            0 :             (&migrate_req.migration_config).into(),
    6027            0 :         ))
    6028            0 :     }
    6029              : 
    6030            0 :     pub(crate) async fn tenant_shard_migrate(
    6031            0 :         &self,
    6032            0 :         tenant_shard_id: TenantShardId,
    6033            0 :         migrate_req: TenantShardMigrateRequest,
    6034            0 :     ) -> Result<TenantShardMigrateResponse, ApiError> {
    6035              :         // Depending on whether the migration is a change and whether it's graceful or immediate, we might
    6036              :         // get a different outcome to handle
    6037              :         enum MigrationOutcome {
    6038              :             Optimization(Option<ScheduleOptimization>),
    6039              :             Reconcile(Option<ReconcilerWaiter>),
    6040              :         }
    6041              : 
    6042            0 :         let outcome = {
    6043            0 :             let mut locked = self.inner.write().unwrap();
    6044            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    6045              : 
    6046            0 :             let Some(node) = nodes.get(&migrate_req.node_id) else {
    6047            0 :                 return Err(ApiError::BadRequest(anyhow::anyhow!(
    6048            0 :                     "Node {} not found",
    6049            0 :                     migrate_req.node_id
    6050            0 :                 )));
    6051              :             };
    6052              : 
    6053              :             // Migration to unavavailable node requires force flag
    6054            0 :             if !node.is_available() {
    6055            0 :                 if migrate_req.migration_config.override_scheduler {
    6056              :                     // Warn but proceed: the caller may intend to manually adjust the placement of
    6057              :                     // a shard even if the node is down, e.g. if intervening during an incident.
    6058            0 :                     tracing::warn!("Forcibly migrating to unavailable node {node}");
    6059              :                 } else {
    6060            0 :                     tracing::warn!("Node {node} is unavailable, refusing migration");
    6061            0 :                     return Err(ApiError::PreconditionFailed(
    6062            0 :                         format!("Node {node} is unavailable").into_boxed_str(),
    6063            0 :                     ));
    6064              :                 }
    6065            0 :             }
    6066              : 
    6067              :             // Calculate the ScheduleContext for this tenant
    6068            0 :             let mut schedule_context = ScheduleContext::default();
    6069            0 :             for (_shard_id, shard) in
    6070            0 :                 tenants.range(TenantShardId::tenant_range(tenant_shard_id.tenant_id))
    6071            0 :             {
    6072            0 :                 schedule_context.avoid(&shard.intent.all_pageservers());
    6073            0 :             }
    6074              : 
    6075              :             // Look up the specific shard we will migrate
    6076            0 :             let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    6077            0 :                 return Err(ApiError::NotFound(
    6078            0 :                     anyhow::anyhow!("Tenant shard not found").into(),
    6079            0 :                 ));
    6080              :             };
    6081              : 
    6082              :             // Migration to a node with unfavorable scheduling score requires a force flag, because it might just
    6083              :             // be migrated back by the optimiser.
    6084            0 :             if let Some(better_node) = shard.find_better_location::<AttachedShardTag>(
    6085            0 :                 scheduler,
    6086            0 :                 &schedule_context,
    6087            0 :                 migrate_req.node_id,
    6088            0 :                 &[],
    6089            0 :             ) {
    6090            0 :                 if !migrate_req.migration_config.override_scheduler {
    6091            0 :                     return Err(ApiError::PreconditionFailed(
    6092            0 :                         "Migration to a worse-scoring node".into(),
    6093            0 :                     ));
    6094              :                 } else {
    6095            0 :                     tracing::info!(
    6096            0 :                         "Migrating to a worse-scoring node {} (optimiser would prefer {better_node})",
    6097              :                         migrate_req.node_id
    6098              :                     );
    6099              :                 }
    6100            0 :             }
    6101              : 
    6102            0 :             if let Some(origin_node_id) = migrate_req.origin_node_id {
    6103            0 :                 if shard.intent.get_attached() != &Some(origin_node_id) {
    6104            0 :                     return Err(ApiError::PreconditionFailed(
    6105            0 :                         format!(
    6106            0 :                             "Migration expected to originate from {} but shard is on {:?}",
    6107            0 :                             origin_node_id,
    6108            0 :                             shard.intent.get_attached()
    6109            0 :                         )
    6110            0 :                         .into(),
    6111            0 :                     ));
    6112            0 :                 }
    6113            0 :             }
    6114              : 
    6115            0 :             if shard.intent.get_attached() == &Some(migrate_req.node_id) {
    6116              :                 // No-op case: we will still proceed to wait for reconciliation in case it is
    6117              :                 // incomplete from an earlier update to the intent.
    6118            0 :                 tracing::info!("Migrating: intent is unchanged {:?}", shard.intent);
    6119              : 
    6120              :                 // An instruction to migrate to the currently attached node should
    6121              :                 // cancel any pending graceful migration
    6122            0 :                 shard.set_preferred_node(None);
    6123            0 : 
    6124            0 :                 MigrationOutcome::Reconcile(self.maybe_configured_reconcile_shard(
    6125            0 :                     shard,
    6126            0 :                     nodes,
    6127            0 :                     (&migrate_req.migration_config).into(),
    6128            0 :                 ))
    6129            0 :             } else if migrate_req.migration_config.prewarm {
    6130            0 :                 MigrationOutcome::Optimization(self.tenant_shard_migrate_with_prewarm(
    6131            0 :                     &migrate_req,
    6132            0 :                     shard,
    6133            0 :                     scheduler,
    6134            0 :                     schedule_context,
    6135            0 :                 )?)
    6136              :             } else {
    6137            0 :                 MigrationOutcome::Reconcile(self.tenant_shard_migrate_immediate(
    6138            0 :                     &migrate_req,
    6139            0 :                     nodes,
    6140            0 :                     shard,
    6141            0 :                     scheduler,
    6142            0 :                 )?)
    6143              :             }
    6144              :         };
    6145              : 
    6146              :         // We may need to validate + apply an optimisation, or we may need to just retrive a reconcile waiter
    6147            0 :         let waiter = match outcome {
    6148            0 :             MigrationOutcome::Optimization(Some(optimization)) => {
    6149              :                 // Validate and apply the optimization -- this would happen anyway in background reconcile loop, but
    6150              :                 // we might as well do it more promptly as this is a direct external request.
    6151            0 :                 let mut validated = self
    6152            0 :                     .optimize_all_validate(vec![(tenant_shard_id, optimization)])
    6153            0 :                     .await;
    6154            0 :                 if let Some((_shard_id, optimization)) = validated.pop() {
    6155            0 :                     let mut locked = self.inner.write().unwrap();
    6156            0 :                     let (nodes, tenants, scheduler) = locked.parts_mut();
    6157            0 :                     let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    6158              :                         // Rare but possible: tenant is removed between generating optimisation and validating it.
    6159            0 :                         return Err(ApiError::NotFound(
    6160            0 :                             anyhow::anyhow!("Tenant shard not found").into(),
    6161            0 :                         ));
    6162              :                     };
    6163              : 
    6164            0 :                     if !shard.apply_optimization(scheduler, optimization) {
    6165              :                         // This can happen but is unusual enough to warn on: something else changed in the shard that made the optimisation stale
    6166              :                         // and therefore not applied.
    6167            0 :                         tracing::warn!(
    6168            0 :                             "Schedule optimisation generated during graceful migration was not applied, shard changed?"
    6169              :                         );
    6170            0 :                     }
    6171            0 :                     self.maybe_configured_reconcile_shard(
    6172            0 :                         shard,
    6173            0 :                         nodes,
    6174            0 :                         (&migrate_req.migration_config).into(),
    6175            0 :                     )
    6176              :                 } else {
    6177            0 :                     None
    6178              :                 }
    6179              :             }
    6180            0 :             MigrationOutcome::Optimization(None) => None,
    6181            0 :             MigrationOutcome::Reconcile(waiter) => waiter,
    6182              :         };
    6183              : 
    6184              :         // Finally, wait for any reconcile we started to complete.  In the case of immediate-mode migrations to cold
    6185              :         // locations, this has a good chance of timing out.
    6186            0 :         if let Some(waiter) = waiter {
    6187            0 :             waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
    6188              :         } else {
    6189            0 :             tracing::info!("Migration is a no-op");
    6190              :         }
    6191              : 
    6192            0 :         Ok(TenantShardMigrateResponse {})
    6193            0 :     }
    6194              : 
    6195            0 :     pub(crate) async fn tenant_shard_migrate_secondary(
    6196            0 :         &self,
    6197            0 :         tenant_shard_id: TenantShardId,
    6198            0 :         migrate_req: TenantShardMigrateRequest,
    6199            0 :     ) -> Result<TenantShardMigrateResponse, ApiError> {
    6200            0 :         let waiter = {
    6201            0 :             let mut locked = self.inner.write().unwrap();
    6202            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    6203              : 
    6204            0 :             let Some(node) = nodes.get(&migrate_req.node_id) else {
    6205            0 :                 return Err(ApiError::BadRequest(anyhow::anyhow!(
    6206            0 :                     "Node {} not found",
    6207            0 :                     migrate_req.node_id
    6208            0 :                 )));
    6209              :             };
    6210              : 
    6211            0 :             if !node.is_available() {
    6212              :                 // Warn but proceed: the caller may intend to manually adjust the placement of
    6213              :                 // a shard even if the node is down, e.g. if intervening during an incident.
    6214            0 :                 tracing::warn!("Migrating to unavailable node {node}");
    6215            0 :             }
    6216              : 
    6217            0 :             let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    6218            0 :                 return Err(ApiError::NotFound(
    6219            0 :                     anyhow::anyhow!("Tenant shard not found").into(),
    6220            0 :                 ));
    6221              :             };
    6222              : 
    6223            0 :             if shard.intent.get_secondary().len() == 1
    6224            0 :                 && shard.intent.get_secondary()[0] == migrate_req.node_id
    6225              :             {
    6226            0 :                 tracing::info!(
    6227            0 :                     "Migrating secondary to {node}: intent is unchanged {:?}",
    6228              :                     shard.intent
    6229              :                 );
    6230            0 :             } else if shard.intent.get_attached() == &Some(migrate_req.node_id) {
    6231            0 :                 tracing::info!(
    6232            0 :                     "Migrating secondary to {node}: already attached where we were asked to create a secondary"
    6233              :                 );
    6234              :             } else {
    6235            0 :                 let old_secondaries = shard.intent.get_secondary().clone();
    6236            0 :                 for secondary in old_secondaries {
    6237            0 :                     shard.intent.remove_secondary(scheduler, secondary);
    6238            0 :                 }
    6239              : 
    6240            0 :                 shard.intent.push_secondary(scheduler, migrate_req.node_id);
    6241            0 :                 shard.sequence = shard.sequence.next();
    6242            0 :                 tracing::info!(
    6243            0 :                     "Migrating secondary to {node}: new intent {:?}",
    6244              :                     shard.intent
    6245              :                 );
    6246              :             }
    6247              : 
    6248            0 :             self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::High)
    6249              :         };
    6250              : 
    6251            0 :         if let Some(waiter) = waiter {
    6252            0 :             waiter.wait_timeout(RECONCILE_TIMEOUT).await?;
    6253              :         } else {
    6254            0 :             tracing::info!("Migration is a no-op");
    6255              :         }
    6256              : 
    6257            0 :         Ok(TenantShardMigrateResponse {})
    6258            0 :     }
    6259              : 
    6260              :     /// 'cancel' in this context means cancel any ongoing reconcile
    6261            0 :     pub(crate) async fn tenant_shard_cancel_reconcile(
    6262            0 :         &self,
    6263            0 :         tenant_shard_id: TenantShardId,
    6264            0 :     ) -> Result<(), ApiError> {
    6265              :         // Take state lock and fire the cancellation token, after which we drop lock and wait for any ongoing reconcile to complete
    6266            0 :         let waiter = {
    6267            0 :             let locked = self.inner.write().unwrap();
    6268            0 :             let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
    6269            0 :                 return Err(ApiError::NotFound(
    6270            0 :                     anyhow::anyhow!("Tenant shard not found").into(),
    6271            0 :                 ));
    6272              :             };
    6273              : 
    6274            0 :             let waiter = shard.get_waiter();
    6275            0 :             match waiter {
    6276              :                 None => {
    6277            0 :                     tracing::info!("Shard does not have an ongoing Reconciler");
    6278            0 :                     return Ok(());
    6279              :                 }
    6280            0 :                 Some(waiter) => {
    6281            0 :                     tracing::info!("Cancelling Reconciler");
    6282            0 :                     shard.cancel_reconciler();
    6283            0 :                     waiter
    6284            0 :                 }
    6285            0 :             }
    6286            0 :         };
    6287            0 : 
    6288            0 :         // Cancellation should be prompt.  If this fails we have still done our job of firing the
    6289            0 :         // cancellation token, but by returning an ApiError we will indicate to the caller that
    6290            0 :         // the Reconciler is misbehaving and not respecting the cancellation token
    6291            0 :         self.await_waiters(vec![waiter], SHORT_RECONCILE_TIMEOUT)
    6292            0 :             .await?;
    6293              : 
    6294            0 :         Ok(())
    6295            0 :     }
    6296              : 
    6297              :     /// This is for debug/support only: we simply drop all state for a tenant, without
    6298              :     /// detaching or deleting it on pageservers.
    6299            0 :     pub(crate) async fn tenant_drop(&self, tenant_id: TenantId) -> Result<(), ApiError> {
    6300            0 :         self.persistence.delete_tenant(tenant_id).await?;
    6301              : 
    6302            0 :         let mut locked = self.inner.write().unwrap();
    6303            0 :         let (_nodes, tenants, scheduler) = locked.parts_mut();
    6304            0 :         let mut shards = Vec::new();
    6305            0 :         for (tenant_shard_id, _) in tenants.range(TenantShardId::tenant_range(tenant_id)) {
    6306            0 :             shards.push(*tenant_shard_id);
    6307            0 :         }
    6308              : 
    6309            0 :         for shard_id in shards {
    6310            0 :             if let Some(mut shard) = tenants.remove(&shard_id) {
    6311            0 :                 shard.intent.clear(scheduler);
    6312            0 :             }
    6313              :         }
    6314              : 
    6315            0 :         Ok(())
    6316            0 :     }
    6317              : 
    6318              :     /// This is for debug/support only: assuming tenant data is already present in S3, we "create" a
    6319              :     /// tenant with a very high generation number so that it will see the existing data.
    6320            0 :     pub(crate) async fn tenant_import(
    6321            0 :         &self,
    6322            0 :         tenant_id: TenantId,
    6323            0 :     ) -> Result<TenantCreateResponse, ApiError> {
    6324            0 :         // Pick an arbitrary available pageserver to use for scanning the tenant in remote storage
    6325            0 :         let maybe_node = {
    6326            0 :             self.inner
    6327            0 :                 .read()
    6328            0 :                 .unwrap()
    6329            0 :                 .nodes
    6330            0 :                 .values()
    6331            0 :                 .find(|n| n.is_available())
    6332            0 :                 .cloned()
    6333              :         };
    6334            0 :         let Some(node) = maybe_node else {
    6335            0 :             return Err(ApiError::BadRequest(anyhow::anyhow!("No nodes available")));
    6336              :         };
    6337              : 
    6338            0 :         let client = PageserverClient::new(
    6339            0 :             node.get_id(),
    6340            0 :             self.http_client.clone(),
    6341            0 :             node.base_url(),
    6342            0 :             self.config.pageserver_jwt_token.as_deref(),
    6343            0 :         );
    6344              : 
    6345            0 :         let scan_result = client
    6346            0 :             .tenant_scan_remote_storage(tenant_id)
    6347            0 :             .await
    6348            0 :             .map_err(|e| passthrough_api_error(&node, e))?;
    6349              : 
    6350              :         // A post-split tenant may contain a mixture of shard counts in remote storage: pick the highest count.
    6351            0 :         let Some(shard_count) = scan_result
    6352            0 :             .shards
    6353            0 :             .iter()
    6354            0 :             .map(|s| s.tenant_shard_id.shard_count)
    6355            0 :             .max()
    6356              :         else {
    6357            0 :             return Err(ApiError::NotFound(
    6358            0 :                 anyhow::anyhow!("No shards found").into(),
    6359            0 :             ));
    6360              :         };
    6361              : 
    6362              :         // Ideally we would set each newly imported shard's generation independently, but for correctness it is sufficient
    6363              :         // to
    6364            0 :         let generation = scan_result
    6365            0 :             .shards
    6366            0 :             .iter()
    6367            0 :             .map(|s| s.generation)
    6368            0 :             .max()
    6369            0 :             .expect("We already validated >0 shards");
    6370              : 
    6371              :         // Find the tenant's stripe size. This wasn't always persisted in the tenant manifest, so
    6372              :         // fall back to the original default stripe size of 32768 (256 MB) if it's not specified.
    6373              :         const ORIGINAL_STRIPE_SIZE: ShardStripeSize = ShardStripeSize(32768);
    6374            0 :         let stripe_size = scan_result
    6375            0 :             .shards
    6376            0 :             .iter()
    6377            0 :             .find(|s| s.tenant_shard_id.shard_count == shard_count && s.generation == generation)
    6378            0 :             .expect("we validated >0 shards above")
    6379            0 :             .stripe_size
    6380            0 :             .unwrap_or_else(|| {
    6381            0 :                 if shard_count.count() > 1 {
    6382            0 :                     warn!("unknown stripe size, assuming {ORIGINAL_STRIPE_SIZE}");
    6383            0 :                 }
    6384            0 :                 ORIGINAL_STRIPE_SIZE
    6385            0 :             });
    6386              : 
    6387            0 :         let (response, waiters) = self
    6388            0 :             .do_tenant_create(TenantCreateRequest {
    6389            0 :                 new_tenant_id: TenantShardId::unsharded(tenant_id),
    6390            0 :                 generation,
    6391            0 : 
    6392            0 :                 shard_parameters: ShardParameters {
    6393            0 :                     count: shard_count,
    6394            0 :                     stripe_size,
    6395            0 :                 },
    6396            0 :                 placement_policy: Some(PlacementPolicy::Attached(0)), // No secondaries, for convenient debug/hacking
    6397            0 :                 config: TenantConfig::default(),
    6398            0 :             })
    6399            0 :             .await?;
    6400              : 
    6401            0 :         if let Err(e) = self.await_waiters(waiters, SHORT_RECONCILE_TIMEOUT).await {
    6402              :             // Since this is a debug/support operation, all kinds of weird issues are possible (e.g. this
    6403              :             // tenant doesn't exist in the control plane), so don't fail the request if it can't fully
    6404              :             // reconcile, as reconciliation includes notifying compute.
    6405            0 :             tracing::warn!(%tenant_id, "Reconcile not done yet while importing tenant ({e})");
    6406            0 :         }
    6407              : 
    6408            0 :         Ok(response)
    6409            0 :     }
    6410              : 
    6411              :     /// For debug/support: a full JSON dump of TenantShards.  Returns a response so that
    6412              :     /// we don't have to make TenantShard clonable in the return path.
    6413            0 :     pub(crate) fn tenants_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
    6414            0 :         let serialized = {
    6415            0 :             let locked = self.inner.read().unwrap();
    6416            0 :             let result = locked.tenants.values().collect::<Vec<_>>();
    6417            0 :             serde_json::to_string(&result).map_err(|e| ApiError::InternalServerError(e.into()))?
    6418              :         };
    6419              : 
    6420            0 :         hyper::Response::builder()
    6421            0 :             .status(hyper::StatusCode::OK)
    6422            0 :             .header(hyper::header::CONTENT_TYPE, "application/json")
    6423            0 :             .body(hyper::Body::from(serialized))
    6424            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))
    6425            0 :     }
    6426              : 
    6427              :     /// Check the consistency of in-memory state vs. persistent state, and check that the
    6428              :     /// scheduler's statistics are up to date.
    6429              :     ///
    6430              :     /// These consistency checks expect an **idle** system.  If changes are going on while
    6431              :     /// we run, then we can falsely indicate a consistency issue.  This is sufficient for end-of-test
    6432              :     /// checks, but not suitable for running continuously in the background in the field.
    6433            0 :     pub(crate) async fn consistency_check(&self) -> Result<(), ApiError> {
    6434            0 :         let (mut expect_nodes, mut expect_shards) = {
    6435            0 :             let locked = self.inner.read().unwrap();
    6436            0 : 
    6437            0 :             locked
    6438            0 :                 .scheduler
    6439            0 :                 .consistency_check(locked.nodes.values(), locked.tenants.values())
    6440            0 :                 .context("Scheduler checks")
    6441            0 :                 .map_err(ApiError::InternalServerError)?;
    6442              : 
    6443            0 :             let expect_nodes = locked
    6444            0 :                 .nodes
    6445            0 :                 .values()
    6446            0 :                 .map(|n| n.to_persistent())
    6447            0 :                 .collect::<Vec<_>>();
    6448            0 : 
    6449            0 :             let expect_shards = locked
    6450            0 :                 .tenants
    6451            0 :                 .values()
    6452            0 :                 .map(|t| t.to_persistent())
    6453            0 :                 .collect::<Vec<_>>();
    6454              : 
    6455              :             // This method can only validate the state of an idle system: if a reconcile is in
    6456              :             // progress, fail out early to avoid giving false errors on state that won't match
    6457              :             // between database and memory under a ReconcileResult is processed.
    6458            0 :             for t in locked.tenants.values() {
    6459            0 :                 if t.reconciler.is_some() {
    6460            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    6461            0 :                         "Shard {} reconciliation in progress",
    6462            0 :                         t.tenant_shard_id
    6463            0 :                     )));
    6464            0 :                 }
    6465              :             }
    6466              : 
    6467            0 :             (expect_nodes, expect_shards)
    6468              :         };
    6469              : 
    6470            0 :         let mut nodes = self.persistence.list_nodes().await?;
    6471            0 :         expect_nodes.sort_by_key(|n| n.node_id);
    6472            0 :         nodes.sort_by_key(|n| n.node_id);
    6473              : 
    6474              :         // Errors relating to nodes are deferred so that we don't skip the shard checks below if we have a node error
    6475            0 :         let node_result = if nodes != expect_nodes {
    6476            0 :             tracing::error!("Consistency check failed on nodes.");
    6477            0 :             tracing::error!(
    6478            0 :                 "Nodes in memory: {}",
    6479            0 :                 serde_json::to_string(&expect_nodes)
    6480            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    6481              :             );
    6482            0 :             tracing::error!(
    6483            0 :                 "Nodes in database: {}",
    6484            0 :                 serde_json::to_string(&nodes)
    6485            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    6486              :             );
    6487            0 :             Err(ApiError::InternalServerError(anyhow::anyhow!(
    6488            0 :                 "Node consistency failure"
    6489            0 :             )))
    6490              :         } else {
    6491            0 :             Ok(())
    6492              :         };
    6493              : 
    6494            0 :         let mut persistent_shards = self.persistence.load_active_tenant_shards().await?;
    6495            0 :         persistent_shards
    6496            0 :             .sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
    6497            0 : 
    6498            0 :         expect_shards.sort_by_key(|tsp| (tsp.tenant_id.clone(), tsp.shard_number, tsp.shard_count));
    6499              : 
    6500              :         // Because JSON contents of persistent tenants might disagree with the fields in current `TenantConfig`
    6501              :         // definition, we will do an encode/decode cycle to ensure any legacy fields are dropped and any new
    6502              :         // fields are added, before doing a comparison.
    6503            0 :         for tsp in &mut persistent_shards {
    6504            0 :             let config: TenantConfig = serde_json::from_str(&tsp.config)
    6505            0 :                 .map_err(|e| ApiError::InternalServerError(e.into()))?;
    6506            0 :             tsp.config = serde_json::to_string(&config).expect("Encoding config is infallible");
    6507              :         }
    6508              : 
    6509            0 :         if persistent_shards != expect_shards {
    6510            0 :             tracing::error!("Consistency check failed on shards.");
    6511              : 
    6512            0 :             tracing::error!(
    6513            0 :                 "Shards in memory: {}",
    6514            0 :                 serde_json::to_string(&expect_shards)
    6515            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    6516              :             );
    6517            0 :             tracing::error!(
    6518            0 :                 "Shards in database: {}",
    6519            0 :                 serde_json::to_string(&persistent_shards)
    6520            0 :                     .map_err(|e| ApiError::InternalServerError(e.into()))?
    6521              :             );
    6522              : 
    6523              :             // The total dump log lines above are useful in testing but in the field grafana will
    6524              :             // usually just drop them because they're so large. So we also do some explicit logging
    6525              :             // of just the diffs.
    6526            0 :             let persistent_shards = persistent_shards
    6527            0 :                 .into_iter()
    6528            0 :                 .map(|tsp| (tsp.get_tenant_shard_id().unwrap(), tsp))
    6529            0 :                 .collect::<HashMap<_, _>>();
    6530            0 :             let expect_shards = expect_shards
    6531            0 :                 .into_iter()
    6532            0 :                 .map(|tsp| (tsp.get_tenant_shard_id().unwrap(), tsp))
    6533            0 :                 .collect::<HashMap<_, _>>();
    6534            0 :             for (tenant_shard_id, persistent_tsp) in &persistent_shards {
    6535            0 :                 match expect_shards.get(tenant_shard_id) {
    6536              :                     None => {
    6537            0 :                         tracing::error!(
    6538            0 :                             "Shard {} found in database but not in memory",
    6539              :                             tenant_shard_id
    6540              :                         );
    6541              :                     }
    6542            0 :                     Some(expect_tsp) => {
    6543            0 :                         if expect_tsp != persistent_tsp {
    6544            0 :                             tracing::error!(
    6545            0 :                                 "Shard {} is inconsistent.  In memory: {}, database has: {}",
    6546            0 :                                 tenant_shard_id,
    6547            0 :                                 serde_json::to_string(expect_tsp).unwrap(),
    6548            0 :                                 serde_json::to_string(&persistent_tsp).unwrap()
    6549              :                             );
    6550            0 :                         }
    6551              :                     }
    6552              :                 }
    6553              :             }
    6554              : 
    6555              :             // Having already logged any differences, log any shards that simply aren't present in the database
    6556            0 :             for (tenant_shard_id, memory_tsp) in &expect_shards {
    6557            0 :                 if !persistent_shards.contains_key(tenant_shard_id) {
    6558            0 :                     tracing::error!(
    6559            0 :                         "Shard {} found in memory but not in database: {}",
    6560            0 :                         tenant_shard_id,
    6561            0 :                         serde_json::to_string(memory_tsp)
    6562            0 :                             .map_err(|e| ApiError::InternalServerError(e.into()))?
    6563              :                     );
    6564            0 :                 }
    6565              :             }
    6566              : 
    6567            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!(
    6568            0 :                 "Shard consistency failure"
    6569            0 :             )));
    6570            0 :         }
    6571            0 : 
    6572            0 :         node_result
    6573            0 :     }
    6574              : 
    6575              :     /// For debug/support: a JSON dump of the [`Scheduler`].  Returns a response so that
    6576              :     /// we don't have to make TenantShard clonable in the return path.
    6577            0 :     pub(crate) fn scheduler_dump(&self) -> Result<hyper::Response<hyper::Body>, ApiError> {
    6578            0 :         let serialized = {
    6579            0 :             let locked = self.inner.read().unwrap();
    6580            0 :             serde_json::to_string(&locked.scheduler)
    6581            0 :                 .map_err(|e| ApiError::InternalServerError(e.into()))?
    6582              :         };
    6583              : 
    6584            0 :         hyper::Response::builder()
    6585            0 :             .status(hyper::StatusCode::OK)
    6586            0 :             .header(hyper::header::CONTENT_TYPE, "application/json")
    6587            0 :             .body(hyper::Body::from(serialized))
    6588            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))
    6589            0 :     }
    6590              : 
    6591              :     /// This is for debug/support only: we simply drop all state for a tenant, without
    6592              :     /// detaching or deleting it on pageservers.  We do not try and re-schedule any
    6593              :     /// tenants that were on this node.
    6594            0 :     pub(crate) async fn node_drop(&self, node_id: NodeId) -> Result<(), ApiError> {
    6595            0 :         self.persistence.delete_node(node_id).await?;
    6596              : 
    6597            0 :         let mut locked = self.inner.write().unwrap();
    6598              : 
    6599            0 :         for shard in locked.tenants.values_mut() {
    6600            0 :             shard.deref_node(node_id);
    6601            0 :             shard.observed.locations.remove(&node_id);
    6602            0 :         }
    6603              : 
    6604            0 :         let mut nodes = (*locked.nodes).clone();
    6605            0 :         nodes.remove(&node_id);
    6606            0 :         locked.nodes = Arc::new(nodes);
    6607            0 :         metrics::METRICS_REGISTRY
    6608            0 :             .metrics_group
    6609            0 :             .storage_controller_pageserver_nodes
    6610            0 :             .set(locked.nodes.len() as i64);
    6611            0 :         metrics::METRICS_REGISTRY
    6612            0 :             .metrics_group
    6613            0 :             .storage_controller_https_pageserver_nodes
    6614            0 :             .set(locked.nodes.values().filter(|n| n.has_https_port()).count() as i64);
    6615            0 : 
    6616            0 :         locked.scheduler.node_remove(node_id);
    6617            0 : 
    6618            0 :         Ok(())
    6619            0 :     }
    6620              : 
    6621              :     /// If a node has any work on it, it will be rescheduled: this is "clean" in the sense
    6622              :     /// that we don't leave any bad state behind in the storage controller, but unclean
    6623              :     /// in the sense that we are not carefully draining the node.
    6624            0 :     pub(crate) async fn node_delete(&self, node_id: NodeId) -> Result<(), ApiError> {
    6625            0 :         let _node_lock =
    6626            0 :             trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Delete).await;
    6627              : 
    6628              :         // 1. Atomically update in-memory state:
    6629              :         //    - set the scheduling state to Pause to make subsequent scheduling ops skip it
    6630              :         //    - update shards' intents to exclude the node, and reschedule any shards whose intents we modified.
    6631              :         //    - drop the node from the main nodes map, so that when running reconciles complete they do not
    6632              :         //      re-insert references to this node into the ObservedState of shards
    6633              :         //    - drop the node from the scheduler
    6634              :         {
    6635            0 :             let mut locked = self.inner.write().unwrap();
    6636            0 :             let (nodes, tenants, scheduler) = locked.parts_mut();
    6637            0 : 
    6638            0 :             {
    6639            0 :                 let mut nodes_mut = (*nodes).deref().clone();
    6640            0 :                 match nodes_mut.get_mut(&node_id) {
    6641            0 :                     Some(node) => {
    6642            0 :                         // We do not bother setting this in the database, because we're about to delete the row anyway, and
    6643            0 :                         // if we crash it would not be desirable to leave the node paused after a restart.
    6644            0 :                         node.set_scheduling(NodeSchedulingPolicy::Pause);
    6645            0 :                     }
    6646              :                     None => {
    6647            0 :                         tracing::info!(
    6648            0 :                             "Node not found: presuming this is a retry and returning success"
    6649              :                         );
    6650            0 :                         return Ok(());
    6651              :                     }
    6652              :                 }
    6653              : 
    6654            0 :                 *nodes = Arc::new(nodes_mut);
    6655              :             }
    6656              : 
    6657            0 :             for (_tenant_id, mut schedule_context, shards) in
    6658            0 :                 TenantShardContextIterator::new(tenants, ScheduleMode::Normal)
    6659              :             {
    6660            0 :                 for shard in shards {
    6661            0 :                     if shard.deref_node(node_id) {
    6662            0 :                         if let Err(e) = shard.schedule(scheduler, &mut schedule_context) {
    6663              :                             // TODO: implement force flag to remove a node even if we can't reschedule
    6664              :                             // a tenant
    6665            0 :                             tracing::error!(
    6666            0 :                                 "Refusing to delete node, shard {} can't be rescheduled: {e}",
    6667              :                                 shard.tenant_shard_id
    6668              :                             );
    6669            0 :                             return Err(e.into());
    6670              :                         } else {
    6671            0 :                             tracing::info!(
    6672            0 :                                 "Rescheduled shard {} away from node during deletion",
    6673              :                                 shard.tenant_shard_id
    6674              :                             )
    6675              :                         }
    6676              : 
    6677            0 :                         self.maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal);
    6678            0 :                     }
    6679              : 
    6680              :                     // Here we remove an existing observed location for the node we're removing, and it will
    6681              :                     // not be re-added by a reconciler's completion because we filter out removed nodes in
    6682              :                     // process_result.
    6683              :                     //
    6684              :                     // Note that we update the shard's observed state _after_ calling maybe_reconcile_shard: that
    6685              :                     // means any reconciles we spawned will know about the node we're deleting, enabling them
    6686              :                     // to do live migrations if it's still online.
    6687            0 :                     shard.observed.locations.remove(&node_id);
    6688              :                 }
    6689              :             }
    6690              : 
    6691            0 :             scheduler.node_remove(node_id);
    6692            0 : 
    6693            0 :             {
    6694            0 :                 let mut nodes_mut = (**nodes).clone();
    6695            0 :                 if let Some(mut removed_node) = nodes_mut.remove(&node_id) {
    6696            0 :                     // Ensure that any reconciler holding an Arc<> to this node will
    6697            0 :                     // drop out when trying to RPC to it (setting Offline state sets the
    6698            0 :                     // cancellation token on the Node object).
    6699            0 :                     removed_node.set_availability(NodeAvailability::Offline);
    6700            0 :                 }
    6701            0 :                 *nodes = Arc::new(nodes_mut);
    6702            0 :                 metrics::METRICS_REGISTRY
    6703            0 :                     .metrics_group
    6704            0 :                     .storage_controller_pageserver_nodes
    6705            0 :                     .set(nodes.len() as i64);
    6706            0 :                 metrics::METRICS_REGISTRY
    6707            0 :                     .metrics_group
    6708            0 :                     .storage_controller_https_pageserver_nodes
    6709            0 :                     .set(nodes.values().filter(|n| n.has_https_port()).count() as i64);
    6710            0 :             }
    6711            0 :         }
    6712            0 : 
    6713            0 :         // Note: some `generation_pageserver` columns on tenant shards in the database may still refer to
    6714            0 :         // the removed node, as this column means "The pageserver to which this generation was issued", and
    6715            0 :         // their generations won't get updated until the reconcilers moving them away from this node complete.
    6716            0 :         // That is safe because in Service::spawn we only use generation_pageserver if it refers to a node
    6717            0 :         // that exists.
    6718            0 : 
    6719            0 :         // 2. Actually delete the node from the database and from in-memory state
    6720            0 :         tracing::info!("Deleting node from database");
    6721            0 :         self.persistence.delete_node(node_id).await?;
    6722              : 
    6723            0 :         Ok(())
    6724            0 :     }
    6725              : 
    6726            0 :     pub(crate) async fn node_list(&self) -> Result<Vec<Node>, ApiError> {
    6727            0 :         let nodes = {
    6728            0 :             self.inner
    6729            0 :                 .read()
    6730            0 :                 .unwrap()
    6731            0 :                 .nodes
    6732            0 :                 .values()
    6733            0 :                 .cloned()
    6734            0 :                 .collect::<Vec<_>>()
    6735            0 :         };
    6736            0 : 
    6737            0 :         Ok(nodes)
    6738            0 :     }
    6739              : 
    6740            0 :     pub(crate) async fn get_node(&self, node_id: NodeId) -> Result<Node, ApiError> {
    6741            0 :         self.inner
    6742            0 :             .read()
    6743            0 :             .unwrap()
    6744            0 :             .nodes
    6745            0 :             .get(&node_id)
    6746            0 :             .cloned()
    6747            0 :             .ok_or(ApiError::NotFound(
    6748            0 :                 format!("Node {node_id} not registered").into(),
    6749            0 :             ))
    6750            0 :     }
    6751              : 
    6752            0 :     pub(crate) async fn get_node_shards(
    6753            0 :         &self,
    6754            0 :         node_id: NodeId,
    6755            0 :     ) -> Result<NodeShardResponse, ApiError> {
    6756            0 :         let locked = self.inner.read().unwrap();
    6757            0 :         let mut shards = Vec::new();
    6758            0 :         for (tid, tenant) in locked.tenants.iter() {
    6759            0 :             let is_intended_secondary = match (
    6760            0 :                 tenant.intent.get_attached() == &Some(node_id),
    6761            0 :                 tenant.intent.get_secondary().contains(&node_id),
    6762            0 :             ) {
    6763              :                 (true, true) => {
    6764            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
    6765            0 :                         "{} attached as primary+secondary on the same node",
    6766            0 :                         tid
    6767            0 :                     )));
    6768              :                 }
    6769            0 :                 (true, false) => Some(false),
    6770            0 :                 (false, true) => Some(true),
    6771            0 :                 (false, false) => None,
    6772              :             };
    6773            0 :             let is_observed_secondary = if let Some(ObservedStateLocation { conf: Some(conf) }) =
    6774            0 :                 tenant.observed.locations.get(&node_id)
    6775              :             {
    6776            0 :                 Some(conf.secondary_conf.is_some())
    6777              :             } else {
    6778            0 :                 None
    6779              :             };
    6780            0 :             if is_intended_secondary.is_some() || is_observed_secondary.is_some() {
    6781            0 :                 shards.push(NodeShard {
    6782            0 :                     tenant_shard_id: *tid,
    6783            0 :                     is_intended_secondary,
    6784            0 :                     is_observed_secondary,
    6785            0 :                 });
    6786            0 :             }
    6787              :         }
    6788            0 :         Ok(NodeShardResponse { node_id, shards })
    6789            0 :     }
    6790              : 
    6791            0 :     pub(crate) async fn get_leader(&self) -> DatabaseResult<Option<ControllerPersistence>> {
    6792            0 :         self.persistence.get_leader().await
    6793            0 :     }
    6794              : 
    6795            0 :     pub(crate) async fn node_register(
    6796            0 :         &self,
    6797            0 :         register_req: NodeRegisterRequest,
    6798            0 :     ) -> Result<(), ApiError> {
    6799            0 :         let _node_lock = trace_exclusive_lock(
    6800            0 :             &self.node_op_locks,
    6801            0 :             register_req.node_id,
    6802            0 :             NodeOperations::Register,
    6803            0 :         )
    6804            0 :         .await;
    6805              : 
    6806              :         #[derive(PartialEq)]
    6807              :         enum RegistrationStatus {
    6808              :             UpToDate,
    6809              :             NeedUpdate,
    6810              :             Mismatched,
    6811              :             New,
    6812              :         }
    6813              : 
    6814            0 :         let registration_status = {
    6815            0 :             let locked = self.inner.read().unwrap();
    6816            0 :             if let Some(node) = locked.nodes.get(&register_req.node_id) {
    6817            0 :                 if node.registration_match(&register_req) {
    6818            0 :                     if node.need_update(&register_req) {
    6819            0 :                         RegistrationStatus::NeedUpdate
    6820              :                     } else {
    6821            0 :                         RegistrationStatus::UpToDate
    6822              :                     }
    6823              :                 } else {
    6824            0 :                     RegistrationStatus::Mismatched
    6825              :                 }
    6826              :             } else {
    6827            0 :                 RegistrationStatus::New
    6828              :             }
    6829              :         };
    6830              : 
    6831            0 :         match registration_status {
    6832              :             RegistrationStatus::UpToDate => {
    6833            0 :                 tracing::info!(
    6834            0 :                     "Node {} re-registered with matching address and is up to date",
    6835              :                     register_req.node_id
    6836              :                 );
    6837              : 
    6838            0 :                 return Ok(());
    6839              :             }
    6840              :             RegistrationStatus::Mismatched => {
    6841              :                 // TODO: decide if we want to allow modifying node addresses without removing and re-adding
    6842              :                 // the node.  Safest/simplest thing is to refuse it, and usually we deploy with
    6843              :                 // a fixed address through the lifetime of a node.
    6844            0 :                 tracing::warn!(
    6845            0 :                     "Node {} tried to register with different address",
    6846              :                     register_req.node_id
    6847              :                 );
    6848            0 :                 return Err(ApiError::Conflict(
    6849            0 :                     "Node is already registered with different address".to_string(),
    6850            0 :                 ));
    6851              :             }
    6852            0 :             RegistrationStatus::New | RegistrationStatus::NeedUpdate => {
    6853            0 :                 // fallthrough
    6854            0 :             }
    6855            0 :         }
    6856            0 : 
    6857            0 :         // We do not require that a node is actually online when registered (it will start life
    6858            0 :         // with it's  availability set to Offline), but we _do_ require that its DNS record exists. We're
    6859            0 :         // therefore not immune to asymmetric L3 connectivity issues, but we are protected against nodes
    6860            0 :         // that register themselves with a broken DNS config.  We check only the HTTP hostname, because
    6861            0 :         // the postgres hostname might only be resolvable to clients (e.g. if we're on a different VPC than clients).
    6862            0 :         if tokio::net::lookup_host(format!(
    6863            0 :             "{}:{}",
    6864            0 :             register_req.listen_http_addr, register_req.listen_http_port
    6865            0 :         ))
    6866            0 :         .await
    6867            0 :         .is_err()
    6868              :         {
    6869              :             // If we have a transient DNS issue, it's up to the caller to retry their registration.  Because
    6870              :             // we can't robustly distinguish between an intermittent issue and a totally bogus DNS situation,
    6871              :             // we return a soft 503 error, to encourage callers to retry past transient issues.
    6872            0 :             return Err(ApiError::ResourceUnavailable(
    6873            0 :                 format!(
    6874            0 :                     "Node {} tried to register with unknown DNS name '{}'",
    6875            0 :                     register_req.node_id, register_req.listen_http_addr
    6876            0 :                 )
    6877            0 :                 .into(),
    6878            0 :             ));
    6879            0 :         }
    6880            0 : 
    6881            0 :         if self.config.use_https_pageserver_api && register_req.listen_https_port.is_none() {
    6882            0 :             return Err(ApiError::PreconditionFailed(
    6883            0 :                 format!(
    6884            0 :                     "Node {} has no https port, but use_https is enabled",
    6885            0 :                     register_req.node_id
    6886            0 :                 )
    6887            0 :                 .into(),
    6888            0 :             ));
    6889            0 :         }
    6890            0 : 
    6891            0 :         // Ordering: we must persist the new node _before_ adding it to in-memory state.
    6892            0 :         // This ensures that before we use it for anything or expose it via any external
    6893            0 :         // API, it is guaranteed to be available after a restart.
    6894            0 :         let new_node = Node::new(
    6895            0 :             register_req.node_id,
    6896            0 :             register_req.listen_http_addr,
    6897            0 :             register_req.listen_http_port,
    6898            0 :             register_req.listen_https_port,
    6899            0 :             register_req.listen_pg_addr,
    6900            0 :             register_req.listen_pg_port,
    6901            0 :             register_req.availability_zone_id.clone(),
    6902            0 :             self.config.use_https_pageserver_api,
    6903            0 :         );
    6904            0 :         let new_node = match new_node {
    6905            0 :             Ok(new_node) => new_node,
    6906            0 :             Err(error) => return Err(ApiError::InternalServerError(error)),
    6907              :         };
    6908              : 
    6909            0 :         match registration_status {
    6910            0 :             RegistrationStatus::New => self.persistence.insert_node(&new_node).await?,
    6911              :             RegistrationStatus::NeedUpdate => {
    6912            0 :                 self.persistence
    6913            0 :                     .update_node_on_registration(
    6914            0 :                         register_req.node_id,
    6915            0 :                         register_req.listen_https_port,
    6916            0 :                     )
    6917            0 :                     .await?
    6918              :             }
    6919            0 :             _ => unreachable!("Other statuses have been processed earlier"),
    6920              :         }
    6921              : 
    6922            0 :         let mut locked = self.inner.write().unwrap();
    6923            0 :         let mut new_nodes = (*locked.nodes).clone();
    6924            0 : 
    6925            0 :         locked.scheduler.node_upsert(&new_node);
    6926            0 :         new_nodes.insert(register_req.node_id, new_node);
    6927            0 : 
    6928            0 :         locked.nodes = Arc::new(new_nodes);
    6929            0 : 
    6930            0 :         metrics::METRICS_REGISTRY
    6931            0 :             .metrics_group
    6932            0 :             .storage_controller_pageserver_nodes
    6933            0 :             .set(locked.nodes.len() as i64);
    6934            0 :         metrics::METRICS_REGISTRY
    6935            0 :             .metrics_group
    6936            0 :             .storage_controller_https_pageserver_nodes
    6937            0 :             .set(locked.nodes.values().filter(|n| n.has_https_port()).count() as i64);
    6938            0 : 
    6939            0 :         match registration_status {
    6940              :             RegistrationStatus::New => {
    6941            0 :                 tracing::info!(
    6942            0 :                     "Registered pageserver {} ({}), now have {} pageservers",
    6943            0 :                     register_req.node_id,
    6944            0 :                     register_req.availability_zone_id,
    6945            0 :                     locked.nodes.len()
    6946              :                 );
    6947              :             }
    6948              :             RegistrationStatus::NeedUpdate => {
    6949            0 :                 tracing::info!(
    6950            0 :                     "Re-registered and updated node {} ({})",
    6951              :                     register_req.node_id,
    6952              :                     register_req.availability_zone_id,
    6953              :                 );
    6954              :             }
    6955            0 :             _ => unreachable!("Other statuses have been processed earlier"),
    6956              :         }
    6957            0 :         Ok(())
    6958            0 :     }
    6959              : 
    6960              :     /// Configure in-memory and persistent state of a node as requested
    6961              :     ///
    6962              :     /// Note that this function does not trigger any immediate side effects in response
    6963              :     /// to the changes. That part is handled by [`Self::handle_node_availability_transition`].
    6964            0 :     async fn node_state_configure(
    6965            0 :         &self,
    6966            0 :         node_id: NodeId,
    6967            0 :         availability: Option<NodeAvailability>,
    6968            0 :         scheduling: Option<NodeSchedulingPolicy>,
    6969            0 :         node_lock: &TracingExclusiveGuard<NodeOperations>,
    6970            0 :     ) -> Result<AvailabilityTransition, ApiError> {
    6971            0 :         if let Some(scheduling) = scheduling {
    6972              :             // Scheduling is a persistent part of Node: we must write updates to the database before
    6973              :             // applying them in memory
    6974            0 :             self.persistence
    6975            0 :                 .update_node_scheduling_policy(node_id, scheduling)
    6976            0 :                 .await?;
    6977            0 :         }
    6978              : 
    6979              :         // If we're activating a node, then before setting it active we must reconcile any shard locations
    6980              :         // on that node, in case it is out of sync, e.g. due to being unavailable during controller startup,
    6981              :         // by calling [`Self::node_activate_reconcile`]
    6982              :         //
    6983              :         // The transition we calculate here remains valid later in the function because we hold the op lock on the node:
    6984              :         // nothing else can mutate its availability while we run.
    6985            0 :         let availability_transition = if let Some(input_availability) = availability.as_ref() {
    6986            0 :             let (activate_node, availability_transition) = {
    6987            0 :                 let locked = self.inner.read().unwrap();
    6988            0 :                 let Some(node) = locked.nodes.get(&node_id) else {
    6989            0 :                     return Err(ApiError::NotFound(
    6990            0 :                         anyhow::anyhow!("Node {} not registered", node_id).into(),
    6991            0 :                     ));
    6992              :                 };
    6993              : 
    6994            0 :                 (
    6995            0 :                     node.clone(),
    6996            0 :                     node.get_availability_transition(input_availability),
    6997            0 :                 )
    6998              :             };
    6999              : 
    7000            0 :             if matches!(availability_transition, AvailabilityTransition::ToActive) {
    7001            0 :                 self.node_activate_reconcile(activate_node, node_lock)
    7002            0 :                     .await?;
    7003            0 :             }
    7004            0 :             availability_transition
    7005              :         } else {
    7006            0 :             AvailabilityTransition::Unchanged
    7007              :         };
    7008              : 
    7009              :         // Apply changes from the request to our in-memory state for the Node
    7010            0 :         let mut locked = self.inner.write().unwrap();
    7011            0 :         let (nodes, _tenants, scheduler) = locked.parts_mut();
    7012            0 : 
    7013            0 :         let mut new_nodes = (**nodes).clone();
    7014              : 
    7015            0 :         let Some(node) = new_nodes.get_mut(&node_id) else {
    7016            0 :             return Err(ApiError::NotFound(
    7017            0 :                 anyhow::anyhow!("Node not registered").into(),
    7018            0 :             ));
    7019              :         };
    7020              : 
    7021            0 :         if let Some(availability) = availability {
    7022            0 :             node.set_availability(availability);
    7023            0 :         }
    7024              : 
    7025            0 :         if let Some(scheduling) = scheduling {
    7026            0 :             node.set_scheduling(scheduling);
    7027            0 :         }
    7028              : 
    7029              :         // Update the scheduler, in case the elegibility of the node for new shards has changed
    7030            0 :         scheduler.node_upsert(node);
    7031            0 : 
    7032            0 :         let new_nodes = Arc::new(new_nodes);
    7033            0 :         locked.nodes = new_nodes;
    7034            0 : 
    7035            0 :         Ok(availability_transition)
    7036            0 :     }
    7037              : 
    7038              :     /// Handle availability transition of one node
    7039              :     ///
    7040              :     /// Note that you should first call [`Self::node_state_configure`] to update
    7041              :     /// the in-memory state referencing that node. If you need to handle more than one transition
    7042              :     /// consider using [`Self::handle_node_availability_transitions`].
    7043            0 :     async fn handle_node_availability_transition(
    7044            0 :         &self,
    7045            0 :         node_id: NodeId,
    7046            0 :         transition: AvailabilityTransition,
    7047            0 :         _node_lock: &TracingExclusiveGuard<NodeOperations>,
    7048            0 :     ) -> Result<(), ApiError> {
    7049            0 :         // Modify scheduling state for any Tenants that are affected by a change in the node's availability state.
    7050            0 :         match transition {
    7051              :             AvailabilityTransition::ToOffline => {
    7052            0 :                 tracing::info!("Node {} transition to offline", node_id);
    7053              : 
    7054            0 :                 let mut locked = self.inner.write().unwrap();
    7055            0 :                 let (nodes, tenants, scheduler) = locked.parts_mut();
    7056            0 : 
    7057            0 :                 let mut tenants_affected: usize = 0;
    7058              : 
    7059            0 :                 for (_tenant_id, mut schedule_context, shards) in
    7060            0 :                     TenantShardContextIterator::new(tenants, ScheduleMode::Normal)
    7061              :                 {
    7062            0 :                     for tenant_shard in shards {
    7063            0 :                         let tenant_shard_id = tenant_shard.tenant_shard_id;
    7064            0 :                         if let Some(observed_loc) =
    7065            0 :                             tenant_shard.observed.locations.get_mut(&node_id)
    7066            0 :                         {
    7067            0 :                             // When a node goes offline, we set its observed configuration to None, indicating unknown: we will
    7068            0 :                             // not assume our knowledge of the node's configuration is accurate until it comes back online
    7069            0 :                             observed_loc.conf = None;
    7070            0 :                         }
    7071              : 
    7072            0 :                         if nodes.len() == 1 {
    7073              :                             // Special case for single-node cluster: there is no point trying to reschedule
    7074              :                             // any tenant shards: avoid doing so, in order to avoid spewing warnings about
    7075              :                             // failures to schedule them.
    7076            0 :                             continue;
    7077            0 :                         }
    7078            0 : 
    7079            0 :                         if !nodes
    7080            0 :                             .values()
    7081            0 :                             .any(|n| matches!(n.may_schedule(), MaySchedule::Yes(_)))
    7082              :                         {
    7083              :                             // Special case for when all nodes are unavailable and/or unschedulable: there is no point
    7084              :                             // trying to reschedule since there's nowhere else to go. Without this
    7085              :                             // branch we incorrectly detach tenants in response to node unavailability.
    7086            0 :                             continue;
    7087            0 :                         }
    7088            0 : 
    7089            0 :                         if tenant_shard.intent.demote_attached(scheduler, node_id) {
    7090            0 :                             tenant_shard.sequence = tenant_shard.sequence.next();
    7091            0 : 
    7092            0 :                             match tenant_shard.schedule(scheduler, &mut schedule_context) {
    7093            0 :                                 Err(e) => {
    7094            0 :                                     // It is possible that some tenants will become unschedulable when too many pageservers
    7095            0 :                                     // go offline: in this case there isn't much we can do other than make the issue observable.
    7096            0 :                                     // TODO: give TenantShard a scheduling error attribute to be queried later.
    7097            0 :                                     tracing::warn!(%tenant_shard_id, "Scheduling error when marking pageserver {} offline: {e}", node_id);
    7098              :                                 }
    7099              :                                 Ok(()) => {
    7100            0 :                                     if self
    7101            0 :                                         .maybe_reconcile_shard(
    7102            0 :                                             tenant_shard,
    7103            0 :                                             nodes,
    7104            0 :                                             ReconcilerPriority::Normal,
    7105            0 :                                         )
    7106            0 :                                         .is_some()
    7107            0 :                                     {
    7108            0 :                                         tenants_affected += 1;
    7109            0 :                                     };
    7110              :                                 }
    7111              :                             }
    7112            0 :                         }
    7113              :                     }
    7114              :                 }
    7115            0 :                 tracing::info!(
    7116            0 :                     "Launched {} reconciler tasks for tenants affected by node {} going offline",
    7117              :                     tenants_affected,
    7118              :                     node_id
    7119              :                 )
    7120              :             }
    7121              :             AvailabilityTransition::ToActive => {
    7122            0 :                 tracing::info!("Node {} transition to active", node_id);
    7123              : 
    7124            0 :                 let mut locked = self.inner.write().unwrap();
    7125            0 :                 let (nodes, tenants, _scheduler) = locked.parts_mut();
    7126              : 
    7127              :                 // When a node comes back online, we must reconcile any tenant that has a None observed
    7128              :                 // location on the node.
    7129            0 :                 for tenant_shard in tenants.values_mut() {
    7130              :                     // If a reconciliation is already in progress, rely on the previous scheduling
    7131              :                     // decision and skip triggering a new reconciliation.
    7132            0 :                     if tenant_shard.reconciler.is_some() {
    7133            0 :                         continue;
    7134            0 :                     }
    7135              : 
    7136            0 :                     if let Some(observed_loc) = tenant_shard.observed.locations.get_mut(&node_id) {
    7137            0 :                         if observed_loc.conf.is_none() {
    7138            0 :                             self.maybe_reconcile_shard(
    7139            0 :                                 tenant_shard,
    7140            0 :                                 nodes,
    7141            0 :                                 ReconcilerPriority::Normal,
    7142            0 :                             );
    7143            0 :                         }
    7144            0 :                     }
    7145              :                 }
    7146              : 
    7147              :                 // TODO: in the background, we should balance work back onto this pageserver
    7148              :             }
    7149              :             // No action required for the intermediate unavailable state.
    7150              :             // When we transition into active or offline from the unavailable state,
    7151              :             // the correct handling above will kick in.
    7152              :             AvailabilityTransition::ToWarmingUpFromActive => {
    7153            0 :                 tracing::info!("Node {} transition to unavailable from active", node_id);
    7154              :             }
    7155              :             AvailabilityTransition::ToWarmingUpFromOffline => {
    7156            0 :                 tracing::info!("Node {} transition to unavailable from offline", node_id);
    7157              :             }
    7158              :             AvailabilityTransition::Unchanged => {
    7159            0 :                 tracing::debug!("Node {} no availability change during config", node_id);
    7160              :             }
    7161              :         }
    7162              : 
    7163            0 :         Ok(())
    7164            0 :     }
    7165              : 
    7166              :     /// Handle availability transition for multiple nodes
    7167              :     ///
    7168              :     /// Note that you should first call [`Self::node_state_configure`] for
    7169              :     /// all nodes being handled here for the handling to use fresh in-memory state.
    7170            0 :     async fn handle_node_availability_transitions(
    7171            0 :         &self,
    7172            0 :         transitions: Vec<(
    7173            0 :             NodeId,
    7174            0 :             TracingExclusiveGuard<NodeOperations>,
    7175            0 :             AvailabilityTransition,
    7176            0 :         )>,
    7177            0 :     ) -> Result<(), Vec<(NodeId, ApiError)>> {
    7178            0 :         let mut errors = Vec::default();
    7179            0 :         for (node_id, node_lock, transition) in transitions {
    7180            0 :             let res = self
    7181            0 :                 .handle_node_availability_transition(node_id, transition, &node_lock)
    7182            0 :                 .await;
    7183            0 :             if let Err(err) = res {
    7184            0 :                 errors.push((node_id, err));
    7185            0 :             }
    7186              :         }
    7187              : 
    7188            0 :         if errors.is_empty() {
    7189            0 :             Ok(())
    7190              :         } else {
    7191            0 :             Err(errors)
    7192              :         }
    7193            0 :     }
    7194              : 
    7195            0 :     pub(crate) async fn node_configure(
    7196            0 :         &self,
    7197            0 :         node_id: NodeId,
    7198            0 :         availability: Option<NodeAvailability>,
    7199            0 :         scheduling: Option<NodeSchedulingPolicy>,
    7200            0 :     ) -> Result<(), ApiError> {
    7201            0 :         let node_lock =
    7202            0 :             trace_exclusive_lock(&self.node_op_locks, node_id, NodeOperations::Configure).await;
    7203              : 
    7204            0 :         let transition = self
    7205            0 :             .node_state_configure(node_id, availability, scheduling, &node_lock)
    7206            0 :             .await?;
    7207            0 :         self.handle_node_availability_transition(node_id, transition, &node_lock)
    7208            0 :             .await
    7209            0 :     }
    7210              : 
    7211              :     /// Wrapper around [`Self::node_configure`] which only allows changes while there is no ongoing
    7212              :     /// operation for HTTP api.
    7213            0 :     pub(crate) async fn external_node_configure(
    7214            0 :         &self,
    7215            0 :         node_id: NodeId,
    7216            0 :         availability: Option<NodeAvailability>,
    7217            0 :         scheduling: Option<NodeSchedulingPolicy>,
    7218            0 :     ) -> Result<(), ApiError> {
    7219            0 :         {
    7220            0 :             let locked = self.inner.read().unwrap();
    7221            0 :             if let Some(op) = locked.ongoing_operation.as_ref().map(|op| op.operation) {
    7222            0 :                 return Err(ApiError::PreconditionFailed(
    7223            0 :                     format!("Ongoing background operation forbids configuring: {op}").into(),
    7224            0 :                 ));
    7225            0 :             }
    7226            0 :         }
    7227            0 : 
    7228            0 :         self.node_configure(node_id, availability, scheduling).await
    7229            0 :     }
    7230              : 
    7231            0 :     pub(crate) async fn start_node_drain(
    7232            0 :         self: &Arc<Self>,
    7233            0 :         node_id: NodeId,
    7234            0 :     ) -> Result<(), ApiError> {
    7235            0 :         let (ongoing_op, node_available, node_policy, schedulable_nodes_count) = {
    7236            0 :             let locked = self.inner.read().unwrap();
    7237            0 :             let nodes = &locked.nodes;
    7238            0 :             let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
    7239            0 :                 anyhow::anyhow!("Node {} not registered", node_id).into(),
    7240            0 :             ))?;
    7241            0 :             let schedulable_nodes_count = nodes
    7242            0 :                 .iter()
    7243            0 :                 .filter(|(_, n)| matches!(n.may_schedule(), MaySchedule::Yes(_)))
    7244            0 :                 .count();
    7245            0 : 
    7246            0 :             (
    7247            0 :                 locked
    7248            0 :                     .ongoing_operation
    7249            0 :                     .as_ref()
    7250            0 :                     .map(|ongoing| ongoing.operation),
    7251            0 :                 node.is_available(),
    7252            0 :                 node.get_scheduling(),
    7253            0 :                 schedulable_nodes_count,
    7254            0 :             )
    7255            0 :         };
    7256              : 
    7257            0 :         if let Some(ongoing) = ongoing_op {
    7258            0 :             return Err(ApiError::PreconditionFailed(
    7259            0 :                 format!("Background operation already ongoing for node: {}", ongoing).into(),
    7260            0 :             ));
    7261            0 :         }
    7262            0 : 
    7263            0 :         if !node_available {
    7264            0 :             return Err(ApiError::ResourceUnavailable(
    7265            0 :                 format!("Node {node_id} is currently unavailable").into(),
    7266            0 :             ));
    7267            0 :         }
    7268            0 : 
    7269            0 :         if schedulable_nodes_count == 0 {
    7270            0 :             return Err(ApiError::PreconditionFailed(
    7271            0 :                 "No other schedulable nodes to drain to".into(),
    7272            0 :             ));
    7273            0 :         }
    7274            0 : 
    7275            0 :         match node_policy {
    7276              :             NodeSchedulingPolicy::Active => {
    7277            0 :                 self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Draining))
    7278            0 :                     .await?;
    7279              : 
    7280            0 :                 let cancel = self.cancel.child_token();
    7281            0 :                 let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
    7282              : 
    7283            0 :                 self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
    7284            0 :                     operation: Operation::Drain(Drain { node_id }),
    7285            0 :                     cancel: cancel.clone(),
    7286            0 :                 });
    7287              : 
    7288            0 :                 let span = tracing::info_span!(parent: None, "drain_node", %node_id);
    7289              : 
    7290            0 :                 tokio::task::spawn({
    7291            0 :                     let service = self.clone();
    7292            0 :                     let cancel = cancel.clone();
    7293            0 :                     async move {
    7294            0 :                         let _gate_guard = gate_guard;
    7295            0 : 
    7296            0 :                         scopeguard::defer! {
    7297            0 :                             let prev = service.inner.write().unwrap().ongoing_operation.take();
    7298            0 : 
    7299            0 :                             if let Some(Operation::Drain(removed_drain)) = prev.map(|h| h.operation) {
    7300            0 :                                 assert_eq!(removed_drain.node_id, node_id, "We always take the same operation");
    7301            0 :                             } else {
    7302            0 :                                 panic!("We always remove the same operation")
    7303            0 :                             }
    7304            0 :                         }
    7305            0 : 
    7306            0 :                         tracing::info!("Drain background operation starting");
    7307            0 :                         let res = service.drain_node(node_id, cancel).await;
    7308            0 :                         match res {
    7309              :                             Ok(()) => {
    7310            0 :                                 tracing::info!("Drain background operation completed successfully");
    7311              :                             }
    7312              :                             Err(OperationError::Cancelled) => {
    7313            0 :                                 tracing::info!("Drain background operation was cancelled");
    7314              :                             }
    7315            0 :                             Err(err) => {
    7316            0 :                                 tracing::error!("Drain background operation encountered: {err}")
    7317              :                             }
    7318              :                         }
    7319            0 :                     }
    7320            0 :                 }.instrument(span));
    7321            0 :             }
    7322              :             NodeSchedulingPolicy::Draining => {
    7323            0 :                 return Err(ApiError::Conflict(format!(
    7324            0 :                     "Node {node_id} has drain in progress"
    7325            0 :                 )));
    7326              :             }
    7327            0 :             policy => {
    7328            0 :                 return Err(ApiError::PreconditionFailed(
    7329            0 :                     format!("Node {node_id} cannot be drained due to {policy:?} policy").into(),
    7330            0 :                 ));
    7331              :             }
    7332              :         }
    7333              : 
    7334            0 :         Ok(())
    7335            0 :     }
    7336              : 
    7337            0 :     pub(crate) async fn cancel_node_drain(&self, node_id: NodeId) -> Result<(), ApiError> {
    7338            0 :         let node_available = {
    7339            0 :             let locked = self.inner.read().unwrap();
    7340            0 :             let nodes = &locked.nodes;
    7341            0 :             let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
    7342            0 :                 anyhow::anyhow!("Node {} not registered", node_id).into(),
    7343            0 :             ))?;
    7344              : 
    7345            0 :             node.is_available()
    7346            0 :         };
    7347            0 : 
    7348            0 :         if !node_available {
    7349            0 :             return Err(ApiError::ResourceUnavailable(
    7350            0 :                 format!("Node {node_id} is currently unavailable").into(),
    7351            0 :             ));
    7352            0 :         }
    7353              : 
    7354            0 :         if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
    7355            0 :             if let Operation::Drain(drain) = op_handler.operation {
    7356            0 :                 if drain.node_id == node_id {
    7357            0 :                     tracing::info!("Cancelling background drain operation for node {node_id}");
    7358            0 :                     op_handler.cancel.cancel();
    7359            0 :                     return Ok(());
    7360            0 :                 }
    7361            0 :             }
    7362            0 :         }
    7363              : 
    7364            0 :         Err(ApiError::PreconditionFailed(
    7365            0 :             format!("Node {node_id} has no drain in progress").into(),
    7366            0 :         ))
    7367            0 :     }
    7368              : 
    7369            0 :     pub(crate) async fn start_node_fill(self: &Arc<Self>, node_id: NodeId) -> Result<(), ApiError> {
    7370            0 :         let (ongoing_op, node_available, node_policy, total_nodes_count) = {
    7371            0 :             let locked = self.inner.read().unwrap();
    7372            0 :             let nodes = &locked.nodes;
    7373            0 :             let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
    7374            0 :                 anyhow::anyhow!("Node {} not registered", node_id).into(),
    7375            0 :             ))?;
    7376              : 
    7377            0 :             (
    7378            0 :                 locked
    7379            0 :                     .ongoing_operation
    7380            0 :                     .as_ref()
    7381            0 :                     .map(|ongoing| ongoing.operation),
    7382            0 :                 node.is_available(),
    7383            0 :                 node.get_scheduling(),
    7384            0 :                 nodes.len(),
    7385            0 :             )
    7386            0 :         };
    7387              : 
    7388            0 :         if let Some(ongoing) = ongoing_op {
    7389            0 :             return Err(ApiError::PreconditionFailed(
    7390            0 :                 format!("Background operation already ongoing for node: {}", ongoing).into(),
    7391            0 :             ));
    7392            0 :         }
    7393            0 : 
    7394            0 :         if !node_available {
    7395            0 :             return Err(ApiError::ResourceUnavailable(
    7396            0 :                 format!("Node {node_id} is currently unavailable").into(),
    7397            0 :             ));
    7398            0 :         }
    7399            0 : 
    7400            0 :         if total_nodes_count <= 1 {
    7401            0 :             return Err(ApiError::PreconditionFailed(
    7402            0 :                 "No other nodes to fill from".into(),
    7403            0 :             ));
    7404            0 :         }
    7405            0 : 
    7406            0 :         match node_policy {
    7407              :             NodeSchedulingPolicy::Active => {
    7408            0 :                 self.node_configure(node_id, None, Some(NodeSchedulingPolicy::Filling))
    7409            0 :                     .await?;
    7410              : 
    7411            0 :                 let cancel = self.cancel.child_token();
    7412            0 :                 let gate_guard = self.gate.enter().map_err(|_| ApiError::ShuttingDown)?;
    7413              : 
    7414            0 :                 self.inner.write().unwrap().ongoing_operation = Some(OperationHandler {
    7415            0 :                     operation: Operation::Fill(Fill { node_id }),
    7416            0 :                     cancel: cancel.clone(),
    7417            0 :                 });
    7418              : 
    7419            0 :                 let span = tracing::info_span!(parent: None, "fill_node", %node_id);
    7420              : 
    7421            0 :                 tokio::task::spawn({
    7422            0 :                     let service = self.clone();
    7423            0 :                     let cancel = cancel.clone();
    7424            0 :                     async move {
    7425            0 :                         let _gate_guard = gate_guard;
    7426            0 : 
    7427            0 :                         scopeguard::defer! {
    7428            0 :                             let prev = service.inner.write().unwrap().ongoing_operation.take();
    7429            0 : 
    7430            0 :                             if let Some(Operation::Fill(removed_fill)) = prev.map(|h| h.operation) {
    7431            0 :                                 assert_eq!(removed_fill.node_id, node_id, "We always take the same operation");
    7432            0 :                             } else {
    7433            0 :                                 panic!("We always remove the same operation")
    7434            0 :                             }
    7435            0 :                         }
    7436            0 : 
    7437            0 :                         tracing::info!("Fill background operation starting");
    7438            0 :                         let res = service.fill_node(node_id, cancel).await;
    7439            0 :                         match res {
    7440              :                             Ok(()) => {
    7441            0 :                                 tracing::info!("Fill background operation completed successfully");
    7442              :                             }
    7443              :                             Err(OperationError::Cancelled) => {
    7444            0 :                                 tracing::info!("Fill background operation was cancelled");
    7445              :                             }
    7446            0 :                             Err(err) => {
    7447            0 :                                 tracing::error!("Fill background operation encountered: {err}")
    7448              :                             }
    7449              :                         }
    7450            0 :                     }
    7451            0 :                 }.instrument(span));
    7452            0 :             }
    7453              :             NodeSchedulingPolicy::Filling => {
    7454            0 :                 return Err(ApiError::Conflict(format!(
    7455            0 :                     "Node {node_id} has fill in progress"
    7456            0 :                 )));
    7457              :             }
    7458            0 :             policy => {
    7459            0 :                 return Err(ApiError::PreconditionFailed(
    7460            0 :                     format!("Node {node_id} cannot be filled due to {policy:?} policy").into(),
    7461            0 :                 ));
    7462              :             }
    7463              :         }
    7464              : 
    7465            0 :         Ok(())
    7466            0 :     }
    7467              : 
    7468            0 :     pub(crate) async fn cancel_node_fill(&self, node_id: NodeId) -> Result<(), ApiError> {
    7469            0 :         let node_available = {
    7470            0 :             let locked = self.inner.read().unwrap();
    7471            0 :             let nodes = &locked.nodes;
    7472            0 :             let node = nodes.get(&node_id).ok_or(ApiError::NotFound(
    7473            0 :                 anyhow::anyhow!("Node {} not registered", node_id).into(),
    7474            0 :             ))?;
    7475              : 
    7476            0 :             node.is_available()
    7477            0 :         };
    7478            0 : 
    7479            0 :         if !node_available {
    7480            0 :             return Err(ApiError::ResourceUnavailable(
    7481            0 :                 format!("Node {node_id} is currently unavailable").into(),
    7482            0 :             ));
    7483            0 :         }
    7484              : 
    7485            0 :         if let Some(op_handler) = self.inner.read().unwrap().ongoing_operation.as_ref() {
    7486            0 :             if let Operation::Fill(fill) = op_handler.operation {
    7487            0 :                 if fill.node_id == node_id {
    7488            0 :                     tracing::info!("Cancelling background drain operation for node {node_id}");
    7489            0 :                     op_handler.cancel.cancel();
    7490            0 :                     return Ok(());
    7491            0 :                 }
    7492            0 :             }
    7493            0 :         }
    7494              : 
    7495            0 :         Err(ApiError::PreconditionFailed(
    7496            0 :             format!("Node {node_id} has no fill in progress").into(),
    7497            0 :         ))
    7498            0 :     }
    7499              : 
    7500              :     /// Like [`Self::maybe_configured_reconcile_shard`], but uses the default reconciler
    7501              :     /// configuration
    7502            0 :     fn maybe_reconcile_shard(
    7503            0 :         &self,
    7504            0 :         shard: &mut TenantShard,
    7505            0 :         nodes: &Arc<HashMap<NodeId, Node>>,
    7506            0 :         priority: ReconcilerPriority,
    7507            0 :     ) -> Option<ReconcilerWaiter> {
    7508            0 :         self.maybe_configured_reconcile_shard(shard, nodes, ReconcilerConfig::new(priority))
    7509            0 :     }
    7510              : 
    7511              :     /// Before constructing a Reconciler, acquire semaphore units from the appropriate concurrency limit (depends on priority)
    7512            0 :     fn get_reconciler_units(
    7513            0 :         &self,
    7514            0 :         priority: ReconcilerPriority,
    7515            0 :     ) -> Result<ReconcileUnits, TryAcquireError> {
    7516            0 :         let units = match priority {
    7517            0 :             ReconcilerPriority::Normal => self.reconciler_concurrency.clone().try_acquire_owned(),
    7518              :             ReconcilerPriority::High => {
    7519            0 :                 match self
    7520            0 :                     .priority_reconciler_concurrency
    7521            0 :                     .clone()
    7522            0 :                     .try_acquire_owned()
    7523              :                 {
    7524            0 :                     Ok(u) => Ok(u),
    7525              :                     Err(TryAcquireError::NoPermits) => {
    7526              :                         // If the high priority semaphore is exhausted, then high priority tasks may steal units from
    7527              :                         // the normal priority semaphore.
    7528            0 :                         self.reconciler_concurrency.clone().try_acquire_owned()
    7529              :                     }
    7530            0 :                     Err(e) => Err(e),
    7531              :                 }
    7532              :             }
    7533              :         };
    7534              : 
    7535            0 :         units.map(ReconcileUnits::new)
    7536            0 :     }
    7537              : 
    7538              :     /// Wrap [`TenantShard`] reconciliation methods with acquisition of [`Gate`] and [`ReconcileUnits`],
    7539            0 :     fn maybe_configured_reconcile_shard(
    7540            0 :         &self,
    7541            0 :         shard: &mut TenantShard,
    7542            0 :         nodes: &Arc<HashMap<NodeId, Node>>,
    7543            0 :         reconciler_config: ReconcilerConfig,
    7544            0 :     ) -> Option<ReconcilerWaiter> {
    7545            0 :         let reconcile_needed = shard.get_reconcile_needed(nodes);
    7546              : 
    7547            0 :         let reconcile_reason = match reconcile_needed {
    7548            0 :             ReconcileNeeded::No => return None,
    7549            0 :             ReconcileNeeded::WaitExisting(waiter) => return Some(waiter),
    7550            0 :             ReconcileNeeded::Yes(reason) => {
    7551            0 :                 // Fall through to try and acquire units for spawning reconciler
    7552            0 :                 reason
    7553              :             }
    7554              :         };
    7555              : 
    7556            0 :         let units = match self.get_reconciler_units(reconciler_config.priority) {
    7557            0 :             Ok(u) => u,
    7558              :             Err(_) => {
    7559            0 :                 tracing::info!(tenant_id=%shard.tenant_shard_id.tenant_id, shard_id=%shard.tenant_shard_id.shard_slug(),
    7560            0 :                     "Concurrency limited: enqueued for reconcile later");
    7561            0 :                 if !shard.delayed_reconcile {
    7562            0 :                     match self.delayed_reconcile_tx.try_send(shard.tenant_shard_id) {
    7563            0 :                         Err(TrySendError::Closed(_)) => {
    7564            0 :                             // Weird mid-shutdown case?
    7565            0 :                         }
    7566              :                         Err(TrySendError::Full(_)) => {
    7567              :                             // It is safe to skip sending our ID in the channel: we will eventually get retried by the background reconcile task.
    7568            0 :                             tracing::warn!(
    7569            0 :                                 "Many shards are waiting to reconcile: delayed_reconcile queue is full"
    7570              :                             );
    7571              :                         }
    7572            0 :                         Ok(()) => {
    7573            0 :                             shard.delayed_reconcile = true;
    7574            0 :                         }
    7575              :                     }
    7576            0 :                 }
    7577              : 
    7578              :                 // We won't spawn a reconciler, but we will construct a waiter that waits for the shard's sequence
    7579              :                 // number to advance.  When this function is eventually called again and succeeds in getting units,
    7580              :                 // it will spawn a reconciler that makes this waiter complete.
    7581            0 :                 return Some(shard.future_reconcile_waiter());
    7582              :             }
    7583              :         };
    7584              : 
    7585            0 :         let Ok(gate_guard) = self.reconcilers_gate.enter() else {
    7586              :             // Gate closed: we're shutting down, drop out.
    7587            0 :             return None;
    7588              :         };
    7589              : 
    7590            0 :         shard.spawn_reconciler(
    7591            0 :             reconcile_reason,
    7592            0 :             &self.result_tx,
    7593            0 :             nodes,
    7594            0 :             &self.compute_hook,
    7595            0 :             reconciler_config,
    7596            0 :             &self.config,
    7597            0 :             &self.persistence,
    7598            0 :             units,
    7599            0 :             gate_guard,
    7600            0 :             &self.reconcilers_cancel,
    7601            0 :             self.http_client.clone(),
    7602            0 :         )
    7603            0 :     }
    7604              : 
    7605              :     /// Check all tenants for pending reconciliation work, and reconcile those in need.
    7606              :     /// Additionally, reschedule tenants that require it.
    7607              :     ///
    7608              :     /// Returns how many reconciliation tasks were started, or `1` if no reconciles were
    7609              :     /// spawned but some _would_ have been spawned if `reconciler_concurrency` units where
    7610              :     /// available.  A return value of 0 indicates that everything is fully reconciled already.
    7611            0 :     fn reconcile_all(&self) -> usize {
    7612            0 :         let mut locked = self.inner.write().unwrap();
    7613            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    7614            0 :         let pageservers = nodes.clone();
    7615            0 : 
    7616            0 :         // This function is an efficient place to update lazy statistics, since we are walking
    7617            0 :         // all tenants.
    7618            0 :         let mut pending_reconciles = 0;
    7619            0 :         let mut az_violations = 0;
    7620            0 : 
    7621            0 :         // If we find any tenants to drop from memory, stash them to offload after
    7622            0 :         // we're done traversing the map of tenants.
    7623            0 :         let mut drop_detached_tenants = Vec::new();
    7624            0 : 
    7625            0 :         let mut reconciles_spawned = 0;
    7626            0 :         for shard in tenants.values_mut() {
    7627              :             // Accumulate scheduling statistics
    7628            0 :             if let (Some(attached), Some(preferred)) =
    7629            0 :                 (shard.intent.get_attached(), shard.preferred_az())
    7630              :             {
    7631            0 :                 let node_az = nodes
    7632            0 :                     .get(attached)
    7633            0 :                     .expect("Nodes exist if referenced")
    7634            0 :                     .get_availability_zone_id();
    7635            0 :                 if node_az != preferred {
    7636            0 :                     az_violations += 1;
    7637            0 :                 }
    7638            0 :             }
    7639              : 
    7640              :             // Skip checking if this shard is already enqueued for reconciliation
    7641            0 :             if shard.delayed_reconcile && self.reconciler_concurrency.available_permits() == 0 {
    7642              :                 // If there is something delayed, then return a nonzero count so that
    7643              :                 // callers like reconcile_all_now do not incorrectly get the impression
    7644              :                 // that the system is in a quiescent state.
    7645            0 :                 reconciles_spawned = std::cmp::max(1, reconciles_spawned);
    7646            0 :                 pending_reconciles += 1;
    7647            0 :                 continue;
    7648            0 :             }
    7649            0 : 
    7650            0 :             // Eventual consistency: if an earlier reconcile job failed, and the shard is still
    7651            0 :             // dirty, spawn another one
    7652            0 :             if self
    7653            0 :                 .maybe_reconcile_shard(shard, &pageservers, ReconcilerPriority::Normal)
    7654            0 :                 .is_some()
    7655            0 :             {
    7656            0 :                 reconciles_spawned += 1;
    7657            0 :             } else if shard.delayed_reconcile {
    7658            0 :                 // Shard wanted to reconcile but for some reason couldn't.
    7659            0 :                 pending_reconciles += 1;
    7660            0 :             }
    7661              : 
    7662              :             // If this tenant is detached, try dropping it from memory. This is usually done
    7663              :             // proactively in [`Self::process_results`], but we do it here to handle the edge
    7664              :             // case where a reconcile completes while someone else is holding an op lock for the tenant.
    7665            0 :             if shard.tenant_shard_id.shard_number == ShardNumber(0)
    7666            0 :                 && shard.policy == PlacementPolicy::Detached
    7667              :             {
    7668            0 :                 if let Some(guard) = self.tenant_op_locks.try_exclusive(
    7669            0 :                     shard.tenant_shard_id.tenant_id,
    7670            0 :                     TenantOperations::DropDetached,
    7671            0 :                 ) {
    7672            0 :                     drop_detached_tenants.push((shard.tenant_shard_id.tenant_id, guard));
    7673            0 :                 }
    7674            0 :             }
    7675              :         }
    7676              : 
    7677              :         // Some metrics are calculated from SchedulerNode state, update these periodically
    7678            0 :         scheduler.update_metrics();
    7679              : 
    7680              :         // Process any deferred tenant drops
    7681            0 :         for (tenant_id, guard) in drop_detached_tenants {
    7682            0 :             self.maybe_drop_tenant(tenant_id, &mut locked, &guard);
    7683            0 :         }
    7684              : 
    7685            0 :         metrics::METRICS_REGISTRY
    7686            0 :             .metrics_group
    7687            0 :             .storage_controller_schedule_az_violation
    7688            0 :             .set(az_violations as i64);
    7689            0 : 
    7690            0 :         metrics::METRICS_REGISTRY
    7691            0 :             .metrics_group
    7692            0 :             .storage_controller_pending_reconciles
    7693            0 :             .set(pending_reconciles as i64);
    7694            0 : 
    7695            0 :         reconciles_spawned
    7696            0 :     }
    7697              : 
    7698              :     /// `optimize` in this context means identifying shards which have valid scheduled locations, but
    7699              :     /// could be scheduled somewhere better:
    7700              :     /// - Cutting over to a secondary if the node with the secondary is more lightly loaded
    7701              :     ///    * e.g. after a node fails then recovers, to move some work back to it
    7702              :     /// - Cutting over to a secondary if it improves the spread of shard attachments within a tenant
    7703              :     ///    * e.g. after a shard split, the initial attached locations will all be on the node where
    7704              :     ///      we did the split, but are probably better placed elsewhere.
    7705              :     /// - Creating new secondary locations if it improves the spreading of a sharded tenant
    7706              :     ///    * e.g. after a shard split, some locations will be on the same node (where the split
    7707              :     ///      happened), and will probably be better placed elsewhere.
    7708              :     ///
    7709              :     /// To put it more briefly: whereas the scheduler respects soft constraints in a ScheduleContext at
    7710              :     /// the time of scheduling, this function looks for cases where a better-scoring location is available
    7711              :     /// according to those same soft constraints.
    7712            0 :     async fn optimize_all(&self) -> usize {
    7713              :         // Limit on how many shards' optmizations each call to this function will execute.  Combined
    7714              :         // with the frequency of background calls, this acts as an implicit rate limit that runs a small
    7715              :         // trickle of optimizations in the background, rather than executing a large number in parallel
    7716              :         // when a change occurs.
    7717              :         const MAX_OPTIMIZATIONS_EXEC_PER_PASS: usize = 16;
    7718              : 
    7719              :         // Synchronous prepare: scan shards for possible scheduling optimizations
    7720            0 :         let candidate_work = self.optimize_all_plan();
    7721            0 :         let candidate_work_len = candidate_work.len();
    7722              : 
    7723              :         // Asynchronous validate: I/O to pageservers to make sure shards are in a good state to apply validation
    7724            0 :         let validated_work = self.optimize_all_validate(candidate_work).await;
    7725              : 
    7726            0 :         let was_work_filtered = validated_work.len() != candidate_work_len;
    7727            0 : 
    7728            0 :         // Synchronous apply: update the shards' intent states according to validated optimisations
    7729            0 :         let mut reconciles_spawned = 0;
    7730            0 :         let mut optimizations_applied = 0;
    7731            0 :         let mut locked = self.inner.write().unwrap();
    7732            0 :         let (nodes, tenants, scheduler) = locked.parts_mut();
    7733            0 :         for (tenant_shard_id, optimization) in validated_work {
    7734            0 :             let Some(shard) = tenants.get_mut(&tenant_shard_id) else {
    7735              :                 // Shard was dropped between planning and execution;
    7736            0 :                 continue;
    7737              :             };
    7738            0 :             tracing::info!(tenant_shard_id=%tenant_shard_id, "Applying optimization: {optimization:?}");
    7739            0 :             if shard.apply_optimization(scheduler, optimization) {
    7740            0 :                 optimizations_applied += 1;
    7741            0 :                 if self
    7742            0 :                     .maybe_reconcile_shard(shard, nodes, ReconcilerPriority::Normal)
    7743            0 :                     .is_some()
    7744            0 :                 {
    7745            0 :                     reconciles_spawned += 1;
    7746            0 :                 }
    7747            0 :             }
    7748              : 
    7749            0 :             if optimizations_applied >= MAX_OPTIMIZATIONS_EXEC_PER_PASS {
    7750            0 :                 break;
    7751            0 :             }
    7752              :         }
    7753              : 
    7754            0 :         if was_work_filtered {
    7755            0 :             // If we filtered any work out during validation, ensure we return a nonzero value to indicate
    7756            0 :             // to callers that the system is not in a truly quiet state, it's going to do some work as soon
    7757            0 :             // as these validations start passing.
    7758            0 :             reconciles_spawned = std::cmp::max(reconciles_spawned, 1);
    7759            0 :         }
    7760              : 
    7761            0 :         reconciles_spawned
    7762            0 :     }
    7763              : 
    7764            0 :     fn optimize_all_plan(&self) -> Vec<(TenantShardId, ScheduleOptimization)> {
    7765              :         // How many candidate optimizations we will generate, before evaluating them for readniess: setting
    7766              :         // this higher than the execution limit gives us a chance to execute some work even if the first
    7767              :         // few optimizations we find are not ready.
    7768              :         const MAX_OPTIMIZATIONS_PLAN_PER_PASS: usize = 64;
    7769              : 
    7770            0 :         let mut work = Vec::new();
    7771            0 :         let mut locked = self.inner.write().unwrap();
    7772            0 :         let (_nodes, tenants, scheduler) = locked.parts_mut();
    7773              : 
    7774              :         // We are going to plan a bunch of optimisations before applying any of them, so the
    7775              :         // utilisation stats on nodes will be effectively stale for the >1st optimisation we
    7776              :         // generate.  To avoid this causing unstable migrations/flapping, it's important that the
    7777              :         // code in TenantShard for finding optimisations uses [`NodeAttachmentSchedulingScore::disregard_utilization`]
    7778              :         // to ignore the utilisation component of the score.
    7779              : 
    7780            0 :         for (_tenant_id, schedule_context, shards) in
    7781            0 :             TenantShardContextIterator::new(tenants, ScheduleMode::Speculative)
    7782              :         {
    7783            0 :             for shard in shards {
    7784            0 :                 if work.len() >= MAX_OPTIMIZATIONS_PLAN_PER_PASS {
    7785            0 :                     break;
    7786            0 :                 }
    7787            0 :                 match shard.get_scheduling_policy() {
    7788            0 :                     ShardSchedulingPolicy::Active => {
    7789            0 :                         // Ok to do optimization
    7790            0 :                     }
    7791            0 :                     ShardSchedulingPolicy::Essential if shard.get_preferred_node().is_some() => {
    7792            0 :                         // Ok to do optimization: we are executing a graceful migration that
    7793            0 :                         // has set preferred_node
    7794            0 :                     }
    7795              :                     ShardSchedulingPolicy::Essential
    7796              :                     | ShardSchedulingPolicy::Pause
    7797              :                     | ShardSchedulingPolicy::Stop => {
    7798              :                         // Policy prevents optimizing this shard.
    7799            0 :                         continue;
    7800              :                     }
    7801              :                 }
    7802              : 
    7803            0 :                 if !matches!(shard.splitting, SplitState::Idle)
    7804            0 :                     || matches!(shard.policy, PlacementPolicy::Detached)
    7805            0 :                     || shard.reconciler.is_some()
    7806              :                 {
    7807              :                     // Do not start any optimizations while another change to the tenant is ongoing: this
    7808              :                     // is not necessary for correctness, but simplifies operations and implicitly throttles
    7809              :                     // optimization changes to happen in a "trickle" over time.
    7810            0 :                     continue;
    7811            0 :                 }
    7812            0 : 
    7813            0 :                 // Fast path: we may quickly identify shards that don't have any possible optimisations
    7814            0 :                 if !shard.maybe_optimizable(scheduler, &schedule_context) {
    7815            0 :                     if cfg!(feature = "testing") {
    7816              :                         // Check that maybe_optimizable doesn't disagree with the actual optimization functions.
    7817              :                         // Only do this in testing builds because it is not a correctness-critical check, so we shouldn't
    7818              :                         // panic in prod if we hit this, or spend cycles on it in prod.
    7819            0 :                         assert!(
    7820            0 :                             shard
    7821            0 :                                 .optimize_attachment(scheduler, &schedule_context)
    7822            0 :                                 .is_none()
    7823            0 :                         );
    7824            0 :                         assert!(
    7825            0 :                             shard
    7826            0 :                                 .optimize_secondary(scheduler, &schedule_context)
    7827            0 :                                 .is_none()
    7828            0 :                         );
    7829            0 :                     }
    7830            0 :                     continue;
    7831            0 :                 }
    7832              : 
    7833            0 :                 if let Some(optimization) =
    7834              :                     // If idle, maybe optimize attachments: if a shard has a secondary location that is preferable to
    7835              :                     // its primary location based on soft constraints, cut it over.
    7836            0 :                     shard.optimize_attachment(scheduler, &schedule_context)
    7837              :                 {
    7838            0 :                     tracing::info!(tenant_shard_id=%shard.tenant_shard_id, "Identified optimization for attachment: {optimization:?}");
    7839            0 :                     work.push((shard.tenant_shard_id, optimization));
    7840            0 :                     break;
    7841            0 :                 } else if let Some(optimization) =
    7842              :                     // If idle, maybe optimize secondary locations: if a shard has a secondary location that would be
    7843              :                     // better placed on another node, based on ScheduleContext, then adjust it.  This
    7844              :                     // covers cases like after a shard split, where we might have too many shards
    7845              :                     // in the same tenant with secondary locations on the node where they originally split.
    7846            0 :                     shard.optimize_secondary(scheduler, &schedule_context)
    7847              :                 {
    7848            0 :                     tracing::info!(tenant_shard_id=%shard.tenant_shard_id, "Identified optimization for secondary: {optimization:?}");
    7849            0 :                     work.push((shard.tenant_shard_id, optimization));
    7850            0 :                     break;
    7851            0 :                 }
    7852              :             }
    7853              :         }
    7854              : 
    7855            0 :         work
    7856            0 :     }
    7857              : 
    7858            0 :     async fn optimize_all_validate(
    7859            0 :         &self,
    7860            0 :         candidate_work: Vec<(TenantShardId, ScheduleOptimization)>,
    7861            0 :     ) -> Vec<(TenantShardId, ScheduleOptimization)> {
    7862            0 :         // Take a clone of the node map to use outside the lock in async validation phase
    7863            0 :         let validation_nodes = { self.inner.read().unwrap().nodes.clone() };
    7864            0 : 
    7865            0 :         let mut want_secondary_status = Vec::new();
    7866            0 : 
    7867            0 :         // Validate our plans: this is an async phase where we may do I/O to pageservers to
    7868            0 :         // check that the state of locations is acceptable to run the optimization, such as
    7869            0 :         // checking that a secondary location is sufficiently warmed-up to cleanly cut over
    7870            0 :         // in a live migration.
    7871            0 :         let mut validated_work = Vec::new();
    7872            0 :         for (tenant_shard_id, optimization) in candidate_work {
    7873            0 :             match optimization.action {
    7874              :                 ScheduleOptimizationAction::MigrateAttachment(MigrateAttachment {
    7875              :                     old_attached_node_id: _,
    7876            0 :                     new_attached_node_id,
    7877            0 :                 }) => {
    7878            0 :                     match validation_nodes.get(&new_attached_node_id) {
    7879            0 :                         None => {
    7880            0 :                             // Node was dropped between planning and validation
    7881            0 :                         }
    7882            0 :                         Some(node) => {
    7883            0 :                             if !node.is_available() {
    7884            0 :                                 tracing::info!(
    7885            0 :                                     "Skipping optimization migration of {tenant_shard_id} to {new_attached_node_id} because node unavailable"
    7886              :                                 );
    7887            0 :                             } else {
    7888            0 :                                 // Accumulate optimizations that require fetching secondary status, so that we can execute these
    7889            0 :                                 // remote API requests concurrently.
    7890            0 :                                 want_secondary_status.push((
    7891            0 :                                     tenant_shard_id,
    7892            0 :                                     node.clone(),
    7893            0 :                                     optimization,
    7894            0 :                                 ));
    7895            0 :                             }
    7896              :                         }
    7897              :                     }
    7898              :                 }
    7899              :                 ScheduleOptimizationAction::ReplaceSecondary(_)
    7900              :                 | ScheduleOptimizationAction::CreateSecondary(_)
    7901              :                 | ScheduleOptimizationAction::RemoveSecondary(_) => {
    7902              :                     // No extra checks needed to manage secondaries: this does not interrupt client access
    7903            0 :                     validated_work.push((tenant_shard_id, optimization))
    7904              :                 }
    7905              :             };
    7906              :         }
    7907              : 
    7908              :         // Call into pageserver API to find out if the destination secondary location is warm enough for a reasonably smooth migration: we
    7909              :         // do this so that we avoid spawning a Reconciler that would have to wait minutes/hours for a destination to warm up: that reconciler
    7910              :         // would hold a precious reconcile semaphore unit the whole time it was waiting for the destination to warm up.
    7911            0 :         let results = self
    7912            0 :             .tenant_for_shards_api(
    7913            0 :                 want_secondary_status
    7914            0 :                     .iter()
    7915            0 :                     .map(|i| (i.0, i.1.clone()))
    7916            0 :                     .collect(),
    7917            0 :                 |tenant_shard_id, client| async move {
    7918            0 :                     client.tenant_secondary_status(tenant_shard_id).await
    7919            0 :                 },
    7920            0 :                 1,
    7921            0 :                 1,
    7922            0 :                 SHORT_RECONCILE_TIMEOUT,
    7923            0 :                 &self.cancel,
    7924            0 :             )
    7925            0 :             .await;
    7926              : 
    7927            0 :         for ((tenant_shard_id, node, optimization), secondary_status) in
    7928            0 :             want_secondary_status.into_iter().zip(results.into_iter())
    7929              :         {
    7930            0 :             match secondary_status {
    7931            0 :                 Err(e) => {
    7932            0 :                     tracing::info!(
    7933            0 :                         "Skipping migration of {tenant_shard_id} to {node}, error querying secondary: {e}"
    7934              :                     );
    7935              :                 }
    7936            0 :                 Ok(progress) => {
    7937              :                     // We require secondary locations to have less than 10GiB of downloads pending before we will use
    7938              :                     // them in an optimization
    7939              :                     const DOWNLOAD_FRESHNESS_THRESHOLD: u64 = 10 * 1024 * 1024 * 1024;
    7940              : 
    7941            0 :                     if progress.heatmap_mtime.is_none()
    7942            0 :                         || progress.bytes_total < DOWNLOAD_FRESHNESS_THRESHOLD
    7943            0 :                             && progress.bytes_downloaded != progress.bytes_total
    7944            0 :                         || progress.bytes_total - progress.bytes_downloaded
    7945            0 :                             > DOWNLOAD_FRESHNESS_THRESHOLD
    7946              :                     {
    7947            0 :                         tracing::info!(
    7948            0 :                             "Skipping migration of {tenant_shard_id} to {node} because secondary isn't ready: {progress:?}"
    7949              :                         );
    7950              : 
    7951              :                         #[cfg(feature = "testing")]
    7952            0 :                         if progress.heatmap_mtime.is_none() {
    7953              :                             // No heatmap might mean the attached location has never uploaded one, or that
    7954              :                             // the secondary download hasn't happened yet.  This is relatively unusual in the field,
    7955              :                             // but fairly common in tests.
    7956            0 :                             self.kick_secondary_download(tenant_shard_id).await;
    7957            0 :                         }
    7958              :                     } else {
    7959              :                         // Location looks ready: proceed
    7960            0 :                         tracing::info!(
    7961            0 :                             "{tenant_shard_id} secondary on {node} is warm enough for migration: {progress:?}"
    7962              :                         );
    7963            0 :                         validated_work.push((tenant_shard_id, optimization))
    7964              :                     }
    7965              :                 }
    7966              :             }
    7967              :         }
    7968              : 
    7969            0 :         validated_work
    7970            0 :     }
    7971              : 
    7972              :     /// Some aspects of scheduling optimisation wait for secondary locations to be warm.  This
    7973              :     /// happens on multi-minute timescales in the field, which is fine because optimisation is meant
    7974              :     /// to be a lazy background thing. However, when testing, it is not practical to wait around, so
    7975              :     /// we have this helper to move things along faster.
    7976              :     #[cfg(feature = "testing")]
    7977            0 :     async fn kick_secondary_download(&self, tenant_shard_id: TenantShardId) {
    7978            0 :         let (attached_node, secondaries) = {
    7979            0 :             let locked = self.inner.read().unwrap();
    7980            0 :             let Some(shard) = locked.tenants.get(&tenant_shard_id) else {
    7981            0 :                 tracing::warn!(
    7982            0 :                     "Skipping kick of secondary download for {tenant_shard_id}: not found"
    7983              :                 );
    7984            0 :                 return;
    7985              :             };
    7986              : 
    7987            0 :             let Some(attached) = shard.intent.get_attached() else {
    7988            0 :                 tracing::warn!(
    7989            0 :                     "Skipping kick of secondary download for {tenant_shard_id}: no attached"
    7990              :                 );
    7991            0 :                 return;
    7992              :             };
    7993              : 
    7994            0 :             let secondaries = shard
    7995            0 :                 .intent
    7996            0 :                 .get_secondary()
    7997            0 :                 .iter()
    7998            0 :                 .map(|n| locked.nodes.get(n).unwrap().clone())
    7999            0 :                 .collect::<Vec<_>>();
    8000            0 : 
    8001            0 :             (locked.nodes.get(attached).unwrap().clone(), secondaries)
    8002            0 :         };
    8003            0 : 
    8004            0 :         // Make remote API calls to upload + download heatmaps: we ignore errors because this is just
    8005            0 :         // a 'kick' to let scheduling optimisation run more promptly.
    8006            0 :         match attached_node
    8007            0 :             .with_client_retries(
    8008            0 :                 |client| async move { client.tenant_heatmap_upload(tenant_shard_id).await },
    8009            0 :                 &self.http_client,
    8010            0 :                 &self.config.pageserver_jwt_token,
    8011            0 :                 3,
    8012            0 :                 10,
    8013            0 :                 SHORT_RECONCILE_TIMEOUT,
    8014            0 :                 &self.cancel,
    8015            0 :             )
    8016            0 :             .await
    8017              :         {
    8018            0 :             Some(Err(e)) => {
    8019            0 :                 tracing::info!(
    8020            0 :                     "Failed to upload heatmap from {attached_node} for {tenant_shard_id}: {e}"
    8021              :                 );
    8022              :             }
    8023              :             None => {
    8024            0 :                 tracing::info!(
    8025            0 :                     "Cancelled while uploading heatmap from {attached_node} for {tenant_shard_id}"
    8026              :                 );
    8027              :             }
    8028              :             Some(Ok(_)) => {
    8029            0 :                 tracing::info!(
    8030            0 :                     "Successfully uploaded heatmap from {attached_node} for {tenant_shard_id}"
    8031              :                 );
    8032              :             }
    8033              :         }
    8034              : 
    8035            0 :         for secondary_node in secondaries {
    8036            0 :             match secondary_node
    8037            0 :                 .with_client_retries(
    8038            0 :                     |client| async move {
    8039            0 :                         client
    8040            0 :                             .tenant_secondary_download(
    8041            0 :                                 tenant_shard_id,
    8042            0 :                                 Some(Duration::from_secs(1)),
    8043            0 :                             )
    8044            0 :                             .await
    8045            0 :                     },
    8046            0 :                     &self.http_client,
    8047            0 :                     &self.config.pageserver_jwt_token,
    8048            0 :                     3,
    8049            0 :                     10,
    8050            0 :                     SHORT_RECONCILE_TIMEOUT,
    8051            0 :                     &self.cancel,
    8052            0 :                 )
    8053            0 :                 .await
    8054              :             {
    8055            0 :                 Some(Err(e)) => {
    8056            0 :                     tracing::info!(
    8057            0 :                         "Failed to download heatmap from {secondary_node} for {tenant_shard_id}: {e}"
    8058              :                     );
    8059              :                 }
    8060              :                 None => {
    8061            0 :                     tracing::info!(
    8062            0 :                         "Cancelled while downloading heatmap from {secondary_node} for {tenant_shard_id}"
    8063              :                     );
    8064              :                 }
    8065            0 :                 Some(Ok(progress)) => {
    8066            0 :                     tracing::info!(
    8067            0 :                         "Successfully downloaded heatmap from {secondary_node} for {tenant_shard_id}: {progress:?}"
    8068              :                     );
    8069              :                 }
    8070              :             }
    8071              :         }
    8072            0 :     }
    8073              : 
    8074              :     /// Asynchronously split a tenant that's eligible for automatic splits. At most one tenant will
    8075              :     /// be split per call.
    8076              :     ///
    8077              :     /// Two sets of criteria are used: initial splits and size-based splits (in that order).
    8078              :     /// Initial splits are used to eagerly split unsharded tenants that may be performing initial
    8079              :     /// ingestion, since sharded tenants have significantly better ingestion throughput. Size-based
    8080              :     /// splits are used to bound the maximum shard size and balance out load.
    8081              :     ///
    8082              :     /// Splits are based on max_logical_size, i.e. the logical size of the largest timeline in a
    8083              :     /// tenant. We use this instead of the total logical size because branches will duplicate
    8084              :     /// logical size without actually using more storage. We could also use visible physical size,
    8085              :     /// but this might overestimate tenants that frequently churn branches.
    8086              :     ///
    8087              :     /// Initial splits (initial_split_threshold):
    8088              :     /// * Applies to tenants with 1 shard.
    8089              :     /// * The largest timeline (max_logical_size) exceeds initial_split_threshold.
    8090              :     /// * Splits into initial_split_shards.
    8091              :     ///
    8092              :     /// Size-based splits (split_threshold):
    8093              :     /// * Applies to all tenants.
    8094              :     /// * The largest timeline (max_logical_size) divided by shard count exceeds split_threshold.
    8095              :     /// * Splits such that max_logical_size / shard_count <= split_threshold, in powers of 2.
    8096              :     ///
    8097              :     /// Tenant shards are ordered by descending max_logical_size, first initial split candidates
    8098              :     /// then size-based split candidates. The first matching candidate is split.
    8099              :     ///
    8100              :     /// The shard count is clamped to max_split_shards. If a candidate is eligible for both initial
    8101              :     /// and size-based splits, the largest shard count will be used.
    8102              :     ///
    8103              :     /// An unsharded tenant will get DEFAULT_STRIPE_SIZE, regardless of what its ShardIdentity says.
    8104              :     /// A sharded tenant will retain its stripe size, as splits do not allow changing it.
    8105              :     ///
    8106              :     /// TODO: consider spawning multiple splits in parallel: this is only called once every 20
    8107              :     /// seconds, so a large backlog can take a long time, and if a tenant fails to split it will
    8108              :     /// block all other splits.
    8109            0 :     async fn autosplit_tenants(self: &Arc<Self>) {
    8110            0 :         // If max_split_shards is set to 0 or 1, we can't split.
    8111            0 :         let max_split_shards = self.config.max_split_shards;
    8112            0 :         if max_split_shards <= 1 {
    8113            0 :             return;
    8114            0 :         }
    8115            0 : 
    8116            0 :         // If initial_split_shards is set to 0 or 1, disable initial splits.
    8117            0 :         let mut initial_split_threshold = self.config.initial_split_threshold.unwrap_or(0);
    8118            0 :         let initial_split_shards = self.config.initial_split_shards;
    8119            0 :         if initial_split_shards <= 1 {
    8120            0 :             initial_split_threshold = 0;
    8121            0 :         }
    8122              : 
    8123              :         // If no split_threshold nor initial_split_threshold, disable autosplits.
    8124            0 :         let split_threshold = self.config.split_threshold.unwrap_or(0);
    8125            0 :         if split_threshold == 0 && initial_split_threshold == 0 {
    8126            0 :             return;
    8127            0 :         }
    8128            0 : 
    8129            0 :         // Fetch split candidates in prioritized order.
    8130            0 :         //
    8131            0 :         // If initial splits are enabled, fetch eligible tenants first. We prioritize initial splits
    8132            0 :         // over size-based splits, since these are often performing initial ingestion and rely on
    8133            0 :         // splits to improve ingest throughput.
    8134            0 :         let mut candidates = Vec::new();
    8135            0 : 
    8136            0 :         if initial_split_threshold > 0 {
    8137              :             // Initial splits: fetch tenants with 1 shard where the logical size of the largest
    8138              :             // timeline exceeds the initial split threshold.
    8139            0 :             let initial_candidates = self
    8140            0 :                 .get_top_tenant_shards(&TopTenantShardsRequest {
    8141            0 :                     order_by: TenantSorting::MaxLogicalSize,
    8142            0 :                     limit: 10,
    8143            0 :                     where_shards_lt: Some(ShardCount(2)),
    8144            0 :                     where_gt: Some(initial_split_threshold),
    8145            0 :                 })
    8146            0 :                 .await;
    8147            0 :             candidates.extend(initial_candidates);
    8148            0 :         }
    8149              : 
    8150            0 :         if split_threshold > 0 {
    8151              :             // Size-based splits: fetch tenants where the logical size of the largest timeline
    8152              :             // divided by shard count exceeds the split threshold.
    8153              :             //
    8154              :             // max_logical_size is only tracked on shard 0, and contains the total logical size
    8155              :             // across all shards. We have to order and filter by MaxLogicalSizePerShard, i.e.
    8156              :             // max_logical_size / shard_count, such that we only receive tenants that are actually
    8157              :             // eligible for splits. But we still use max_logical_size for later split calculations.
    8158            0 :             let size_candidates = self
    8159            0 :                 .get_top_tenant_shards(&TopTenantShardsRequest {
    8160            0 :                     order_by: TenantSorting::MaxLogicalSizePerShard,
    8161            0 :                     limit: 10,
    8162            0 :                     where_shards_lt: Some(ShardCount(max_split_shards)),
    8163            0 :                     where_gt: Some(split_threshold),
    8164            0 :                 })
    8165            0 :                 .await;
    8166              :             #[cfg(feature = "testing")]
    8167            0 :             assert!(
    8168            0 :                 size_candidates.iter().all(|c| c.id.is_shard_zero()),
    8169            0 :                 "MaxLogicalSizePerShard returned non-zero shard: {size_candidates:?}",
    8170              :             );
    8171            0 :             candidates.extend(size_candidates);
    8172            0 :         }
    8173              : 
    8174              :         // Filter out tenants in a prohibiting scheduling modes
    8175              :         // and tenants with an ongoing import.
    8176              :         //
    8177              :         // Note that the import check here is oportunistic. An import might start
    8178              :         // after the check before we actually update [`TenantShard::splitting`].
    8179              :         // [`Self::tenant_shard_split`] checks the database whilst holding the exclusive
    8180              :         // tenant lock. Imports might take a long time, so the check here allows us
    8181              :         // to split something else instead of trying the same shard over and over.
    8182            0 :         {
    8183            0 :             let state = self.inner.read().unwrap();
    8184            0 :             candidates.retain(|i| {
    8185            0 :                 let shard = state.tenants.get(&i.id);
    8186            0 :                 match shard {
    8187            0 :                     Some(t) => {
    8188            0 :                         t.get_scheduling_policy() == ShardSchedulingPolicy::Active
    8189            0 :                             && t.importing == TimelineImportState::Idle
    8190              :                     }
    8191            0 :                     None => false,
    8192              :                 }
    8193            0 :             });
    8194            0 :         }
    8195              : 
    8196              :         // Pick the first candidate to split. This will generally always be the first one in
    8197              :         // candidates, but we defensively skip candidates that end up not actually splitting.
    8198            0 :         let Some((candidate, new_shard_count)) = candidates
    8199            0 :             .into_iter()
    8200            0 :             .filter_map(|candidate| {
    8201            0 :                 let new_shard_count = Self::compute_split_shards(ShardSplitInputs {
    8202            0 :                     shard_count: candidate.id.shard_count,
    8203            0 :                     max_logical_size: candidate.max_logical_size,
    8204            0 :                     split_threshold,
    8205            0 :                     max_split_shards,
    8206            0 :                     initial_split_threshold,
    8207            0 :                     initial_split_shards,
    8208            0 :                 });
    8209            0 :                 new_shard_count.map(|shards| (candidate, shards.count()))
    8210            0 :             })
    8211            0 :             .next()
    8212              :         else {
    8213            0 :             debug!("no split-eligible tenants found");
    8214            0 :             return;
    8215              :         };
    8216              : 
    8217              :         // Retain the stripe size of sharded tenants, as splits don't allow changing it. Otherwise,
    8218              :         // use DEFAULT_STRIPE_SIZE for unsharded tenants -- their stripe size doesn't really matter,
    8219              :         // and if we change the default stripe size we want to use the new default rather than an
    8220              :         // old, persisted stripe size.
    8221            0 :         let new_stripe_size = match candidate.id.shard_count.count() {
    8222            0 :             0 => panic!("invalid shard count 0"),
    8223            0 :             1 => Some(DEFAULT_STRIPE_SIZE),
    8224            0 :             2.. => None,
    8225              :         };
    8226              : 
    8227              :         // We spawn a task to run this, so it's exactly like some external API client requesting
    8228              :         // it.  We don't want to block the background reconcile loop on this.
    8229            0 :         let old_shard_count = candidate.id.shard_count.count();
    8230            0 :         info!(
    8231            0 :             "auto-splitting tenant {old_shard_count} → {new_shard_count} shards, \
    8232            0 :                 current size {candidate:?} (split_threshold={split_threshold} \
    8233            0 :                 initial_split_threshold={initial_split_threshold})"
    8234              :         );
    8235              : 
    8236            0 :         let this = self.clone();
    8237            0 :         tokio::spawn(
    8238            0 :             async move {
    8239            0 :                 match this
    8240            0 :                     .tenant_shard_split(
    8241            0 :                         candidate.id.tenant_id,
    8242            0 :                         TenantShardSplitRequest {
    8243            0 :                             new_shard_count,
    8244            0 :                             new_stripe_size,
    8245            0 :                         },
    8246            0 :                     )
    8247            0 :                     .await
    8248              :                 {
    8249              :                     Ok(_) => {
    8250            0 :                         info!("successful auto-split {old_shard_count} → {new_shard_count} shards")
    8251              :                     }
    8252            0 :                     Err(err) => error!("auto-split failed: {err}"),
    8253              :                 }
    8254            0 :             }
    8255            0 :             .instrument(info_span!("auto_split", tenant_id=%candidate.id.tenant_id)),
    8256              :         );
    8257            0 :     }
    8258              : 
    8259              :     /// Returns the number of shards to split a tenant into, or None if the tenant shouldn't split,
    8260              :     /// based on the total logical size of the largest timeline summed across all shards. Uses the
    8261              :     /// larger of size-based and initial splits, clamped to max_split_shards.
    8262              :     ///
    8263              :     /// NB: the thresholds are exclusive, since TopTenantShardsRequest uses where_gt.
    8264           25 :     fn compute_split_shards(inputs: ShardSplitInputs) -> Option<ShardCount> {
    8265           25 :         let ShardSplitInputs {
    8266           25 :             shard_count,
    8267           25 :             max_logical_size,
    8268           25 :             split_threshold,
    8269           25 :             max_split_shards,
    8270           25 :             initial_split_threshold,
    8271           25 :             initial_split_shards,
    8272           25 :         } = inputs;
    8273           25 : 
    8274           25 :         let mut new_shard_count: u8 = shard_count.count();
    8275           25 : 
    8276           25 :         // Size-based splits. Ensures max_logical_size / new_shard_count <= split_threshold, using
    8277           25 :         // power-of-two shard counts.
    8278           25 :         //
    8279           25 :         // If the current shard count is not a power of two, and does not exceed split_threshold,
    8280           25 :         // then we leave it alone rather than forcing a power-of-two split.
    8281           25 :         if split_threshold > 0
    8282           18 :             && max_logical_size.div_ceil(split_threshold) > shard_count.count() as u64
    8283           12 :         {
    8284           12 :             new_shard_count = max_logical_size
    8285           12 :                 .div_ceil(split_threshold)
    8286           12 :                 .checked_next_power_of_two()
    8287           12 :                 .unwrap_or(u8::MAX as u64)
    8288           12 :                 .try_into()
    8289           12 :                 .unwrap_or(u8::MAX);
    8290           13 :         }
    8291              : 
    8292              :         // Initial splits. Use the larger of size-based and initial split shard counts. This only
    8293              :         // applies to unsharded tenants, i.e. changes to initial_split_threshold or
    8294              :         // initial_split_shards are not retroactive for sharded tenants.
    8295           25 :         if initial_split_threshold > 0
    8296           14 :             && shard_count.count() <= 1
    8297           11 :             && max_logical_size > initial_split_threshold
    8298            8 :         {
    8299            8 :             new_shard_count = new_shard_count.max(initial_split_shards);
    8300           17 :         }
    8301              : 
    8302              :         // Clamp to max shards.
    8303           25 :         new_shard_count = new_shard_count.min(max_split_shards);
    8304           25 : 
    8305           25 :         // Don't split if we're not increasing the shard count.
    8306           25 :         if new_shard_count <= shard_count.count() {
    8307           10 :             return None;
    8308           15 :         }
    8309           15 : 
    8310           15 :         Some(ShardCount(new_shard_count))
    8311           25 :     }
    8312              : 
    8313              :     /// Fetches the top tenant shards from every node, in descending order of
    8314              :     /// max logical size. Any node errors will be logged and ignored.
    8315            0 :     async fn get_top_tenant_shards(
    8316            0 :         &self,
    8317            0 :         request: &TopTenantShardsRequest,
    8318            0 :     ) -> Vec<TopTenantShardItem> {
    8319            0 :         let nodes = self
    8320            0 :             .inner
    8321            0 :             .read()
    8322            0 :             .unwrap()
    8323            0 :             .nodes
    8324            0 :             .values()
    8325            0 :             .cloned()
    8326            0 :             .collect_vec();
    8327            0 : 
    8328            0 :         let mut futures = FuturesUnordered::new();
    8329            0 :         for node in nodes {
    8330            0 :             futures.push(async move {
    8331            0 :                 node.with_client_retries(
    8332            0 :                     |client| async move { client.top_tenant_shards(request.clone()).await },
    8333            0 :                     &self.http_client,
    8334            0 :                     &self.config.pageserver_jwt_token,
    8335            0 :                     3,
    8336            0 :                     3,
    8337            0 :                     Duration::from_secs(5),
    8338            0 :                     &self.cancel,
    8339            0 :                 )
    8340            0 :                 .await
    8341            0 :             });
    8342            0 :         }
    8343              : 
    8344            0 :         let mut top = Vec::new();
    8345            0 :         while let Some(output) = futures.next().await {
    8346            0 :             match output {
    8347            0 :                 Some(Ok(response)) => top.extend(response.shards),
    8348            0 :                 Some(Err(mgmt_api::Error::Cancelled)) => {}
    8349            0 :                 Some(Err(err)) => warn!("failed to fetch top tenants: {err}"),
    8350            0 :                 None => {} // node is shutting down
    8351              :             }
    8352              :         }
    8353              : 
    8354            0 :         top.sort_by_key(|i| i.max_logical_size);
    8355            0 :         top.reverse();
    8356            0 :         top
    8357            0 :     }
    8358              : 
    8359              :     /// Useful for tests: run whatever work a background [`Self::reconcile_all`] would have done, but
    8360              :     /// also wait for any generated Reconcilers to complete.  Calling this until it returns zero should
    8361              :     /// put the system into a quiescent state where future background reconciliations won't do anything.
    8362            0 :     pub(crate) async fn reconcile_all_now(&self) -> Result<usize, ReconcileWaitError> {
    8363            0 :         let reconciles_spawned = self.reconcile_all();
    8364            0 :         let reconciles_spawned = if reconciles_spawned == 0 {
    8365              :             // Only optimize when we are otherwise idle
    8366            0 :             self.optimize_all().await
    8367              :         } else {
    8368            0 :             reconciles_spawned
    8369              :         };
    8370              : 
    8371            0 :         let waiters = {
    8372            0 :             let mut waiters = Vec::new();
    8373            0 :             let locked = self.inner.read().unwrap();
    8374            0 :             for (_tenant_shard_id, shard) in locked.tenants.iter() {
    8375            0 :                 if let Some(waiter) = shard.get_waiter() {
    8376            0 :                     waiters.push(waiter);
    8377            0 :                 }
    8378              :             }
    8379            0 :             waiters
    8380            0 :         };
    8381            0 : 
    8382            0 :         let waiter_count = waiters.len();
    8383            0 :         match self.await_waiters(waiters, RECONCILE_TIMEOUT).await {
    8384            0 :             Ok(()) => {}
    8385            0 :             Err(ReconcileWaitError::Failed(_, reconcile_error))
    8386            0 :                 if matches!(*reconcile_error, ReconcileError::Cancel) =>
    8387            0 :             {
    8388            0 :                 // Ignore reconciler cancel errors: this reconciler might have shut down
    8389            0 :                 // because some other change superceded it.  We will return a nonzero number,
    8390            0 :                 // so the caller knows they might have to call again to quiesce the system.
    8391            0 :             }
    8392            0 :             Err(e) => {
    8393            0 :                 return Err(e);
    8394              :             }
    8395              :         };
    8396              : 
    8397            0 :         tracing::info!(
    8398            0 :             "{} reconciles in reconcile_all, {} waiters",
    8399              :             reconciles_spawned,
    8400              :             waiter_count
    8401              :         );
    8402              : 
    8403            0 :         Ok(std::cmp::max(waiter_count, reconciles_spawned))
    8404            0 :     }
    8405              : 
    8406            0 :     async fn stop_reconciliations(&self, reason: StopReconciliationsReason) {
    8407            0 :         // Cancel all on-going reconciles and wait for them to exit the gate.
    8408            0 :         tracing::info!("{reason}: cancelling and waiting for in-flight reconciles");
    8409            0 :         self.reconcilers_cancel.cancel();
    8410            0 :         self.reconcilers_gate.close().await;
    8411              : 
    8412              :         // Signal the background loop in [`Service::process_results`] to exit once
    8413              :         // it has proccessed the results from all the reconciles we cancelled earlier.
    8414            0 :         tracing::info!("{reason}: processing results from previously in-flight reconciles");
    8415            0 :         self.result_tx.send(ReconcileResultRequest::Stop).ok();
    8416            0 :         self.result_tx.closed().await;
    8417            0 :     }
    8418              : 
    8419            0 :     pub async fn shutdown(&self) {
    8420            0 :         self.stop_reconciliations(StopReconciliationsReason::ShuttingDown)
    8421            0 :             .await;
    8422              : 
    8423              :         // Background tasks hold gate guards: this notifies them of the cancellation and
    8424              :         // waits for them all to complete.
    8425            0 :         tracing::info!("Shutting down: cancelling and waiting for background tasks to exit");
    8426            0 :         self.cancel.cancel();
    8427            0 :         self.gate.close().await;
    8428            0 :     }
    8429              : 
    8430              :     /// Spot check the download lag for a secondary location of a shard.
    8431              :     /// Should be used as a heuristic, since it's not always precise: the
    8432              :     /// secondary might have not downloaded the new heat map yet and, hence,
    8433              :     /// is not aware of the lag.
    8434              :     ///
    8435              :     /// Returns:
    8436              :     /// * Ok(None) if the lag could not be determined from the status,
    8437              :     /// * Ok(Some(_)) if the lag could be determind
    8438              :     /// * Err on failures to query the pageserver.
    8439            0 :     async fn secondary_lag(
    8440            0 :         &self,
    8441            0 :         secondary: &NodeId,
    8442            0 :         tenant_shard_id: TenantShardId,
    8443            0 :     ) -> Result<Option<u64>, mgmt_api::Error> {
    8444            0 :         let nodes = self.inner.read().unwrap().nodes.clone();
    8445            0 :         let node = nodes.get(secondary).ok_or(mgmt_api::Error::ApiError(
    8446            0 :             StatusCode::NOT_FOUND,
    8447            0 :             format!("Node with id {} not found", secondary),
    8448            0 :         ))?;
    8449              : 
    8450            0 :         match node
    8451            0 :             .with_client_retries(
    8452            0 :                 |client| async move { client.tenant_secondary_status(tenant_shard_id).await },
    8453            0 :                 &self.http_client,
    8454            0 :                 &self.config.pageserver_jwt_token,
    8455            0 :                 1,
    8456            0 :                 3,
    8457            0 :                 Duration::from_millis(250),
    8458            0 :                 &self.cancel,
    8459            0 :             )
    8460            0 :             .await
    8461              :         {
    8462            0 :             Some(Ok(status)) => match status.heatmap_mtime {
    8463            0 :                 Some(_) => Ok(Some(status.bytes_total - status.bytes_downloaded)),
    8464            0 :                 None => Ok(None),
    8465              :             },
    8466            0 :             Some(Err(e)) => Err(e),
    8467            0 :             None => Err(mgmt_api::Error::Cancelled),
    8468              :         }
    8469            0 :     }
    8470              : 
    8471              :     /// Drain a node by moving the shards attached to it as primaries.
    8472              :     /// This is a long running operation and it should run as a separate Tokio task.
    8473            0 :     pub(crate) async fn drain_node(
    8474            0 :         self: &Arc<Self>,
    8475            0 :         node_id: NodeId,
    8476            0 :         cancel: CancellationToken,
    8477            0 :     ) -> Result<(), OperationError> {
    8478              :         const MAX_SECONDARY_LAG_BYTES_DEFAULT: u64 = 256 * 1024 * 1024;
    8479            0 :         let max_secondary_lag_bytes = self
    8480            0 :             .config
    8481            0 :             .max_secondary_lag_bytes
    8482            0 :             .unwrap_or(MAX_SECONDARY_LAG_BYTES_DEFAULT);
    8483              : 
    8484              :         // By default, live migrations are generous about the wait time for getting
    8485              :         // the secondary location up to speed. When draining, give up earlier in order
    8486              :         // to not stall the operation when a cold secondary is encountered.
    8487              :         const SECONDARY_WARMUP_TIMEOUT: Duration = Duration::from_secs(20);
    8488              :         const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
    8489            0 :         let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal)
    8490            0 :             .secondary_warmup_timeout(SECONDARY_WARMUP_TIMEOUT)
    8491            0 :             .secondary_download_request_timeout(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT)
    8492            0 :             .build();
    8493            0 : 
    8494            0 :         let mut waiters = Vec::new();
    8495            0 : 
    8496            0 :         let mut tid_iter = TenantShardIterator::new({
    8497            0 :             let service = self.clone();
    8498            0 :             move |last_inspected_shard: Option<TenantShardId>| {
    8499            0 :                 let locked = &service.inner.read().unwrap();
    8500            0 :                 let tenants = &locked.tenants;
    8501            0 :                 let entry = match last_inspected_shard {
    8502            0 :                     Some(skip_past) => {
    8503            0 :                         // Skip to the last seen tenant shard id
    8504            0 :                         let mut cursor = tenants.iter().skip_while(|(tid, _)| **tid != skip_past);
    8505            0 : 
    8506            0 :                         // Skip past the last seen
    8507            0 :                         cursor.nth(1)
    8508              :                     }
    8509            0 :                     None => tenants.first_key_value(),
    8510              :                 };
    8511              : 
    8512            0 :                 entry.map(|(tid, _)| tid).copied()
    8513            0 :             }
    8514            0 :         });
    8515              : 
    8516            0 :         while !tid_iter.finished() {
    8517            0 :             if cancel.is_cancelled() {
    8518            0 :                 match self
    8519            0 :                     .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
    8520            0 :                     .await
    8521              :                 {
    8522            0 :                     Ok(()) => return Err(OperationError::Cancelled),
    8523            0 :                     Err(err) => {
    8524            0 :                         return Err(OperationError::FinalizeError(
    8525            0 :                             format!(
    8526            0 :                                 "Failed to finalise drain cancel of {} by setting scheduling policy to Active: {}",
    8527            0 :                                 node_id, err
    8528            0 :                             )
    8529            0 :                             .into(),
    8530            0 :                         ));
    8531              :                     }
    8532              :                 }
    8533            0 :             }
    8534            0 : 
    8535            0 :             drain_utils::validate_node_state(&node_id, self.inner.read().unwrap().nodes.clone())?;
    8536              : 
    8537            0 :             while waiters.len() < MAX_RECONCILES_PER_OPERATION {
    8538            0 :                 let tid = match tid_iter.next() {
    8539            0 :                     Some(tid) => tid,
    8540              :                     None => {
    8541            0 :                         break;
    8542              :                     }
    8543              :                 };
    8544              : 
    8545            0 :                 let tid_drain = TenantShardDrain {
    8546            0 :                     drained_node: node_id,
    8547            0 :                     tenant_shard_id: tid,
    8548            0 :                 };
    8549              : 
    8550            0 :                 let dest_node_id = {
    8551            0 :                     let locked = self.inner.read().unwrap();
    8552            0 : 
    8553            0 :                     match tid_drain
    8554            0 :                         .tenant_shard_eligible_for_drain(&locked.tenants, &locked.scheduler)
    8555              :                     {
    8556            0 :                         Some(node_id) => node_id,
    8557              :                         None => {
    8558            0 :                             continue;
    8559              :                         }
    8560              :                     }
    8561              :                 };
    8562              : 
    8563            0 :                 match self.secondary_lag(&dest_node_id, tid).await {
    8564            0 :                     Ok(Some(lag)) if lag <= max_secondary_lag_bytes => {
    8565            0 :                         // The secondary is reasonably up to date.
    8566            0 :                         // Migrate to it
    8567            0 :                     }
    8568            0 :                     Ok(Some(lag)) => {
    8569            0 :                         tracing::info!(
    8570            0 :                             tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    8571            0 :                             "Secondary on node {dest_node_id} is lagging by {lag}. Skipping reconcile."
    8572              :                         );
    8573            0 :                         continue;
    8574              :                     }
    8575              :                     Ok(None) => {
    8576            0 :                         tracing::info!(
    8577            0 :                             tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    8578            0 :                             "Could not determine lag for secondary on node {dest_node_id}. Skipping reconcile."
    8579              :                         );
    8580            0 :                         continue;
    8581              :                     }
    8582            0 :                     Err(err) => {
    8583            0 :                         tracing::warn!(
    8584            0 :                             tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    8585            0 :                             "Failed to get secondary lag from node {dest_node_id}. Skipping reconcile: {err}"
    8586              :                         );
    8587            0 :                         continue;
    8588              :                     }
    8589              :                 }
    8590              : 
    8591              :                 {
    8592            0 :                     let mut locked = self.inner.write().unwrap();
    8593            0 :                     let (nodes, tenants, scheduler) = locked.parts_mut();
    8594            0 :                     let rescheduled = tid_drain.reschedule_to_secondary(
    8595            0 :                         dest_node_id,
    8596            0 :                         tenants,
    8597            0 :                         scheduler,
    8598            0 :                         nodes,
    8599            0 :                     )?;
    8600              : 
    8601            0 :                     if let Some(tenant_shard) = rescheduled {
    8602            0 :                         let waiter = self.maybe_configured_reconcile_shard(
    8603            0 :                             tenant_shard,
    8604            0 :                             nodes,
    8605            0 :                             reconciler_config,
    8606            0 :                         );
    8607            0 :                         if let Some(some) = waiter {
    8608            0 :                             waiters.push(some);
    8609            0 :                         }
    8610            0 :                     }
    8611              :                 }
    8612              :             }
    8613              : 
    8614            0 :             waiters = self
    8615            0 :                 .await_waiters_remainder(waiters, WAITER_FILL_DRAIN_POLL_TIMEOUT)
    8616            0 :                 .await;
    8617              : 
    8618            0 :             failpoint_support::sleep_millis_async!("sleepy-drain-loop", &cancel);
    8619              :         }
    8620              : 
    8621            0 :         while !waiters.is_empty() {
    8622            0 :             if cancel.is_cancelled() {
    8623            0 :                 match self
    8624            0 :                     .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
    8625            0 :                     .await
    8626              :                 {
    8627            0 :                     Ok(()) => return Err(OperationError::Cancelled),
    8628            0 :                     Err(err) => {
    8629            0 :                         return Err(OperationError::FinalizeError(
    8630            0 :                             format!(
    8631            0 :                                 "Failed to finalise drain cancel of {} by setting scheduling policy to Active: {}",
    8632            0 :                                 node_id, err
    8633            0 :                             )
    8634            0 :                             .into(),
    8635            0 :                         ));
    8636              :                     }
    8637              :                 }
    8638            0 :             }
    8639            0 : 
    8640            0 :             tracing::info!("Awaiting {} pending drain reconciliations", waiters.len());
    8641              : 
    8642            0 :             waiters = self
    8643            0 :                 .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
    8644            0 :                 .await;
    8645              :         }
    8646              : 
    8647              :         // At this point we have done the best we could to drain shards from this node.
    8648              :         // Set the node scheduling policy to `[NodeSchedulingPolicy::PauseForRestart]`
    8649              :         // to complete the drain.
    8650            0 :         if let Err(err) = self
    8651            0 :             .node_configure(node_id, None, Some(NodeSchedulingPolicy::PauseForRestart))
    8652            0 :             .await
    8653              :         {
    8654              :             // This is not fatal. Anything that is polling the node scheduling policy to detect
    8655              :             // the end of the drain operations will hang, but all such places should enforce an
    8656              :             // overall timeout. The scheduling policy will be updated upon node re-attach and/or
    8657              :             // by the counterpart fill operation.
    8658            0 :             return Err(OperationError::FinalizeError(
    8659            0 :                 format!(
    8660            0 :                     "Failed to finalise drain of {node_id} by setting scheduling policy to PauseForRestart: {err}"
    8661            0 :                 )
    8662            0 :                 .into(),
    8663            0 :             ));
    8664            0 :         }
    8665            0 : 
    8666            0 :         Ok(())
    8667            0 :     }
    8668              : 
    8669              :     /// Create a node fill plan (pick secondaries to promote), based on:
    8670              :     /// 1. Shards which have a secondary on this node, and this node is in their home AZ, and are currently attached to a node
    8671              :     ///    outside their home AZ, should be migrated back here.
    8672              :     /// 2. If after step 1 we have not migrated enough shards for this node to have its fair share of
    8673              :     ///    attached shards, we will promote more shards from the nodes with the most attached shards, unless
    8674              :     ///    those shards have a home AZ that doesn't match the node we're filling.
    8675            0 :     fn fill_node_plan(&self, node_id: NodeId) -> Vec<TenantShardId> {
    8676            0 :         let mut locked = self.inner.write().unwrap();
    8677            0 :         let (nodes, tenants, _scheduler) = locked.parts_mut();
    8678            0 : 
    8679            0 :         let node_az = nodes
    8680            0 :             .get(&node_id)
    8681            0 :             .expect("Node must exist")
    8682            0 :             .get_availability_zone_id()
    8683            0 :             .clone();
    8684            0 : 
    8685            0 :         // The tenant shard IDs that we plan to promote from secondary to attached on this node
    8686            0 :         let mut plan = Vec::new();
    8687            0 : 
    8688            0 :         // Collect shards which do not have a preferred AZ & are elegible for moving in stage 2
    8689            0 :         let mut free_tids_by_node: HashMap<NodeId, Vec<TenantShardId>> = HashMap::new();
    8690            0 : 
    8691            0 :         // Don't respect AZ preferences if there is only one AZ.  This comes up in tests, but it could
    8692            0 :         // conceivably come up in real life if deploying a single-AZ region intentionally.
    8693            0 :         let respect_azs = nodes
    8694            0 :             .values()
    8695            0 :             .map(|n| n.get_availability_zone_id())
    8696            0 :             .unique()
    8697            0 :             .count()
    8698            0 :             > 1;
    8699              : 
    8700              :         // Step 1: collect all shards that we are required to migrate back to this node because their AZ preference
    8701              :         // requires it.
    8702            0 :         for (tsid, tenant_shard) in tenants {
    8703            0 :             if !tenant_shard.intent.get_secondary().contains(&node_id) {
    8704              :                 // Shard doesn't have a secondary on this node, ignore it.
    8705            0 :                 continue;
    8706            0 :             }
    8707            0 : 
    8708            0 :             // AZ check: when filling nodes after a restart, our intent is to move _back_ the
    8709            0 :             // shards which belong on this node, not to promote shards whose scheduling preference
    8710            0 :             // would be on their currently attached node.  So will avoid promoting shards whose
    8711            0 :             // home AZ doesn't match the AZ of the node we're filling.
    8712            0 :             match tenant_shard.preferred_az() {
    8713            0 :                 _ if !respect_azs => {
    8714            0 :                     if let Some(primary) = tenant_shard.intent.get_attached() {
    8715            0 :                         free_tids_by_node.entry(*primary).or_default().push(*tsid);
    8716            0 :                     }
    8717              :                 }
    8718              :                 None => {
    8719              :                     // Shard doesn't have an AZ preference: it is elegible to be moved, but we
    8720              :                     // will only do so if our target shard count requires it.
    8721            0 :                     if let Some(primary) = tenant_shard.intent.get_attached() {
    8722            0 :                         free_tids_by_node.entry(*primary).or_default().push(*tsid);
    8723            0 :                     }
    8724              :                 }
    8725            0 :                 Some(az) if az == &node_az => {
    8726              :                     // This shard's home AZ is equal to the node we're filling: it should
    8727              :                     // be moved back to this node as part of filling, unless its currently
    8728              :                     // attached location is also in its home AZ.
    8729            0 :                     if let Some(primary) = tenant_shard.intent.get_attached() {
    8730            0 :                         if nodes
    8731            0 :                             .get(primary)
    8732            0 :                             .expect("referenced node must exist")
    8733            0 :                             .get_availability_zone_id()
    8734            0 :                             != tenant_shard
    8735            0 :                                 .preferred_az()
    8736            0 :                                 .expect("tenant must have an AZ preference")
    8737              :                         {
    8738            0 :                             plan.push(*tsid)
    8739            0 :                         }
    8740              :                     } else {
    8741            0 :                         plan.push(*tsid)
    8742              :                     }
    8743              :                 }
    8744            0 :                 Some(_) => {
    8745            0 :                     // This shard's home AZ is somewhere other than the node we're filling,
    8746            0 :                     // it may not be moved back to this node as part of filling.  Ignore it
    8747            0 :                 }
    8748              :             }
    8749              :         }
    8750              : 
    8751              :         // Step 2: also promote any AZ-agnostic shards as required to achieve the target number of attachments
    8752            0 :         let fill_requirement = locked.scheduler.compute_fill_requirement(node_id);
    8753            0 : 
    8754            0 :         let expected_attached = locked.scheduler.expected_attached_shard_count();
    8755            0 :         let nodes_by_load = locked.scheduler.nodes_by_attached_shard_count();
    8756            0 : 
    8757            0 :         let mut promoted_per_tenant: HashMap<TenantId, usize> = HashMap::new();
    8758              : 
    8759            0 :         for (node_id, attached) in nodes_by_load {
    8760            0 :             let available = locked.nodes.get(&node_id).is_some_and(|n| n.is_available());
    8761            0 :             if !available {
    8762            0 :                 continue;
    8763            0 :             }
    8764            0 : 
    8765            0 :             if plan.len() >= fill_requirement
    8766            0 :                 || free_tids_by_node.is_empty()
    8767            0 :                 || attached <= expected_attached
    8768              :             {
    8769            0 :                 break;
    8770            0 :             }
    8771            0 : 
    8772            0 :             let can_take = attached - expected_attached;
    8773            0 :             let needed = fill_requirement - plan.len();
    8774            0 :             let mut take = std::cmp::min(can_take, needed);
    8775            0 : 
    8776            0 :             let mut remove_node = false;
    8777            0 :             while take > 0 {
    8778            0 :                 match free_tids_by_node.get_mut(&node_id) {
    8779            0 :                     Some(tids) => match tids.pop() {
    8780            0 :                         Some(tid) => {
    8781            0 :                             let max_promote_for_tenant = std::cmp::max(
    8782            0 :                                 tid.shard_count.count() as usize / locked.nodes.len(),
    8783            0 :                                 1,
    8784            0 :                             );
    8785            0 :                             let promoted = promoted_per_tenant.entry(tid.tenant_id).or_default();
    8786            0 :                             if *promoted < max_promote_for_tenant {
    8787            0 :                                 plan.push(tid);
    8788            0 :                                 *promoted += 1;
    8789            0 :                                 take -= 1;
    8790            0 :                             }
    8791              :                         }
    8792              :                         None => {
    8793            0 :                             remove_node = true;
    8794            0 :                             break;
    8795              :                         }
    8796              :                     },
    8797              :                     None => {
    8798            0 :                         break;
    8799              :                     }
    8800              :                 }
    8801              :             }
    8802              : 
    8803            0 :             if remove_node {
    8804            0 :                 free_tids_by_node.remove(&node_id);
    8805            0 :             }
    8806              :         }
    8807              : 
    8808            0 :         plan
    8809            0 :     }
    8810              : 
    8811              :     /// Fill a node by promoting its secondaries until the cluster is balanced
    8812              :     /// with regards to attached shard counts. Note that this operation only
    8813              :     /// makes sense as a counterpart to the drain implemented in [`Service::drain_node`].
    8814              :     /// This is a long running operation and it should run as a separate Tokio task.
    8815            0 :     pub(crate) async fn fill_node(
    8816            0 :         &self,
    8817            0 :         node_id: NodeId,
    8818            0 :         cancel: CancellationToken,
    8819            0 :     ) -> Result<(), OperationError> {
    8820              :         const SECONDARY_WARMUP_TIMEOUT: Duration = Duration::from_secs(20);
    8821              :         const SECONDARY_DOWNLOAD_REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
    8822            0 :         let reconciler_config = ReconcilerConfigBuilder::new(ReconcilerPriority::Normal)
    8823            0 :             .secondary_warmup_timeout(SECONDARY_WARMUP_TIMEOUT)
    8824            0 :             .secondary_download_request_timeout(SECONDARY_DOWNLOAD_REQUEST_TIMEOUT)
    8825            0 :             .build();
    8826            0 : 
    8827            0 :         let mut tids_to_promote = self.fill_node_plan(node_id);
    8828            0 :         let mut waiters = Vec::new();
    8829              : 
    8830              :         // Execute the plan we've composed above. Before aplying each move from the plan,
    8831              :         // we validate to ensure that it has not gone stale in the meantime.
    8832            0 :         while !tids_to_promote.is_empty() {
    8833            0 :             if cancel.is_cancelled() {
    8834            0 :                 match self
    8835            0 :                     .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
    8836            0 :                     .await
    8837              :                 {
    8838            0 :                     Ok(()) => return Err(OperationError::Cancelled),
    8839            0 :                     Err(err) => {
    8840            0 :                         return Err(OperationError::FinalizeError(
    8841            0 :                             format!(
    8842            0 :                                 "Failed to finalise drain cancel of {} by setting scheduling policy to Active: {}",
    8843            0 :                                 node_id, err
    8844            0 :                             )
    8845            0 :                             .into(),
    8846            0 :                         ));
    8847              :                     }
    8848              :                 }
    8849            0 :             }
    8850            0 : 
    8851            0 :             {
    8852            0 :                 let mut locked = self.inner.write().unwrap();
    8853            0 :                 let (nodes, tenants, scheduler) = locked.parts_mut();
    8854              : 
    8855            0 :                 let node = nodes.get(&node_id).ok_or(OperationError::NodeStateChanged(
    8856            0 :                     format!("node {node_id} was removed").into(),
    8857            0 :                 ))?;
    8858              : 
    8859            0 :                 let current_policy = node.get_scheduling();
    8860            0 :                 if !matches!(current_policy, NodeSchedulingPolicy::Filling) {
    8861              :                     // TODO(vlad): maybe cancel pending reconciles before erroring out. need to think
    8862              :                     // about it
    8863            0 :                     return Err(OperationError::NodeStateChanged(
    8864            0 :                         format!("node {node_id} changed state to {current_policy:?}").into(),
    8865            0 :                     ));
    8866            0 :                 }
    8867              : 
    8868            0 :                 while waiters.len() < MAX_RECONCILES_PER_OPERATION {
    8869            0 :                     if let Some(tid) = tids_to_promote.pop() {
    8870            0 :                         if let Some(tenant_shard) = tenants.get_mut(&tid) {
    8871              :                             // If the node being filled is not a secondary anymore,
    8872              :                             // skip the promotion.
    8873            0 :                             if !tenant_shard.intent.get_secondary().contains(&node_id) {
    8874            0 :                                 continue;
    8875            0 :                             }
    8876            0 : 
    8877            0 :                             let previously_attached_to = *tenant_shard.intent.get_attached();
    8878            0 :                             match tenant_shard.reschedule_to_secondary(Some(node_id), scheduler) {
    8879            0 :                                 Err(e) => {
    8880            0 :                                     tracing::warn!(
    8881            0 :                                         tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    8882            0 :                                         "Scheduling error when filling pageserver {} : {e}", node_id
    8883              :                                     );
    8884              :                                 }
    8885              :                                 Ok(()) => {
    8886            0 :                                     tracing::info!(
    8887            0 :                                         tenant_id=%tid.tenant_id, shard_id=%tid.shard_slug(),
    8888            0 :                                         "Rescheduled shard while filling node {}: {:?} -> {}",
    8889              :                                         node_id,
    8890              :                                         previously_attached_to,
    8891              :                                         node_id
    8892              :                                     );
    8893              : 
    8894            0 :                                     if let Some(waiter) = self.maybe_configured_reconcile_shard(
    8895            0 :                                         tenant_shard,
    8896            0 :                                         nodes,
    8897            0 :                                         reconciler_config,
    8898            0 :                                     ) {
    8899            0 :                                         waiters.push(waiter);
    8900            0 :                                     }
    8901              :                                 }
    8902              :                             }
    8903            0 :                         }
    8904              :                     } else {
    8905            0 :                         break;
    8906              :                     }
    8907              :                 }
    8908              :             }
    8909              : 
    8910            0 :             waiters = self
    8911            0 :                 .await_waiters_remainder(waiters, WAITER_FILL_DRAIN_POLL_TIMEOUT)
    8912            0 :                 .await;
    8913              :         }
    8914              : 
    8915            0 :         while !waiters.is_empty() {
    8916            0 :             if cancel.is_cancelled() {
    8917            0 :                 match self
    8918            0 :                     .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
    8919            0 :                     .await
    8920              :                 {
    8921            0 :                     Ok(()) => return Err(OperationError::Cancelled),
    8922            0 :                     Err(err) => {
    8923            0 :                         return Err(OperationError::FinalizeError(
    8924            0 :                             format!(
    8925            0 :                                 "Failed to finalise drain cancel of {} by setting scheduling policy to Active: {}",
    8926            0 :                                 node_id, err
    8927            0 :                             )
    8928            0 :                             .into(),
    8929            0 :                         ));
    8930              :                     }
    8931              :                 }
    8932            0 :             }
    8933            0 : 
    8934            0 :             tracing::info!("Awaiting {} pending fill reconciliations", waiters.len());
    8935              : 
    8936            0 :             waiters = self
    8937            0 :                 .await_waiters_remainder(waiters, SHORT_RECONCILE_TIMEOUT)
    8938            0 :                 .await;
    8939              :         }
    8940              : 
    8941            0 :         if let Err(err) = self
    8942            0 :             .node_configure(node_id, None, Some(NodeSchedulingPolicy::Active))
    8943            0 :             .await
    8944              :         {
    8945              :             // This isn't a huge issue since the filling process starts upon request. However, it
    8946              :             // will prevent the next drain from starting. The only case in which this can fail
    8947              :             // is database unavailability. Such a case will require manual intervention.
    8948            0 :             return Err(OperationError::FinalizeError(
    8949            0 :                 format!("Failed to finalise fill of {node_id} by setting scheduling policy to Active: {err}")
    8950            0 :                     .into(),
    8951            0 :             ));
    8952            0 :         }
    8953            0 : 
    8954            0 :         Ok(())
    8955            0 :     }
    8956              : 
    8957              :     /// Updates scrubber metadata health check results.
    8958            0 :     pub(crate) async fn metadata_health_update(
    8959            0 :         &self,
    8960            0 :         update_req: MetadataHealthUpdateRequest,
    8961            0 :     ) -> Result<(), ApiError> {
    8962            0 :         let now = chrono::offset::Utc::now();
    8963            0 :         let (healthy_records, unhealthy_records) = {
    8964            0 :             let locked = self.inner.read().unwrap();
    8965            0 :             let healthy_records = update_req
    8966            0 :                 .healthy_tenant_shards
    8967            0 :                 .into_iter()
    8968            0 :                 // Retain only health records associated with tenant shards managed by storage controller.
    8969            0 :                 .filter(|tenant_shard_id| locked.tenants.contains_key(tenant_shard_id))
    8970            0 :                 .map(|tenant_shard_id| MetadataHealthPersistence::new(tenant_shard_id, true, now))
    8971            0 :                 .collect();
    8972            0 :             let unhealthy_records = update_req
    8973            0 :                 .unhealthy_tenant_shards
    8974            0 :                 .into_iter()
    8975            0 :                 .filter(|tenant_shard_id| locked.tenants.contains_key(tenant_shard_id))
    8976            0 :                 .map(|tenant_shard_id| MetadataHealthPersistence::new(tenant_shard_id, false, now))
    8977            0 :                 .collect();
    8978            0 : 
    8979            0 :             (healthy_records, unhealthy_records)
    8980            0 :         };
    8981            0 : 
    8982            0 :         self.persistence
    8983            0 :             .update_metadata_health_records(healthy_records, unhealthy_records, now)
    8984            0 :             .await?;
    8985            0 :         Ok(())
    8986            0 :     }
    8987              : 
    8988              :     /// Lists the tenant shards that has unhealthy metadata status.
    8989            0 :     pub(crate) async fn metadata_health_list_unhealthy(
    8990            0 :         &self,
    8991            0 :     ) -> Result<Vec<TenantShardId>, ApiError> {
    8992            0 :         let result = self
    8993            0 :             .persistence
    8994            0 :             .list_unhealthy_metadata_health_records()
    8995            0 :             .await?
    8996            0 :             .iter()
    8997            0 :             .map(|p| p.get_tenant_shard_id().unwrap())
    8998            0 :             .collect();
    8999            0 : 
    9000            0 :         Ok(result)
    9001            0 :     }
    9002              : 
    9003              :     /// Lists the tenant shards that have not been scrubbed for some duration.
    9004            0 :     pub(crate) async fn metadata_health_list_outdated(
    9005            0 :         &self,
    9006            0 :         not_scrubbed_for: Duration,
    9007            0 :     ) -> Result<Vec<MetadataHealthRecord>, ApiError> {
    9008            0 :         let earlier = chrono::offset::Utc::now() - not_scrubbed_for;
    9009            0 :         let result = self
    9010            0 :             .persistence
    9011            0 :             .list_outdated_metadata_health_records(earlier)
    9012            0 :             .await?
    9013            0 :             .into_iter()
    9014            0 :             .map(|record| record.into())
    9015            0 :             .collect();
    9016            0 :         Ok(result)
    9017            0 :     }
    9018              : 
    9019            0 :     pub(crate) fn get_leadership_status(&self) -> LeadershipStatus {
    9020            0 :         self.inner.read().unwrap().get_leadership_status()
    9021            0 :     }
    9022              : 
    9023              :     /// Handler for step down requests
    9024              :     ///
    9025              :     /// Step down runs in separate task since once it's called it should
    9026              :     /// be driven to completion. Subsequent requests will wait on the same
    9027              :     /// step down task.
    9028            0 :     pub(crate) async fn step_down(self: &Arc<Self>) -> GlobalObservedState {
    9029            0 :         let handle = self.step_down_barrier.get_or_init(|| {
    9030            0 :             let step_down_self = self.clone();
    9031            0 :             let (tx, rx) = tokio::sync::watch::channel::<Option<GlobalObservedState>>(None);
    9032            0 :             tokio::spawn(async move {
    9033            0 :                 let state = step_down_self.step_down_task().await;
    9034            0 :                 tx.send(Some(state))
    9035            0 :                     .expect("Task Arc<Service> keeps receiver alive");
    9036            0 :             });
    9037            0 : 
    9038            0 :             rx
    9039            0 :         });
    9040            0 : 
    9041            0 :         handle
    9042            0 :             .clone()
    9043            0 :             .wait_for(|observed_state| observed_state.is_some())
    9044            0 :             .await
    9045            0 :             .expect("Task Arc<Service> keeps sender alive")
    9046            0 :             .deref()
    9047            0 :             .clone()
    9048            0 :             .expect("Checked above")
    9049            0 :     }
    9050              : 
    9051            0 :     async fn step_down_task(&self) -> GlobalObservedState {
    9052            0 :         tracing::info!("Received step down request from peer");
    9053            0 :         failpoint_support::sleep_millis_async!("sleep-on-step-down-handling");
    9054              : 
    9055            0 :         self.inner.write().unwrap().step_down();
    9056            0 : 
    9057            0 :         let stop_reconciliations =
    9058            0 :             self.stop_reconciliations(StopReconciliationsReason::SteppingDown);
    9059            0 :         let mut stop_reconciliations = std::pin::pin!(stop_reconciliations);
    9060            0 : 
    9061            0 :         let started_at = Instant::now();
    9062              : 
    9063              :         // Wait for reconciliations to stop and warn if that's taking a long time
    9064              :         loop {
    9065            0 :             tokio::select! {
    9066            0 :                 _ = &mut stop_reconciliations => {
    9067            0 :                     tracing::info!("Reconciliations stopped, proceeding with step down");
    9068            0 :                     break;
    9069              :                 }
    9070            0 :                 _ = tokio::time::sleep(Duration::from_secs(10)) => {
    9071            0 :                     tracing::warn!(
    9072            0 :                         elapsed_sec=%started_at.elapsed().as_secs(),
    9073            0 :                         "Stopping reconciliations during step down is taking too long"
    9074              :                     );
    9075              :                 }
    9076              :             }
    9077              :         }
    9078              : 
    9079            0 :         let mut global_observed = GlobalObservedState::default();
    9080            0 :         let locked = self.inner.read().unwrap();
    9081            0 :         for (tid, tenant_shard) in locked.tenants.iter() {
    9082            0 :             global_observed
    9083            0 :                 .0
    9084            0 :                 .insert(*tid, tenant_shard.observed.clone());
    9085            0 :         }
    9086              : 
    9087            0 :         global_observed
    9088            0 :     }
    9089              : 
    9090            0 :     pub(crate) async fn update_shards_preferred_azs(
    9091            0 :         &self,
    9092            0 :         req: ShardsPreferredAzsRequest,
    9093            0 :     ) -> Result<ShardsPreferredAzsResponse, ApiError> {
    9094            0 :         let preferred_azs = req.preferred_az_ids.into_iter().collect::<Vec<_>>();
    9095            0 :         let updated = self
    9096            0 :             .persistence
    9097            0 :             .set_tenant_shard_preferred_azs(preferred_azs)
    9098            0 :             .await
    9099            0 :             .map_err(|err| {
    9100            0 :                 ApiError::InternalServerError(anyhow::anyhow!(
    9101            0 :                     "Failed to persist preferred AZs: {err}"
    9102            0 :                 ))
    9103            0 :             })?;
    9104              : 
    9105            0 :         let mut updated_in_mem_and_db = Vec::default();
    9106            0 : 
    9107            0 :         let mut locked = self.inner.write().unwrap();
    9108            0 :         let state = locked.deref_mut();
    9109            0 :         for (tid, az_id) in updated {
    9110            0 :             let shard = state.tenants.get_mut(&tid);
    9111            0 :             if let Some(shard) = shard {
    9112            0 :                 shard.set_preferred_az(&mut state.scheduler, az_id);
    9113            0 :                 updated_in_mem_and_db.push(tid);
    9114            0 :             }
    9115              :         }
    9116              : 
    9117            0 :         Ok(ShardsPreferredAzsResponse {
    9118            0 :             updated: updated_in_mem_and_db,
    9119            0 :         })
    9120            0 :     }
    9121              : }
    9122              : 
    9123              : #[cfg(test)]
    9124              : mod tests {
    9125              :     use super::*;
    9126              : 
    9127              :     /// Tests Service::compute_split_shards. For readability, this specifies sizes in GBs rather
    9128              :     /// than bytes. Note that max_logical_size is the total logical size of the largest timeline
    9129              :     /// summed across all shards.
    9130              :     #[test]
    9131            1 :     fn compute_split_shards() {
    9132            1 :         // Size-based split: two shards have a 500 GB timeline, which need to split into 8 shards
    9133            1 :         // that are <= 64 GB,
    9134            1 :         assert_eq!(
    9135            1 :             Service::compute_split_shards(ShardSplitInputs {
    9136            1 :                 shard_count: ShardCount(2),
    9137            1 :                 max_logical_size: 500,
    9138            1 :                 split_threshold: 64,
    9139            1 :                 max_split_shards: 16,
    9140            1 :                 initial_split_threshold: 0,
    9141            1 :                 initial_split_shards: 0,
    9142            1 :             }),
    9143            1 :             Some(ShardCount(8))
    9144            1 :         );
    9145              : 
    9146              :         // Size-based split: noop at or below threshold, fires above.
    9147            1 :         assert_eq!(
    9148            1 :             Service::compute_split_shards(ShardSplitInputs {
    9149            1 :                 shard_count: ShardCount(2),
    9150            1 :                 max_logical_size: 127,
    9151            1 :                 split_threshold: 64,
    9152            1 :                 max_split_shards: 16,
    9153            1 :                 initial_split_threshold: 0,
    9154            1 :                 initial_split_shards: 0,
    9155            1 :             }),
    9156            1 :             None,
    9157            1 :         );
    9158            1 :         assert_eq!(
    9159            1 :             Service::compute_split_shards(ShardSplitInputs {
    9160            1 :                 shard_count: ShardCount(2),
    9161            1 :                 max_logical_size: 128,
    9162            1 :                 split_threshold: 64,
    9163            1 :                 max_split_shards: 16,
    9164            1 :                 initial_split_threshold: 0,
    9165            1 :                 initial_split_shards: 0,
    9166            1 :             }),
    9167            1 :             None,
    9168            1 :         );
    9169            1 :         assert_eq!(
    9170            1 :             Service::compute_split_shards(ShardSplitInputs {
    9171            1 :                 shard_count: ShardCount(2),
    9172            1 :                 max_logical_size: 129,
    9173            1 :                 split_threshold: 64,
    9174            1 :                 max_split_shards: 16,
    9175            1 :                 initial_split_threshold: 0,
    9176            1 :                 initial_split_shards: 0,
    9177            1 :             }),
    9178            1 :             Some(ShardCount(4)),
    9179            1 :         );
    9180              : 
    9181              :         // Size-based split: clamped to max_split_shards.
    9182            1 :         assert_eq!(
    9183            1 :             Service::compute_split_shards(ShardSplitInputs {
    9184            1 :                 shard_count: ShardCount(2),
    9185            1 :                 max_logical_size: 10000,
    9186            1 :                 split_threshold: 64,
    9187            1 :                 max_split_shards: 16,
    9188            1 :                 initial_split_threshold: 0,
    9189            1 :                 initial_split_shards: 0,
    9190            1 :             }),
    9191            1 :             Some(ShardCount(16))
    9192            1 :         );
    9193              : 
    9194              :         // Size-based split: tenant already at or beyond max_split_shards is not split.
    9195            1 :         assert_eq!(
    9196            1 :             Service::compute_split_shards(ShardSplitInputs {
    9197            1 :                 shard_count: ShardCount(16),
    9198            1 :                 max_logical_size: 10000,
    9199            1 :                 split_threshold: 64,
    9200            1 :                 max_split_shards: 16,
    9201            1 :                 initial_split_threshold: 0,
    9202            1 :                 initial_split_shards: 0,
    9203            1 :             }),
    9204            1 :             None
    9205            1 :         );
    9206              : 
    9207            1 :         assert_eq!(
    9208            1 :             Service::compute_split_shards(ShardSplitInputs {
    9209            1 :                 shard_count: ShardCount(32),
    9210            1 :                 max_logical_size: 10000,
    9211            1 :                 split_threshold: 64,
    9212            1 :                 max_split_shards: 16,
    9213            1 :                 initial_split_threshold: 0,
    9214            1 :                 initial_split_shards: 0,
    9215            1 :             }),
    9216            1 :             None
    9217            1 :         );
    9218              : 
    9219              :         // Size-based split: a non-power-of-2 shard count is normalized to power-of-2 if it
    9220              :         // exceeds split_threshold (i.e. a 3-shard tenant splits into 8, not 6).
    9221            1 :         assert_eq!(
    9222            1 :             Service::compute_split_shards(ShardSplitInputs {
    9223            1 :                 shard_count: ShardCount(3),
    9224            1 :                 max_logical_size: 320,
    9225            1 :                 split_threshold: 64,
    9226            1 :                 max_split_shards: 16,
    9227            1 :                 initial_split_threshold: 0,
    9228            1 :                 initial_split_shards: 0,
    9229            1 :             }),
    9230            1 :             Some(ShardCount(8))
    9231            1 :         );
    9232              : 
    9233              :         // Size-based split: a non-power-of-2 shard count is not normalized to power-of-2 if the
    9234              :         // existing shards are below or at split_threshold, but splits into 4 if it exceeds it.
    9235            1 :         assert_eq!(
    9236            1 :             Service::compute_split_shards(ShardSplitInputs {
    9237            1 :                 shard_count: ShardCount(3),
    9238            1 :                 max_logical_size: 191,
    9239            1 :                 split_threshold: 64,
    9240            1 :                 max_split_shards: 16,
    9241            1 :                 initial_split_threshold: 0,
    9242            1 :                 initial_split_shards: 0,
    9243            1 :             }),
    9244            1 :             None
    9245            1 :         );
    9246            1 :         assert_eq!(
    9247            1 :             Service::compute_split_shards(ShardSplitInputs {
    9248            1 :                 shard_count: ShardCount(3),
    9249            1 :                 max_logical_size: 192,
    9250            1 :                 split_threshold: 64,
    9251            1 :                 max_split_shards: 16,
    9252            1 :                 initial_split_threshold: 0,
    9253            1 :                 initial_split_shards: 0,
    9254            1 :             }),
    9255            1 :             None
    9256            1 :         );
    9257            1 :         assert_eq!(
    9258            1 :             Service::compute_split_shards(ShardSplitInputs {
    9259            1 :                 shard_count: ShardCount(3),
    9260            1 :                 max_logical_size: 193,
    9261            1 :                 split_threshold: 64,
    9262            1 :                 max_split_shards: 16,
    9263            1 :                 initial_split_threshold: 0,
    9264            1 :                 initial_split_shards: 0,
    9265            1 :             }),
    9266            1 :             Some(ShardCount(4))
    9267            1 :         );
    9268              : 
    9269              :         // Initial split: tenant has a 10 GB timeline, split into 4 shards.
    9270            1 :         assert_eq!(
    9271            1 :             Service::compute_split_shards(ShardSplitInputs {
    9272            1 :                 shard_count: ShardCount(1),
    9273            1 :                 max_logical_size: 10,
    9274            1 :                 split_threshold: 0,
    9275            1 :                 max_split_shards: 16,
    9276            1 :                 initial_split_threshold: 8,
    9277            1 :                 initial_split_shards: 4,
    9278            1 :             }),
    9279            1 :             Some(ShardCount(4))
    9280            1 :         );
    9281              : 
    9282              :         // Initial split: 0 ShardCount is equivalent to 1.
    9283            1 :         assert_eq!(
    9284            1 :             Service::compute_split_shards(ShardSplitInputs {
    9285            1 :                 shard_count: ShardCount(0),
    9286            1 :                 max_logical_size: 10,
    9287            1 :                 split_threshold: 0,
    9288            1 :                 max_split_shards: 16,
    9289            1 :                 initial_split_threshold: 8,
    9290            1 :                 initial_split_shards: 4,
    9291            1 :             }),
    9292            1 :             Some(ShardCount(4))
    9293            1 :         );
    9294              : 
    9295              :         // Initial split: at or below threshold is noop.
    9296            1 :         assert_eq!(
    9297            1 :             Service::compute_split_shards(ShardSplitInputs {
    9298            1 :                 shard_count: ShardCount(1),
    9299            1 :                 max_logical_size: 7,
    9300            1 :                 split_threshold: 0,
    9301            1 :                 max_split_shards: 16,
    9302            1 :                 initial_split_threshold: 8,
    9303            1 :                 initial_split_shards: 4,
    9304            1 :             }),
    9305            1 :             None,
    9306            1 :         );
    9307            1 :         assert_eq!(
    9308            1 :             Service::compute_split_shards(ShardSplitInputs {
    9309            1 :                 shard_count: ShardCount(1),
    9310            1 :                 max_logical_size: 8,
    9311            1 :                 split_threshold: 0,
    9312            1 :                 max_split_shards: 16,
    9313            1 :                 initial_split_threshold: 8,
    9314            1 :                 initial_split_shards: 4,
    9315            1 :             }),
    9316            1 :             None,
    9317            1 :         );
    9318            1 :         assert_eq!(
    9319            1 :             Service::compute_split_shards(ShardSplitInputs {
    9320            1 :                 shard_count: ShardCount(1),
    9321            1 :                 max_logical_size: 9,
    9322            1 :                 split_threshold: 0,
    9323            1 :                 max_split_shards: 16,
    9324            1 :                 initial_split_threshold: 8,
    9325            1 :                 initial_split_shards: 4,
    9326            1 :             }),
    9327            1 :             Some(ShardCount(4))
    9328            1 :         );
    9329              : 
    9330              :         // Initial split: already sharded tenant is not affected, even if above threshold and below
    9331              :         // shard count.
    9332            1 :         assert_eq!(
    9333            1 :             Service::compute_split_shards(ShardSplitInputs {
    9334            1 :                 shard_count: ShardCount(2),
    9335            1 :                 max_logical_size: 20,
    9336            1 :                 split_threshold: 0,
    9337            1 :                 max_split_shards: 16,
    9338            1 :                 initial_split_threshold: 8,
    9339            1 :                 initial_split_shards: 4,
    9340            1 :             }),
    9341            1 :             None,
    9342            1 :         );
    9343              : 
    9344              :         // Initial split: clamped to max_shards.
    9345            1 :         assert_eq!(
    9346            1 :             Service::compute_split_shards(ShardSplitInputs {
    9347            1 :                 shard_count: ShardCount(1),
    9348            1 :                 max_logical_size: 10,
    9349            1 :                 split_threshold: 0,
    9350            1 :                 max_split_shards: 3,
    9351            1 :                 initial_split_threshold: 8,
    9352            1 :                 initial_split_shards: 4,
    9353            1 :             }),
    9354            1 :             Some(ShardCount(3)),
    9355            1 :         );
    9356              : 
    9357              :         // Initial+size split: tenant eligible for both will use the larger shard count.
    9358            1 :         assert_eq!(
    9359            1 :             Service::compute_split_shards(ShardSplitInputs {
    9360            1 :                 shard_count: ShardCount(1),
    9361            1 :                 max_logical_size: 10,
    9362            1 :                 split_threshold: 64,
    9363            1 :                 max_split_shards: 16,
    9364            1 :                 initial_split_threshold: 8,
    9365            1 :                 initial_split_shards: 4,
    9366            1 :             }),
    9367            1 :             Some(ShardCount(4)),
    9368            1 :         );
    9369            1 :         assert_eq!(
    9370            1 :             Service::compute_split_shards(ShardSplitInputs {
    9371            1 :                 shard_count: ShardCount(1),
    9372            1 :                 max_logical_size: 500,
    9373            1 :                 split_threshold: 64,
    9374            1 :                 max_split_shards: 16,
    9375            1 :                 initial_split_threshold: 8,
    9376            1 :                 initial_split_shards: 4,
    9377            1 :             }),
    9378            1 :             Some(ShardCount(8)),
    9379            1 :         );
    9380              : 
    9381              :         // Initial+size split: sharded tenant is only eligible for size-based split.
    9382            1 :         assert_eq!(
    9383            1 :             Service::compute_split_shards(ShardSplitInputs {
    9384            1 :                 shard_count: ShardCount(2),
    9385            1 :                 max_logical_size: 200,
    9386            1 :                 split_threshold: 64,
    9387            1 :                 max_split_shards: 16,
    9388            1 :                 initial_split_threshold: 8,
    9389            1 :                 initial_split_shards: 8,
    9390            1 :             }),
    9391            1 :             Some(ShardCount(4)),
    9392            1 :         );
    9393              : 
    9394              :         // Initial+size split: uses the larger shard count even with initial_split_threshold above
    9395              :         // split_threshold.
    9396            1 :         assert_eq!(
    9397            1 :             Service::compute_split_shards(ShardSplitInputs {
    9398            1 :                 shard_count: ShardCount(1),
    9399            1 :                 max_logical_size: 10,
    9400            1 :                 split_threshold: 4,
    9401            1 :                 max_split_shards: 16,
    9402            1 :                 initial_split_threshold: 8,
    9403            1 :                 initial_split_shards: 8,
    9404            1 :             }),
    9405            1 :             Some(ShardCount(8)),
    9406            1 :         );
    9407              : 
    9408              :         // Test backwards compatibility with production settings when initial/size-based splits were
    9409              :         // rolled out: a single split into 8 shards at 64 GB. Any already sharded tenants with <8
    9410              :         // shards will split according to split_threshold.
    9411            1 :         assert_eq!(
    9412            1 :             Service::compute_split_shards(ShardSplitInputs {
    9413            1 :                 shard_count: ShardCount(1),
    9414            1 :                 max_logical_size: 65,
    9415            1 :                 split_threshold: 64,
    9416            1 :                 max_split_shards: 8,
    9417            1 :                 initial_split_threshold: 64,
    9418            1 :                 initial_split_shards: 8,
    9419            1 :             }),
    9420            1 :             Some(ShardCount(8)),
    9421            1 :         );
    9422              : 
    9423            1 :         assert_eq!(
    9424            1 :             Service::compute_split_shards(ShardSplitInputs {
    9425            1 :                 shard_count: ShardCount(1),
    9426            1 :                 max_logical_size: 64,
    9427            1 :                 split_threshold: 64,
    9428            1 :                 max_split_shards: 8,
    9429            1 :                 initial_split_threshold: 64,
    9430            1 :                 initial_split_shards: 8,
    9431            1 :             }),
    9432            1 :             None,
    9433            1 :         );
    9434              : 
    9435            1 :         assert_eq!(
    9436            1 :             Service::compute_split_shards(ShardSplitInputs {
    9437            1 :                 shard_count: ShardCount(2),
    9438            1 :                 max_logical_size: 129,
    9439            1 :                 split_threshold: 64,
    9440            1 :                 max_split_shards: 8,
    9441            1 :                 initial_split_threshold: 64,
    9442            1 :                 initial_split_shards: 8,
    9443            1 :             }),
    9444            1 :             Some(ShardCount(4)),
    9445            1 :         );
    9446            1 :     }
    9447              : }
        

Generated by: LCOV version 2.1-beta