perf(quota): reuse recovered v2 credit under shared locking

Probe orphan owners outside the allocator and shard locks. Apply
recovery and a fitting reservation in one shard write. Drain any
commit-started orphan publication before accounting its live bytes.

Fund donor-backed refills with the exact shortfall so other shards
can draw on the returned excess, including after interrupted donor
preparation.

Co-Authored-By: heihutu <heihutu@gmail.com>
Co-Authored-By: zhi22915 <qiuzgang@gmail.com>
Co-Authored-By: qunjiazhu <qunjiazhu@gmail.com>
This commit is contained in:
Hauser Zhi
2026-12-01 00:15:09 +08:00
parent d5aeed62aa
commit ef73493765
2 changed files with 175 additions and 152 deletions
+173 -146
View File
@@ -58,8 +58,8 @@ static FAIL_NEXT_LEDGER_SAVE: std::sync::atomic::AtomicBool = std::sync::atomic:
// Lock order: caller-held destination object/upload, bucket metadata
// transaction (read), operation reservation, then quota ledger. Protocol v2
// uses allocator(read) -> shard(write); credit refill releases the operation
// and shard guards before taking allocator(write), and orphan probes never
// uses allocator(read) -> shard(write); credit refill retains the operation
// guard and releases shard and allocator(read) before taking allocator(write). Orphan probes never
// hold allocator/shard guards while acquiring an operation lock.
// When Object Lock already holds the metadata transaction read lock, reuse
// that guard: reacquiring it behind a waiting metadata writer would deadlock.
@@ -403,6 +403,41 @@ impl QuotaShardLedger {
Ok(())
}
async fn reap_orphans(
&mut self,
store: &Arc<ECStore>,
bucket: &str,
guards: &[(Uuid, NamespaceLockGuard)],
cursor: Option<Uuid>,
) -> Result<bool> {
let mut removed = false;
for (operation_id, guard) in guards {
if guard.is_lock_lost() {
continue;
}
let Some(reservation) = self.reservations.get(operation_id).cloned() else {
continue;
};
if reservation.commit_started {
// Drain the old publication before a recount can release its credit.
fence_namespace_mutations(store, bucket, &reservation.object, reservation.target()).await?;
if guard.is_lock_lost() {
continue;
}
self.reservations.remove(operation_id);
self.reconcile_required = true;
} else {
self.abort(*operation_id, &reservation)?;
}
removed = true;
}
let cursor_changed = cursor.is_some() && self.reap_cursor != cursor;
if cursor.is_some() {
self.reap_cursor = cursor;
}
Ok(removed || cursor_changed)
}
fn reap_candidates(&self, now: i64) -> (Vec<Uuid>, Option<Uuid>) {
let aged = self
.reservations
@@ -557,6 +592,7 @@ async fn reserve_sharded(context: QuotaContext, old_size: u64, new_size: u64) ->
// The operation lock stays held across the shared-to-exclusive allocator retry.
let mut exclusive = false;
let mut orphan_probe = None::<(Vec<_>, Option<_>)>;
loop {
let allocator_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.allocator_object).await?;
let allocator_guard = Arc::new(if exclusive {
@@ -599,7 +635,8 @@ async fn reserve_sharded(context: QuotaContext, old_size: u64, new_size: u64) ->
let shard_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.shard_object).await?;
let shard_guard = Arc::new(shard_lock.get_write_lock(get_lock_acquire_timeout()).await?);
check_guards(&shard_guard)?;
if exclusive {
let reaping = orphan_probe.is_some();
if exclusive || reaping {
fence_namespace_mutations(&store, RUSTFS_META_BUCKET, &data.shard_object, None).await?;
}
let (mut shard, shard_created) = load_current_shard_locked(
@@ -612,17 +649,31 @@ async fn reserve_sharded(context: QuotaContext, old_size: u64, new_size: u64) ->
&allocator,
)
.await?;
let mut reaped = false;
if let Some((guards, cursor)) = &orphan_probe {
reaped = shard.reap_orphans(&store, &data.bucket, guards, *cursor).await?;
if reaped && shard.reservations.is_empty() && shard.reconcile_required {
reconcile_shard_exact(&store, &data.bucket, &mut shard).await?;
}
}
let shortfall = growth.saturating_sub(shard.available_credit()?);
if shortfall != 0 && !exclusive {
let now = now_unix();
let has_aged_reservations = shard.reservations.values().any(|reservation| reservation.is_aged(now));
drop(shard_guard);
drop(allocator_guard);
#[cfg(test)]
tests::pause_before_allocator_refill(&data.bucket, &data.reservation.object).await;
if has_aged_reservations {
reap_sharded_reservations(Arc::clone(&store), &data, bucket_incarnation, quota_revision, quota_limit).await?;
if reaped {
check_guards(&shard_guard)?;
save_shard_locked(Arc::clone(&store), &data.shard_object, &shard, &shard_guard, &allocator_guard).await?;
} else if !reaping {
let (candidates, cursor) = shard.reap_candidates(now_unix());
drop(shard_guard);
drop(allocator_guard);
#[cfg(test)]
tests::pause_before_allocator_refill(&data.bucket, &data.reservation.object).await;
if !candidates.is_empty() {
let guards = probe_sharded_orphans(&data, candidates).await?;
orphan_probe = Some((guards, cursor));
continue;
}
}
orphan_probe = None;
exclusive = true;
continue;
}
@@ -632,7 +683,7 @@ async fn reserve_sharded(context: QuotaContext, old_size: u64, new_size: u64) ->
.await?;
shard.adopt_grants(&allocator)?;
}
if !exclusive {
if !exclusive && !reaping {
fence_namespace_mutations(&store, RUSTFS_META_BUCKET, &data.shard_object, None).await?;
}
check_guards(&shard_guard)?;
@@ -2083,24 +2134,6 @@ async fn load_allocator_locked(store: Arc<ECStore>, object: &str) -> Result<Quot
Ok(allocator)
}
async fn load_current_allocator_locked(
store: Arc<ECStore>,
object: &str,
bucket_incarnation: Uuid,
quota_revision: OffsetDateTime,
quota_limit: u64,
) -> Result<QuotaAllocatorLedger> {
match load_allocator_locked(Arc::clone(&store), object).await {
Ok(allocator) if allocator.matches(bucket_incarnation, quota_revision, quota_limit) => Ok(allocator),
Ok(allocator) if allocator.grants.is_empty() => {
Ok(QuotaAllocatorLedger::new(bucket_incarnation, quota_revision, quota_limit))
}
Ok(_) => Err(StorageError::PartMissingOrCorrupt),
Err(StorageError::ConfigNotFound) => Err(StorageError::PartMissingOrCorrupt),
Err(err) => Err(err),
}
}
async fn load_shard_locked(store: Arc<ECStore>, object: &str) -> Result<QuotaShardLedger> {
let data = read_config_no_lock(store, object).await?;
let shard: QuotaShardLedger = serde_json::from_slice(&data)?;
@@ -2280,9 +2313,9 @@ async fn refill_sharded_credit(
}
}
// Size the first empty requester's grant before any donor preparation advances
// the generation. Speculative credit here can strand room needed by another shard.
let amount = if allocator.generation == SHARDED_BOOTSTRAP_GENERATION && requester.grants.is_empty() {
// Return excess donor credit to the common pool instead of moving the
// same stranded balance to the requester.
let amount = if !donors.is_empty() || (allocator.generation == SHARDED_BOOTSTRAP_GENERATION && requester.grants.is_empty()) {
shortfall
} else {
shortfall
@@ -2348,53 +2381,10 @@ async fn refill_sharded_credit(
save_allocator_locked(Arc::clone(store), &data.allocator_object, allocator, allocator_guard).await
}
async fn reap_sharded_reservations(
store: Arc<ECStore>,
data: &ShardedReservationData,
bucket_incarnation: Uuid,
quota_revision: OffsetDateTime,
quota_limit: u64,
) -> Result<()> {
let allocator_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.allocator_object).await?;
let allocator_guard = allocator_lock.get_read_lock(get_lock_acquire_timeout()).await?;
if allocator_guard.is_lock_lost() {
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "quota_allocator",
bucket: RUSTFS_META_BUCKET.to_string(),
object: data.allocator_object.clone(),
required: 1,
achieved: 0,
});
}
let allocator = load_current_allocator_locked(
Arc::clone(&store),
&data.allocator_object,
bucket_incarnation,
quota_revision,
quota_limit,
)
.await?;
let shard_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.shard_object).await?;
let shard_guard = shard_lock.get_write_lock(get_lock_acquire_timeout()).await?;
let (shard, _) = load_current_shard_locked(
Arc::clone(&store),
&data.shard_object,
bucket_incarnation,
quota_revision,
data.shard_index,
false,
&allocator,
)
.await?;
let (candidates, next_cursor) = shard.reap_candidates(now_unix());
drop(shard_guard);
drop(allocator_guard);
if candidates.is_empty() && next_cursor.is_none() {
return Ok(());
}
async fn probe_sharded_orphans(data: &ShardedReservationData, candidates: Vec<Uuid>) -> Result<Vec<(Uuid, NamespaceLockGuard)>> {
let probe_results = stream::iter(candidates)
.map(|operation_id| {
let store = Arc::clone(&store);
let store = Arc::clone(&data.store);
let object = data.shard_object.clone();
async move {
let lock_object = operation_lock_object(&object, operation_id);
@@ -2417,72 +2407,7 @@ async fn reap_sharded_reservations(
orphan_guards.push(guard);
}
}
let allocator_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.allocator_object).await?;
let allocator_guard = allocator_lock.get_read_lock(get_lock_acquire_timeout()).await?;
if allocator_guard.is_lock_lost() {
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "quota_allocator",
bucket: RUSTFS_META_BUCKET.to_string(),
object: data.allocator_object.clone(),
required: 1,
achieved: 0,
});
}
let allocator = load_current_allocator_locked(
Arc::clone(&store),
&data.allocator_object,
bucket_incarnation,
quota_revision,
quota_limit,
)
.await?;
let shard_lock = store.new_ns_lock(RUSTFS_META_BUCKET, &data.shard_object).await?;
let shard_guard = Arc::new(shard_lock.get_write_lock(get_lock_acquire_timeout()).await?);
let (mut shard, _) = load_current_shard_locked(
Arc::clone(&store),
&data.shard_object,
bucket_incarnation,
quota_revision,
data.shard_index,
false,
&allocator,
)
.await?;
let mut removed = false;
for (operation_id, _guard) in &orphan_guards {
let Some(reservation) = shard.reservations.get(operation_id).cloned() else {
continue;
};
if reservation.commit_started {
shard.reservations.remove(operation_id);
shard.reconcile_required = true;
} else {
shard.abort(*operation_id, &reservation)?;
}
removed = true;
}
let cursor_changed = next_cursor.is_some() && shard.reap_cursor != next_cursor;
if next_cursor.is_some() {
shard.reap_cursor = next_cursor;
}
if !removed && !cursor_changed {
return Ok(());
}
if shard.reservations.is_empty() && shard.reconcile_required {
reconcile_shard_exact(&store, &data.bucket, &mut shard).await?;
}
fence_namespace_mutations(&store, RUSTFS_META_BUCKET, &data.shard_object, None).await?;
if allocator_guard.is_lock_lost() || shard_guard.is_lock_lost() {
return Err(StorageError::NamespaceLockQuorumUnavailable {
mode: "quota_shard_reap",
bucket: data.bucket.clone(),
object: data.shard_object.clone(),
required: 1,
achieved: 0,
});
}
save_shard_locked(Arc::clone(&store), &data.shard_object, &shard, &shard_guard, &allocator_guard).await?;
Ok(())
Ok(orphan_guards)
}
async fn mark_commit_started_sharded(data: &Arc<ShardedReservationData>) -> Result<()> {
@@ -4515,6 +4440,80 @@ mod tests {
assert_eq!(allocator.generation, initial_generation + 1, "both PUTs must share the same refill");
}
#[tokio::test]
#[serial]
async fn sharded_reservation_reuses_orphan_credit_under_the_shared_allocator_lock() {
for commit_started in [false, true] {
let (_directories, job) = reconciliation_fixture(16).await;
let quota = super::super::BucketQuota::new_sharded(16);
job.store
.update_bucket_metadata_config(&job.bucket, "quota.json", serde_json::to_vec(&quota).expect("serialize v2 quota"))
.await
.expect("enable v2 quota");
let mut keys = (0..1000)
.map(|index| format!("orphan-credit-{index}"))
.filter(|key| shard_index(key) == (shard_index("seed") + 1) % SHARDED_LEDGER_COUNT);
let orphan_key = keys.next().expect("find an orphan key");
let writer_key = keys.next().expect("find a writer key in the same shard");
let opts = ObjectOptions::default();
let mut abandoned = begin(&job.store.ctx, &job.bucket, &orphan_key, &opts, 0, 0)
.await
.expect("open quota context")
.reserve(0, 6)
.await
.expect("reserve the remaining six bytes");
let publication = if commit_started {
abandoned.mark_commit_started().await.expect("mark the old publication");
let disk = job.store.pools[0].disk_set[0].disks.read().await[0]
.clone()
.expect("fixture disk");
let fence = crate::disk::quota_mutation_fence_path(&job.bucket, &orphan_key);
let token = disk
.acquire_snapshot_lease(RUSTFS_META_BUCKET, &fence)
.await
.expect("old publication token");
Some((disk, fence, token))
} else {
None
};
abandoned.defer_after_fence();
let (_, incarnation, revision) = job
.store
.bucket_quota_and_incarnation_from_disk(&job.bucket)
.await
.expect("quota identity");
let allocator_path = allocator_object(&ledger_object(&job.bucket), incarnation, revision);
let lock = job
.store
.new_ns_lock(RUSTFS_META_BUCKET, &allocator_path)
.await
.expect("allocator lock");
let other_reader = lock
.get_read_lock(get_lock_acquire_timeout())
.await
.expect("hold a shared allocator lock");
// A refill requiring an exclusive allocator lock cannot proceed while this reader is held.
let write = tokio::time::timeout(Duration::from_secs(30), put_test_object(&job, &writer_key, 6, &opts)).await;
drop(other_reader);
write
.expect("PUT completes while the other allocator reader is held")
.expect("reuse the orphan's credit");
let shard_path = shard_object(&ledger_object(&job.bucket), shard_index(&writer_key), incarnation, revision);
let shard = load_shard_locked(Arc::clone(&job.store), &shard_path)
.await
.expect("read settled shard");
assert_eq!(shard.accounted_usage, 6);
assert!(shard.reservations.is_empty());
if let Some((disk, fence, token)) = publication {
assert!(matches!(
disk.renew_snapshot_lease(RUSTFS_META_BUCKET, &fence, token).await,
Err(DiskError::FileNotFound)
));
}
}
}
#[tokio::test]
#[serial]
async fn sharded_reservation_recovers_an_empty_requester_after_bootstrap() {
@@ -4595,7 +4594,7 @@ mod tests {
#[tokio::test]
#[serial]
async fn sharded_reservation_issues_exact_first_grant_when_a_bootstrap_donor_is_needed() {
async fn sharded_reservation_leaves_excess_donor_credit_unissued_after_replay() {
let (_directories, job) = reconciliation_fixture(160).await;
let quota = super::super::BucketQuota::new_sharded(160);
job.store
@@ -4608,6 +4607,34 @@ mod tests {
put_test_object(&job, "seed", 0, &ObjectOptions::default())
.await
.expect("shrink the bootstrap donor while retaining its grant");
let (_, incarnation, revision) = job
.store
.bucket_quota_and_incarnation_from_disk(&job.bucket)
.await
.expect("quota identity");
let allocator_path = allocator_object(&ledger_object(&job.bucket), incarnation, revision);
let lock = job
.store
.new_ns_lock(RUSTFS_META_BUCKET, &allocator_path)
.await
.expect("allocator lock");
let guard = Arc::new(
lock.get_write_lock(get_lock_acquire_timeout())
.await
.expect("exclusive allocator"),
);
let mut allocator = load_allocator_locked(Arc::clone(&job.store), &allocator_path)
.await
.expect("read allocator before preparation");
assert_eq!(allocator.generation, SHARDED_BOOTSTRAP_GENERATION);
for grant in allocator.grants.values_mut() {
grant.initial_usage = 0;
}
allocator.generation += 1;
save_allocator_locked(Arc::clone(&job.store), &allocator_path, &allocator, &guard)
.await
.expect("persist the preparation stage before the donor write");
drop(guard);
let mut shards = HashSet::from([shard_index("seed")]);
let keys = (0..100)
.map(|index| format!("cold-donor-{index}"))
@@ -4619,7 +4646,7 @@ mod tests {
.expect("reclaim the original bootstrap grant");
put_test_object(&job, &keys[1], 151, &ObjectOptions::default())
.await
.expect("preparing the donor must not turn the first one-byte grant into a chunk");
.expect("the returned donor credit must remain available to other shards after replay");
}
#[tokio::test]
@@ -22,11 +22,7 @@ sum(shard grant amounts) <= quota_limit
shard.accounted_usage <= sum(shard grant amounts)
```
`accounted_usage` includes committed bytes and pending positive reservation
growth. An abort removes the pending growth; a commit removes only the pending
record because its growth is already accounted. A reservation whose commit
marker was persisted is removed only as a precharged reconcile candidate; the
shard is then rebuilt from objects belonging to that shard.
`accounted_usage` includes committed bytes and pending positive reservation growth. An abort removes pending growth. A commit removes the pending record because its growth is already accounted. Before releasing a commit-started orphan's precharged bytes, recovery revokes and drains the orphan's object publication and then reconciles the shard against its objects.
## Locking and fencing
@@ -103,7 +99,7 @@ encoding that makes pre-reservation coordinators reject positive growth.
## Performance boundary
Normal v2 admission acquires the shared allocator lock and reads the allocator once, then acquires the shard write lock. The same allocator snapshot remains protected until the reservation is saved. When a write exhausts its shard credit, the exclusive allocator lock protects the recheck, refill and reservation. If the remaining unissued credit is insufficient, the allocator can reuse whole grants from other shards, scanning at most the quota's 16 shard ledgers and performing no object listing. An empty requester at the bootstrap generation receives only its requested growth. Subsequent refills aim for roughly one sixteenth of the quota, or the shortfall when larger, within the available budget.
Normal v2 admission acquires the shared allocator lock and reads the allocator once, then acquires the shard write lock. The same allocator snapshot remains protected until the reservation is saved. When orphan recovery frees enough local credit, the recovered and new reservations are saved together under the shared allocator lock. When a write exhausts its shard credit, the exclusive allocator lock protects the recheck, refill and reservation. If the remaining unissued credit is insufficient, the allocator can reuse whole grants from other shards, scanning at most the quota's 16 shard ledgers. Donor selection performs no object listing. A donor-backed refill issues the exact shortfall and returns excess credit to the common pool. An empty requester at the bootstrap generation also receives only its requested growth. Ordinary refills from unissued credit aim for roughly one sixteenth of the quota, or the shortfall when larger, within the available budget.
A shard can still hold idle credit inside a partly used grant. The allocator selects whole grants greedily, so it may also miss a combination of smaller grants. When the allocator cannot refill the write, the quota error reports total accounted usage across the shard ledgers, including pending growth. Deletes can leave accounted usage above the live object bytes.