Skip to content

Seed zero-value quota metric on bucket create / quota enable#6221

Open
delthas wants to merge 5 commits into
development/9.4from
improvement/CLDSRV-949/seed-empty-bucket-quota-metric
Open

Seed zero-value quota metric on bucket create / quota enable#6221
delthas wants to merge 5 commits into
development/9.4from
improvement/CLDSRV-949/seed-empty-bucket-quota-metric

Conversation

@delthas

@delthas delthas commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Context

Bucket/account quota enforcement reads utilization metrics from Scuba, which serves the __infostore collection. Those documents are written today only by the s3utils count-items cron (every 6–24h). A freshly created bucket — or a bucket that has a quota enabled while empty — has no metric document until the next cron run, so validateQuotas_evaluateQuotas gets NoSuchEntity from Scuba and fails open: the quota is not enforced for up to 24h (ARTESCA-17063).

Change

Seed a zero-value bucket metric document in __infostore at the moments CloudServer knows the bucket is empty, so the quota is enforceable immediately:

  1. On createBucket — the bucket is empty by definition, so seed unconditionally.
  2. On bucketUpdateQuota — seed only when the bucket is verifiably empty (a maxKeys:1 DelimiterVersions listing). Never default to zero for a bucket that may hold uncounted data (that would silently under-enforce).

Both paths:

  • are gated on config.isQuotaEnabled();
  • are best-effort / non-fatal — a seeding failure is logged and never fails the request (quota simply stays disabled until count-items, i.e. today's behavior);
  • use the new arsenal MetadataWrapper.initializeBucketCapacity (idempotent $setOnInsert, so an existing count-items document is never overwritten), keyed by the bucket's metastore creationDate — exactly what _evaluateQuotas queries with, so the create-window lookup is an exact match.

Account-level metrics are intentionally out of scope: a brand-new bucket's account may hold data in other, not-yet-counted buckets, so seeding account_<id>=0 would under-report. Empty-account coverage stays with count-items (S3UTILS-224).

Dependency

Requires ARSN-610 (arsenal#2666). The first commit here temporarily pins arsenal to that branch commit so the new method resolves; it should be replaced with a released arsenal 8.5 tag once ARSN-610 merges.

Tests

New unit tests: bucketUpdateQuota seeds on an empty bucket, does not seed on a non-empty bucket, still succeeds when seeding errors, and does not seed when quotas are disabled; bucketPut seeds on creation, stays non-fatal on seed error, and does not seed when quotas are disabled.

Issue: CLDSRV-949

@bert-e

bert-e commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Hello delthas,

My role is to assist you with the merge of this
pull request. Please type @bert-e help to get information
on this process, or consult the user documentation.

Available options
name description privileged authored
/after_pull_request Wait for the given pull request id to be merged before continuing with the current one.
/bypass_author_approval Bypass the pull request author's approval
/bypass_build_status Bypass the build and test status
/bypass_commit_size Bypass the check on the size of the changeset TBA
/bypass_incompatible_branch Bypass the check on the source branch prefix
/bypass_jira_check Bypass the Jira issue check
/bypass_peer_approval Bypass the pull request peers' approval
/bypass_leader_approval Bypass the pull request leaders' approval
/approve Instruct Bert-E that the author has approved the pull request. ✍️
/create_pull_requests Allow the creation of integration pull requests.
/create_integration_branches Allow the creation of integration branches.
/no_octopus Prevent Wall-E from doing any octopus merge and use multiple consecutive merge instead
/unanimity Change review acceptance criteria from one reviewer at least to all reviewers
/wait Instruct Bert-E not to run until further notice.
Available commands
name description privileged
/help Print Bert-E's manual in the pull request.
/status Print Bert-E's current status in the pull request TBA
/clear Remove all comments from Bert-E from the history TBA
/retry Re-start a fresh build TBA
/build Re-start a fresh build TBA
/force_reset Delete integration branches & pull requests, and restart merge process from the beginning.
/reset Try to remove integration branches unless there are commits on them which do not appear on the source branch.

Status report is not available.

@scality scality deleted a comment from bert-e Jul 6, 2026
@bert-e

bert-e commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Waiting for approval

The following approvals are needed before I can proceed with the merge:

  • the author

  • 2 peers

Comment thread package.json Outdated
"@opentelemetry/instrumentation-mongodb": "~0.69.0",
"@smithy/node-http-handler": "^3.0.0",
"arsenal": "git+https://github.com/scality/arsenal#8.5.4",
"arsenal": "git+https://github.com/scality/arsenal#05db0fa2268958fac066204ad2a48d2e083311dd",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arsenal is pinned to a commit hash instead of a release tag. Per repo conventions, git-based dependencies must be pinned to a tag (e.g. 8.5.x).

The PR description mentions this is temporary pending ARSN-610 — please ensure this is updated to a released tag before merging.

Suggested change
"arsenal": "git+https://github.com/scality/arsenal#05db0fa2268958fac066204ad2a48d2e083311dd",
"arsenal": "git+https://github.com/scality/arsenal#8.5.5",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know

Comment thread lib/api/apiUtils/bucket/bucketCreation.js Fixed
Comment thread lib/api/bucketUpdateQuota.js Fixed
Comment thread lib/api/bucketUpdateQuota.js Fixed
@codecov

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.83333% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.03%. Comparing base (9314dc5) to head (9e549e4).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
lib/api/apiUtils/bucket/bucketCreation.js 96.34% 3 Missing ⚠️
lib/api/bucketUpdateQuota.js 95.16% 3 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

Files with missing lines Coverage Δ
lib/api/apiUtils/bucket/bucketCreation.js 97.01% <96.34%> (+3.62%) ⬆️
lib/api/bucketUpdateQuota.js 96.15% <95.16%> (+0.07%) ⬆️

... and 2 files with indirect coverage changes

@@                 Coverage Diff                 @@
##           development/9.4    #6221      +/-   ##
===================================================
+ Coverage            85.99%   86.03%   +0.03%     
===================================================
  Files                  212      212              
  Lines                14415    14455      +40     
===================================================
+ Hits                 12396    12436      +40     
  Misses                2019     2019              
Flag Coverage Δ
file-ft-tests 69.51% <66.66%> (-0.06%) ⬇️
file-ft-tests-null-compat 69.94% <66.66%> (-0.06%) ⬇️
kmip-ft-tests 28.05% <38.19%> (+0.04%) ⬆️
mongo-v0-ft-tests 70.56% <66.66%> (-0.11%) ⬇️
mongo-v1-ft-tests 70.57% <66.66%> (-0.09%) ⬇️
multiple-backend 36.04% <38.19%> (+0.02%) ⬆️
s3c-ft-tests-v0 64.85% <72.22%> (-0.05%) ⬇️
s3c-ft-tests-v0-null-compat 64.91% <72.22%> (-0.05%) ⬇️
s3c-ft-tests-v1 64.83% <72.22%> (-0.05%) ⬇️
sur-tests 35.11% <62.50%> (+0.15%) ⬆️
sur-tests-inflights 37.85% <62.50%> (+0.14%) ⬆️
unit 73.28% <88.19%> (+0.30%) ⬆️
utapi-v2-tests 35.23% <43.75%> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@delthas delthas force-pushed the improvement/CLDSRV-949/seed-empty-bucket-quota-metric branch from c463226 to 64c60e4 Compare July 6, 2026 15:13
Comment on lines +270 to -242
if (err) {
return callback(err);
}
return callback(null, data);
});
},
},
},
// Function to run upon finishing both parallel requests
(err, results) => {
if (err) {
return cb(err);
Comment on lines -243 to +277
}
const existingBucketMD = results.getAnyExistingBucketInfo;
if (existingBucketMD instanceof BucketInfo &&
existingBucketMD.getOwner() !== canonicalID &&
!isServiceAccount(canonicalID)) {
// return existingBucketMD to collect cors headers
return cb(errors.BucketAlreadyExists, existingBucketMD);
}
const newBucketMD = results.prepareNewBucketMD;
if (existingBucketMD === 'NoBucketYet') {
const bucketSseConfig = parseBucketEncryptionHeaders(headers);
// Function to run upon finishing both parallel requests
Comment on lines +78 to +79
return bucketUpdateQuota(authInfo, request, log)
.then(corsHeaders => callback(null, corsHeaders))
Comment thread lib/api/bucketUpdateQuota.js
@delthas delthas force-pushed the improvement/CLDSRV-949/seed-empty-bucket-quota-metric branch 2 times, most recently from 7930f2c to 815f61c Compare July 7, 2026 08:36
Comment thread lib/api/apiUtils/bucket/bucketCreation.js Fixed
@delthas delthas force-pushed the improvement/CLDSRV-949/seed-empty-bucket-quota-metric branch 3 times, most recently from 7d8d376 to 049c059 Compare July 7, 2026 14:02
Isolates prettier reformatting of files that were already
prettier-dirty on development/9.4, so the functional change commits
that follow stay prettier-clean.

Issue: CLDSRV-949
@delthas delthas force-pushed the improvement/CLDSRV-949/seed-empty-bucket-quota-metric branch from 049c059 to b0c3fc9 Compare July 7, 2026 14:17
@bert-e

bert-e commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Waiting for approval

The following approvals are needed before I can proceed with the merge:

  • the author

  • 2 peers

@scality scality deleted a comment from bert-e Jul 7, 2026
@delthas delthas marked this pull request as ready for review July 7, 2026 14:21
@delthas delthas requested review from a team, DarkIsDude and benzekrimaha July 8, 2026 09:39
@delthas delthas force-pushed the improvement/CLDSRV-949/seed-empty-bucket-quota-metric branch from b0c3fc9 to 7e7a71a Compare July 8, 2026 09:41
Comment thread package.json Outdated
"@opentelemetry/instrumentation-mongodb": "~0.69.0",
"@smithy/node-http-handler": "^3.0.0",
"arsenal": "git+https://github.com/scality/arsenal#8.5.6",
"arsenal": "git+https://github.com/scality/arsenal#43a1d0577dffd6e77a712ab813abaff57ace43ae",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Be careful 🙏

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, known and flagged by Claude already, keeping open until the Arsenal part is merged

return metadata.updateBucket(bucketName, bucket, log, callback);
}

function seedBucketQuotaCapacity(bucket, log, done) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function is a new one and must use async/await. We agreed to don't do it for prettier one, but this one is a new one 🙏

return callback(err);
}
return removeTransientOrDeletedLabel(bucket, log, callback);
return removeTransientOrDeletedLabel(bucket, log, labelErr => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, you touch the function, it's not only a formatting 🙏

}
return metadata.initializeBucketCapacity(bucket.getName(), bucket.getCreationDate(), log, err => {
if (err) {
log.error('error seeding bucket quota capacity metric', { error: err });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why we just log and don't propagate it ?

if (labelErr) {
return callback(labelErr);
}
return seedBucketQuotaCapacity(bucket, log, () => callback(null));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why callback(null) ? Why not callback() ?

undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, isNFSEnabled,
undefined, undefined, objectLockEnabled);
const objectLockEnabled = headerObjectLock && headerObjectLock.toLowerCase() === 'true';
const bucket = new BucketInfo(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😂 this is where you know that a class is too large 😂

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(nothing to do)

Comment thread lib/api/bucketUpdateQuota.js Outdated
}
const bucketName = bucket.getName();
try {
const list = await promisify(metadata.listObject.bind(metadata))(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To avoid promisify always, you can do promise.custom. See the confluence page. does it make sense here ?

Comment thread lib/api/bucketUpdateQuota.js Outdated
}
await promisify(metadata.initializeBucketCapacity.bind(metadata))(bucketName, bucket.getCreationDate(), log);
} catch (err) {
log.error('error seeding bucket quota capacity metric', { error: err });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why just a log and not a propagate ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

warn, not error: IMO the failure is best-effort and self-heals at the next count-items run; nothing for a human to do. Also worth a one-line comment stating why it's non-fatal

@bert-e

bert-e commented Jul 8, 2026

Copy link
Copy Markdown
Contributor

Waiting for approval

The following approvals are needed before I can proceed with the merge:

  • the author

  • 2 peers

The following reviewers are expecting changes from the author, or must review again:

const quotaValue = validateBucketQuotaProperty(requestBody);
bucket.setQuota(quotaValue);
await promisify(metadata.updateBucket.bind(metadata))(bucket.getName(), bucket, log);
await seedEmptyBucketCapacity(bucket, log);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why seed after updateBucket persists the quota? Done in this order there's still a window where the quota is set but no metric exists (fail-open, the exact bug we're fixing here). Listing + seeding first, then enabling the quota, closes the window entirely IMO and the emptiness check can't be invalidated by the quota becoming visible in between

Comment thread lib/api/bucketUpdateQuota.js Outdated
},
log,
);
const isEmpty =

@benzekrimaha benzekrimaha Jul 8, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

a DelimiterVersions listing won't see in-progress MPU parts (shadow bucket), but those hold real storage. If count-items includes MPU parts in the bucket metric, seeding 0 here under-enforces for a bucket that only has uncommitted uploads , the exact case the description says must never happen ("never default to zero for a bucket that may hold uncounted data"). Does count-items count MPU parts? and if yes, shouldn't the emptiness check also probe the MPU shadow bucket?

Suggested change
const isEmpty =
const isEmpty = (list.Versions?.length ?? 0) + (list.DeleteMarkers?.length ?? 0) === 0;

if (labelErr) {
return callback(labelErr);
}
return seedBucketQuotaCapacity(bucketMD, log, () => callback(null));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seeding also fires on the transient/deleted-flag cleanup path (re-creating a bucket left in transient state), which the PR description doesn't mention and no test covers, codecov flags 5 missed lines in this file. Is the creationDate used here guaranteed to be the new incarnation's metastore date that _evaluateQuotas will query? can we add a test for this path (or explain why it can't be hit with quotas enabled).

bucketPut(authInfo, testRequest, log, err => {
assert.ifError(err);
assert(initStub.calledOnce, 'expected initializeBucketCapacity to be called once');
assert.strictEqual(initStub.firstCall.args[0], bucketName);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the exact-match creationDate keying is the load-bearing part of the design; the test should also pin it:

Suggested change
assert.strictEqual(initStub.firstCall.args[0], bucketName);
assert.strictEqual(initStub.firstCall.args[0], bucketName);
assert.strictEqual(initStub.firstCall.args[1], md.getCreationDate());

.stub(metadata, 'initializeBucketCapacity')
.callsFake((name, creationDate, l, cb) => process.nextTick(() => cb(errors.InternalError)));
return bucketUpdateQuota(authInfo, updateQuotaRequest, log, err => {
assert.ifError(err);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the test only asserts no error we should assert md.getQuota() === 1000 after the call, otherwise "still update the quota" isn't actually verified.

return;
}
await promisify(metadata.initializeBucketCapacity.bind(metadata))(bucketName, bucket.getCreationDate(), log);
} catch (err) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we add the test case where listObject errors (seed skipped, request still succeeds).

delthas added 3 commits July 9, 2026 11:06
Temporary pin to the ARSN-610 branch commit so the quota metric
seeding can resolve MetadataWrapper.initializeBucketCapacity. To be
replaced with a released arsenal 8.5 tag once ARSN-610 is merged.

Issue: CLDSRV-949
Seed a zero-value bucket metric document in __infostore when the
bucket is known to be empty, so bucket quota checks are enforceable
immediately instead of waiting up to 24h for the periodic count-items
job (ARTESCA-17063):

- on createBucket, the bucket is empty by definition, so seed it;
- on bucketUpdateQuota, seed only when the bucket is verifiably empty
  (a maxKeys:1 DelimiterVersions listing), never defaulting to zero
  for a bucket that may hold uncounted data.

Both paths are gated on config.isQuotaEnabled() and are best-effort:
a seeding failure is logged and never fails the request. The write
uses the new arsenal MetadataWrapper.initializeBucketCapacity
(idempotent $setOnInsert), keyed by the bucket's metastore
creationDate to match the enforcement lookup.

Issue: CLDSRV-949
Migrate the callback-style bucketUpdateQuota handler to async/await
using the dual callback+async trampoline, to preempt the CodeQL
"callback-style function" alert triggered by modifying it. The
callback contract and behavior are unchanged. Callback-based
dependencies are promisified at call time so the wrapper's method
identity (and test stubs) are honored.

Issue: CLDSRV-949
@delthas delthas force-pushed the improvement/CLDSRV-949/seed-empty-bucket-quota-metric branch from 7e7a71a to 3bd38a8 Compare July 9, 2026 09:07
- migrate seedBucketQuotaCapacity / freshStartCreateBucket / cleanUpBucket
  to async/await (callback trampoline keeps existing callers working)
- bucketUpdateQuota: seed the zero metric before persisting the quota to
  close the fail-open window, and probe the MPU shadow bucket so a bucket
  with only in-progress uploads is never seeded to zero
- log seeding failures at warn (best-effort, self-heals next count-items)
- cache promisified metadata methods at module level
- tests: transient/deleted cleanup path, exact creationDate match,
  listing-error and in-progress-MPU cases

Issue: CLDSRV-949
Comment on lines +109 to +110
return freshStartCreateBucket(bucket, canonicalID, log)
.then(() => callback(null))
Comment on lines +136 to +137
return cleanUpBucket(bucketMD, canonicalID, log)
.then(() => callback(null))
return bucketUpdateQuota(authInfo, updateQuotaRequest, log, err => {
assert.ifError(err);
assert(initStub.calledOnce, 'expected seeding for an empty bucket');
assert.strictEqual(initStub.firstCall.args[0], bucketName);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing creationDate assertion. The bucketPut test was updated to verify initStub.firstCall.args[1] === md.getCreationDate() (the load-bearing keying for quota lookups), but this test only checks args[0]. Add the same verification here:

Suggested change
assert.strictEqual(initStub.firstCall.args[0], bucketName);
assert.strictEqual(initStub.firstCall.args[0], bucketName);
return metadata.getBucket(bucketName, log, (getErr, md) => {
assert.ifError(getErr);
assert.strictEqual(
initStub.firstCall.args[1],
md.getCreationDate(),
'must seed with the metastore creationDate used by quota lookups',
);
done();
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants